<commit_before>/*
*  AngularJs Fullcalendar Wrapper for the JQuery FullCalendar
*  API @ http://arshaw.com/fullcalendar/
*
*  Angular Calendar Directive that takes in the [eventSources] nested array object as the ng-model and watches it deeply changes.
*       Can also take in multiple event urls as a source object(s) and feed the events per view.
*       The calendar will watch any eventSource array and update itself when a change is made.
*
*/

angular.module('ui.calendar', [])

    .constant('uiCalendarConfig', {
        calendars : {}
    })
    .controller('uiCalendarCtrl', ['$scope', '$locale',
        function ($scope, $locale) {

            var sources = $scope.eventSources;
            var extraEventSignature = $scope.calendarWatchEvent ? $scope.calendarWatchEvent : angular.noop;

            var wrapFunctionWithScopeApply = function (functionToWrap) {
                return function () {
                    // This may happen outside of angular context, so create one if outside.
                    if ($scope.$root.$$phase) {
                        return functionToWrap.apply(this, arguments);
                    }

                    var args = arguments;
                    var that = this;
                    return $scope.$root.$apply(
                        function () {
                            return functionToWrap.apply(that, args);
                        }
                    );
                };
            };

            var eventSerialId = 1;
            // @return {String} fingerprint of the event object and its properties
            this.eventFingerprint = function (e) {
                if (!e._id) {
                    e._id = eventSerialId++;
                }

                var extraSignature = extraEventSignature({
                    event : e
                }) || '';
                var start = moment.isMoment(e.start) ? e.start.unix() : (e.start ? moment(e.start).unix() : '');
                var end = moment.isMoment(e.end) ? e.end.unix() : (e.end ? moment(e.end).unix() : '');

                // This extracts all the information we need from the event. http://jsperf.com/angular-calendar-events-fingerprint/3
                return [e._id, e.id || '', e.title || '', e.url || '', start, end, e.allDay || '', e.className || '', extraSignature].join('');
            };

            var sourceSerialId = 1;
            var sourceEventsSerialId = 1;
            // @return {String} fingerprint of the source object and its events array
            this.sourceFingerprint = function (source) {
                var fp = '' + (source.__id || (source.__id = sourceSerialId++));
                var events = angular.isObject(source) && source.events;

                if (events) {
                    fp = fp + '-' + (events.__id || (events.__id = sourceEventsSerialId++));
                }
                return fp;
            };

            // @return {Array} all events from all sources
            this.allEvents = function () {
                return Array.prototype.concat.apply(
                    [],
                    (sources || []).reduce(
                        function (previous, source) {
                            if (angular.isArray(source)) {
                                previous.push(source);
                            } else if (angular.isObject(source) && angular.isArray(source.events)) {
                                var extEvent = Object.keys(source).filter(
                                    function (key) {
                                        return (key !== '_id' && key !== 'events');
                                    }
                                );

                                source.events.forEach(
                                    function (event) {
                                        angular.extend(event, extEvent);
                                    }
                                );

                                previous.push(source.events);
                            }
                            return previous;
                        },
                        []
                    )
                );
            };

            // Track changes in array of objects by assigning id tokens to each element and watching the scope for changes in the tokens
            // @param {Array|Function} arraySource array of objects to watch
            // @param tokenFn {Function} that returns the token for a given object
            // @return {Object}
            //  subscribe: function(scope, function(newTokens, oldTokens))
            //    called when source has changed. return false to prevent individual callbacks from firing
            //  onAdded/Removed/Changed:
            //    when set to a callback, called each item where a respective change is detected
            this.changeWatcher = function (arraySource, tokenFn) {
                var self;

                var getTokens = function () {
                    return ((angular.isFunction(arraySource) ? arraySource() : arraySource) || []).reduce(
                        function (rslt, el) {
                            var token = tokenFn(el);
                            map[token] = el;
                            rslt.push(token);
                            return rslt;
                        },
                        []
                    );
                };

                // @param {Array} a
                // @param {Array} b
                // @return {Array} elements in that are in a but not in b
                // @example
                //  subtractAsSets([6, 100, 4, 5], [4, 5, 7]) // [6, 100]
                var subtractAsSets = function (a, b) {
                    var obj = (b || []).reduce(
                        function (rslt, val) {
                            rslt[val] = true;
                            return rslt;
                        },
                        Object.create(null)
                    );
                    return (a || []).filter(
                        function (val) {
                            return !obj[val];
                        }
                    );
                };

                // Map objects to tokens and vice-versa
                var map = {};

                // Compare newTokens to oldTokens and call onAdded, onRemoved, and onChanged handlers for each affected event respectively.
                var applyChanges = function (newTokens, oldTokens) {
                    var i;
                    var token;
                    var replacedTokens = {};
                    var removedTokens = subtractAsSets(oldTokens, newTokens);
                    for (i = 0; i < removedTokens.length; i++) {
                        var removedToken = removedTokens[i];
                        var el = map[removedToken];
                        delete map[removedToken];
                        var newToken = tokenFn(el);
                        // if the element wasn't removed but simply got a new token, its old token will be different from the current one
                        if (newToken === removedToken) {
                            self.onRemoved(el);
                        } else {
                            replacedTokens[newToken] = removedToken;
                            self.onChanged(el);
                        }
                    }

                    var addedTokens = subtractAsSets(newTokens, oldTokens);
                    for (i = 0; i < addedTokens.length; i++) {
                        token = addedTokens[i];
                        if (!replacedTokens[token]) {
                            self.onAdded(map[token]);
                        }
                    }
                };

                self = {
                    subscribe : function (scope, onArrayChanged) {
                        scope.$watch(getTokens, function (newTokens, oldTokens) {
                            var notify = !(onArrayChanged && onArrayChanged(newTokens, oldTokens) === false);
                            if (notify) {
                                applyChanges(newTokens, oldTokens);
                            }
                        }, true);
                    },
                    onAdded : angular.noop,
                    onChanged : angular.noop,
                    onRemoved : angular.noop
                };
                return self;
            };

            this.getFullCalendarConfig = function (calendarSettings, uiCalendarConfig) {
                var config = {};

                angular.extend(config, uiCalendarConfig);
                angular.extend(config, calendarSettings);

                angular.forEach(config, function (value, key) {
                    if (typeof value === 'function') {
                        config[key] = wrapFunctionWithScopeApply(config[key]);
                    }
                });

                return config;
            };

            this.getLocaleConfig = function (fullCalendarConfig) {
                if (!fullCalendarConfig.lang || fullCalendarConfig.useNgLocale) {
                    // Configure to use locale names by default
                    var tValues = function (data) {
                        // convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...]
                        return (Object.keys(data) || []).reduce(
                            function (rslt, el) {
                                rslt.push(data[el]);
                                return rslt;
                            },
                            []
                        );
                    };

                    var dtf = $locale.DATETIME_FORMATS;
                    return {
                        monthNames : tValues(dtf.MONTH),
                        monthNamesShort : tValues(dtf.SHORTMONTH),
                        dayNames : tValues(dtf.DAY),
                        dayNamesShort : tValues(dtf.SHORTDAY)
                    };
                }

                return {};
            };
        }
    ])
    .directive('uiCalendar', ['uiCalendarConfig',
        function (uiCalendarConfig) {

            return {
                restrict : 'A',
                scope : {
                    eventSources : '=ngModel',
                    calendarWatchEvent : '&'
                },
                controller : 'uiCalendarCtrl',
                link : function (scope, elm, attrs, controller) {
                    var sources = scope.eventSources;
                    var sourcesChanged = false;
                    var calendar;
                    var eventSourcesWatcher = controller.changeWatcher(sources, controller.sourceFingerprint);
                    var eventsWatcher = controller.changeWatcher(controller.allEvents, controller.eventFingerprint);
                    var options = null;

                    function getOptions () {
                        var calendarSettings = attrs.uiCalendar ? scope.$parent.$eval(attrs.uiCalendar) : {};
                        var fullCalendarConfig = controller.getFullCalendarConfig(calendarSettings, uiCalendarConfig);
                        var localeFullCalendarConfig = controller.getLocaleConfig(fullCalendarConfig);
                        angular.extend(localeFullCalendarConfig, fullCalendarConfig);
                        options = {
                            eventSources : sources
                        };
                        angular.extend(options, localeFullCalendarConfig);
                        //remove calendars from options
                        options.calendars = null;

                        var options2 = {};
                        for (var o in options) {
                            if (o !== 'eventSources') {
                                options2[o] = options[o];
                            }
                        }
                        return JSON.stringify(options2);
                    }

                    scope.destroyCalendar = function () {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('destroy');
                        }
                        if (attrs.calendar) {
                            calendar = uiCalendarConfig.calendars[attrs.calendar] = angular.element(elm).html('');
                        } else {
                            calendar = angular.element(elm).html('');
                        }
                    };

                    scope.initCalendar = function () {
                        if (!calendar) {
                            calendar = angular.element(elm).html('');
                        }
                        calendar.fullCalendar(options);
                        if (attrs.calendar) {
                            uiCalendarConfig.calendars[attrs.calendar] = calendar;
                        }
                    };

                    scope.$on('$destroy', function () {
                        scope.destroyCalendar();
                    });

                    eventSourcesWatcher.onAdded = function (source) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar(options);
                            if (attrs.calendar) {
                                uiCalendarConfig.calendars[attrs.calendar] = calendar;
                            }
                            calendar.fullCalendar('addEventSource', source);
                            sourcesChanged = true;
                        }
                    };

                    eventSourcesWatcher.onRemoved = function (source) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('removeEventSource', source);
                            sourcesChanged = true;
                        }
                    };

                    eventSourcesWatcher.onChanged = function () {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('refetchEvents');
                            sourcesChanged = true;
                        }
                    };

                    eventsWatcher.onAdded = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('renderEvent', event, !!event.stick);
                        }
                    };

                    eventsWatcher.onRemoved = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('removeEvents', event._id);
                        }
                    };

                    eventsWatcher.onChanged = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            var clientEvents = calendar.fullCalendar('clientEvents', event._id);
                            for (var i = 0; i < clientEvents.length; i++) {
                                var clientEvent = clientEvents[i];
                                clientEvent = angular.extend(clientEvent, event);
                                calendar.fullCalendar('updateEvent', clientEvent);
                            }
                        }
                    };

                    eventSourcesWatcher.subscribe(scope);
                    eventsWatcher.subscribe(scope, function () {
                        if (sourcesChanged === true) {
                            sourcesChanged = false;
                            // return false to prevent onAdded/Removed/Changed handlers from firing in this case
                            return false;
                        }
                    });

                    scope.$watch(getOptions, function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            scope.destroyCalendar();
                            scope.initCalendar();
                        } else if ((newValue && angular.isUndefined(calendar))) {
                            scope.initCalendar();
                        }
                    });
                }
            };
        }
    ]
);
<commit_msg>re-apply fix for #267<commit_after>/*
*  AngularJs Fullcalendar Wrapper for the JQuery FullCalendar
*  API @ http://arshaw.com/fullcalendar/
*
*  Angular Calendar Directive that takes in the [eventSources] nested array object as the ng-model and watches it deeply changes.
*       Can also take in multiple event urls as a source object(s) and feed the events per view.
*       The calendar will watch any eventSource array and update itself when a change is made.
*
*/

