<commit_before>//
//  match-js
//  A simple yet powerful pattern matching library for Javascript.
//
//  Read readme.md for instructions and LICENSE license.
//
//  Copyright (c) 2010 Johan Dahlberg
//
var Match = (function() {
    var NO_MATCH = { __matchtype__: 'no-match', toString: function() { return 'no-match' }};
    var TYPE_RE = /function\s([A-Za-z_1-9$]+)/;
    var IS_FIELD_OP = /\s\=$|\s\!$|\s\>$|\s\<$|\s\>\=$|\s\<\=$/;

    function is_prim_type(obj) {
        return obj == String || obj == Number || obj == Date || obj == Boolean
    }

    function is_empty(value) {
        return value == null || value == undefined;
    }

    function get_op_resolver(operator, value_a) {
        var op_resolver = function() { return true };
        switch(operator) {
            case ' =':
                op_resolver = function(value_b, parent, state) {
                    if(value_a == value_b) return true;
                    return false;
                }
                break;
            case ' >':
                op_resolver = function(value_b, parent, state) {
                    if(value_a > value_b) return true;
                    return false;
                }
                break;
            case ' <':
                op_resolver = function(value_b, parent, state) {
                    if(value_a < value_b) return true;
                    return false;
                }
                break;
            case ' >=':
                op_resolver = function(value_b, parent, state) {
                    if(value_a >= value_b) return true;
                    return false;
                }
                break;
            case ' <=':
                op_resolver = function(value_b, parent, state) {
                    if(value_a <= value_b) return true;
                    return false;
                }
                break;
            case ' !':
                op_resolver = function(value_b, parent, state) {
                    if(value_a != value_b) return true;
                    return false;
                }
                break;
        }
        op_resolver.is_op = true;
        return op_resolver;
    }

    function get_resolver(obj) {
        var ctor;

        // Check if we got an instance __compare__ method (most valuable)
        if(obj && obj['__compare__']) return function(value) {
            return obj.__compare__(value);
        }

        // Check if we got an instance __equals__ method (most second most
        // valuable)
        else if(obj && obj['__equals__']) return function(value) {
            if(obj.__equals__(value)) return [value];
            throw NO_MATCH;
        }

        // Check if the instance constructor class has an __compare__ method.
        else if(obj && obj.constructor && obj.constructor['__compare__']) return function(value) {
            return obj.constructor.__compare__(obj, value);
        }

        // Check if the instance constructor class has an __equals__ method.
        else if(obj && obj.constructor && obj.constructor['__equals__']) return function(value) {
            var comp = obj.constructor.__equals__;
            if(comp(obj, value)) return [value];
            throw NO_MATCH;
        }

        // Check for native type's (Strings, Number and Regexp's)
        else if(is_prim_type(obj)) return function(value) {
            if(is_empty(value) || value.constructor !== obj) throw NO_MATCH;
            return [value];
        }

        // Check for null and undefined types
        else if(is_empty(obj)) return function(value) {
            if(obj !== value) throw NO_MATCH;
            return [value];
        }

        // Didnt match any of the special case resolvers. Find it in
        // the TYPE_RESOLVERS list instead.
        var type_name = TYPE_RE(obj.constructor.toString())[1];
        ctor = TYPE_RESOLVERS[type_name];
        if(!ctor) ctor = TYPE_RESOLVERS['Object'];
        return ctor(obj);
    }

    var TYPE_RESOLVERS = {

        // Function (class constructor) resolver.
        Function: function(ctor) {
            return function(value) {
                var c = value !== undefined ? value.constructor : undefined;
                if(c) {
                    if(c === ctor) return [value];
                    while((c = c.super_)) if(c === ctor) return [value];
                }
                throw NO_MATCH;
            }
        },

        // Array resolver
        Array: function(arr) {
            if(arr.length == 0) {
                return function(value) {
                    if(value.constructor != Array || value.length != 0)
                        throw NO_MATCH;
                }
            } else {
                var resolvers = []
                for(var i = 0; i < arr.length; i++){
                  resolvers[i] = get_resolver(arr[i]);
                }
                return function(value) {
                    var result = [];
                    if(!value || value.constructor != Array) throw NO_MATCH;
                    for(var count=0; count < resolvers.length; count++) {
                        result = result.concat(
                             resolvers[count](value[count])
                        );
                    }
                    return result;
                }
            }
        },

        // Boolean resolver
        Boolean: function(b) {
            return function(value) {
                if(b !== value) throw NO_MATCH;
                return [];
            }
        },

        // Regexp resolver
        RegExp: function(regexp) {
            return function(value) {
                if(!value || !regexp.test(value)) throw NO_MATCH;
                return [];
            }
        },

        // Number resolver
        Number: function(no) {
            return function(value) {
                if(no !== value) throw NO_MATCH;
                return [];
            }
        },

        // String resolver
        String: function(str) {
            return function(value) {
                if(str !== value) throw NO_MATCH;
                return [];
            }
        },

        Object: function(obj) {
            var resolvers = {},
                has_ops = false;
            for(var key in obj) {
                var resolver, akey = key, operator;
                if((operator = IS_FIELD_OP(key))) {
                    has_ops = true;
                    akey = key.substr(0, key.length - operator.length - 1);
                    resolver = get_op_resolver(operator, obj[key]);
                } else {
                    resolver = get_resolver(obj[key]);
                }
                resolvers[akey] = resolver;
            }
            if(has_ops) {
                return function(obj) {
                    if(obj === null || obj === undefined) throw NO_MATCH;
                    var result_a = [], result_b = [], match = null;
                    for(var key in resolvers) {
                        var resolver = resolvers[key];
                        if(resolver.is_op) {
                            match = resolver(obj[key])
                            result = result_b;
                        } else if(match === null) {
                            result_a = result_a.concat(resolver(obj[key]));
                        } else {
                            result_b = result_b.concat(resolver(obj[key]));
                        }
                    }
                    return match ? result_a.concat([obj]).concat(result_b) :
                                   result_a.concat(result_b);
                }
            } else {
                return function(obj) {
                    if(obj === null || obj === undefined) throw NO_MATCH;
                    var result = [];
                    for(var key in resolvers) {
                        var resolver = resolvers[key];
                        result = result.concat(resolver(obj[key]));
                    }
                    return result;
                }
            }
        }
    }

    var Result = function() {
        var args = Array.prototype.slice.call(arguments);
        var cases = [], default_case;
        while(args.length) {
            var left = args.shift()
            if(left.__matchtype__ == 'matcher') {
                // This is a filter-
                cases.unshift({ filter: left });
            } else if(left.constructor == Function && !args.length) {
                // The ´default´ case. This callback is called when no other
                // case is matching. This MUST be the last argument.
                default_case = left;
            } else {
                var right = args.shift();
                var resolver = get_resolver(left), callback;
                if(right.constructor == Array) {
                    // The right argument is an array. The first argument in the
                    // Array is the callback. The remaining arguments are the
                    // arguments to parse to the callback.
                    var fn = right.shift();
                    callback = function() { return fn.apply(null, right.concat(arguments)) };
                } else if(right.constructor == Function) {
                    callback = right;
                }
                cases.unshift({ resolver: resolver, callback: callback });
            }
        }

        // Matches against defined patterns. The first argument is the object
        // to match agaisnt. The second argument is optional and respresent the
        // value that is return if no pattern was matched.
        var Matcher = function(orig, nomatch_res) {
            var l = cases.length,
                errors = [],
                obj = orig,
                nomatch = nomatch_res || undefined; // undefined is default
            while(l-- > 0) {
                var c = cases[l]
                if(c.resolver) {
                    try {
                        var result = c.resolver(obj);
                    } catch(ex) {
                        if(ex == NO_MATCH) continue;
                        throw ex;
                    }
                    // We got a match! Concat the result array with the
                    // (filtered) object and the original object.
                    return c.callback.apply(this, result.concat([obj, orig]));
                } else if(c.filter){
                    // Run the object through the provided filter.
                    obj = c.filter(obj);
                }
            }

            // Check if a default case is defined.
            if(default_case) default_case.apply(this, [obj, orig]);

            // No pattern was matched. Return the default nomatch value.
            else return nomatch;
        };

        // Identify the new matcher as a Matcher
        Matcher.__matchtype__ = 'matcher';

        // Return the Matcher.
        return Matcher;
    }

    // A comparer that ignores a value in the pattern
    var pass = {
        __compare__: function(value) {
            return [];
        }
    }

    // A comparer that includes a value without matching.
    var incl = {
        __compare__: function(value) {
            return [value];
        }
    }

    // Export public members
    Result.TYPE_RESOLVERS = TYPE_RESOLVERS;
    Result.NO_MATCH = NO_MATCH;
    Result.get_resolver = get_resolver;
    Result.pass = pass;
    Result.incl = incl;

    return Result;
})();
try{ exports.Match = Match } catch(e) {}; // Support for node.js<commit_msg>Fixed small bug in the new op field matching system<commit_after>//
//  match-js
//  A simple yet powerful pattern matching library for Javascript.
//
//  Read readme.md for instructions and LICENSE license.
//
//  Copyright (c) 2010 Johan Dahlberg
//
var Match = (function() {
    var NO_MATCH = { __matchtype__: 'no-match', toString: function() { return 'no-match' }};
    var TYPE_RE = /function\s([A-Za-z_1-9$]+)/;
    var IS_FIELD_OP = /\s(\=|\!|\>|\<|\>\=|\<\=)$/;

    function is_prim_type(obj) {
        return obj == String || obj == Number || obj == Date || obj == Boolean
    }

    function is_empty(value) {
        return value == null || value == undefined;
    }

    function get_op_resolver(op, value_a) {
        var op_resolver = function() { throw NO_MATCH };
        switch(op) {
            case '=':
                op_resolver = function(value_b, parent, state) {
                    if(value_a == value_b) {
                        var result = state.matched ? [] : [parent];
                        state.matched = true;
                        return result;
                    }
                    throw NO_MATCH;
                }
                break;
            case '>':
                op_resolver = function(value_b, parent, state) {
                  if(value_a > value_b) {
                      var result = state.matched ? [] : [parent];
                      state.matched = true;
                      return result;
                  }
                  throw NO_MATCH;
                }
                break;
            case '<':
                op_resolver = function(value_b, parent, state) {
                    if(value_a < value_b) {
                        var result = state.matched ? [] : [parent];
                        state.matched = true;
                        return result;
                    }
                    throw NO_MATCH;
                }
                break;
            case '>=':
                op_resolver = function(value_b, parent, state) {
                    if(value_a >= value_b) {
                        var result = state.matched ? [] : [parent];
                        state.matched = true;
                        return result;
                    }
                    throw NO_MATCH;
                }
                break;
            case '<=':
                op_resolver = function(value_b, parent, state) {
                  if(value_a <= value_b) {
                      var result = state.matched ? [] : [parent];
                      state.matched = true;
                      return result;
                  }
                  throw NO_MATCH;
                }
                break;
            case '!':
                op_resolver = function(value_b, parent, state) {
                  if(value_a != value_b) {
                      var result = state.matched ? [] : [parent];
                      state.matched = true;
                      return result;
                  }
                  throw NO_MATCH;
                }
                break;
        }
        op_resolver.is_op = true;
        return op_resolver;
    }

    function get_resolver(obj) {
        var ctor;

        // Check if we got an instance __compare__ method (most valuable)
        if(obj && obj['__compare__']) return function(value) {
            return obj.__compare__(value);
        }

        // Check if we got an instance __equals__ method (most second most
        // valuable)
        else if(obj && obj['__equals__']) return function(value) {
            if(obj.__equals__(value)) return [value];
            throw NO_MATCH;
        }

        // Check if the instance constructor class has an __compare__ method.
        else if(obj && obj.constructor && obj.constructor['__compare__']) return function(value) {
            return obj.constructor.__compare__(obj, value);
        }

        // Check if the instance constructor class has an __equals__ method.
        else if(obj && obj.constructor && obj.constructor['__equals__']) return function(value) {
            var comp = obj.constructor.__equals__;
            if(comp(obj, value)) return [value];
            throw NO_MATCH;
        }

        // Check for native type's (Strings, Number and Regexp's)
        else if(is_prim_type(obj)) return function(value) {
            if(is_empty(value) || value.constructor !== obj) throw NO_MATCH;
            return [value];
        }

        // Check for null and undefined types
        else if(is_empty(obj)) return function(value) {
            if(obj !== value) throw NO_MATCH;
            return [value];
        }

        // Didnt match any of the special case resolvers. Find it in
        // the TYPE_RESOLVERS list instead.
        var type_name = TYPE_RE(obj.constructor.toString())[1];
        ctor = TYPE_RESOLVERS[type_name];
        if(!ctor) ctor = TYPE_RESOLVERS['Object'];
        return ctor(obj);
    }

    var TYPE_RESOLVERS = {

        // Function (class constructor) resolver.
        Function: function(ctor) {
            return function(value) {
                var c = value !== undefined ? value.constructor : undefined;
                if(c) {
                    if(c === ctor) return [value];
                    while((c = c.super_)) if(c === ctor) return [value];
                }
                throw NO_MATCH;
            }
        },

        // Array resolver
        Array: function(arr) {
            if(arr.length == 0) {
                return function(value) {
                    if(value.constructor != Array || value.length != 0)
                        throw NO_MATCH;
                }
            } else {
                var resolvers = []
                for(var i = 0; i < arr.length; i++){
                  resolvers[i] = get_resolver(arr[i]);
                }
                return function(value) {
                    var result = [];
                    if(!value || value.constructor != Array) throw NO_MATCH;
                    for(var count=0; count < resolvers.length; count++) {
                        result = result.concat(
                             resolvers[count](value[count])
                        );
                    }
                    return result;
                }
            }
        },

        // Boolean resolver
        Boolean: function(b) {
            return function(value) {
                if(b !== value) throw NO_MATCH;
                return [];
            }
        },

        // Regexp resolver
        RegExp: function(regexp) {
            return function(value) {
                if(!value || !regexp.test(value)) throw NO_MATCH;
                return [];
            }
        },

        // Number resolver
        Number: function(no) {
            return function(value) {
                if(no !== value) throw NO_MATCH;
                return [];
            }
        },

        // String resolver
        String: function(str) {
            return function(value) {
                if(str !== value) throw NO_MATCH;
                return [];
            }
        },

        Object: function(obj) {
            var resolvers = {};
            for(var key in obj) {
                var resolver, akey = key, op;
                if((op = IS_FIELD_OP(key)[1])) {
                    akey = key.substr(0, key.length - op.length - 1);
                    resolver = get_op_resolver(op, obj[key]);
                } else {
                    resolver = get_resolver(obj[key]);
                }
                resolvers[akey] = resolver;
            }
            return function(value) {
                if(value === null || value === undefined) throw NO_MATCH;
                var result = [], state = {};
                for(var key in resolvers) {
                    var resolver = resolvers[key];
                    result = result.concat(resolver(value[key], value, state));
                }
                return result;
            }
        }
    }

    var Result = function() {
        var args = Array.prototype.slice.call(arguments);
        var cases = [], default_case;
        while(args.length) {
            var left = args.shift()
            if(left.__matchtype__ == 'matcher') {
                // This is a filter-
                cases.unshift({ filter: left });
            } else if(left.constructor == Function && !args.length) {
                // The ´default´ case. This callback is called when no other
                // case is matching. This MUST be the last argument.
                default_case = left;
            } else {
                var right = args.shift();
                var resolver = get_resolver(left), callback;
                if(right.constructor == Array) {
                    // The right argument is an array. The first argument in the
                    // Array is the callback. The remaining arguments are the
                    // arguments to parse to the callback.
                    var fn = right.shift();
                    callback = function() { return fn.apply(null, right.concat(arguments)) };
                } else if(right.constructor == Function) {
                    callback = right;
                }
                cases.unshift({ resolver: resolver, callback: callback });
            }
        }

        // Matches against defined patterns. The first argument is the object
        // to match agaisnt. The second argument is optional and respresent the
        // value that is return if no pattern was matched.
        var Matcher = function(orig, nomatch_res) {
            var l = cases.length,
                errors = [],
                obj = orig,
                nomatch = nomatch_res || undefined; // undefined is default
            while(l-- > 0) {
                var c = cases[l]
                if(c.resolver) {
                    try {
                        var result = c.resolver(obj);
                    } catch(ex) {
                        if(ex == NO_MATCH) continue;
                        throw ex;
                    }
                    // We got a match! Concat the result array with the
                    // (filtered) object and the original object.
                    return c.callback.apply(this, result.concat([obj, orig]));
                } else if(c.filter){
                    // Run the object through the provided filter.
                    obj = c.filter(obj);
                }
            }

            // Check if a default case is defined.
            if(default_case) default_case.apply(this, [obj, orig]);

            // No pattern was matched. Return the default nomatch value.
            else return nomatch;
        };

        // Identify the new matcher as a Matcher
        Matcher.__matchtype__ = 'matcher';

        // Return the Matcher.
        return Matcher;
    }

    // A comparer that ignores a value in the pattern
    var pass = {
        __compare__: function(value) {
            return [];
        }
    }

    // A comparer that includes a value without matching.
    var incl = {
        __compare__: function(value) {
            return [value];
        }
    }

    // Export public members
    Result.TYPE_RESOLVERS = TYPE_RESOLVERS;
    Result.NO_MATCH = NO_MATCH;
    Result.get_resolver = get_resolver;
    Result.pass = pass;
    Result.incl = incl;

    return Result;
})();
try{ exports.Match = Match } catch(e) {}; // Support for node.js<|endoftext|>