angular.module('ui.calendar', [])

    .constant('uiCalendarConfig', {
        calendars : {}
    })
    .controller('uiCalendarCtrl', ['$scope', '$locale',
        function ($scope, $locale) {

            var sources = $scope.eventSources;
            var extraEventSignature = $scope.calendarWatchEvent ? $scope.calendarWatchEvent : angular.noop;

            var wrapFunctionWithScopeApply = function (functionToWrap) {
                return function () {
                    // This may happen outside of angular context, so create one if outside.
                    if ($scope.$root.$$phase) {
                        return functionToWrap.apply(this, arguments);
                    }

                    var args = arguments;
                    var that = this;
                    return $scope.$root.$apply(
                        function () {
                            return functionToWrap.apply(that, args);
                        }
                    );
                };
            };

            var eventSerialId = 1;
            // @return {String} fingerprint of the event object and its properties
            this.eventFingerprint = function (e) {
                if (!e._id) {
                    e._id = eventSerialId++;
                }

                var extraSignature = extraEventSignature({
                    event : e
                }) || '';
                var start = moment.isMoment(e.start) ? e.start.unix() : (e.start ? moment(e.start).unix() : '');
                var end = moment.isMoment(e.end) ? e.end.unix() : (e.end ? moment(e.end).unix() : '');

                // This extracts all the information we need from the event. http://jsperf.com/angular-calendar-events-fingerprint/3
                return [e._id, e.id || '', e.title || '', e.url || '', start, end, e.allDay || '', e.className || '', extraSignature].join('');
            };

            var sourceSerialId = 1;
            var sourceEventsSerialId = 1;
            // @return {String} fingerprint of the source object and its events array
            this.sourceFingerprint = function (source) {
                var fp = '' + (source.__id || (source.__id = sourceSerialId++));
                var events = angular.isObject(source) && source.events;

                if (events) {
                    fp = fp + '-' + (events.__id || (events.__id = sourceEventsSerialId++));
                }
                return fp;
            };

            // @return {Array} all events from all sources
            this.allEvents = function () {
                return Array.prototype.concat.apply(
                    [],
                    (sources || []).reduce(
                        function (previous, source) {
                            if (angular.isArray(source)) {
                                previous.push(source);
                            } else if (angular.isObject(source) && angular.isArray(source.events)) {
                                var extEvent = Object.keys(source).filter(
                                    function (key) {
                                        return (key !== '_id' && key !== 'events');
                                    }
                                );

                                source.events.forEach(
                                    function (event) {
                                        angular.extend(event, extEvent);
                                    }
                                );

                                previous.push(source.events);
                            }
                            return previous;
                        },
                        []
                    )
                );
            };

            // Track changes in array of objects by assigning id tokens to each element and watching the scope for changes in the tokens
            // @param {Array|Function} arraySource array of objects to watch
            // @param tokenFn {Function} that returns the token for a given object
            // @return {Object}
            //  subscribe: function(scope, function(newTokens, oldTokens))
            //    called when source has changed. return false to prevent individual callbacks from firing
            //  onAdded/Removed/Changed:
            //    when set to a callback, called each item where a respective change is detected
            this.changeWatcher = function (arraySource, tokenFn) {
                var self;

                var getTokens = function () {
                    return ((angular.isFunction(arraySource) ? arraySource() : arraySource) || []).reduce(
                        function (rslt, el) {
                            var token = tokenFn(el);
                            map[token] = el;
                            rslt.push(token);
                            return rslt;
                        },
                        []
                    );
                };

                // @param {Array} a
                // @param {Array} b
                // @return {Array} elements in that are in a but not in b
                // @example
                //  subtractAsSets([6, 100, 4, 5], [4, 5, 7]) // [6, 100]
                var subtractAsSets = function (a, b) {
                    var obj = (b || []).reduce(
                        function (rslt, val) {
                            rslt[val] = true;
                            return rslt;
                        },
                        Object.create(null)
                    );
                    return (a || []).filter(
                        function (val) {
                            return !obj[val];
                        }
                    );
                };

                // Map objects to tokens and vice-versa
                var map = {};

                // Compare newTokens to oldTokens and call onAdded, onRemoved, and onChanged handlers for each affected event respectively.
                var applyChanges = function (newTokens, oldTokens) {
                    var i;
                    var token;
                    var replacedTokens = {};
                    var removedTokens = subtractAsSets(oldTokens, newTokens);
                    for (i = 0; i < removedTokens.length; i++) {
                        var removedToken = removedTokens[i];
                        var el = map[removedToken];
                        delete map[removedToken];
                        var newToken = tokenFn(el);
                        // if the element wasn't removed but simply got a new token, its old token will be different from the current one
                        if (newToken === removedToken) {
                            self.onRemoved(el);
                        } else {
                            replacedTokens[newToken] = removedToken;
                            self.onChanged(el);
                        }
                    }

                    var addedTokens = subtractAsSets(newTokens, oldTokens);
                    for (i = 0; i < addedTokens.length; i++) {
                        token = addedTokens[i];
                        if (!replacedTokens[token]) {
                            self.onAdded(map[token]);
                        }
                    }
                };

                self = {
                    subscribe : function (scope, onArrayChanged) {
                        scope.$watch(getTokens, function (newTokens, oldTokens) {
                            var notify = !(onArrayChanged && onArrayChanged(newTokens, oldTokens) === false);
                            if (notify) {
                                applyChanges(newTokens, oldTokens);
                            }
                        }, true);
                    },
                    onAdded : angular.noop,
                    onChanged : angular.noop,
                    onRemoved : angular.noop
                };
                return self;
            };

            this.getFullCalendarConfig = function (calendarSettings, uiCalendarConfig) {
                var config = {};

                angular.extend(config, uiCalendarConfig);
                angular.extend(config, calendarSettings);

                angular.forEach(config, function (value, key) {
                    if (typeof value === 'function') {
                        config[key] = wrapFunctionWithScopeApply(config[key]);
                    }
                });

                return config;
            };

            this.getLocaleConfig = function (fullCalendarConfig) {
                if (!fullCalendarConfig.lang || fullCalendarConfig.useNgLocale) {
                    // Configure to use locale names by default
                    var tValues = function (data) {
                        // convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...]
                        return (Object.keys(data) || []).reduce(
                            function (rslt, el) {
                                rslt.push(data[el]);
                                return rslt;
                            },
                            []
                        );
                    };

                    var dtf = $locale.DATETIME_FORMATS;
                    return {
                        monthNames : tValues(dtf.MONTH),
                        monthNamesShort : tValues(dtf.SHORTMONTH),
                        dayNames : tValues(dtf.DAY),
                        dayNamesShort : tValues(dtf.SHORTDAY)
                    };
                }

                return {};
            };
        }
    ])
    .directive('uiCalendar', ['uiCalendarConfig',
        function (uiCalendarConfig) {

            return {
                restrict : 'A',
                scope : {
                    eventSources : '=ngModel',
                    calendarWatchEvent : '&'
                },
                controller : 'uiCalendarCtrl',
                link : function (scope, elm, attrs, controller) {
                    var sources = scope.eventSources;
                    var sourcesChanged = false;
                    var calendar;
                    var eventSourcesWatcher = controller.changeWatcher(sources, controller.sourceFingerprint);
                    var eventsWatcher = controller.changeWatcher(controller.allEvents, controller.eventFingerprint);
                    var options = null;

                    function getOptions () {
                        var calendarSettings = attrs.uiCalendar ? scope.$parent.$eval(attrs.uiCalendar) : {};
                        var fullCalendarConfig = controller.getFullCalendarConfig(calendarSettings, uiCalendarConfig);
                        var localeFullCalendarConfig = controller.getLocaleConfig(fullCalendarConfig);
                        angular.extend(localeFullCalendarConfig, fullCalendarConfig);
                        options = {
                            eventSources : sources
                        };
                        angular.extend(options, localeFullCalendarConfig);
                        //remove calendars from options
                        options.calendars = null;

                        var options2 = {};
                        for (var o in options) {
                            if (o !== 'eventSources') {
                                options2[o] = options[o];
                            }
                        }
                        return JSON.stringify(options2);
                    }

                    scope.destroyCalendar = function () {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('destroy');
                        }
                        if (attrs.calendar) {
                            calendar = uiCalendarConfig.calendars[attrs.calendar] = angular.element(elm).html('');
                        } else {
                            calendar = angular.element(elm).html('');
                        }
                    };

                    scope.initCalendar = function () {
                        if (!calendar) {
                            calendar = $(elm).html('');
                        }
                        calendar.fullCalendar(options);
                        if (attrs.calendar) {
                            uiCalendarConfig.calendars[attrs.calendar] = calendar;
                        }
                    };

                    scope.$on('$destroy', function () {
                        scope.destroyCalendar();
                    });

                    eventSourcesWatcher.onAdded = function (source) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar(options);
                            if (attrs.calendar) {
                                uiCalendarConfig.calendars[attrs.calendar] = calendar;
                            }
                            calendar.fullCalendar('addEventSource', source);
                            sourcesChanged = true;
                        }
                    };

                    eventSourcesWatcher.onRemoved = function (source) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('removeEventSource', source);
                            sourcesChanged = true;
                        }
                    };

                    eventSourcesWatcher.onChanged = function () {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('refetchEvents');
                            sourcesChanged = true;
                        }
                    };

                    eventsWatcher.onAdded = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('renderEvent', event, !!event.stick);
                        }
                    };

                    eventsWatcher.onRemoved = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            calendar.fullCalendar('removeEvents', event._id);
                        }
                    };

                    eventsWatcher.onChanged = function (event) {
                        if (calendar && calendar.fullCalendar) {
                            var clientEvents = calendar.fullCalendar('clientEvents', event._id);
                            for (var i = 0; i < clientEvents.length; i++) {
                                var clientEvent = clientEvents[i];
                                clientEvent = angular.extend(clientEvent, event);
                                calendar.fullCalendar('updateEvent', clientEvent);
                            }
                        }
                    };

                    eventSourcesWatcher.subscribe(scope);
                    eventsWatcher.subscribe(scope, function () {
                        if (sourcesChanged === true) {
                            sourcesChanged = false;
                            // return false to prevent onAdded/Removed/Changed handlers from firing in this case
                            return false;
                        }
                    });

                    scope.$watch(getOptions, function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            scope.destroyCalendar();
                            scope.initCalendar();
                        } else if ((newValue && angular.isUndefined(calendar))) {
                            scope.initCalendar();
                        }
                    });
                }
            };
        }
    ]
);
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------
//
//  Classify.js v@VERSION
//  http://github.com/petebrowne/classify
//
//  Copyright (c) 2010, Peter Browne
//
//--------------------------------------------------------------------------

(function() {

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

  var UNDEFINED = 'undefined',
  FUNCTION      = 'function',
  STRING        = 'string',

  //----------------------------------
  //  Internal Properties
  //----------------------------------

  // The namespace where the keyword methods will be attached to.
  namespace = this,

  // The current scope to define Classes, Modules, and Methods on.
  currentObject = namespace,

  // The current Class to define Methods on.
  currentClass = null,

  // Flag to signal when we are initializing a superclass during inheritance
  inheriting = false;

  //----------------------------------
  //  Internal Methods
  //----------------------------------

  // Builds a new Class, with optional inheritance.
  function buildClass(name, superclass) {
    function Class() {
      if (!inheriting && typeof this.initialize === FUNCTION) {
        this.initialize.apply(this, arguments);
      }
    }

    if (superclass != null) {
      inheriting = true;
      Class.prototype = new superclass();
      for (var method in superclass) {
        if (typeof superclass[method] === FUNCTION) {
          namespace.def(Class, method, superclass[method]);
        }
      }
      inheriting = false;
    }

    Class.superclass            = superclass;
    Class.prototype.constructor = Class;
    Class.prototype.toString    = function() {
      return '[object ' + this.constructor.toString() + ']';
    };

    addName(currentObject, Class, name);

    return Class;
  }

  // Builds a new module.
  function buildModule(name) {
    return addName(currentObject, {}, name);
  }

  // Adds a toString method that returns the name of the object
  function addName(currentObject, object, name) {
    object.toString = function(includeModules) {
      if (includeModules === false || currentObject == null || currentObject === namespace) {
        return name;
      }
      else {
        return currentObject + '.' + name;
      }
    };
    return object;
  }

  // Add the given methods to the object.
  function addDefinition(withClass, withObject, definition) {
    if (withObject == null || definition == null) {
      return;
    }

    var oldClass  = currentClass,
        oldObject = currentObject;

    currentClass  = withClass;
    currentObject = withObject;

    if (typeof definition === FUNCTION) {
      definition.call(withObject);
    }
    else {
      for (var name in definition) {
        if (!(/^(constructor|prototype|toString|valueOf)$/).test(name)) {
          namespace.def(name, definition[name]);
        }
      }
    }

    currentClass  = oldClass;
    currentObject = oldObject;
  }

  // If necessary add a `callSuper` method to access the superclass's method.
  function addCallSuper(definition, superDefinition) {
    if (typeof superDefinition === FUNCTION && callsSuper(definition)) {
      return function() {
        var defArgs  = arguments,
            oldSuper = this.callSuper,
            result;

        this.callSuper = function() {
          return superDefinition.apply(this, arguments.length ? arguments : defArgs);
        };

        result = definition.apply(this, defArgs);
        if (typeof oldSuper !== UNDEFINED) {
          this.callSuper = oldSuper;
        }

        return result;
      };
    }

    return definition;
  }

  // Test to see if a function contains a call to `callSuper`
  function callsSuper(method) {
    return (/\bthis\.callSuper\b/).test(method.toString());
  }

  //----------------------------------
  //  Public Methods
  //----------------------------------

  // Defines a new method. The method will be defined on the _current scope_, which will
  // be either the `window`, a Class, or Module. Within the method definition, `this` will
  // refer to the _current scope_. Optionally, you can set the object to define the method on as the
  // first argument.
  namespace.def = function(object, name, definition) {
    if (typeof definition === UNDEFINED) {
      definition = name;
      name       = object;
      object     = currentClass || currentObject;
    }

    object[name] = addCallSuper(definition, object[name]);

    return object[name];
  };

  // Creates a new Class. The Class will be defined on the _current scope_, which will
  // be either the `window` or a Module. Optionally you can pass in a Superclass as the first argument.
  namespace.classify = function(superclass, object, definition) {
    if (typeof definition === UNDEFINED) {
      definition = object;
      object     = superclass;
      superclass = null;
    }

    if (typeof object === STRING) {
      if (typeof currentObject[object] === UNDEFINED) {
        currentObject[object] = buildClass(object, superclass);
      }
      object = currentObject[object];
    }

    addDefinition(object.prototype, object, definition);

    return object;
  };

  // Creates a new Module. Modules can be used as namespaces for other Modules
  // and Classes. They can also be used as a collection of method definitions
  // to be included into other Classes.
  namespace.module = function(object, definition) {
    if (typeof object === STRING) {
      if (typeof currentObject[object] === UNDEFINED) {
        currentObject[object] = buildModule(object);
      }
      object = currentObject[object];
    }

    addDefinition(null, object, definition);

    return object;
  };

  // Includes the given Module methods into either the current Class or, optionally, the
  // given Class Definition. The included methods will be available on the instance of the Class.
  namespace.include = function(object, definition) {
    if (typeof definition === UNDEFINED) {
      definition = object;
      object     = currentClass || currentObject;
    }
    else if (typeof object === STRING) {
      object = currentObject[object];
    }

    addDefinition(currentClass, object, definition);
  };

  // Extends the current Class or, optionally, the given Class Definition with the given
  // Module methods. The methods wil be available as Class methods.
  namespace.extend = function(object, definition) {
    if (typeof definition === UNDEFINED) {
      definition = object;
      object     = currentObject;
    }
    else if (typeof object === STRING) {
      object = currentObject[object];
    }

    addDefinition(null, object, definition);
  };

  // Creates a alias for the given Method, Class, or Module definition.
  namespace.alias = function(alias, method) {
    var object = currentClass || currentObject;

    object[alias] = object[method];
  };

})();
<commit_msg>Cleaning up typeof checks. Using === only where appropriate<commit_after>//--------------------------------------------------------------------------
//
//  Classify.js v@VERSION
//  http://classify.petebrowne.com/
//
//  Copyright (c) 2010, Peter Browne
//
//--------------------------------------------------------------------------