<commit_before>module.exports = {
    "מיידי": {
        seconds: 0,
        time: "מיידי",
        time_en: "Immediately"
    },
    "דקה": {
        seconds: 60,
        time: "דקה",
        time_en: "A minute"
    },
    "דקה וחצי": {
        seconds: 90,
        time: "דקה וחצי",
        time_en: "A minute and a half"
    },
    "30 שניות": {
        seconds: 90,
        time: "30 שניות",
        time_en: "30 seconds"
    },
    "15 שניות": {
        seconds: 15,
        time: "15 שניות",
        time_en: "15 seconds"
    },
    "45 שניות": {
        seconds: 45,
        time: "45 שניות",
        time_en: "45 seconds"
    },
    "3 דקות": {
        seconds: 180,
        time: "3 דקות",
        time_en: "3 minutes"
    },
    // Yeah, Pikud Haoref returns this string when requesting shelter instructions in Hebrew... :-P
    "One minute": {
        seconds: 60,
        time: "דקה",
        time_en: "1 minute"
    }
};<commit_msg>Rename countdown property<commit_after>module.exports = {
    "מיידי": {
        countdown: 0,
        time: "מיידי",
        time_en: "Immediately"
    },
    "דקה": {
        countdown: 60,
        time: "דקה",
        time_en: "A minute"
    },
    "דקה וחצי": {
        countdown: 90,
        time: "דקה וחצי",
        time_en: "A minute and a half"
    },
    "30 שניות": {
        countdown: 90,
        time: "30 שניות",
        time_en: "30 seconds"
    },
    "15 שניות": {
        countdown: 15,
        time: "15 שניות",
        time_en: "15 seconds"
    },
    "45 שניות": {
        countdown: 45,
        time: "45 שניות",
        time_en: "45 seconds"
    },
    "3 דקות": {
        countdown: 180,
        time: "3 דקות",
        time_en: "3 minutes"
    },
    // Yeah, Pikud Haoref returns this string when requesting shelter instructions in Hebrew... :-P
    "One minute": {
        countdown: 60,
        time: "דקה",
        time_en: "1 minute"
    }
};<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const path = require("path");
const crypto = require("crypto");
const RequestShortener = require("./RequestShortener");
const ConcatSource = require("webpack-sources").ConcatSource;
const RawSource = require("webpack-sources").RawSource;
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");