(function() {

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

  var FUNCTION  = 'function',
  STRING        = 'string',

  //----------------------------------
  //  Internal Properties
  //----------------------------------

  // The namespace where the keyword methods will be attached to.
  namespace = this,

  // The current scope to define Classes, Modules, and Methods on.
  currentObject = namespace,

  // The current Class to define Methods on.
  currentClass = null,

  // Flag to signal when we are initializing a superclass during inheritance
  inheriting = false;

  //----------------------------------
  //  Internal Methods
  //----------------------------------

  // Builds a new Class, with optional inheritance.
  function buildClass(name, superclass) {
    function Class() {
      if (!inheriting && typeof this.initialize == FUNCTION) {
        this.initialize.apply(this, arguments);
      }
    }

    if (superclass != null) {
      inheriting = true;
      Class.prototype = new superclass();
      for (var method in superclass) {
        if (typeof superclass[method] == FUNCTION) {
          namespace.def(Class, method, superclass[method]);
        }
      }
      inheriting = false;
    }

    Class.superclass            = superclass;
    Class.prototype.constructor = Class;
    Class.prototype.toString    = function() {
      return '[object ' + this.constructor.toString() + ']';
    };

    addName(currentObject, Class, name);

    return Class;
  }

  // Builds a new module.
  function buildModule(name) {
    return addName(currentObject, {}, name);
  }

  // Adds a toString method that returns the name of the object
  function addName(currentObject, object, name) {
    object.toString = function(includeModules) {
      if (includeModules === false || currentObject == null || currentObject === namespace) {
        return name;
      }
      else {
        return currentObject + '.' + name;
      }
    };
    return object;
  }

  // Add the given methods to the object.
  function addDefinition(withClass, withObject, definition) {
    if (withObject == null || definition == null) {
      return;
    }

    var oldClass  = currentClass,
        oldObject = currentObject;

    currentClass  = withClass;
    currentObject = withObject;

    if (typeof definition == FUNCTION) {
      definition.call(withObject);
    }
    else {
      for (var name in definition) {
        if (!(/^(constructor|prototype|toString|valueOf)$/).test(name)) {
          namespace.def(name, definition[name]);
        }
      }
    }

    currentClass  = oldClass;
    currentObject = oldObject;
  }

  // If necessary add a `callSuper` method to access the superclass's method.
  function addCallSuper(definition, superDefinition) {
    if (typeof superDefinition == FUNCTION && callsSuper(definition)) {
      return function() {
        var defArgs  = arguments,
            oldSuper = this.callSuper,
            result;

        this.callSuper = function() {
          return superDefinition.apply(this, arguments.length ? arguments : defArgs);
        };

        result = definition.apply(this, defArgs);
        this.callSuper = oldSuper;

        return result;
      };
    }

    return definition;
  }

  // Test to see if a function contains a call to `callSuper`
  function callsSuper(method) {
    return (/\bthis\.callSuper\b/).test(method.toString());
  }

  //----------------------------------
  //  Public Methods
  //----------------------------------

  // Defines a new method. The method will be defined on the _current scope_, which will
  // be either the `window`, a Class, or Module. Within the method definition, `this` will
  // refer to the _current scope_. Optionally, you can set the object to define the method on as the
  // first argument.
  namespace.def = function(object, name, definition) {
    if (definition == null) {
      definition = name;
      name       = object;
      object     = currentClass || currentObject;
    }

    object[name] = addCallSuper(definition, object[name]);

    return object[name];
  };

  // Creates a new Class. The Class will be defined on the _current scope_, which will
  // be either the `window` or a Module. Optionally you can pass in a Superclass as the first argument.
  namespace.classify = function(superclass, object, definition) {
    if (definition == null) {
      definition = object;
      object     = superclass;
      superclass = null;
    }

    if (typeof object == STRING) {
      if (currentObject[object] == null) {
        currentObject[object] = buildClass(object, superclass);
      }
      object = currentObject[object];
    }

    addDefinition(object.prototype, object, definition);

    return object;
  };

  // Creates a new Module. Modules can be used as namespaces for other Modules
  // and Classes. They can also be used as a collection of method definitions
  // to be included into other Classes.
  namespace.module = function(object, definition) {
    if (typeof object == STRING) {
      if (currentObject[object] == null) {
        currentObject[object] = buildModule(object);
      }
      object = currentObject[object];
    }

    addDefinition(null, object, definition);

    return object;
  };

  // Includes the given Module methods into either the current Class or, optionally, the
  // given Class Definition. The included methods will be available on the instance of the Class.
  namespace.include = function(object, definition) {
    if (definition == null) {
      definition = object;
      object     = currentClass || currentObject;
    }
    else if (typeof object == STRING) {
      object = currentObject[object];
    }

    addDefinition(currentClass, object, definition);
  };

  // Extends the current Class or, optionally, the given Class Definition with the given
  // Module methods. The methods wil be available as Class methods.
  namespace.extend = function(object, definition) {
    if (definition == null) {
      definition = object;
      object     = currentObject;
    }
    else if (typeof object == STRING) {
      object = currentObject[object];
    }

    addDefinition(null, object, definition);
  };

  // Creates a alias for the given Method, Class, or Module definition.
  namespace.alias = function(alias, method) {
    var object = currentClass || currentObject;

    object[alias] = object[method];
  };

})();
<|endoftext|>


<commit_before>var el = require('./el');
var outputEl = document.querySelector('#el-js');

function assertDomContent(elTree, expected) {
    el(outputEl, elTree);
    var actual = outputEl.innerHTML.replace(/\s+/g, ' ').trim();
    if (actual === expected) return;
    throw new Error('Unexpected element output; to debug this, break on errors and inspect the DOM');
}

function resetOutputEl() {
    outputEl.innerHTML = '';
}

describe('el.js', function() {

    afterEach(resetOutputEl);

    it('produces the simplest possible element', function() {
        assertDomContent(
            el('div', 'Hello World'),
            '
Hello World
'
        );
    });

});
<commit_msg>Add a more involved test case.<commit_after>var el = require('./el');
var outputEl = document.querySelector('#el-js');

function assertDomContent(elTree, expected) {
    el(outputEl, elTree);
    var actual = outputEl.innerHTML.replace(/\s+/g, ' ').trim();
    if (actual === expected) return;
    throw new Error('\n\nExpected: ' + expected + '\n  Actual: ' + actual + '\n\n');
}

function resetOutputEl() {
    outputEl.innerHTML = '';
}

describe('el.js', function() {

    afterEach(resetOutputEl);

    it('produces the simplest possible element', function() {
        assertDomContent(
            el('div', 'Hello World'),
            '
Hello World
'
        );
    });

    it('produces more complex elements', function() {
        assertDomContent(
            el('p', { class: 'cool' },
                el('<!', 'this is a comment'),
                el('a', 'Click here', {
                    href: '#some-location'
                }),
                el('', 'Text after link')
            ),
            '
Click hereText after link
'
        );
    });

});
<|endoftext|>


<commit_before>import { Route, match } from 'i40';

var R    = require('ramda');
var path = require('path');

export class CliRouter {
  constructor(controllers_root, route_regex) {
    route_regex = route_regex || '/:controller/:action?';
    this.controllers_root = controllers_root || './';

    var rule = Route(route_regex, 0);

    this.route_rules      = [ rule ];
    this.routes           = [];
    this.controller_names = [];
  }

  add(pathname, controller, startAt) {
    var route = match(this.route_rules, pathname, startAt);

    if (route) {
      var controller_name = route.params.controller;
      if (!R.isNil(controller_name) && !R.contains(controller_name)(this.controller_names)) {
        this.controller_names.push(controller_name);
      }

      controller = controller || pathname;

      if (typeof controller === 'string') {
        route.Controller = this.loadController(pathname, controller);
      } else if (typeof controller === 'function') {
        route.fn = controller;
      } else {
        throw new Error(' route ' + pathname.toString() + ' requires a `controller`');
      }

      this.routes.push(route);
    } else {
      throw new Error(' invalid route ' + pathname.toString());

    }
    return this;
  }

  match(pathname, startAt) {
    var params = match(this.route_rules, pathname, startAt);
    return params;
  }

  loadController(pathname) {
    try { return require(path.join(this.controllers_root, pathname)); } catch (e) { }
  }

  findRoute(controller, action) {
    var routes = [];
    for (var i = 0; i < this.routes.length; i++) {
      if (this.routes[i].params.controller == controller &&
        this.routes[i].params.action == action ) {
        routes.push(this.routes[i]);
      }
    }
    return R.last(routes);
  }

  findRouteByParams(params) {
    var route = this.findRoute(params.controller, params.action);
    if (!route) {
      route = this.findRoute(params.controller);
    }

    return route;
  }

  getFn(route, params, opts) {
    if (!R.is(Object, route) || !R.is(Object, params)) { return; }
    var fn;

    if (route.hasOwnProperty('Controller')) {
      var controller = new route.Controller(opts);
      fn = controller[params.action] || controller.index;
    } else if (route.hasOwnProperty('fn')) {
      fn = route.fn;
    }
    return fn;
  }

  exatractCommads(args) {
    var cmds = [];
    for (var i = 0; i < this.controller_names.length; i++) {
      var controller_name = this.controller_names[i];
      if (args.hasOwnProperty(controller_name) && !!args[controller_name]) {
        cmds.push(controller_name);
      }
    }
    cmds = R.uniq(R.concat(cmds, (R.invert(args).true || [])));

    return cmds;
  }

  run(args, opts) {
    var cmds = this.exatractCommads(args);

    if (!R.isNil(cmds) && !R.isEmpty(cmds)) {
      var url    = `/${cmds.join('/')}/`;
      var params = this.match(url).params;
      var route  = this.findRouteByParams(params);
      var fn     = this.getFn(route, params, opts);

      if (R.is(Function, fn)) {
        return fn(args);
      }
    }
  }
}
<commit_msg>Adding support to lazy require controllers<commit_after>import { Route, match } from 'i40';

var R    = require('ramda');
var path = require('path');

export class CliRouter {
  constructor(controllers_root, route_regex) {
    route_regex = route_regex || '/:controller/:action?';
    this.controllers_root = controllers_root || './';

    var rule = Route(route_regex, 0);

    this.route_rules      = [ rule ];
    this.routes           = [];
    this.controller_names = [];
  }

  add(pathname, controller, startAt) {
    var route = match(this.route_rules, pathname, startAt);

    if (route) {
      var controller_name = route.params.controller;
      if (!R.isNil(controller_name) && !R.contains(controller_name)(this.controller_names)) {
        this.controller_names.push(controller_name);
      }

      controller = controller || pathname;

      if (typeof controller === 'string') {
        route.Controller = controller;
      } else if (typeof controller === 'function') {
        route.fn = controller;
      } else {
        throw new Error(' route ' + pathname.toString() + ' requires a `controller`');
      }

      this.routes.push(route);
    } else {
      throw new Error(' invalid route ' + pathname.toString());

    }
    return this;
  }

  match(pathname, startAt) {
    var params = match(this.route_rules, pathname, startAt);
    return params;
  }

  loadController(pathname) {
    return require(path.join(this.controllers_root, pathname));
  }

  findRoute(controller, action) {
    var routes = [];
    for (var i = 0; i < this.routes.length; i++) {
      if (this.routes[i].params.controller == controller &&
        this.routes[i].params.action == action ) {
        routes.push(this.routes[i]);
      }
    }
    return R.last(routes);
  }

  findRouteByParams(params) {
    var route = this.findRoute(params.controller, params.action);
    if (!route) {
      route = this.findRoute(params.controller);
    }

    return route;
  }