const basename = (name) => {
	if(name.indexOf("/") < 0) return name;
	return name.substr(name.lastIndexOf("/") + 1);
};

class SourceMapDevToolPlugin {
	constructor(options) {
		if(arguments.length > 1)
			throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)");
		// TODO: remove in webpack 3
		if(typeof options === "string") {
			options = {
				sourceMapFilename: options
			};
		}
		if(!options) options = {};
		this.sourceMapFilename = options.filename;
		this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]";
		this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resourcePath]";
		this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack:///[resourcePath]?[hash]";
		this.options = options;
	}

	apply(compiler) {
		const sourceMapFilename = this.sourceMapFilename;
		const sourceMappingURLComment = this.sourceMappingURLComment;
		const moduleFilenameTemplate = this.moduleFilenameTemplate;
		const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
		const requestShortener = new RequestShortener(compiler.context);
		const options = this.options;
		options.test = options.test || /\.(js|css)($|\?)/i;
		compiler.plugin("compilation", compilation => {
			new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
			compilation.plugin("after-optimize-chunk-assets", function(chunks) {
				const moduleToSourceNameMapping = new Map();
				const tasks = [];
				chunks.forEach(function(chunk) {
					chunk.files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)).map(function(file) {
						const asset = compilation.assets[file];
						if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) {
							const data = asset.__SourceMapDevToolData;
							for(const cachedFile in data) {
								compilation.assets[cachedFile] = data[cachedFile];
								if(cachedFile !== file)
									chunk.files.push(cachedFile);
							}
							return;
						}
						let source, sourceMap;
						if(asset.sourceAndMap) {
							const sourceAndMap = asset.sourceAndMap(options);
							sourceMap = sourceAndMap.map;
							source = sourceAndMap.source;
						} else {
							sourceMap = asset.map(options);
							source = asset.source();
						}
						if(sourceMap) {
							return {
								chunk,
								file,
								asset,
								source,
								sourceMap
							};
						}
					}).filter(Boolean).map(task => {
						const modules = task.sourceMap.sources.map(source => {
							const module = compilation.findModule(source);
							return module || source;
						});
						for(const module of modules) {
							if(!moduleToSourceNameMapping.get(module)) {
								moduleToSourceNameMapping.set(module, ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener));
							}
						}
						task.modules = modules;
						return task;
					}).forEach(task => {
						tasks.push(task);
					});
				});
				const usedNamesSet = new Set(moduleToSourceNameMapping.values());
				const conflictDetectionSet = new Set();

				// all modules in defined order (longest identifier first)
				const allModules = Array.from(moduleToSourceNameMapping.keys()).sort((a, b) => {
					const ai = typeof a === "string" ? a : a.identifier();
					const bi = typeof b === "string" ? b : b.identifier();
					return ai.length - bi.length;
				});

				// find modules with conflicting source names
				for(const module of allModules) {
					let sourceName = moduleToSourceNameMapping.get(module);
					let hasName = conflictDetectionSet.has(sourceName);
					if(!hasName) {
						conflictDetectionSet.add(sourceName);
						continue;
					}

					// try the fallback name first
					sourceName = ModuleFilenameHelpers.createFilename(module, fallbackModuleFilenameTemplate, requestShortener);
					hasName = usedNamesSet.has(sourceName);
					if(!hasName) {
						moduleToSourceNameMapping.set(module, sourceName);
						usedNamesSet.add(sourceName);
						continue;
					}

					// elsewise just append stars until we have a valid name
					while(hasName) {
						sourceName += "*";
						hasName = usedNamesSet.has(sourceName);
					}
					moduleToSourceNameMapping.set(module, sourceName);
					usedNamesSet.add(sourceName);
				}
				tasks.forEach(function(task) {
					const chunk = task.chunk;
					const file = task.file;
					const asset = task.asset;
					const sourceMap = task.sourceMap;
					const source = task.source;
					const modules = task.modules;
					const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m));
					sourceMap.sources = moduleFilenames;
					if(sourceMap.sourcesContent && !options.noSources) {
						sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}`);
					} else {
						sourceMap.sourcesContent = undefined;
					}
					sourceMap.sourceRoot = options.sourceRoot || "";
					sourceMap.file = file;
					asset.__SourceMapDevToolFile = file;
					asset.__SourceMapDevToolData = {};
					let currentSourceMappingURLComment = sourceMappingURLComment;
					if(currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file)) {
						currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/");
					}
					const sourceMapString = JSON.stringify(sourceMap);
					if(sourceMapFilename) {
						let filename = file;
						let query = "";
						const idx = filename.indexOf("?");
						if(idx >= 0) {
							query = filename.substr(idx);
							filename = filename.substr(0, idx);
						}
						let sourceMapFile = compilation.getPath(sourceMapFilename, {
							chunk,
							filename,
							query,
							basename: basename(filename)
						});
						if(sourceMapFile.indexOf("[contenthash]") !== -1) {
							sourceMapFile = sourceMapFile.replace(/\[contenthash\]/g, crypto.createHash("md5").update(sourceMapString).digest("hex"));
						}
						const sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
						if(currentSourceMappingURLComment !== false) {
							asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
						}
						asset.__SourceMapDevToolData[sourceMapFile] = compilation.assets[sourceMapFile] = new RawSource(sourceMapString);
						chunk.files.push(sourceMapFile);
					} else {
						asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment
							.replace(/\[map\]/g, () => sourceMapString)
							.replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${new Buffer(sourceMapString, "utf-8").toString("base64")}`) // eslint-disable-line
						);
					}
				});
			});
		});
	}
}