  getFn(route, params, opts) {
    if (!R.is(Object, route) || !R.is(Object, params)) { return; }
    var fn;

    if (route.hasOwnProperty('Controller')) {
      if (R.is(String, route.Controller)) {
        route.Controller = this.loadController(route.Controller);
      }
      var controller = new route.Controller(opts);
      fn = !R.isNil(params.action) ? controller[params.action] : controller.index;
    } else if (route.hasOwnProperty('fn')) {
      fn = route.fn;
    }
    return fn;
  }

  exatractCommads(args) {
    var cmds = [];
    for (var i = 0; i < this.controller_names.length; i++) {
      var controller_name = this.controller_names[i];
      if (args.hasOwnProperty(controller_name) && !!args[controller_name]) {
        cmds.push(controller_name);
      }
    }
    cmds = R.uniq(R.concat(cmds, (R.invert(args).true || [])));

    return cmds;
  }

  run(args, opts) {
    var cmds = this.exatractCommads(args);

    if (!R.isNil(cmds) && !R.isEmpty(cmds)) {
      var url    = `/${cmds.join('/')}/`;
      var params = this.match(url).params;
      var route  = this.findRouteByParams(params);
      var fn     = this.getFn(route, params, opts);

      if (R.is(Function, fn)) {
        return fn(args);
      }
    }
  }
}
<|endoftext|>


<commit_before>javascript: (function() {
    wpTextbox1.value = wpTextbox1.value.replace(/<!-- 在下一行填写你的理由\/在下一行填寫你的理由 -->\n?/, "").replace(/<!-- 以下文字请勿变更\/以下文字請勿變更 -->\n?/, "");
    if (confirm("Done?")) {
        wpTextbox1.value = wpTextbox1.value.replace(/\n*{{(Editprotected(?:\|.*?)?)}}\s*/i, "\n{{$1|ok=1|sign=--~~~~}}\n\n");
        wpSummary.value = wpSummary.value + " EP done";
    } else {
        wpTextbox1.value = wpTextbox1.value.replace(/\n*{{(Editprotected(?:\|.*?)?)}}\s*/i, "\n{{$1|no=1|sign=--~~~~}}\n\n");
        wpSummary.value = wpSummary.value + " EP not done";
    }
    if (confirm("Save?")) {
        wpSave.click();
    }
}
)();
<commit_msg>ep-done: Fix regex<commit_after>javascript: (function() {
    wpTextbox1.value = wpTextbox1.value.replace(/<!-- 在下一行填写你的理由\/在下一行填寫你的理由 -->\n?/, "").replace(/<!-- 以下文字请勿变更\/以下文字請勿變更 -->\n?/, "");
    if (confirm("Done?")) {
        wpTextbox1.value = wpTextbox1.value.replace(/\n*{{((?:Editprotected|EP)(?:\|.*?)?)}}\s*/i, "\n{{$1|ok=1|sign=--~~~~}}\n\n");
        wpSummary.value = wpSummary.value + " EP done";
    } else {
        wpTextbox1.value = wpTextbox1.value.replace(/\n*{{((?:Editprotected|EP)(?:\|.*?)?)}}\s*/i, "\n{{$1|no=1|sign=--~~~~}}\n\n");
        wpSummary.value = wpSummary.value + " EP not done";
    }
    if (confirm("Save?")) {
        wpSave.click();
    }
}
)();
<|endoftext|>


<commit_before>import { createElement } from './create-element.js';
import { parseArguments, isString, isNode } from './util.js';

const ns = 'http://www.w3.org/2000/svg';

const svgCache = {};

const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));

export const svg = (query, ...args) => {
  let element;

  if (isString(query)) {
    element = memoizeSVG(query).cloneNode(false);
  } else if (isNode(query)) {
    element = query.cloneNode(false);
  } else if (isFunction(query)) {
    element = new query(...args);
  } else {
    throw new Error('At least one argument required');
  }

  parseArguments(element, args);

  return element;
};

svg.extend = function (query) {
  const clone = memoizeSVG(query);

  return svg.bind(this, clone);
};

svg.ns = ns;

export const s = svg;
<commit_msg>Import isFunction<commit_after>import { createElement } from './create-element.js';
import { parseArguments, isString, isNode, isFunction } from './util.js';

const ns = 'http://www.w3.org/2000/svg';

const svgCache = {};

const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));

export const svg = (query, ...args) => {
  let element;

  if (isString(query)) {
    element = memoizeSVG(query).cloneNode(false);
  } else if (isNode(query)) {
    element = query.cloneNode(false);
  } else if (isFunction(query)) {
    element = new query(...args);
  } else {
    throw new Error('At least one argument required');
  }

  parseArguments(element, args);

  return element;
};

svg.extend = function (query) {
  const clone = memoizeSVG(query);

  return svg.bind(this, clone);
};

svg.ns = ns;

export const s = svg;
<|endoftext|>


<commit_before>import Color from './color';
import {CMYK} from './space';
import toRgb from '../converter/rgb';
import toHsl from '../converter/hsl';
import toHsv from '../converter/hsv';
import toCmy from '../converter/cmy';

const KEY = Object.freeze({
  'C': Symbol.for('c'),
  'M': Symbol.for('m'),
  'Y': Symbol.for('y'),
  'K': Symbol.for('k')
});

export default class Cmyk extends Color {
  constructor(c, m, y, k) {
    super(CMYK, [[KEY.C, c], [KEY.M, m], [KEY.Y, y], [KEY.K, k]]);
  }

  toBytes() {
    let k = this.k();
    if (k === 1) {
      return [0, 0, 0, 0];
    }
    return [
      Math.floor(0xFF * (1 - this.c()) * (1 - k)),
      Math.floor(0xFF * (1 - this.m()) * (1 - k)),
      Math.floor(0xFF * (1 - this.y()) * (1 - k)),
      0
    ];
  }

  isValid() {
    for (let value of this.values()) {
      if (!Number.isFinite(value)) {
        return false;
      }
      if (value < 0 || value > 1) {
        return false;
      }
    }
    return true;
  }

  rgb() {
    return toRgb(this);
  }

  hsl() {
    return toHsl(this);
  }

  hsv() {
    return toHsv(this);
  }

  cmy() {
    return toCmy(this);
  }

  cmyk() {
    return this;
  }

  c(value = null) {
    return this.access(KEY.C, value);
  }

  m(value = null) {
    return this.access(KEY.M, value);
  }

  y(value = null) {
    return this.access(KEY.Y, value);
  }

  k(value = null) {
    return this.access(KEY.K, value);
  }
}
<commit_msg>Modified implementation of CMYK to fit parent class<commit_after>import Space from './space';

const SPACE = 'CMYK';
const KEY_C = 'c';
const KEY_M = 'm';
const KEY_Y = 'y';
const KEY_K = 'k';

export default const CMYK = new class extends Space {
  constructor(c, m, y, k) {
    super(SPACE, [KEY_C, KEY_M, KEY_Y, KEY_K]);
  }

  isValid(color) {
    for (let value of color.values()) {
      if (!Number.isFinite(value)) {
        return false;
      }
      if (value < 0 || value > 1) {
        return false;
      }
    }
    return true;
  }

  cmy(c, m, y, k) {
    let delta = 1 - k;
    return [c, m, y].map(value => {
      value * delta + k;
    });
  }
}
<|endoftext|>


<commit_before>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Command line interface for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.Cli');

goog.require('sre.Debugger');
goog.require('sre.System');
goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Cli = function() {};

/**
 * Method for the command line interface of the Speech Rule Engine
 */
sre.Cli.prototype.commandLine = function() {
  var commander = sre.SystemExternal.commander;
  // These are necessary to avoid closure errors.
  /** @type {!string} */
  // commander.domain is already in use by the commander module!
  commander.dom = '';
  /** @type {!boolean} */
  commander.enumerate = false;
  /** @type {!string} */
  commander.input = '';
  /** @type {!string} */
  commander.log = '';
  /** @type {!string} */
  commander.output = '';
  /** @type {!boolean} */
  commander.semantics = false;
  /** @type {!string} */
  commander.style = '';
  /** @type {!boolean} */
  commander.verbose = false;

  commander.version(sre.System.getInstance().version).
      option('-d, --dom [name]', 'Domain or subject area [name]').
      option('-e, --enumerate', 'Enumerates available domains and styles').
      option('-i, --input [name]', 'Input file [name]').
      option('-l, --log [name]', 'Log file [name]').
      option('-o, --output [name]', 'Output file [name]').
      option('-s, --semantics', 'Switch on semantics interpretation').
      option('-t, --style [name]', 'Speech style [name]').
      option('-v, --verbose', 'Verbose mode').
      parse(process.argv);
  if (commander.enumerate) {
    sre.System.getInstance().setupEngine({});
    var output = 'Domain options: ' +
        sre.Engine.getInstance().allDomains.sort().join(', ') +
        'Style options:  ' +
        sre.Engine.getInstance().allStyles.sort().join(', ');
    console.log(output);
    return;
  }
  sre.System.getInstance().setupEngine(
      {
        'semantics': commander.semantics,
        'domain': commander.dom,
        'style': commander.style
      });
  if (commander.verbose) {
    sre.Debugger.getInstance().init(commander.log);
  }
  if (commander.input) {
    sre.System.getInstance().processFile(commander.input, commander.output);
  }
};

(new sre.Cli()).commandLine();
<commit_msg>Better command line error handling.<commit_after>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Command line interface for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.Cli');

goog.require('sre.Debugger');
goog.require('sre.System');
goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Cli = function() {};

/**
 * Method for the command line interface of the Speech Rule Engine
 */