module.exports = SourceMapDevToolPlugin;
<commit_msg>refactor: collapse several array iterators into single reduce<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const path = require("path");
const crypto = require("crypto");
const RequestShortener = require("./RequestShortener");
const ConcatSource = require("webpack-sources").ConcatSource;
const RawSource = require("webpack-sources").RawSource;
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");

const basename = (name) => {
	if(name.indexOf("/") < 0) return name;
	return name.substr(name.lastIndexOf("/") + 1);
};

function getTaskForFile(file, chunk, options, compilation) {
	const asset = compilation.assets[file];
	if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) {
		const data = asset.__SourceMapDevToolData;
		for(const cachedFile in data) {
			compilation.assets[cachedFile] = data[cachedFile];
			if(cachedFile !== file)
				chunk.files.push(cachedFile);
		}
		return;
	}
	let source, sourceMap;
	if(asset.sourceAndMap) {
		const sourceAndMap = asset.sourceAndMap(options);
		sourceMap = sourceAndMap.map;
		source = sourceAndMap.source;
	} else {
		sourceMap = asset.map(options);
		source = asset.source();
	}
	if(sourceMap) {
		return {
			chunk,
			file,
			asset,
			source,
			sourceMap
		};
	}
}

class SourceMapDevToolPlugin {
	constructor(options) {
		if(arguments.length > 1)
			throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)");
		// TODO: remove in webpack 3
		if(typeof options === "string") {
			options = {
				sourceMapFilename: options
			};
		}
		if(!options) options = {};
		this.sourceMapFilename = options.filename;
		this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]";
		this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resourcePath]";
		this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack:///[resourcePath]?[hash]";
		this.options = options;
	}

	apply(compiler) {
		const sourceMapFilename = this.sourceMapFilename;
		const sourceMappingURLComment = this.sourceMappingURLComment;
		const moduleFilenameTemplate = this.moduleFilenameTemplate;
		const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
		const requestShortener = new RequestShortener(compiler.context);
		const options = this.options;
		options.test = options.test || /\.(js|css)($|\?)/i;

		const matchObject = ModuleFilenameHelpers.matchObject.bind(undefined, options);

		compiler.plugin("compilation", compilation => {
			new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);

			compilation.plugin("after-optimize-chunk-assets", function(chunks) {
				const moduleToSourceNameMapping = new Map();
				let tasks = [];

				chunks.forEach(function(chunk) {
					tasks = chunk.files.reduce((queue, file) => {
						if(matchObject(file)) {
							const task = getTaskForFile(file, chunk, options, compilation);

							if(task) {
								const modules = task.sourceMap.sources.map(source => {
									const module = compilation.findModule(source);
									return module || source;
								});

								for(const module of modules) {
									if(!moduleToSourceNameMapping.get(module)) {
										moduleToSourceNameMapping.set(module, ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener));
									}
								}

								task.modules = modules;

								queue.push(task);
							}
						}

						return queue;
					}, tasks);
				});

				const usedNamesSet = new Set(moduleToSourceNameMapping.values());
				const conflictDetectionSet = new Set();

				// all modules in defined order (longest identifier first)
				const allModules = Array.from(moduleToSourceNameMapping.keys()).sort((a, b) => {
					const ai = typeof a === "string" ? a : a.identifier();
					const bi = typeof b === "string" ? b : b.identifier();
					return ai.length - bi.length;
				});

				// find modules with conflicting source names
				for(const module of allModules) {
					let sourceName = moduleToSourceNameMapping.get(module);
					let hasName = conflictDetectionSet.has(sourceName);
					if(!hasName) {
						conflictDetectionSet.add(sourceName);
						continue;
					}

					// try the fallback name first
					sourceName = ModuleFilenameHelpers.createFilename(module, fallbackModuleFilenameTemplate, requestShortener);
					hasName = usedNamesSet.has(sourceName);
					if(!hasName) {
						moduleToSourceNameMapping.set(module, sourceName);
						usedNamesSet.add(sourceName);
						continue;
					}

					// elsewise just append stars until we have a valid name
					while(hasName) {
						sourceName += "*";
						hasName = usedNamesSet.has(sourceName);
					}
					moduleToSourceNameMapping.set(module, sourceName);
					usedNamesSet.add(sourceName);
				}
				tasks.forEach(function(task) {
					const chunk = task.chunk;
					const file = task.file;
					const asset = task.asset;
					const sourceMap = task.sourceMap;
					const source = task.source;
					const modules = task.modules;
					const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m));
					sourceMap.sources = moduleFilenames;
					if(sourceMap.sourcesContent && !options.noSources) {
						sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}`);
					} else {
						sourceMap.sourcesContent = undefined;
					}
					sourceMap.sourceRoot = options.sourceRoot || "";
					sourceMap.file = file;
					asset.__SourceMapDevToolFile = file;
					asset.__SourceMapDevToolData = {};
					let currentSourceMappingURLComment = sourceMappingURLComment;
					if(currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file)) {
						currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/");
					}
					const sourceMapString = JSON.stringify(sourceMap);
					if(sourceMapFilename) {
						let filename = file;
						let query = "";
						const idx = filename.indexOf("?");
						if(idx >= 0) {
							query = filename.substr(idx);
							filename = filename.substr(0, idx);
						}
						let sourceMapFile = compilation.getPath(sourceMapFilename, {
							chunk,
							filename,
							query,
							basename: basename(filename)
						});
						if(sourceMapFile.indexOf("[contenthash]") !== -1) {
							sourceMapFile = sourceMapFile.replace(/\[contenthash\]/g, crypto.createHash("md5").update(sourceMapString).digest("hex"));
						}
						const sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
						if(currentSourceMappingURLComment !== false) {
							asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
						}
						asset.__SourceMapDevToolData[sourceMapFile] = compilation.assets[sourceMapFile] = new RawSource(sourceMapString);
						chunk.files.push(sourceMapFile);
					} else {
						asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment
							.replace(/\[map\]/g, () => sourceMapString)
							.replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${new Buffer(sourceMapString, "utf-8").toString("base64")}`) // eslint-disable-line
						);
					}
				});
			});
		});
	}
}

module.exports = SourceMapDevToolPlugin;
<|endoftext|>


<commit_before>/*---------------------
	:: <%- entity %>
	-> model
---------------------*/
var <%- entity %> = {

	// Attributes / Schema
	attributes	: {

		// Simple attribute:
		// name: 'STRING',

		// Or for more flexibility:
		// phoneNumber: {
		//	type: 'STRING',
		//	defaultValue: '555-555-5555'
		// }
	}

};
module.exports = <%- entity %>;<commit_msg>Removed local var from model blueprint.<commit_after>/*---------------------
	:: <%- entity %>
	-> model
---------------------*/
module.exports = {

	// Attributes / Schema
	attributes	: {

		// Simple attribute:
		// name: 'STRING',

		// Or for more flexibility:
		// phoneNumber: {
		//	type: 'STRING',
		//	defaultValue: '555-555-5555'
		// }
	}

};<|endoftext|>