sre.Cli.prototype.commandLine = function() {
  var commander = sre.SystemExternal.commander;
  // These are necessary to avoid closure errors.
  /** @type {!string} */
  // commander.domain is already in use by the commander module!
  commander.dom = '';
  /** @type {!boolean} */
  commander.enumerate = false;
  /** @type {!string} */
  commander.input = '';
  /** @type {!string} */
  commander.log = '';
  /** @type {!string} */
  commander.output = '';
  /** @type {!boolean} */
  commander.semantics = false;
  /** @type {!string} */
  commander.style = '';
  /** @type {!boolean} */
  commander.verbose = false;

  commander.version(sre.System.getInstance().version).
      option('-d, --dom [name]', 'Domain or subject area [name]').
      option('-e, --enumerate', 'Enumerates available domains and styles').
      option('-i, --input [name]', 'Input file [name]').
      option('-l, --log [name]', 'Log file [name]').
      option('-o, --output [name]', 'Output file [name]').
      option('-s, --semantics', 'Switch on semantics interpretation').
      option('-t, --style [name]', 'Speech style [name]').
      option('-v, --verbose', 'Verbose mode').
      parse(process.argv);
  try {
    if (commander.enumerate) {
      sre.System.getInstance().setupEngine({});
      var output = 'Domain options: ' +
            sre.Engine.getInstance().allDomains.sort().join(', ') +
            '\nStyle options:  ' +
            sre.Engine.getInstance().allStyles.sort().join(', ');
      console.log(output);
      process.exit(0);
    }
    sre.System.getInstance().setupEngine(
      {
        'semantics': commander.semantics,
        'domain': commander.dom,
        'style': commander.style
      });
    if (commander.verbose) {
      sre.Debugger.getInstance().init(commander.log);
    }
    if (commander.input) {
      sre.System.getInstance().processFile(commander.input, commander.output);
    }
  } catch (err) {
    console.log(err.message);
    process.exit(1);
  }
  process.exit(0);
};

(new sre.Cli()).commandLine();
<|endoftext|>


<commit_before>"use strict";

// For conditions of distribution and use, see copyright notice in LICENSE

/*
 *      @author Tapani Jamsa
 *      Date: 2014
 */

var app;
// var carSize; // TODO debug remove
var ground_material;

function init() {
    app = new CarApp();
    var host = "10.10.2.7"; // hostname of the Tundra server
    var port = 2345; // and port to the server

    app.start();

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    // Custom app specific properties
    app.dataConnection.loginData = {
        "name": Date.now().toString() + getRandomInt(0, 2000000).toString()
    };

    // STATS
    app.physics_stats = new Stats();
    app.physics_stats.domElement.style.position = 'absolute';
    app.physics_stats.domElement.style.bottom = '50px';
    app.physics_stats.domElement.style.zIndex = 100;
    app.viewer.container.appendChild(app.physics_stats.domElement);

    // GROUND

    ground_material = Physijs.createMaterial(
        new THREE.MeshLambertMaterial({
        map: THREE.ImageUtils.loadTexture('images/rocks.jpg')
    }),
        0.8, // high friction
    .3 // low restitution
    );
    ground_material.map.wrapS = ground_material.map.wrapT = THREE.RepeatWrapping;
    ground_material.map.repeat.set(3, 3);

    var ground = new Physijs.BoxMesh(
        new THREE.CubeGeometry(400, 1, 400),
        ground_material,
        0 // mass
    );
    ground.position.set(0, -3, 0);
    // ground.rotation.set(0,0,0.2);
    ground.receiveShadow = true;
    app.viewer.scene.add(ground);

    // WALLS

    var wall = new Physijs.BoxMesh(
        new THREE.CubeGeometry(1, 25, 50),
        ground_material,
        0 // mass
    );
    wall.position.set(-25, 0, 0);
    wall.receiveShadow = true;
    app.viewer.scene.add(wall);

    var wall = new Physijs.BoxMesh(
        new THREE.CubeGeometry(1, 25, 50),
        ground_material,
        0 // mass
    );
    wall.position.set(25, 0, 0);
    wall.receiveShadow = true;
    app.viewer.scene.add(wall);

    var wall = new Physijs.BoxMesh(
        new THREE.CubeGeometry(50, 25, 1),
        ground_material,
        0 // mass
    );
    wall.position.set(0, 0, -25);
    wall.receiveShadow = true;
    app.viewer.scene.add(wall);

    var wall = new Physijs.BoxMesh(
        new THREE.CubeGeometry(50, 5, 1),
        ground_material,
        0 // mass
    );
    wall.position.set(0, 0, 25);
    wall.receiveShadow = true;
    app.viewer.scene.add(wall);

    // carSize = new Physijs.BoxMesh(
    //     new THREE.CubeGeometry(1, 4, 1),
    //     ground_material,
    //     0 // mass
    // );
    // carSize.position.set(0, 0, 0);
    // carSize.receiveShadow = true;
    // app.viewer.scene.add(carSize);

    // Car
    app.car = new Car(app, new THREE.Vector3( 0, 2, 0));

    // CAMERA
    app.viewer.camera.position.set(0, 50, 60);
    app.viewer.camera.lookAt(new THREE.Vector3());

    // // FREE LOOK
    // var freeLookCtrl = new THREE.FreeLookControls(app.viewer.camera, app.viewer.renderer.domElement);
    // app.scene.add(freeLookCtrl.getObject());
    // // An object in freeLookCtrl that carries the camera. Set it's position instead of setting camera position directly
    // freeLookCtrl.getObject().position.set(0, 8.50, 28.50);

    app.connect(host, port);
}

function CarApp() {
    Application.call(this); // Super class
}

CarApp.prototype = new Application();

CarApp.prototype.constructor = CarApp;

CarApp.prototype.createViewer = function() {
    return new PhysijsView();
};

CarApp.prototype.logicUpdate = function(dt) {

    // PHYSICS

    this.viewer.scene.simulate(); // run physics

    if (this.physics_stats) {
        this.physics_stats.update();
    }

};

init();
<commit_msg>Refactor and add ramps<commit_after>"use strict";

// For conditions of distribution and use, see copyright notice in LICENSE

/*
 *      @author Tapani Jamsa
 *      Date: 2014
 */

var app;
// var carSize; // TODO debug remove
var ground_material;

function init() {
    app = new CarApp();
    var host = "10.10.2.7"; // hostname of the Tundra server
    var port = 2345; // and port to the server

    app.start();

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    // Custom app specific properties
    app.dataConnection.loginData = {
        "name": Date.now().toString() + getRandomInt(0, 2000000).toString()
    };

    // STATS
    app.physics_stats = new Stats();
    app.physics_stats.domElement.style.position = 'absolute';
    app.physics_stats.domElement.style.bottom = '50px';
    app.physics_stats.domElement.style.zIndex = 100;
    app.viewer.container.appendChild(app.physics_stats.domElement);

    function createElement(pos, rot, scale) {
        var element = new Physijs.BoxMesh(
            new THREE.CubeGeometry(scale.x, scale.y, scale.z),
            ground_material,
            0 // mass
        );
        element.position.set(pos.x, pos.y, pos.z);
        element.rotation.set(rot.x, rot.y, rot.z);
        element.receiveShadow = true;
        app.viewer.scene.add(element);
    }

    // GROUND
    ground_material = Physijs.createMaterial(
        new THREE.MeshLambertMaterial({
        map: THREE.ImageUtils.loadTexture('images/rocks.jpg')
    }),
        0.8, // high friction
    .3 // low restitution
    );
    ground_material.map.wrapS = ground_material.map.wrapT = THREE.RepeatWrapping;
    ground_material.map.repeat.set(3, 3);
    createElement({x: 0, y:-3, z:0}, {x: 0, y:0, z:0}, {x: 400, y:1, z:400});

    // RAMPS
    createElement({x: 0, y:-3, z:-10}, {x: -0.2, y:0, z:0}, {x: 10, y:1, z:13});
    createElement({x: 10, y:-3, z:-10}, {x: -0.5, y:0, z:0}, {x: 10, y:1, z:25});

    // WALLS
    createElement({x: -25, y:0, z:-25}, {x: 0, y:0, z:0}, {x: 1, y:25, z:100});
    createElement({x: 25, y:0, z:-25}, {x: 0, y:0, z:0}, {x: 1, y:25, z:100});
    createElement({x: 0, y:0, z:-75}, {x: 0, y:0, z:0}, {x: 50, y:25, z:1});
    createElement({x: 0, y:0, z:25}, {x: 0, y:0, z:0}, {x: 50, y:5, z:1});

    // Car
    app.car = new Car(app, new THREE.Vector3(0, 2, -60));

    // CAMERA
    app.viewer.camera.position.set(0, 40, 60);
    app.viewer.camera.lookAt(new THREE.Vector3());

    // // FREE LOOK
    // var freeLookCtrl = new THREE.FreeLookControls(app.viewer.camera, app.viewer.renderer.domElement);
    // app.scene.add(freeLookCtrl.getObject());
    // // An object in freeLookCtrl that carries the camera. Set it's position instead of setting camera position directly
    // freeLookCtrl.getObject().position.set(0, 8.50, 28.50);

    app.connect(host, port);
}

function CarApp() {
    Application.call(this); // Super class
}

CarApp.prototype = new Application();

CarApp.prototype.constructor = CarApp;

CarApp.prototype.createViewer = function() {
    return new PhysijsView();
};

CarApp.prototype.logicUpdate = function(dt) {

    // PHYSICS

    this.viewer.scene.simulate(); // run physics

    if (this.physics_stats) {
        this.physics_stats.update();
    }

};

init();
<|endoftext|>


<commit_before><commit_msg>fix example require<commit_after><|endoftext|>


<commit_before>import defaults from "./config"
import generate from "babel-generator"
import {parse} from "babylon"
import {produce,consume,kit} from "estransducers"
import * as Kit from "./kit"
// import * as fs from "fs"
import * as R from "ramda"
import * as path from "path"
import * as T from "./transform"
import * as Policy from "./policy"
import {sync as findup} from "findup"

const CONFIG_NAME = "effectfuljs-config.json"

export const tok = Kit.tok, configDiff = Policy.configDiff,
  profile = Policy.profile, defaultGensTransform = T.defaultGensTransform,
  injectFuncOpts = T.injectFuncOpts, injectOpts = T.injectOpts

function convOptions(v, fn) {
  var f
  if (v == null || v === true)
    v = {}
  else {
    v = {override:v,require:v.require,profile:v.profile}
  }
  if (v.substr != null)
    v = {profile: v}
  v = Object.assign({}, defaults, v)
  if (fn == null)
    fn = v.filename
  if (fn != null) {
    v.parser.source = v.filename = fn
    try {
      f = findup.sync(path.dirname(fn), CONFIG_NAME)
      if (defaults.versbose)
        console.log(`using config ${f}`)
    } catch (error) {
      if (defaults.verbose)
        console.log(`looking for ${CONFIG_NAME} failed: ${error}`)
    }
    if (f != null)
      Object.assign(v, require(path.join(f, CONFIG_NAME)))
  }
  return v
}

export function transform(ast, opts) {
  return T.main(ast,convOptions(opts))
}

export default transform

export function babelPreset(opts) {
  opts = convOptions(opts)
  return T.babelPreset(opts)
}
<commit_msg>babel preset options fix<commit_after>import defaults from "./config"
import generate from "babel-generator"
import {parse} from "babylon"
import {produce,consume,kit} from "estransducers"
import * as Kit from "./kit"
// import * as fs from "fs"
import * as R from "ramda"
import * as path from "path"
import * as T from "./transform"
import * as Policy from "./policy"
import {sync as findup} from "findup"

const CONFIG_NAME = "effectfuljs-config.json"

export const tok = Kit.tok, configDiff = Policy.configDiff,
  profile = Policy.profile, defaultGensTransform = T.defaultGensTransform,
  injectFuncOpts = T.injectFuncOpts, injectOpts = T.injectOpts

function convOptions(v, fn) {
  var f
  if (v == null || v === true)
    v = {}
  else {
    v = Object.assign({},v,{override:v})
  }
  if (v.substr != null)
    v = {profile: v}
  v = Object.assign({}, defaults, v)
  if (fn == null)
    fn = v.filename
  if (fn != null) {
    v.parser.source = v.filename = fn
    try {
      f = findup.sync(path.dirname(fn), CONFIG_NAME)
      if (defaults.versbose)
        console.log(`using config ${f}`)
    } catch (error) {
      if (defaults.verbose)
        console.log(`looking for ${CONFIG_NAME} failed: ${error}`)
    }
    if (f != null)
      Object.assign(v, require(path.join(f, CONFIG_NAME)))
  }
  return v
}

export function transform(ast, opts) {
  return T.main(ast,convOptions(opts))
}

export default transform

export function babelPreset(opts) {
  opts = convOptions(opts)
  return T.babelPreset(opts)
}
<|endoftext|>


<commit_before>'use strict';

const {BrowserWindow, app, Menu} = require('electron');
const electronLocalshortcut = require('.');

app.on('ready', () => {
	const win = new BrowserWindow({});
	const win2 = new BrowserWindow({});

	// Should raise a warning in console
	try {
		electronLocalshortcut.register(win, 'C+C', () => {});
	} catch {}

	electronLocalshortcut.register(win, 'CmdOrCtrl+Z', () => {
		process.stdout.write('A\n');
	});

	electronLocalshortcut.register(win, 'Ctrl+B', () => {
		process.stdout.write('B\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+A', () => {
		process.stdout.write('A2\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+B', () => {
		process.stdout.write('B2\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+C', () => {
		process.stdout.write('C2\n');
	});

	electronLocalshortcut.register(win2, ['Ctrl+R', 'F5'], () => {
		process.stdout.write('Refresh\n');
	});

	const template = [
		{
			label: 'test',
			submenu: [
				{
					label: 'Unregister all shortcuts',
					click() {
						electronLocalshortcut.unregisterAll(win);
					}
				}
			]
		}
	];

	win.setMenu(Menu.buildFromTemplate(template));
	win.loadURL('about://blank');
	win.show();

	const template2 = [
		{
			label: 'test',
			submenu: [
				{
					label: 'Unregister C2',
					click() {
						electronLocalshortcut.unregister(win2, 'Ctrl+C');
					}
				},
				{
					label: 'Register unvalid shortcut',
					click() {
						electronLocalshortcut.unregister(win2, 'Ctrl+Alt');
					}
				},
				{
					label: 'Register C2',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+C', () => {
							process.stdout.write('C2\n');
						});
					}
				},
				{
					label: 'Disable shortcuts',
					click() {
						electronLocalshortcut.disableAll(win2);
					}
				},
				{
					label: 'Enable shortcuts',
					click() {
						electronLocalshortcut.enableAll(win2);
					}
				},
				{
					label: 'Check C2',
					click() {
						const isRegistered = electronLocalshortcut.isRegistered(
							win2,
							'Ctrl+C'
						);
						process.stdout.write(`${isRegistered}\n`);
					}
				},
				{
					label: 'Check existing global shortcut',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+E', () => {
							console.log('Control E !');
						});
					}
				},
				{
					label: 'Check Space',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+Space', () => {
							console.log('Ctrl+Space!');
						});
					}
				}
			]
		},
		{
			label: 'test all window',
			submenu: [
				{
					label: 'Unregister ALL',
					click() {
						electronLocalshortcut.unregister('Alt+A');
					}
				},
				{
					label: 'Unregister any ALL',
					click() {
						electronLocalshortcut.unregisterAll();
					}
				},
				{
					label: 'Register ALL',
					click() {
						electronLocalshortcut.register('Alt+A', () => {
							process.stdout.write('ALL\n');
						});
					}
				},
				{
					label: 'Check ALL',
					click() {
						const isRegistered = electronLocalshortcut.isRegistered('Alt+A');
						process.stdout.write(`${isRegistered}\n`);
					}
				}
			]
		}
	];

	win2.setMenu(Menu.buildFromTemplate(template2));
	win2.loadURL('about://blank');
	win2.show();
	win2.openDevTools();
	win2.webContents.executeJavaScript(`
		document.body.innerHTML = '<textarea></textarea>';
		document.addEventListener('keydown', e => {
			console.log(e);
		});
	`);
});
<commit_msg>test array<commit_after>'use strict';

const {BrowserWindow, app, Menu} = require('electron');
const electronLocalshortcut = require('.');

app.on('ready', () => {
	const win = new BrowserWindow({});
	const win2 = new BrowserWindow({});

	// Should raise a warning in console
	try {
		electronLocalshortcut.register(win, 'C+C', () => {});
	} catch {}

	electronLocalshortcut.register(win, 'CmdOrCtrl+Z', () => {
		process.stdout.write('A\n');
	});

	electronLocalshortcut.register(win, 'Ctrl+B', () => {
		process.stdout.write('B\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+A', () => {
		process.stdout.write('A2\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+B', () => {
		process.stdout.write('B2\n');
	});

	electronLocalshortcut.register(win2, 'Ctrl+C', () => {
		process.stdout.write('C2\n');
	});

	electronLocalshortcut.register(win2, ['Ctrl+R', 'F5'], () => {
		process.stdout.write('Refresh\n');
	});

	const template = [
		{
			label: 'test',
			submenu: [
				{
					label: 'Unregister all shortcuts',
					click() {
						electronLocalshortcut.unregisterAll(win);
					}
				}
			]
		}
	];

	win.setMenu(Menu.buildFromTemplate(template));
	win.loadURL('about://blank');
	win.show();

	const template2 = [
		{
			label: 'test',
			submenu: [
				{
					label: 'Unregister C2',
					click() {
						electronLocalshortcut.unregister(win2, 'Ctrl+C');
					}
				},
				{
					label: 'Register unvalid shortcut',
					click() {
						electronLocalshortcut.unregister(win2, 'Ctrl+Alt');
					}
				},
				{
					label: 'Register C2',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+C', () => {
							process.stdout.write('C2\n');
						});
					}
				},
				{
					label: 'Disable shortcuts',
					click() {
						electronLocalshortcut.disableAll(win2);
					}
				},
				{
					label: 'Enable shortcuts',
					click() {
						electronLocalshortcut.enableAll(win2);
					}
				},
				{
					label: 'Check C2',
					click() {
						const isRegistered = electronLocalshortcut.isRegistered(
							win2,
							'Ctrl+C'
						);
						process.stdout.write(`${isRegistered}\n`);
					}
				},
				{
					label: 'Check existing global shortcut',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+E', () => {
							console.log('Control E !');
						});
					}
				},
				{
					label: 'Check Space',
					click() {
						electronLocalshortcut.register(win2, 'Ctrl+Space', () => {
							console.log('Ctrl+Space!');
						});
					}
				},
				{
					label: 'Cmd+S & Ctrl+S',
					click() {
						electronLocalshortcut.register(win2, ['Alt+S', 'Ctrl+S'], () => {
							console.log('use array');
						});
					}
				}

			]
		},
		{
			label: 'test all window',
			submenu: [
				{
					label: 'Unregister ALL',
					click() {
						electronLocalshortcut.unregister('Alt+A');
					}
				},
				{
					label: 'Unregister any ALL',
					click() {
						electronLocalshortcut.unregisterAll();
					}
				},
				{
					label: 'Register ALL',
					click() {
						electronLocalshortcut.register('Alt+A', () => {
							process.stdout.write('ALL\n');
						});
					}
				},
				{
					label: 'Check ALL',
					click() {
						const isRegistered = electronLocalshortcut.isRegistered('Alt+A');
						process.stdout.write(`${isRegistered}\n`);
					}
				}
			]
		}
	];

	win2.setMenu(Menu.buildFromTemplate(template2));
	win2.loadURL('about://blank');
	win2.show();
	win2.openDevTools();
	win2.webContents.executeJavaScript(`
		document.body.innerHTML = '<textarea></textarea>';
		document.addEventListener('keydown', e => {
			console.log(e);
		});
	`);
});
<|endoftext|>