<commit_before>(function ( mw, $ ) {
	"use strict";
	mw.dualScreenControlBar = function (settings){
		this.$controlBar = null;
		this.embedPlayer = settings.embedPlayer;
		this.templatePath = settings.templatePath;
		this.menuFadeout = settings.menuFadeout;
		this.cssClass = settings.cssClass;
		this.controlBarComponents = {
			sideBySide: {
				id: 'sideBySide',
				title: 'Side By Side',
				event: "SbS"
			},
			singleView: {
				id: 'singleView',
				title: 'Single View',
				event: "hide"
			},
			pip: {
				id: 'pip',
				title: 'Picture In Picture',
				event: "PiP"
			},
			switchView: {
				id: 'switchView',
				title: 'Toggle Main View',
				event: "switchView"
			}
		};
		this.disabled = false;
		this.getComponent();
		this.addBindings();
	};

	mw.dualScreenControlBar.prototype = {
		bind: function(name, handler){
			this.embedPlayer.bindHelper(name, handler);
		},
		getComponent: function ( ) {
			if ( !this.$controlBar ) {
				var rawHTML = window.kalturaIframePackageData.templates[ this.templatePath ];
				var transformedHTML = mw.util.tmpl( rawHTML );
				transformedHTML = transformedHTML({buttons: this.controlBarComponents});
				this.$controlBar = $( '
' )
					.addClass( 'controlBar componentOff' + this.cssClass )
					.append(transformedHTML);
				this.embedPlayer.getInterface().append( this.$controlBar );
				//If top bar exist then position controlBar under it
				if (this.embedPlayer.getTopBarContainer().length) {
					var height = this.embedPlayer.getTopBarContainer().height();
					this.$controlBar.css("top", height + "px");
				}
				if (mw.isNativeApp()){
					this.$controlBar.find("#" + this.controlBarComponents.sideBySide.id ).remove();
				}
			}
			return this.$controlBar;
		},

		addBindings: function () {
			//Set control bar visiblity handlers
			var _this = this;
			this.embedPlayer.getInterface()
				.on( 'mousemove touchstart', function(){
					_this.show();
				})
				.on( 'mouseleave', function(){
					if (!mw.isMobileDevice()){
						_this.hide();
					}
				});

			this.bind("dualScreenControlsHide", function(){
				_this.hide();
			});
			this.bind("dualScreenControlsShow", function(){
				_this.show();
			});
			this.bind("dualScreenControlsDisable", function(){
				_this.disable();
			});
			this.bind("dualScreenControlsEnable", function(){
				_this.enable();
			});

			//add drop shadow containers for control bar
			this.embedPlayer.getVideoHolder()
				.prepend($("

")
					.addClass('componentOff')
					.on("click mouseover mousemove mouseout touchstart touchend", function(e){
						_this.embedPlayer.triggerHelper(e);
					})
			);

			//Cache buttons
			var buttons = _this.getComponent().find( "span" );
			//Attach control bar action handlers
			_this.getComponent()
				.on( 'click touchstart', 'li > span', function (e) {
					e.stopPropagation();
					e.preventDefault();
					var btn = _this.controlBarComponents[this.id];
					var obj = $(this);
					//Change state button disabled state
					if (obj.data("type") === "state") {
						buttons.removeClass( "disabled" );
						obj.addClass( "disabled" );
					}
					if (btn && btn.event){
						_this.embedPlayer.triggerHelper("dualScreenStateChange", btn.event);
					}
					return false;
				} );

			//Set tooltips
			var buttons = this.getComponent().find('li > span' );
			buttons.attr('data-show-tooltip', true);
			this.embedPlayer.layoutBuilder.setupTooltip(buttons, "arrowTop");
		},
		disable: function () {
			clearTimeout(this.getComponent().handleTouchTimeoutId);
			this.disabled = true;
		},
		enable: function () {
			this.disabled = false;
		},
		hide: function ( ) {
			if ( !this.disabled ) {
				this.embedPlayer.triggerHelper( 'clearTooltip' );
				if ( this.isVisible ) {
					this.getComponent().addClass( 'componentOff componentAnimation' ).removeClass( 'componentOn' );
					this.embedPlayer.getVideoHolder().find( ".controlBarShadow" ).addClass( 'componentOff componentAnimation' ).removeClass( 'componentOn' );
					this.isVisible = false;
				}
			}
		},
		show: function ( ) {
			if ( !this.disabled) {
				if ( !this.isVisible ) {
					this.getComponent().removeClass( 'componentAnimation' ).addClass( 'componentOn' ).removeClass( 'componentOff' );
					this.isVisible = true;
					this.embedPlayer.getVideoHolder().find( ".controlBarShadow" ).removeClass( 'componentAnimation' ).addClass( 'componentOn' ).removeClass( 'componentOff' );
				}

				var _this = this;
				if ( this.getComponent().handleTouchTimeoutId ) {
					clearTimeout( this.getComponent().handleTouchTimeoutId );
				}
				this.getComponent().handleTouchTimeoutId = setTimeout( function () {
					_this.hide();
				}, this.menuFadeout );
			}
		}
	};
})( window.mw, window.jQuery );

/*
*
*
*
*
*
 //Control Bar
 getControlBar: function ( ) {
 if ( !this.$controlBar ) {
 this.$controlBar = $( '
' )
 .addClass( 'controlBar componentOff' + this.getCssClass() )
 .append(
 $( '
 ' ).append(
 this.getTemplateHTML( )
 )
 );
 this.getPlayer().getInterface().append( this.$controlBar );
 this.setControlBarWidth();
 }
 return this.$controlBar;
 },
 setControlBarWidth: function(){
 var width = 0;
 this.getControlBar().find("#displayControlBar").each(function() {
 width += $(this).outerWidth( true );
 });
 this.getControlBar().
 css({'width': width + 10});
 },
 positionControlBar: function (  ) {
 var height = 0;
 if (this.getPlayer().getTopBarContainer().length) {
 height = this.getPlayer().getTopBarContainer().height();
 }
 this.getControlBar().position( {
 my: 'right top+'+height,
 at: 'right top',
 of: this.getPlayer().getInterface(),
 collision: 'none'
 } );
 },
 setControlBarBindings: function () {
 //Set control bar visiblity handlers
 var _this = this;
 this.getPlayer().getInterface()
 .on( 'mousemove touchstart', function(e){_this.showControlBar( )} )
 .on( 'mouseleave', function(e){if (!mw.isMobileDevice()){_this.hideControlBar( )} } );

 //add drop shadow containers for control bar
 this.getPlayer().getInterface().find(".mwEmbedPlayer").prepend($("

").addClass('componentOff'));
 this.getComponent().prepend($("

").addClass('componentOff'));
 //Attach control bar action handlers
 $.each( _this.controlBarComponents, function ( name, component ) {
 _this.getControlBar()
 .on( 'click', 'li > span#' + component.id, function () {
 var event = null;
 switch ( component.id ) {
 case 'sideBySide':
 event = "SbS";
 break;
 case 'switchView':
 event = "switchView";
 break;
 case 'singleView':
 event = 'hide';
 break;
 case 'pip':
 event = 'PiP';
 break;
 }
 if ( event != null ) {
 _this.fsm.consumeEvent( event );
 }
 } )
 .find('li > span#' + component.id)
 .attr('title', component.title)
 .attr('data-show-tooltip', true);
 } );

 this.bind("showPlayerControls" , function(){
 _this.showControlBar();
 });
 },
 disable: function () {
 clearTimeout(this.getControlBar().handleTouchTimeoutId);
 this.monitorControlBarDisabled = false;
 this.hideControlBar( );
 this.monitorControlBarDisabled = true;
 },
 enable: function () {
 this.monitorControlBarDisabled = false;
 this.showControlBar( );
 },
 hideControlBar: function ( ) {
 if ( this.monitorControlBarDisabled ) {
 return;
 }
 if ( this.getControlBar().isVisible ) {
 this.getControlBar().addClass('componentOff componentAnimation' ).removeClass('componentOn');
 this.getFirstMonitor().obj.find(".controlBarShadow" ).addClass('componentOff componentAnimation' ).removeClass('componentOn');
 this.getControlBar().isVisible = false;
 }
 },
 showControlBar: function ( ) {
 if ( this.monitorControlBarDisabled || this.ignoreNextMouseEvent) {
 this.ignoreNextMouseEvent = false;
 return;
 }
 if ( !this.getControlBar().isVisible ) {
 this.getControlBar().removeClass('componentAnimation').addClass('componentOn' ).removeClass('componentOff');
 this.positionControlBar();
 this.getControlBar().isVisible = true;
 this.getFirstMonitor().obj.find(".controlBarShadow" ).removeClass('componentAnimation').addClass('componentOn' ).removeClass('componentOff');
 }

 var _this = this;
 if (this.getControlBar().handleTouchTimeoutId){
 clearTimeout(this.getControlBar().handleTouchTimeoutId);
 }
 this.getControlBar().handleTouchTimeoutId = setTimeout( function () {
 _this.ignoreNextMouseEvent = true;
 _this.hideControlBar( );
 }, this.getConfig('menuFadeout') );

 },

 *
*
* */
<commit_msg>Controls state handling for native app<commit_after>(function ( mw, $ ) {
	"use strict";
	mw.dualScreenControlBar = function (settings){
		this.$controlBar = null;
		this.embedPlayer = settings.embedPlayer;
		this.templatePath = settings.templatePath;
		this.menuFadeout = settings.menuFadeout;
		this.cssClass = settings.cssClass;
		this.controlBarComponents = {
			sideBySide: {
				id: 'sideBySide',
				title: 'Side By Side',
				event: "SbS"
			},
			singleView: {
				id: 'singleView',
				title: 'Single View',
				event: "hide"
			},
			pip: {
				id: 'pip',
				title: 'Picture In Picture',
				event: "PiP"
			},
			switchView: {
				id: 'switchView',
				title: 'Toggle View',
				event: "switchView"
			}
		};
		this.disabled = false;
		this.getComponent();
		this.addBindings();
	};

	mw.dualScreenControlBar.prototype = {
		bind: function(name, handler){
			this.embedPlayer.bindHelper(name, handler);
		},
		getComponent: function ( ) {
			if ( !this.$controlBar ) {
				var rawHTML = window.kalturaIframePackageData.templates[ this.templatePath ];
				var transformedHTML = mw.util.tmpl( rawHTML );
				transformedHTML = transformedHTML({buttons: this.controlBarComponents});
				this.$controlBar = $( '
' )
					.addClass( 'controlBar componentOff' + this.cssClass )
					.append(transformedHTML);
				this.embedPlayer.getInterface().append( this.$controlBar );
				//If top bar exist then position controlBar under it
				if (this.embedPlayer.getTopBarContainer().length) {
					var height = this.embedPlayer.getTopBarContainer().height();
					this.$controlBar.css("top", height + "px");
				}
				if (mw.isNativeApp()){
					this.$controlBar.find("#" + this.controlBarComponents.sideBySide.id ).remove();
				}
			}
			return this.$controlBar;
		},

		addBindings: function () {
			//Set control bar visiblity handlers
			var _this = this;
			this.embedPlayer.getInterface()
				.on( 'mousemove touchstart', function(){
					_this.show();
				})
				.on( 'mouseleave', function(){
					if (!mw.isMobileDevice()){
						_this.hide();
					}
				});

			this.bind("dualScreenControlsHide", function(){
				_this.hide();
			});
			this.bind("dualScreenControlsShow", function(){
				_this.show();
			});
			this.bind("dualScreenControlsDisable", function(){
				_this.disable();
			});
			this.bind("dualScreenControlsEnable", function(){
				_this.enable();
			});

			//add drop shadow containers for control bar
			this.embedPlayer.getVideoHolder()
				.prepend($("

")
					.addClass('componentOff')
					.on("click mouseover mousemove mouseout touchstart touchend", function(e){
						_this.embedPlayer.triggerHelper(e);
					})
			);

			//Cache buttons
			var buttons = _this.getComponent().find( "span" );
			var switchBtn = buttons.filter('[data-type="switch"]');
			//Attach control bar action handlers
			_this.getComponent()
				.on( 'click touchstart', 'li > span', function (e) {
					e.stopPropagation();
					e.preventDefault();
					var btn = _this.controlBarComponents[this.id];
					var obj = $(this);
					//Change state button disabled state
					if (obj.data("type") === "state") {
						buttons.removeClass( "disabled" );
						obj.addClass( "disabled" );
					}
					if (mw.isNativeApp()){
						if (this.id === _this.controlBarComponents.pip.id){
							switchBtn
								.addClass("disabled")
								.tooltip( "option", "content", nativeAppTooltip);
						} else if(this.id === _this.controlBarComponents.singleView.id){
							switchBtn.tooltip( "option", "content", _this.controlBarComponents.switchView.title);
						}
					}
					if (btn && btn.event){
						_this.embedPlayer.triggerHelper("dualScreenStateChange", btn.event);
					}
					return false;
				} );

			if (mw.isNativeApp()){
				var nativeAppTooltip = "Switching content
on current view
is not yet
supported.

Try single view";
				switchBtn.addClass("disabled" )
					.attr("title", nativeAppTooltip );
			}

			//Set tooltips
			buttons.attr('data-show-tooltip', true);
			this.embedPlayer.layoutBuilder.setupTooltip(buttons, "arrowTop");
		},
		disable: function () {
			clearTimeout(this.getComponent().handleTouchTimeoutId);
			this.disabled = true;
		},
		enable: function () {
			this.disabled = false;
		},
		hide: function ( ) {
			if ( !this.disabled ) {
				this.embedPlayer.triggerHelper( 'clearTooltip' );
				if ( this.isVisible ) {
					this.getComponent().addClass( 'componentOff componentAnimation' ).removeClass( 'componentOn' );
					this.embedPlayer.getVideoHolder().find( ".controlBarShadow" ).addClass( 'componentOff componentAnimation' ).removeClass( 'componentOn' );
					this.isVisible = false;
				}
			}
		},
		show: function ( ) {
			if ( !this.disabled) {
				if ( !this.isVisible ) {
					this.getComponent().removeClass( 'componentAnimation' ).addClass( 'componentOn' ).removeClass( 'componentOff' );
					this.isVisible = true;
					this.embedPlayer.getVideoHolder().find( ".controlBarShadow" ).removeClass( 'componentAnimation' ).addClass( 'componentOn' ).removeClass( 'componentOff' );
				}

				var _this = this;
				if ( this.getComponent().handleTouchTimeoutId ) {
					clearTimeout( this.getComponent().handleTouchTimeoutId );
				}
				this.getComponent().handleTouchTimeoutId = setTimeout( function () {
					_this.hide();
				}, this.menuFadeout );
			}
		}
	};
})( window.mw, window.jQuery );

/*
*
*
*
*
*
 //Control Bar
 getControlBar: function ( ) {
 if ( !this.$controlBar ) {
 this.$controlBar = $( '
' )
 .addClass( 'controlBar componentOff' + this.getCssClass() )
 .append(
 $( '
 ' ).append(
 this.getTemplateHTML( )
 )
 );
 this.getPlayer().getInterface().append( this.$controlBar );
 this.setControlBarWidth();
 }
 return this.$controlBar;
 },
 setControlBarWidth: function(){
 var width = 0;
 this.getControlBar().find("#displayControlBar").each(function() {
 width += $(this).outerWidth( true );
 });
 this.getControlBar().
 css({'width': width + 10});
 },
 positionControlBar: function (  ) {
 var height = 0;
 if (this.getPlayer().getTopBarContainer().length) {
 height = this.getPlayer().getTopBarContainer().height();
 }
 this.getControlBar().position( {
 my: 'right top+'+height,
 at: 'right top',
 of: this.getPlayer().getInterface(),
 collision: 'none'
 } );
 },
 setControlBarBindings: function () {
 //Set control bar visiblity handlers
 var _this = this;
 this.getPlayer().getInterface()
 .on( 'mousemove touchstart', function(e){_this.showControlBar( )} )
 .on( 'mouseleave', function(e){if (!mw.isMobileDevice()){_this.hideControlBar( )} } );

 //add drop shadow containers for control bar
 this.getPlayer().getInterface().find(".mwEmbedPlayer").prepend($("

").addClass('componentOff'));
 this.getComponent().prepend($("

").addClass('componentOff'));
 //Attach control bar action handlers
 $.each( _this.controlBarComponents, function ( name, component ) {
 _this.getControlBar()
 .on( 'click', 'li > span#' + component.id, function () {
 var event = null;
 switch ( component.id ) {
 case 'sideBySide':
 event = "SbS";
 break;
 case 'switchView':
 event = "switchView";
 break;
 case 'singleView':
 event = 'hide';
 break;
 case 'pip':
 event = 'PiP';
 break;
 }
 if ( event != null ) {
 _this.fsm.consumeEvent( event );
 }
 } )
 .find('li > span#' + component.id)
 .attr('title', component.title)
 .attr('data-show-tooltip', true);
 } );

 this.bind("showPlayerControls" , function(){
 _this.showControlBar();
 });
 },
 disable: function () {
 clearTimeout(this.getControlBar().handleTouchTimeoutId);
 this.monitorControlBarDisabled = false;
 this.hideControlBar( );
 this.monitorControlBarDisabled = true;
 },
 enable: function () {
 this.monitorControlBarDisabled = false;
 this.showControlBar( );
 },
 hideControlBar: function ( ) {
 if ( this.monitorControlBarDisabled ) {
 return;
 }
 if ( this.getControlBar().isVisible ) {
 this.getControlBar().addClass('componentOff componentAnimation' ).removeClass('componentOn');
 this.getFirstMonitor().obj.find(".controlBarShadow" ).addClass('componentOff componentAnimation' ).removeClass('componentOn');
 this.getControlBar().isVisible = false;
 }
 },
 showControlBar: function ( ) {
 if ( this.monitorControlBarDisabled || this.ignoreNextMouseEvent) {
 this.ignoreNextMouseEvent = false;
 return;
 }
 if ( !this.getControlBar().isVisible ) {
 this.getControlBar().removeClass('componentAnimation').addClass('componentOn' ).removeClass('componentOff');
 this.positionControlBar();
 this.getControlBar().isVisible = true;
 this.getFirstMonitor().obj.find(".controlBarShadow" ).removeClass('componentAnimation').addClass('componentOn' ).removeClass('componentOff');
 }

 var _this = this;
 if (this.getControlBar().handleTouchTimeoutId){
 clearTimeout(this.getControlBar().handleTouchTimeoutId);
 }
 this.getControlBar().handleTouchTimeoutId = setTimeout( function () {
 _this.ignoreNextMouseEvent = true;
 _this.hideControlBar( );
 }, this.getConfig('menuFadeout') );

 },

 *
*
* */
<|endoftext|>


<commit_before>var prolific = require('prolific.sink')
var abend = require('abend')
var Isochronous = require('isochronous')

exports.createShuttle = function (net, Shuttle) {
// TODO Is the interval necessary? Just flush constantly. Use Reactor (as heavy
// as Isochronous.)
    return function (program, interval, finale) {
        if (program.env.PROLIFIC_CONFIGURATION != null) {
// TODO Maybe delete and internalize?
            var configuration = JSON.parse(program.env.PROLIFIC_CONFIGURATION)
            var pipe = new net.Socket({ fd: configuration.fd  })
            var shuttle = new Shuttle(pipe, pipe, program.stderr, finale, interval)
            prolific.writer = shuttle.queue
// TODO Would love to be able to HUP this somehow.
// TODO Make `levels` a required thing.
            ; (configuration.levels || []).forEach(function (level) {
                prolific.setLevel.apply(prolific, level)
            })
            program.on('uncaughtException', shuttle.uncaughtException.bind(shuttle))
            program.on('exit', shuttle.exit.bind(shuttle))
// TODO Not right. Want to stop queue before exiting, there might still be
// messages.
            program.on('SIGINT', shuttle.stop.bind(shuttle))
            program.on('SIGTERM', shuttle.stop.bind(shuttle))
            return shuttle
        }
        return { stop: function() {} }
    }
}
<commit_msg>Configuration better be having levels.<commit_after>var prolific = require('prolific.sink')
var abend = require('abend')
var Isochronous = require('isochronous')

exports.createShuttle = function (net, Shuttle) {
// TODO Is the interval necessary? Just flush constantly. Use Reactor (as heavy
// as Isochronous.)
    return function (program, interval, finale) {
        if (program.env.PROLIFIC_CONFIGURATION != null) {
// TODO Maybe delete and internalize?
            var configuration = JSON.parse(program.env.PROLIFIC_CONFIGURATION)
            var pipe = new net.Socket({ fd: configuration.fd  })
            var shuttle = new Shuttle(pipe, pipe, program.stderr, finale, interval)
            prolific.writer = shuttle.queue
// TODO Would love to be able to HUP this somehow.
            configuration.levels.forEach(function (level) {
                prolific.setLevel.apply(prolific, level)
            })
            program.on('uncaughtException', shuttle.uncaughtException.bind(shuttle))
            program.on('exit', shuttle.exit.bind(shuttle))
// TODO Not right. Want to stop queue before exiting, there might still be
// messages.
            program.on('SIGINT', shuttle.stop.bind(shuttle))
            program.on('SIGTERM', shuttle.stop.bind(shuttle))
            return shuttle
        }
        return { stop: function() {} }
    }
}
<|endoftext|>


<commit_before>/**
 * Keeps track of the latest snapshot time for each blob in every container.
 * This is needed since the time resolution in most SDKs work on a second level. In particular,
 * during unit-tests chances are high that subsequent snapshots of a blob collide time-wise since
 * they only differ on the milliseconds level.
 *
 * SnapshotTimeManager provides means to avoid such conflicts by returning a timestamp that is at least
 * one second greater than the last snapshot time of a particular blob.
 *
 * @class SnapshotTimeManager
 */
class SnapshotTimeManager {
    constructor() {
        this.times = {};
    }

    /**
     * Updates / Adds the date of the latest snapshot of a particular blob.
     *
     * @param {String} containerName
     * @param {String} blobName
     * @param {Date} date
     *
     * @memberof SnapshotTimeManager
     */
    update(containerName, blobName, date) {
        this.times[`${containerName}-${blobName}`] = date;
    }

    /**
     * Returns a timestamp (UTC String) that is at least one second greater than the
     * last snapshot time of a particular blob.
     *
     * @param {String} containerName
     * @param {String} blobName
     *
     * @memberof SnapshotTimeManager
     */
    getDate(containerName, blobName) {
        let date = this.times[`${containerName}-${blobName}`];
        if (date === undefined) {
            return new Date();
        }
        date.setSeconds(date.getSeconds()+1);
        return date;
    }
}

module.exports = new SnapshotTimeManager();<commit_msg>added 'use strict' for node versions < 6<commit_after>'use strict';

/**
 * Keeps track of the latest snapshot time for each blob in every container.
 * This is needed since time resolution in most SDKs work on a second level. In particular,
 * during unit-tests chances are high that subsequent snapshots of a blob collide time-wise since
 * they only differ at the milliseconds level.
 *
 * SnapshotTimeManager provides means to avoid such conflicts by returning a timestamp that is at least
 * one second greater than the last snapshot time of a particular blob.
 *
 * @class SnapshotTimeManager
 */
class SnapshotTimeManager {
    constructor() {
        this.times = {};
    }

    /**
     * Updates / Adds the date of the latest snapshot of a particular blob.
     *
     * @param {String} containerName
     * @param {String} blobName
     * @param {Date} date
     *
     * @memberof SnapshotTimeManager
     */
    update(containerName, blobName, date) {
        this.times[`${containerName}-${blobName}`] = date;
    }

    /**
     * Returns a timestamp (UTC String) that is at least one second greater than the
     * last snapshot time of a particular blob.
     *
     * @param {String} containerName
     * @param {String} blobName
     *
     * @memberof SnapshotTimeManager
     */
    getDate(containerName, blobName) {
        let date = this.times[`${containerName}-${blobName}`];
        if (date === undefined) {
            return new Date();
        }
        date.setSeconds(date.getSeconds()+1);
        return date;
    }
}

module.exports = new SnapshotTimeManager();<|endoftext|>


<commit_before>var autils = require('../AUtils');
var GenericDiffReporterBase = require('./GenericDiffReporterBase');
var child_process = require('child_process');

var TortiseMergeReporter = function () {
	this.name = "TortiseMerge";
	this.exePath = autils.findWindowsExecutable("TortoiseGit/bin", "TortoiseMerge.exe");
};

TortiseMergeReporter.prototype = new GenericDiffReporterBase();

TortiseMergeReporter.prototype.report = function (approved, received, process) {
	process = process || child_process.spawn;
	autils.createEmptyFileIfNotExists(approved);
	process(this.exePath, [received, approved]);
};

module.exports = TortiseMergeReporter;
<commit_msg>search multiple locations for tortisemerge should help fix #2<commit_after>var autils = require('../AUtils');
var GenericDiffReporterBase = require('./GenericDiffReporterBase');
var child_process = require('child_process');

var TortiseMergeReporter = function () {
  this.name = "TortiseMerge";

  var rootPaths = [
    "TortoiseGit/bin",
    "TortoiseSVN/bin",
  ];
  var path = null;
  for (var i = 0; i < rootPaths.length; i++) {
    path = autils.findWindowsExecutable(rootPaths[i], "TortoiseMerge.exe");
    if (path) break;
  }
  this.exePath = path;
};

TortiseMergeReporter.prototype = new GenericDiffReporterBase();

TortiseMergeReporter.prototype.report = function (approved, received, process) {
  process = process || child_process.spawn;
  autils.createEmptyFileIfNotExists(approved);
  process(this.exePath, [received, approved]);
};

module.exports = TortiseMergeReporter;
<|endoftext|>


<commit_before>//  LauncherOSX
//
//  Created by Boris Schneiderman.
// Modified by Daniel Weck
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.

ReadiumSDK.Views.IFrameLoader = function() {

    var self = this;
    var eventListeners = {};

    this.addIFrameEventListener = function(eventName, callback, context) {

        if(eventListeners[eventName] == undefined) {
            eventListeners[eventName] = [];
        }

        eventListeners[eventName].push({callback: callback, context: context});
    };

    this.updateIframeEvents = function(iframe) {

        _.each(eventListeners, function(value, key){
            for(var i = 0, count = value.length; i< count; i++) {
                $(iframe.contentWindow).off(key);
                $(iframe.contentWindow).on(key, value[i].callback, value[i].context);
            }
        });
    };

    this.loadIframe = function(iframe, src, callback, context) {

        var isWaitingForFrameLoad = true;

        injectScripts(src, function (htmlText) {

            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(htmlText);

            iframe.onload = function () {

                isWaitingForFrameLoad = false;

                self.updateIframeEvents(iframe);

                callback.call(context, true);
            };

            iframe.contentWindow.document.close();
        });

        //yucks! iframe doesn't trigger onerror event - there is no reliable way to know that iframe finished
        // attempt tot load resource (successfully or not;
        window.setTimeout(function(){

            if(isWaitingForFrameLoad) {

                isWaitingForFrameLoad = false;
                callback.call(context, false);
            }

        }, 8000);

    };

    function getFileText(path, callback) {

        $.ajax({
            url: path,
            dataType: 'html',
            async: true,
            success: function (result) {

                callback(result);
            },
            error: function (xhr, status, errorThrown) {
                console.error('Error when AJAX fetching ' + path);
                console.error(status);
                console.error(errorThrown);
                callback();
            }
        });
    }

    function injectScripts(src, callback) {

        getFileText(src, function (contentFileData) {

            if (!contentFileData) {
                callback();
                return;
            }

            var sourceParts = src.split("/");
            sourceParts.pop(); //remove source file name

            /* TODO:
             IE requires the base href to be a full absolute URI, with protocol and hostname.
             There needs to be a way to determine if the given source URI (`src` parameter) is already an absolute URI.
             */
            if (!window.location.origin) {
                window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
            }
            var base = "<base href=\"" + window.location.origin + "/" + sourceParts.join("/") + "/" + "\">";

            var securityScript = "<script>(" + disableParent.toString() + ")()<\/script>";
            var readingSystemScript = "<script>navigator.epubReadingSystem = "+readingSystemForInjection()+";<\/script>";

            var mangledContent = contentFileData.replace(/(<head.*?>)/, "$1" + base + securityScript + readingSystemScript);
            callback(mangledContent);
        });
    }

    function disableParent() {

        window.parent = undefined;
    }

    function readingSystemForInjection() {

        var functions = [];
        return JSON.stringify(navigator.epubReadingSystem, function (key, value) {
            if (typeof value === 'function') {
                functions.push(value.toString());
                return "{{fn#" + (functions.length - 1) + "}}";
            }
            return value;
        }).replace(/"\{\{fn#(.*?)\}\}"/g, function (match, value) {
            return functions[value];
        });
    }
};
<commit_msg>Inject reading system object before writing to the iframe DOM. Remove previous attempt at reading system injection.<commit_after>//  LauncherOSX
//
//  Created by Boris Schneiderman.
// Modified by Daniel Weck
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.

ReadiumSDK.Views.IFrameLoader = function() {

    var self = this;
    var eventListeners = {};

    this.addIFrameEventListener = function(eventName, callback, context) {

        if(eventListeners[eventName] == undefined) {
            eventListeners[eventName] = [];
        }

        eventListeners[eventName].push({callback: callback, context: context});
    };

    this.updateIframeEvents = function(iframe) {

        _.each(eventListeners, function(value, key){
            for(var i = 0, count = value.length; i< count; i++) {
                $(iframe.contentWindow).off(key);
                $(iframe.contentWindow).on(key, value[i].callback, value[i].context);
            }
        });
    };

    this.loadIframe = function(iframe, src, callback, context) {

        var isWaitingForFrameLoad = true;

        injectScripts(src, function (htmlText) {

            iframe.contentWindow.document.open();
            //inject reading system object before writing to the iframe DOM
            iframe.contentWindow.navigator.epubReadingSystem = navigator.epubReadingSystem;

            iframe.contentWindow.document.write(htmlText);

            iframe.onload = function () {

                isWaitingForFrameLoad = false;

                self.updateIframeEvents(iframe);

                callback.call(context, true);
            };

            iframe.contentWindow.document.close();
        });

        //yucks! iframe doesn't trigger onerror event - there is no reliable way to know that iframe finished
        // attempt tot load resource (successfully or not;
        window.setTimeout(function(){

            if(isWaitingForFrameLoad) {

                isWaitingForFrameLoad = false;
                callback.call(context, false);
            }

        }, 8000);

    };

    function getFileText(path, callback) {

        $.ajax({
            url: path,
            dataType: 'html',
            async: true,
            success: function (result) {

                callback(result);
            },
            error: function (xhr, status, errorThrown) {
                console.error('Error when AJAX fetching ' + path);
                console.error(status);
                console.error(errorThrown);
                callback();
            }
        });
    }

    function injectScripts(src, callback) {

        getFileText(src, function (contentFileData) {

            if (!contentFileData) {
                callback();
                return;
            }

            var sourceParts = src.split("/");
            sourceParts.pop(); //remove source file name

            /* TODO:
             IE requires the base href to be a full absolute URI, with protocol and hostname.
             There needs to be a way to determine if the given source URI (`src` parameter) is already an absolute URI.
             */
            if (!window.location.origin) {
                window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
            }
            var base = "<base href=\"" + window.location.origin + "/" + sourceParts.join("/") + "/" + "\">";

            var securityScript = "<script>(" + disableParent.toString() + ")()<\/script>";

            var mangledContent = contentFileData.replace(/(<head.*?>)/, "$1" + base + securityScript);
            callback(mangledContent);
        });
    }

    function disableParent() {

        window.parent = undefined;
    }

};
<|endoftext|>