<commit_before>var Canvas = require('./');
var line = require('bresenham');

var c = new Canvas(160, 160);

function draw() {
  c.clear();
  var t = new Date();
  var sin = function(i, l) {
    return Math.floor(Math.sin(i*2*Math.PI)*l+80);
  }, cos = function(i, l) {
    return Math.floor(Math.cos(i*2*Math.PI)*l+80);
  };
  line(80, 80, sin(t.getHours()/24, 30), 160-cos(t.getHours()/24, 30), c.set.bind(c));
  line(80, 80, sin(t.getMinutes()/60, 50), 160-cos(t.getMinutes()/60, 50), c.set.bind(c));
  line(80, 80, sin(t.getSeconds()/60+(+t%1000)/60000, 75), 160-cos(t.getSeconds()/60+(+t%1000)/60000, 75), c.set.bind(c));
  setTimeout(draw, 1000/60);
  console.log(c.frame());
}

draw();
<commit_msg>use process.stdout.write instead of console.log<commit_after>var Canvas = require('./');
var line = require('bresenham');

var c = new Canvas(160, 160);

function draw() {
  c.clear();
  var t = new Date();
  var sin = function(i, l) {
    return Math.floor(Math.sin(i*2*Math.PI)*l+80);
  }, cos = function(i, l) {
    return Math.floor(Math.cos(i*2*Math.PI)*l+80);
  };
  line(80, 80, sin(t.getHours()/24, 30), 160-cos(t.getHours()/24, 30), c.set.bind(c));
  line(80, 80, sin(t.getMinutes()/60, 50), 160-cos(t.getMinutes()/60, 50), c.set.bind(c));
  line(80, 80, sin(t.getSeconds()/60+(+t%1000)/60000, 75), 160-cos(t.getSeconds()/60+(+t%1000)/60000, 75), c.set.bind(c));
  setTimeout(draw, 1000/60);
  process.stdout.write(c.frame());
}

draw();
<|endoftext|>


<commit_before>'use strict';

var input, regex, extra;
var parth = require('./.')();

// #set
input = [
  '/',
  '/page',
  '/page/:number(\\d+)',
  'get /',
  'get /page',
  'get /page/:number(\\d+)',
  'get /:page(\\w+)/number',
  'get /:page(\\w+)/:number(\\d+)',
  '(get|post) /page/number',
  '(get|post) /:page(\\w+)/number',
  '(get|post) /:page(\\w+)/:Number(\\w+)',
  'get /page/number',
  ':n(get|post) /:page(\\w+)/:view(\\d+)',
  '(get|post) /:page(\\w+)/:view(\\d+)',
  '1', '2', '1 2',
  'obj.path',
  'obj.:path(\\S+).:number(\\d+)',
  'obj.path.:here',
  'obj.(prop|path).:here',
  ':obj.(method|prop).:here'

];

console.log('\n -- parth.add -- ');
input.forEach(function(stem, index){
  extra = { }; regex = parth.add(stem, extra);
  console.log(' input =', stem);
  console.log('return =', regex);
  console.log((input[index+1] ? ' -- ' : ''));
});

// #get
input = [
  '1',
  '2',
  '1 2',
  'obj.path.10',
  'obj.10.prop',
  'obj.10.10',
  'array.method.prop',
  'get /weekend/baby?query=string#hash user.10.beers now',
  'get /user/view/#hash',
  'post /user/page/photo?query=name&path=tree#hash'
];

console.log(' -- parth.match -- ');
input.forEach(function(stem, index){
  extra = { }; regex = parth.match(stem, extra);
  console.log(' input =', stem);
  console.log('return =', regex);
  console.log(' extra =', extra);
  console.log((input[index+1] ? ' -- ' : '' ));
});

if(process.argv.indexOf('-l') < 0){ return ; }
Object.keys(parth).forEach(function(prop){
  console.log(parth[prop]);
  console.log(' --\n');
});

parth.regex.forEach(function(re){
  console.log(re.path);
});
<commit_msg>tweak<commit_after>'use strict';

var input, regex, extra;
var parth = require('./.')();

// #set
input = [
  '/',
  '/page',
  '/page/:number(\\d+)',
  'get /',
  'get /page',
  'get /page/:number(\\d+)',
  'get /:page(\\w+)/number',
  'get /:page(\\w+)/:number(\\d+)',
  '(get|post) /page/number',
  '(get|post) /:page(\\w+)/number',
  '(get|post) /:page(\\w+)/:Number(\\d+)',
  'get /page/number',
  '(get|post) /:page(\\w+)/:view([^./]+)',
  '1', '2', '1 2',
  'obj.path',
  'obj.:path(\\S+).:number(\\d+)',
  'obj.path.:here',
  'obj.(prop|path).:here',
  ':obj.(method|prop).:here'

];

console.log('\n -- parth.add -- ');
input.forEach(function(stem, index){
  extra = { }; regex = parth.add(stem, extra);
  console.log(' input =', stem);
  console.log('return =', regex);
  console.log((input[index+1] ? ' -- ' : ''));
});

// #get
input = [
  '1',
  '2',
  '1 2',
  'obj.path.10',
  'obj.10.prop',
  'obj.10.10',
  'array.method.prop',
  'get /weekend/baby?query=string#hash user.10.beers now',
  'get /user/view/#hash',
  'post /user/page/photo?query=name&path=tree#hash'
];

console.log(' -- parth.match -- ');
input.forEach(function(stem, index){
  extra = { }; regex = parth.match(stem, extra);
  console.log(' input =', stem);
  console.log('return =', regex);
  console.log(' extra =', extra);
  console.log((input[index+1] ? ' -- ' : '' ));
});

if(process.argv.indexOf('-l') < 0){ return ; }
Object.keys(parth).forEach(function(prop){
  console.log(parth[prop]);
  console.log(' --\n');
});

parth.regex.forEach(function(re){
  console.log(re.path);
});
<|endoftext|>


<commit_before>let address = document.getElementById('connect-address'),
  connect = document.getElementById('connect'),
  buttonConnect = document.getElementById('connect-button');

let loginShown = true;

// Set function to be called on NetworkTables connect. Not implemented.
//NetworkTables.addWsConnectionListener(onNetworkTablesConnection, true);

// Set function to be called when robot dis/connects
NetworkTables.addRobotConnectionListener(onRobotConnection, false);

// Sets function to be called when any NetworkTables key/value changes
//NetworkTables.addGlobalListener(onValueChanged, true);

// Function for hiding the connect box
onkeydown = key => {
  if (key.key === 'Escape') {
    document.body.classList.toggle('login', false);
    loginShown = false;
  }
};

/**
 * Function to be called when robot connects
 * @param {boolean} connected
 */
function onRobotConnection(connected) {
  var state = connected ? 'Robot connected!' : 'Robot disconnected.';
  console.log(state);
  ui.robotState.textContent = state;

  buttonConnect.onclick = () => {
    document.body.classList.toggle('login', true);
    loginShown = true;
  };
  if (connected) {
    // On connect hide the connect popup
    document.body.classList.toggle('login', false);
    loginShown = false;
  } else if (loginShown) {
    setLogin();
  }
}
function setLogin() {
  // Add Enter key handler
  // Enable the input and the button
  address.disabled = connect.disabled = false;
  connect.textContent = 'Connect';
  // Add the default address and select xxxx
  address.value = 'roborio-xxxx-frc.local';
  address.focus();
  address.setSelectionRange(8, 12);
}
// On click try to connect and disable the input and the button
connect.onclick = () => {
  ipc.send('connect', address.value);
  address.disabled = connect.disabled = true;
  connect.textContent = 'Connecting...';
};
address.onkeydown = ev => {
  if (ev.key === 'Enter') {
    connect.click();
    ev.preventDefault();
    ev.stopPropagation();
  }
};

// Show login when starting
document.body.classList.toggle('login', true);
setLogin();
<commit_msg>Fix connect modal issues<commit_after>let address = document.getElementById('connect-address'),
  connect = document.getElementById('connect'),
  buttonConnect = document.getElementById('connect-button');

let loginShown = true;

// Set function to be called on NetworkTables connect. Not implemented.
//NetworkTables.addWsConnectionListener(onNetworkTablesConnection, true);

// Set function to be called when robot dis/connects
NetworkTables.addRobotConnectionListener(onRobotConnection, false);

// Sets function to be called when any NetworkTables key/value changes
//NetworkTables.addGlobalListener(onValueChanged, true);

// Function for hiding the connect box
onkeydown = key => {
  if (key.key === 'Escape') {
    document.body.classList.toggle('login', false);
    loginShown = false;
  }
};

buttonConnect.onclick = () => {
  document.body.classList.toggle('login', true);
  loginShown = true;

  setLogin();
};

/**
 * Function to be called when robot connects
 * @param {boolean} connected
 */
function onRobotConnection(connected) {
  var state = connected ? 'Robot connected!' : 'Robot disconnected.';
  console.log(state);
  ui.robotState.textContent = state;

  if (connected) {
    // On connect hide the connect popup
    document.body.classList.toggle('login', false);
    loginShown = false;
  } else if (loginShown) {
    setLogin();
  }
}
function setLogin() {
  // Add Enter key handler
  // Enable the input and the button
  address.disabled = connect.disabled = false;
  connect.textContent = 'Connect';
  // Add the default address and select xxxx
  address.value = 'roborio-xxxx-frc.local';
  address.focus();
  address.setSelectionRange(8, 12);
}
// On click try to connect and disable the input and the button
connect.onclick = () => {
  ipc.send('connect', address.value);
  address.disabled = connect.disabled = true;
  connect.textContent = 'Connecting...';
};
address.onkeydown = ev => {
  if (ev.key === 'Enter') {
    connect.click();
    ev.preventDefault();
    ev.stopPropagation();
  }
};

// Show login when starting
document.body.classList.toggle('login', true);
setLogin();
<|endoftext|>