<commit_before>/*
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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.
 */

if (!('inert' in HTMLElement.prototype)) {
  Object.defineProperty(HTMLElement.prototype, 'inert', {
    enumerable: true,

    /**
     * @return {boolean}
     * @this {Element}
     */
    get: function() { return this.hasAttribute('inert'); },

    /**
     * @param {boolean} inert
     * @this {Element}
     */
    set: function(inert) {
      if (inert) {
        this.setAttribute('inert', '');
      } else {
        this.removeAttribute('inert');
      }
    }
  });

  window.addEventListener('load', function() {
    function applyStyle(css) {
      var style = document.createElement('style');
      style.type = 'text/css';
      if (style.styleSheet) {
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(document.createTextNode(css));
      }
      document.body.appendChild(style);
    }
    var css = "/*[inert]*/*[inert]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none}";
    applyStyle(css);

    /**
     * Sends a fake tab event. This is only supported by some browsers.
     *
     * @param {boolean=} opt_shiftKey whether to send this tab with shiftKey
     */
    function dispatchTabEvent(opt_shiftKey) {
      var ev = null;
      try {
        ev = new KeyboardEvent('keydown', {
          keyCode: 9,
          which: 9,
          key: 'Tab',
          code: 'Tab',
          keyIdentifier: 'U+0009',
          shiftKey: !!opt_shiftKey,
          bubbles: true
        });
      } catch (e) {
        try {
          // Internet Explorer
          ev = document.createEvent('KeyboardEvent');
          ev.initKeyboardEvent(
            'keydown',
            true,
            true,
            window,
            'Tab',
            0,
            opt_shiftKey ? 'Shift' : '',
            false,
            'en'
          )
        } catch (e) {}
      }
      if (ev) {
        try {
          Object.defineProperty(ev, 'keyCode', { value: 9 });
        } catch (e) {}
        document.dispatchEvent(ev);
      }
    }

    /**
     * Finds the nearest adjacent Element in the specified direction. If this is
     * negative, this will include the parent element.
     *
     * @param {!Element} e to find adjacent of
     * @param {number} dir to move in (+ve or -ve)
     * @param {!Element=} opt_initial to prevent descent into
     * @return {Element} adjacent element
     */
    function walkElementTree(e, dir, opt_initial) {
      if (dir < 0) {
        if (e.previousElementSibling) {
          e = e.previousElementSibling;
          while (e.lastElementChild) {
            e = e.lastElementChild;
          }
          return e;
        }
        return e.parentElement;
      }
      if (e != opt_initial && e.firstElementChild) {
        return e.firstElementChild;
      }
      while (e) {
        if (e.nextElementSibling) {
          return e.nextElementSibling;
        }
        e = /** @type {!Element} */ (e.parentElement);
      }
      return null;
    }

    /**
     * Determines whether the specified element is inert, and returns the element
     * which caused this state. This is limited to, but may include, the body
     * element.
     *
     * @param {Element} e to check
     * @return {Element} element is made inert by, if any
     */
    function madeInertBy(e) {
      while (e && e !== document.documentElement) {
        if (e.hasAttribute('inert')) {
          return e;
        }
        e = e.parentElement;
      }
      return null;
    }

    /**
     * Finds the nearest shadow root from an element that's within said shadow root.
     *
     * TODO(samthor): We probably want to find the highest shadow root.
     *
     * @param {Element} e to check
     * @return {Node} shadow root, if any
     */
    var findShadowRoot = function(e) { return null; };
    if (window.ShadowRoot) {
      findShadowRoot = function(e) {
        while (e && e !== document.documentElement) {
          if (e instanceof window.ShadowRoot) { return e; }
          e = e.parentNode;
        }
        return null;
      }
    }

    /**
     * Returns the target of the passed event. If there's a path (shadow DOM only), then prefer it.
     *
     * @param {!Event} event
     * @return {Element} target of event
     */
    function targetForEvent(event) {
      var p = event.path;
      return  /** @type {Element} */ (p && p[0] || event.target);
    }

    // Hold onto the last tab direction: next (tab) or previous (shift-tab). This
    // can be used to step over inert elements in the correct direction. Mouse
    // or non-tab events should reset this and inert events should focus nothing.
    var lastTabDirection = 0;
    document.addEventListener('keydown', function(ev) {
      if (ev.keyCode === 9) {
        lastTabDirection = ev.shiftKey ? -1 : +1;
      } else {
        lastTabDirection = 0;
      }
    });
    document.addEventListener('mousedown', function(ev) {
      lastTabDirection = 0;
    });

    // Retain the currently focused shadowRoot.
    var focusedShadowRoot = null;
    function updateFocusedShadowRoot(root) {
      if (root == focusedShadowRoot) { return; }
      if (focusedShadowRoot) {
        if (!(focusedShadowRoot instanceof window.ShadowRoot)) {
          throw new Error('not shadow root: ' + focusedShadowRoot);
        }
        focusedShadowRoot.removeEventListener('focusin', shadowFocusHandler, true);  // remove
      }
      if (root) {
        root.addEventListener('focusin', shadowFocusHandler, true);  // add
      }
      focusedShadowRoot = root;
    }

    /**
     * Focus handler on a Shadow DOM host. This traps focus events within that root.
     *
     * @param {!Event} ev
     */
    function shadowFocusHandler(ev) {
      // ignore "direct" focus, we only want shadow root focus
      var last = ev.path[ev.path.length - 1];
      if (last === /** @type {*} */ (window)) { return; }
      sharedFocusHandler(targetForEvent(ev));
      ev.preventDefault();
      ev.stopPropagation();
    }

    /**
     * Called indirectly by both the regular focus handler and Shadow DOM host focus handler. This
     * is the bulk of the polyfill which prevents focus.
     *
     * @param {Element} target focused on
     */
    function sharedFocusHandler(target) {
      var inertElement = madeInertBy(target);
      if (!inertElement) { return; }

      // If the page has been tabbed recently, then focus the next element
      // in the known direction (if available).
      if (document.hasFocus() && lastTabDirection !== 0) {
        function getFocused() {
          return (focusedShadowRoot || document).activeElement;
        }

        // Send a fake tab event to enumerate through the browser's view of
        // focusable elements. This is supported in some browsers (not Firefox).
        var previous = getFocused();
        dispatchTabEvent(lastTabDirection < 0 ? true : false);
        if (previous != getFocused()) { return; }

        // Otherwise, enumerate through adjacent elements to find the next
        // focusable element. This won't respect any custom tabIndex.
        var candidate = inertElement;
        for (;;) {
          candidate = walkElementTree(candidate, lastTabDirection, inertElement);
          if (!candidate) { break; }
          if (!candidate.focus) { continue; }
          if (!(candidate.tabIndex < 0)) {
            candidate.focus();
            if (getFocused() !== previous) { return; }
          }
        }

        // FIXME: If a focusable element can't be found here, it's likely to mean
        // that this is the start or end of the page. Blurring is then not quite
        // right, as it prevents access to the browser chrome.
      }

      // Otherwise, immediately blur the targeted element. Technically, this
      // still generates focus and blur events on the element. This is (probably)
      // the price to pay for this polyfill.
      target.blur();
    }

    // The 'focusin' event bubbles, but instead, use 'focus' with useCapture set
    // to true as this is supported in Firefox. Additionally, target the body so
    // this doesn't generate superfluous events on document itself.
    document.body.addEventListener('focus', function(ev) {
      var target = targetForEvent(ev);
      updateFocusedShadowRoot((target == ev.target ? null : findShadowRoot(target)));
      sharedFocusHandler(target);  // either real DOM node or shadow node
    }, true);

    // Use a capturing click listener as both a safety fallback where pointer-events is not
    // available (IE10 and below), and to prevent accessKey access to inert elements.
    // TODO(samthor): Note that pointer-events polyfills trap more mouse events, e.g.-
    //   https://github.com/kmewhort/pointer_events_polyfill
    document.addEventListener('click', function(ev) {
      var target = targetForEvent(ev);
      if (madeInertBy(target)) {
        ev.preventDefault();
        ev.stopPropagation();
      }
    }, true);
  });
}<commit_msg>remove walkElementTree in favor of TreeWalker<commit_after>/*
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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.
 */

if (!('inert' in HTMLElement.prototype)) {
  Object.defineProperty(HTMLElement.prototype, 'inert', {
    enumerable: true,

    /**
     * @return {boolean}
     * @this {Element}
     */
    get: function() { return this.hasAttribute('inert'); },

    /**
     * @param {boolean} inert
     * @this {Element}
     */
    set: function(inert) {
      if (inert) {
        this.setAttribute('inert', '');
      } else {
        this.removeAttribute('inert');
      }
    }
  });

  window.addEventListener('load', function() {
    function applyStyle(css) {
      var style = document.createElement('style');
      style.type = 'text/css';
      if (style.styleSheet) {
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(document.createTextNode(css));
      }
      document.body.appendChild(style);
    }
    var css = "/*[inert]*/*[inert]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none}";
    applyStyle(css);

    /**
     * Sends a fake tab event. This is only supported by some browsers.
     *
     * @param {boolean=} opt_shiftKey whether to send this tab with shiftKey
     */
    function dispatchTabEvent(opt_shiftKey) {
      var ev = null;
      try {
        ev = new KeyboardEvent('keydown', {
          keyCode: 9,
          which: 9,
          key: 'Tab',
          code: 'Tab',
          keyIdentifier: 'U+0009',
          shiftKey: !!opt_shiftKey,
          bubbles: true
        });
      } catch (e) {
        try {
          // Internet Explorer
          ev = document.createEvent('KeyboardEvent');
          ev.initKeyboardEvent(
            'keydown',
            true,
            true,
            window,
            'Tab',
            0,
            opt_shiftKey ? 'Shift' : '',
            false,
            'en'
          )
        } catch (e) {}
      }
      if (ev) {
        try {
          Object.defineProperty(ev, 'keyCode', { value: 9 });
        } catch (e) {}
        document.dispatchEvent(ev);
      }
    }

    /**
     * Determines whether the specified element is inert, and returns the element
     * which caused this state. This is limited to, but may include, the body
     * element.
     *
     * @param {Element} e to check
     * @return {Element} element is made inert by, if any
     */
    function madeInertBy(e) {
      while (e && e !== document.documentElement) {
        if (e.hasAttribute('inert')) {
          return e;
        }
        e = e.parentElement;
      }
      return null;
    }

    /**
     * Finds the nearest shadow root from an element that's within said shadow root.
     *
     * TODO(samthor): We probably want to find the highest shadow root.
     *
     * @param {Element} e to check
     * @return {Node} shadow root, if any
     */
    var findShadowRoot = function(e) { return null; };
    if (window.ShadowRoot) {
      findShadowRoot = function(e) {
        while (e && e !== document.documentElement) {
          if (e instanceof window.ShadowRoot) { return e; }
          e = e.parentNode;
        }
        return null;
      }
    }

    /**
     * Returns the target of the passed event. If there's a path (shadow DOM only), then prefer it.
     *
     * @param {!Event} event
     * @return {Element} target of event
     */
    function targetForEvent(event) {
      var p = event.path;
      return  /** @type {Element} */ (p && p[0] || event.target);
    }

    // Hold onto the last tab direction: next (tab) or previous (shift-tab). This
    // can be used to step over inert elements in the correct direction. Mouse
    // or non-tab events should reset this and inert events should focus nothing.
    var lastTabDirection = 0;
    document.addEventListener('keydown', function(ev) {
      if (ev.keyCode === 9) {
        lastTabDirection = ev.shiftKey ? -1 : +1;
      } else {
        lastTabDirection = 0;
      }
    });
    document.addEventListener('mousedown', function(ev) {
      lastTabDirection = 0;
    });

    // Retain the currently focused shadowRoot.
    var focusedShadowRoot = null;
    function updateFocusedShadowRoot(root) {
      if (root == focusedShadowRoot) { return; }
      if (focusedShadowRoot) {
        if (!(focusedShadowRoot instanceof window.ShadowRoot)) {
          throw new Error('not shadow root: ' + focusedShadowRoot);
        }
        focusedShadowRoot.removeEventListener('focusin', shadowFocusHandler, true);  // remove
      }
      if (root) {
        root.addEventListener('focusin', shadowFocusHandler, true);  // add
      }
      focusedShadowRoot = root;
    }

    /**
     * Focus handler on a Shadow DOM host. This traps focus events within that root.
     *
     * @param {!Event} ev
     */
    function shadowFocusHandler(ev) {
      // ignore "direct" focus, we only want shadow root focus
      var last = ev.path[ev.path.length - 1];
      if (last === /** @type {*} */ (window)) { return; }
      sharedFocusHandler(targetForEvent(ev));
      ev.preventDefault();
      ev.stopPropagation();
    }

    /**
     * Called indirectly by both the regular focus handler and Shadow DOM host focus handler. This
     * is the bulk of the polyfill which prevents focus.
     *
     * @param {Element} target focused on
     */
    function sharedFocusHandler(target) {
      var inertElement = madeInertBy(target);
      if (!inertElement) { return; }

      // If the page has been tabbed recently, then focus the next element
      // in the known direction (if available).
      if (document.hasFocus() && lastTabDirection !== 0) {
        function getFocused() {
          return (focusedShadowRoot || document).activeElement;
        }

        // Send a fake tab event to enumerate through the browser's view of
        // focusable elements. This is supported in some browsers (not Firefox).
        var previous = getFocused();
        dispatchTabEvent(lastTabDirection < 0 ? true : false);
        if (previous != getFocused()) { return; }

        // Otherwise, enumerate through adjacent elements to find the next
        // focusable element. This won't respect any custom tabIndex.
        var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {
          acceptNode: function(node) {
            if (!node.focus || node.tabIndex < 0) {
              return NodeFilter.FILTER_SKIP;  // look at descendants
            }
            var contained = inertElement.contains(node);
            return contained ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
          },
        });
        walker.currentNode = inertElement;

        var nextFunc = Math.sign(lastTabDirection) === -1 ? walker.previousNode : walker.nextNode
        var next = nextFunc.bind(walker);
        for (var candidate; candidate = next(); ) {
          candidate.focus();
          if (getFocused() !== previous) { return; }
        }

        // FIXME: If a focusable element can't be found here, it's likely to mean
        // that this is the start or end of the page. Blurring is then not quite
        // right, as it prevents access to the browser chrome.
      }

      // Otherwise, immediately blur the targeted element. Technically, this
      // still generates focus and blur events on the element. This is (probably)
      // the price to pay for this polyfill.
      target.blur();
    }

    // The 'focusin' event bubbles, but instead, use 'focus' with useCapture set
    // to true as this is supported in Firefox. Additionally, target the body so
    // this doesn't generate superfluous events on document itself.
    document.body.addEventListener('focus', function(ev) {
      var target = targetForEvent(ev);
      updateFocusedShadowRoot((target == ev.target ? null : findShadowRoot(target)));
      sharedFocusHandler(target);  // either real DOM node or shadow node
    }, true);

    // Use a capturing click listener as both a safety fallback where pointer-events is not
    // available (IE10 and below), and to prevent accessKey access to inert elements.
    // TODO(samthor): Note that pointer-events polyfills trap more mouse events, e.g.-
    //   https://github.com/kmewhort/pointer_events_polyfill
    document.addEventListener('click', function(ev) {
      var target = targetForEvent(ev);
      if (madeInertBy(target)) {
        ev.preventDefault();
        ev.stopPropagation();
      }
    }, true);
  });
}<|endoftext|>


<commit_before>"use strict";
var rl = require('readline').createInterface({
	input: require('fs').createReadStream('challenge-in.txt')
});

var MAX_LENGTH = 1000,
		lightsMap = {},
		TURN_ON = "turn on",
		TURN_OFF = "turn off",
		TOGGLE = "toggle";

initializeLightMap();

rl.on('line', function (line) {
  var instruction = parseInstruction(line);
  var ranges = getRanges(line);

  // Execute the parsed instruction for the specified range
  executeInstruction(instruction, ranges);
});

rl.on('close', function() {
	console.log('Lights lit after executing the instructions is ' + getLitLightsCount());
});

function getLitLightsCount() {
	var litLights = 0;
	for (var i in lightsMap) {
		var arr = lightsMap[i];
		for (var j = 0, len = arr.length; j < len; j++) {
			if (arr[j]) {
				litLights++;
			}
		}
	}

	return litLights;
}

function executeInstruction(instruction, range) {
	var columnStart = range[2],
			columnEnd = range[3];

	while (columnStart <= columnEnd) {
		var rowStart = range[0],
				rowEnd = range[1];

		while (rowStart <= rowEnd) {
			if (instruction === TURN_ON) {
				lightsMap[rowStart][columnStart] = true;
			} else if (instruction === TURN_OFF) {
				lightsMap[rowStart][columnStart] = false;
			} else if (instruction === TOGGLE) {
				lightsMap[rowStart][columnStart] = !lightsMap[rowStart][columnStart];
			}

			rowStart++;
		}
		columnStart++;
	}
}

function initializeLightMap() {
	for (var i = 0; i < MAX_LENGTH; i++) {
		var arr = new Array(MAX_LENGTH);
		for (var j = 0, len = arr.length; j < len; j++) {
			// Set to false to indicate that the lights are off.
			arr[j] = false;
		}
		lightsMap[i] = arr;
	}
}

function parseInstruction(instruction) {
	var x = instruction.match(TURN_ON) || instruction.match(TURN_OFF) || instruction.match(TOGGLE);
	return x[0];
}

function getRanges(input) {
	var range = [],
			rangeRegex = /(\d)+,(\d)+/gi,
			rangeString = input.match(rangeRegex),
			startingRange = rangeString[0].split(','),
			endRange = rangeString[1].split(',');

	for (var i = 0; i < 2; i++) {
		range.push(parseInt(startingRange[i]));
		range.push(parseInt(endRange[i]));
	}

	return range;
}<commit_msg>Fixed weird spacing issues<commit_after>"use strict";
var rl = require('readline').createInterface({
	input: require('fs').createReadStream('challenge-in.txt')
});

var MAX_LENGTH = 1000,
		lightsMap = {},
		TURN_ON = "turn on",
		TURN_OFF = "turn off",
		TOGGLE = "toggle";

initializeLightMap();

rl.on('line', function (line) {
  var instruction = parseInstruction(line);
  var ranges = getRanges(line);

  // Execute the parsed instruction for the specified range
  executeInstruction(instruction, ranges);
});

rl.on('close', function() {
	console.log('Lights lit after executing the instructions is ' + getLitLightsCount());
});

function getLitLightsCount() {
	var litLights = 0;
	for (var i in lightsMap) {
		var arr = lightsMap[i];
		for (var j = 0, len = arr.length; j < len; j++) {
			if (arr[j]) {
				litLights++;
			}
		}
	}

	return litLights;
}

function executeInstruction(instruction, range) {
	var columnStart = range[2],
			columnEnd = range[3];

	while (columnStart <= columnEnd) {
		var rowStart = range[0],
				rowEnd = range[1];

		while (rowStart <= rowEnd) {
			if (instruction === TURN_ON) {
				lightsMap[rowStart][columnStart] = true;
			} else if (instruction === TURN_OFF) {
				lightsMap[rowStart][columnStart] = false;
			} else if (instruction === TOGGLE) {
				lightsMap[rowStart][columnStart] = !lightsMap[rowStart][columnStart];
			}

			rowStart++;
		}
		columnStart++;
	}
}

function initializeLightMap() {
	for (var i = 0; i < MAX_LENGTH; i++) {
		var arr = new Array(MAX_LENGTH);
		for (var j = 0, len = arr.length; j < len; j++) {
			// Set to false to indicate that the lights are off.
			arr[j] = false;
		}
		lightsMap[i] = arr;
	}
}

function parseInstruction(instruction) {
	var x = instruction.match(TURN_ON) || instruction.match(TURN_OFF) || instruction.match(TOGGLE);
	return x[0];
}

function getRanges(input) {
	var range = [],
			rangeRegex = /(\d)+,(\d)+/gi,
			rangeString = input.match(rangeRegex),
			startingRange = rangeString[0].split(','),
			endRange = rangeString[1].split(',');

	for (var i = 0; i < 2; i++) {
	  range.push(parseInt(startingRange[i]));
  	range.push(parseInt(endRange[i]));
	}

	return range;
}
<|endoftext|>


<commit_before>angular.module('anol.map')

/**
 * @ngdoc object
 * @name anol.map.ClusterSelectServiceProvider
 */
.provider('ClusterSelectService', [function() {

    var _clusterSelectOptions;

    this.setClusterSelectOptions = function(options) {
        _clusterSelectOptions = options;
    };

    this.$get = ['MapService', function(MapService) {

        var defaultClusterOptions = {
            selectCluster: true,
            pointRadius: 10,
            spiral: true,
            circleMaxObjects: 10,
            maxObjects: 60,
            animate: true,
            animationDuration: 500
        };

        var ClusterSelect = function(clusterSelectOptions) {
            this.clusterLayers = [];
            this.selectRevealedFeatureCallbacks = [];
            this.clusterSelectOptions = clusterSelectOptions;
            this.selectedClusterLayer = undefined;
        };

        ClusterSelect.prototype.registerSelectRevealedFeatureCallback = function(f) {
            this.selectRevealedFeatureCallbacks.push(f);
        };

        ClusterSelect.prototype.addLayer = function(layer) {
            var self = this;
            layer.olLayer.on('change:visible', function() {
                if(!layer.getVisible() && layer === self.selectedClusterLayer) {
                    self.selectClusterInteraction.clear();
                }
            });
            this.clusterLayers.push(layer);
        };

        ClusterSelect.prototype.layerByFeature = function(feature) {
            var self = this;
            var resultLayer;
            // TODO collect all anol.layer.Feature into a list
            angular.forEach(self.clusterLayers, function(layer) {
                if(angular.isDefined(resultLayer)) {
                    return;
                }
                if(layer.unclusteredSource.getFeatures().indexOf(feature) > -1) {
                    if(layer instanceof anol.layer.DynamicGeoJSON) {
                        if(feature.get('__layer__') === layer.name) {
                            resultLayer = layer;
                        }
                    } else {
                        resultLayer = layer;
                    }
                }
            });
            return resultLayer;
        };

        ClusterSelect.prototype.getControl = function(recreate) {
            var self = this;
            if(self.clusterLayers.length === 0) {
                return;
            }

            if(angular.isDefined(self.selectClusterControl) && recreate !== true) {
                return self.selectClusterControl;
            }

            var olClusterLayers = [];
            angular.forEach(self.clusterLayers, function(layer) {
                olClusterLayers.push(layer.olLayer);
            });

            var interactionOptions = $.extend({}, defaultClusterOptions, this.clusterSelectOptions, {
                layers: olClusterLayers,
                // for each revealed feature of selected cluster, this function is called
                featureStyle: function(revealedFeature, resolution) {
                    var style = new ol.style.Style();
                    // style link lines
                    if(revealedFeature.get('selectclusterlink') === true) {
                        style = new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: '#f00',
                                width: 1
                            })
                        });
                    }
                    if(revealedFeature.get('selectclusterfeature') === true) {
                        var originalFeature = revealedFeature.get('features')[0];
                        var layer = self.layerByFeature(originalFeature);
                        var layerStyle = layer.olLayer.getStyle();

                        if(angular.isFunction(layerStyle)) {
                            layerStyle = layerStyle(originalFeature, resolution)[0];
                        }

                        style = layerStyle;
                    }

                    return [style];
                },
                style: function(clusterFeature, resolution) {
                    if(clusterFeature.get('features').length === 1) {
                        var layer = self.layerByFeature(clusterFeature.get('features')[0]);
                        var style = layer.olLayer.getStyle();
                        if(angular.isFunction(style)) {
                            style = style(clusterFeature, resolution);
                        }
                        if(angular.isArray(style)) {
                            return style;
                        }
                        return [style];
                    }
                    return [new ol.style.Style()];
                }
            });

            var selectedCluster;
            self.selectClusterInteraction = new ol.interaction.SelectCluster(interactionOptions);

            var changeCursorCondition = function(pixel) {
                return MapService.getMap().hasFeatureAtPixel(pixel, function(layer) {
                    var found = false;
                    if(self.selectClusterInteraction.overlayLayer_ === layer) {
                        MapService.getMap().forEachFeatureAtPixel(pixel, function(feature) {
                            if(found) {
                                return;
                            }
                            if(feature.get('selectclusterfeature')) {
                                found = true;
                            }
                        });
                    }
                    return found;
                });
            };

            MapService.addCursorPointerCondition(changeCursorCondition);

            self.selectClusterInteraction.on('select', function(a) {
                if(a.selected.length === 1) {
                    var revealedFeature = a.selected[0];
                    if(revealedFeature.get('features').length > interactionOptions.maxObjects) {
                        var view = MapService.getMap().getView();
                        view.setZoom(view.getZoom() + 1);
                        return;
                    }
                    if(revealedFeature.get('features').length > 1) {
                        // cluster open
                        selectedCluster = revealedFeature;
                        selectedCluster.setStyle(new ol.style.Style());
                        MapService.addCursorPointerCondition(changeCursorCondition);
                        return;
                    }
                    if(revealedFeature.get('selectclusterfeature') === true) {
                        // revealedFeature selected
                        var originalFeature = revealedFeature.get('features')[0];
                        var layer = self.layerByFeature(originalFeature);
                        angular.forEach(self.selectRevealedFeatureCallbacks, function(f) {
                            f(revealedFeature, originalFeature, layer);
                        });
                    }
                } else if(a.selected.length === 0 && angular.isDefined(selectedCluster)) {
                    // cluster closed
                    selectedCluster.setStyle(null);
                    selectedCluster = undefined;
                    MapService.removeCursorPointerCondition(changeCursorCondition);
                }
            });

            self.selectClusterInteraction.getFeatures().on('add', function(e) {
                var features = e.element.get('features');
                var layer = self.layerByFeature(features[0]);
                self.selectedClusterLayer = layer;
                if(angular.isFunction(layer.clusterOptions.onSelect)) {
                    layer.clusterOptions.onSelect(features);
                }
            });

            MapService.getMap().addInteraction(self.selectClusterInteraction);

            self.selectClusterControl = new anol.control.Control({
                subordinate: true,
                olControl: null,
                interactions: [self.selectClusterInteraction]
            });

            self.selectClusterControl.onDeactivate(function() {
                self.selectClusterInteraction.setActive(false);
                MapService.removeCursorPointerCondition(changeCursorCondition);
            });

            // control active by default
            MapService.addCursorPointerCondition(changeCursorCondition);

            return this.selectClusterControl;
        };

        return new ClusterSelect(_clusterSelectOptions);
    }];
}]);<commit_msg>Set cluster select animate initial to false<commit_after>angular.module('anol.map')

/**
 * @ngdoc object
 * @name anol.map.ClusterSelectServiceProvider
 */
.provider('ClusterSelectService', [function() {

    var _clusterSelectOptions;

    this.setClusterSelectOptions = function(options) {
        _clusterSelectOptions = options;
    };

    this.$get = ['MapService', function(MapService) {

        var defaultClusterOptions = {
            selectCluster: true,
            pointRadius: 10,
            spiral: true,
            circleMaxObjects: 10,
            maxObjects: 60,
            animate: false,
            animationDuration: 500
        };

        var ClusterSelect = function(clusterSelectOptions) {
            this.clusterLayers = [];
            this.selectRevealedFeatureCallbacks = [];
            this.clusterSelectOptions = clusterSelectOptions;
            this.selectedClusterLayer = undefined;
        };

        ClusterSelect.prototype.registerSelectRevealedFeatureCallback = function(f) {
            this.selectRevealedFeatureCallbacks.push(f);
        };

        ClusterSelect.prototype.addLayer = function(layer) {
            var self = this;
            layer.olLayer.on('change:visible', function() {
                if(!layer.getVisible() && layer === self.selectedClusterLayer) {
                    self.selectClusterInteraction.clear();
                }
            });
            this.clusterLayers.push(layer);
        };

        ClusterSelect.prototype.layerByFeature = function(feature) {
            var self = this;
            var resultLayer;
            // TODO collect all anol.layer.Feature into a list
            angular.forEach(self.clusterLayers, function(layer) {
                if(angular.isDefined(resultLayer)) {
                    return;
                }
                if(layer.unclusteredSource.getFeatures().indexOf(feature) > -1) {
                    if(layer instanceof anol.layer.DynamicGeoJSON) {
                        if(feature.get('__layer__') === layer.name) {
                            resultLayer = layer;
                        }
                    } else {
                        resultLayer = layer;
                    }
                }
            });
            return resultLayer;
        };

        ClusterSelect.prototype.getControl = function(recreate) {
            var self = this;
            if(self.clusterLayers.length === 0) {
                return;
            }

            if(angular.isDefined(self.selectClusterControl) && recreate !== true) {
                return self.selectClusterControl;
            }

            var olClusterLayers = [];
            angular.forEach(self.clusterLayers, function(layer) {
                olClusterLayers.push(layer.olLayer);
            });

            var interactionOptions = $.extend({}, defaultClusterOptions, this.clusterSelectOptions, {
                layers: olClusterLayers,
                // for each revealed feature of selected cluster, this function is called
                featureStyle: function(revealedFeature, resolution) {
                    var style = new ol.style.Style();
                    // style link lines
                    if(revealedFeature.get('selectclusterlink') === true) {
                        style = new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: '#f00',
                                width: 1
                            })
                        });
                    }
                    if(revealedFeature.get('selectclusterfeature') === true) {
                        var originalFeature = revealedFeature.get('features')[0];
                        var layer = self.layerByFeature(originalFeature);
                        var layerStyle = layer.olLayer.getStyle();

                        if(angular.isFunction(layerStyle)) {
                            layerStyle = layerStyle(originalFeature, resolution)[0];
                        }

                        style = layerStyle;
                    }

                    return [style];
                },
                style: function(clusterFeature, resolution) {
                    if(clusterFeature.get('features').length === 1) {
                        var layer = self.layerByFeature(clusterFeature.get('features')[0]);
                        var style = layer.olLayer.getStyle();
                        if(angular.isFunction(style)) {
                            style = style(clusterFeature, resolution);
                        }
                        if(angular.isArray(style)) {
                            return style;
                        }
                        return [style];
                    }
                    return [new ol.style.Style()];
                }
            });

            var selectedCluster;
            self.selectClusterInteraction = new ol.interaction.SelectCluster(interactionOptions);

            var changeCursorCondition = function(pixel) {
                return MapService.getMap().hasFeatureAtPixel(pixel, function(layer) {
                    var found = false;
                    if(self.selectClusterInteraction.overlayLayer_ === layer) {
                        MapService.getMap().forEachFeatureAtPixel(pixel, function(feature) {
                            if(found) {
                                return;
                            }
                            if(feature.get('selectclusterfeature')) {
                                found = true;
                            }
                        });
                    }
                    return found;
                });
            };

            MapService.addCursorPointerCondition(changeCursorCondition);

            self.selectClusterInteraction.on('select', function(a) {
                if(a.selected.length === 1) {
                    var revealedFeature = a.selected[0];
                    if(revealedFeature.get('features').length > interactionOptions.maxObjects) {
                        var view = MapService.getMap().getView();
                        view.setZoom(view.getZoom() + 1);
                        return;
                    }
                    if(revealedFeature.get('features').length > 1) {
                        // cluster open
                        selectedCluster = revealedFeature;
                        selectedCluster.setStyle(new ol.style.Style());
                        MapService.addCursorPointerCondition(changeCursorCondition);
                        return;
                    }
                    if(revealedFeature.get('selectclusterfeature') === true) {
                        // revealedFeature selected
                        var originalFeature = revealedFeature.get('features')[0];
                        var layer = self.layerByFeature(originalFeature);
                        angular.forEach(self.selectRevealedFeatureCallbacks, function(f) {
                            f(revealedFeature, originalFeature, layer);
                        });
                    }
                } else if(a.selected.length === 0 && angular.isDefined(selectedCluster)) {
                    // cluster closed
                    selectedCluster.setStyle(null);
                    selectedCluster = undefined;
                    MapService.removeCursorPointerCondition(changeCursorCondition);
                }
            });

            self.selectClusterInteraction.getFeatures().on('add', function(e) {
                var features = e.element.get('features');
                var layer = self.layerByFeature(features[0]);
                self.selectedClusterLayer = layer;
                if(angular.isFunction(layer.clusterOptions.onSelect)) {
                    layer.clusterOptions.onSelect(features);
                }
            });

            MapService.getMap().addInteraction(self.selectClusterInteraction);

            self.selectClusterControl = new anol.control.Control({
                subordinate: true,
                olControl: null,
                interactions: [self.selectClusterInteraction]
            });

            self.selectClusterControl.onDeactivate(function() {
                self.selectClusterInteraction.setActive(false);
                MapService.removeCursorPointerCondition(changeCursorCondition);
            });

            // control active by default
            MapService.addCursorPointerCondition(changeCursorCondition);

            return this.selectClusterControl;
        };

        return new ClusterSelect(_clusterSelectOptions);
    }];
}]);<|endoftext|>


<commit_before><commit_msg>Add file for solo challenge<commit_after><!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<textarea id="box" rows="4" cols="80"></textarea>
<textarea id ="display-area"></textarea>
<button type="button" onClick="guess()">compare</button>
<script>
var textbox = document.getElementById("box");
var paragraph = document.getElementById("display-area");
paragraph.readOnly = true;

var counter = 5
var answer = 5

function guess() {

 if (textbox.value < answer){
 	paragraph.value = "lower"
 	counter -=1;
 	if (counter === 0){
		alert("you lose");
	}
 }
 else if (textbox.value > answer){
 	paragraph.value =  "higher"
 	counter-=1;
 	if (counter === 0){
		alert("you lose");
	}
 }

 else

 	{counter-=1;
 		alert("you win")}

}
</script>
</body>
</html><|endoftext|>


<commit_before>let history = []

export function log() {
  const args = Array.from(arguments)
  history.push([new Date(), 'log', args.join(' '), args])
  if (process.env.NODE_ENV !== 'test') {
    console.log('%c' + args.join(' '), 'background: #ececec; color: #3a7df8;')
  }
}
export function warn() {
  const args = Array.from(arguments)
  console.warn(...args)
  history.push([new Date(), 'warn', args])
}
export function error() {
  const args = Array.from(arguments)
  console.error(...args)
  history.push([new Date(), 'error', args])
}
export function logHistory() {
  return history
}<commit_msg>Fix Error Handling in Logger<commit_after>let history = []

export function log() {
  const args = Array.from(arguments)
  history.push([new Date(), 'log', args.join(' '), args])
  if (process.env.NODE_ENV !== 'test') {
    console.log('%c' + args.join(' '), 'background: #ececec; color: #3a7df8;')
  }
}
export function warn() {
  const args = Array.from(arguments)
  console.warn(...args)
  history.push([new Date(), 'warn', args.join(' '), args])
}
export function error() {
  const args = Array.from(arguments)
  console.error(...args)
  history.push([new Date(), 'error', args.join(' '), args])
}
export function logHistory() {
  return history
}
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var os = require('os')

var platformToMethod = {
  aix: 'ps',
  alpine: 'procfile',
  darwin: 'ps',
  freebsd: 'ps',
  linux: 'procfile',
  netbsd: 'procfile',
  sunos: 'ps',
  win: 'wmic'
}

var ps = require('./ps')
var platform = os.platform()

if (fs.existsSync('/etc/alpine-release')) {
  platform = 'alpine'
}

if (platform.match(/^win/)) {
  platform = 'win'
}

var stat
try {
  stat = require('./' + platformToMethod[platform])
} catch (err) {}

/**
 * @callback pidCallback
 * @param {Error} err A possible error.
 * @param {Object} statistics The object containing the statistics.
 */

/**
 * Get pid informations.
 * @public
 * @param  {Number|Number[]|String|String[]} pids A pid or a list of pids.
 * @param  {Object} [options={}] Options object
 * @param  {pidCallback} callback Called when the statistics are ready.
 */
function get (pids, options, callback) {
  var fn = stat
  if (platform !== 'win' && options.usePs === true) {
    fn = ps
  }

  if (stat === undefined) {
    return callback(new Error(os.platform() + ' is not supported yet, please open an issue (https://github.com/soyuka/pidusage)'))
  }

  var single = false
  if (!Array.isArray(pids)) {
    single = true
    pids = [pids]
  }

  if (pids.length === 0) {
    return callback(new TypeError('You must provide at least one pid'))
  }

  for (var i = 0; i < pids.length; i++) {
    pids[i] = parseInt(pids[i], 10)
    if (isNaN(pids[i]) || pids[i] < 0) {
      return callback(new TypeError('One of the pids provided is invalid'))
    }
  }

  fn(pids, options, function (err, stats) {
    if (err) {
      return callback(err)
    }

    if (single) {
      callback(null, stats[pids[0]])
    } else {
      callback(null, stats)
    }
  })
}

module.exports = get
<commit_msg>Add android stat<commit_after>'use strict'

var fs = require('fs')
var os = require('os')

var platformToMethod = {
  aix: 'ps',
  android: 'procfile',
  alpine: 'procfile',
  darwin: 'ps',
  freebsd: 'ps',
  linux: 'procfile',
  netbsd: 'procfile',
  sunos: 'ps',
  win: 'wmic'
}

var ps = require('./ps')
var platform = os.platform()

if (fs.existsSync('/etc/alpine-release')) {
  platform = 'alpine'
}

if (platform.match(/^win/)) {
  platform = 'win'
}

var stat
try {
  stat = require('./' + platformToMethod[platform])
} catch (err) {}

/**
 * @callback pidCallback
 * @param {Error} err A possible error.
 * @param {Object} statistics The object containing the statistics.
 */

/**
 * Get pid informations.
 * @public
 * @param  {Number|Number[]|String|String[]} pids A pid or a list of pids.
 * @param  {Object} [options={}] Options object
 * @param  {pidCallback} callback Called when the statistics are ready.
 */
function get (pids, options, callback) {
  var fn = stat
  if (platform !== 'win' && options.usePs === true) {
    fn = ps
  }

  if (stat === undefined) {
    return callback(new Error(os.platform() + ' is not supported yet, please open an issue (https://github.com/soyuka/pidusage)'))
  }

  var single = false
  if (!Array.isArray(pids)) {
    single = true
    pids = [pids]
  }

  if (pids.length === 0) {
    return callback(new TypeError('You must provide at least one pid'))
  }

  for (var i = 0; i < pids.length; i++) {
    pids[i] = parseInt(pids[i], 10)
    if (isNaN(pids[i]) || pids[i] < 0) {
      return callback(new TypeError('One of the pids provided is invalid'))
    }
  }

  fn(pids, options, function (err, stats) {
    if (err) {
      return callback(err)
    }

    if (single) {
      callback(null, stats[pids[0]])
    } else {
      callback(null, stats)
    }
  })
}

module.exports = get
<|endoftext|>


<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright 2016 Chuan Ji                                                   *
 *                                                                           *
 * Permission is hereby granted, free of charge, to any person obtaining a   *
 * copy of this software and associated documentation files (the             *
 * "Software"), to deal in the Software without restriction, including       *
 * without limitation the rights to use, copy, modify, merge, publish,       *
 * distribute, sublicense, and/or sell copies of the Software, and to permit *
 * persons to whom the Software is furnished to do so, subject to the        *
 * following conditions:                                                     *
 *                                                                           *
 * The above copyright notice and this permission notice shall be included   *
 * in all copies or substantial portions of the Software.                    *
 *                                                                           *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS   *
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN *
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,  *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR     *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function isStorageTypeSupported(storageType) {
  return window[storageType] !== undefined;
}

function storageProperty(storageType, propertyName, defaultValue) {
  if (!isStorageTypeSupported(storageType)) {
    console.warn('Browser does not support %s', storageType);
    window[storageType] = {};
  }

  return {
    get() {
      if (window[storageType][propertyName] === undefined) {
        window[storageType][propertyName] = JSON.stringify(defaultValue);
      }
      return JSON.parse(window[storageType][propertyName]);
    },
    set(key, value) {
      window[storageType][propertyName] = JSON.stringify(value);
      return value;
    }
  };
}

export const isLocalStorageSupported =
  isStorageTypeSupported('localStorage');
export const localStorageProperty =
  storageProperty.bind(window, 'localStorage');

export const isSessionStorageSupported =
  isStorageTypeSupported('sessionStorage');
export const sessionStorageProperty =
  storageProperty.bind(window, 'sessionStorage');
<commit_msg>Fix for undefined.<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright 2016 Chuan Ji                                                   *
 *                                                                           *
 * Permission is hereby granted, free of charge, to any person obtaining a   *
 * copy of this software and associated documentation files (the             *
 * "Software"), to deal in the Software without restriction, including       *
 * without limitation the rights to use, copy, modify, merge, publish,       *
 * distribute, sublicense, and/or sell copies of the Software, and to permit *
 * persons to whom the Software is furnished to do so, subject to the        *
 * following conditions:                                                     *
 *                                                                           *
 * The above copyright notice and this permission notice shall be included   *
 * in all copies or substantial portions of the Software.                    *
 *                                                                           *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS   *
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN *
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,  *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR     *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function isStorageTypeSupported(storageType) {
  return window[storageType] !== undefined;
}

function storageProperty(storageType, propertyName, defaultValue) {
  if (!isStorageTypeSupported(storageType)) {
    console.warn('Browser does not support %s', storageType);
    window[storageType] = {};
  }

  return {
    get() {
      if (!(propertyName in window[storageType])) {
        window[storageType][propertyName] = JSON.stringify(defaultValue);
      }
      if (window[storageType][propertyName] === 'undefined') {
        return undefined;
      }
      return JSON.parse(window[storageType][propertyName]);
    },
    set(key, value) {
      window[storageType][propertyName] = JSON.stringify(value);
      return value;
    }
  };
}

export const isLocalStorageSupported =
  isStorageTypeSupported('localStorage');
export const localStorageProperty =
  storageProperty.bind(window, 'localStorage');

export const isSessionStorageSupported =
  isStorageTypeSupported('sessionStorage');
export const sessionStorageProperty =
  storageProperty.bind(window, 'sessionStorage');
<|endoftext|>


<commit_before>/*
CSS Browser Selector v0.4.4 (Sep 21, 2012)

-- original --
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
-- /original --

Fork project: http://code.google.com/p/css-browser-selector/
Song Hyo-Jin (shj at xenosi.de)
*/
function css_browser_selector(u) {
	var ua = u.toLowerCase(),
		is = function (t) {
			return ua.indexOf(t) > -1
		},
		g = 'gecko',
		w = 'webkit',
		s = 'safari',
		c = 'chrome',
		o = 'opera',
		m = 'mobile',
		r = window.devicePixelRatio ? (window.devicePixelRatio + '').replace('.', '_') : '1';
	return [
/* IE */
		(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua) && (v = RegExp.$1 * 1)) ?
			('ie ie' + v + ((v == 6 || v == 7) ?
				' ie67 ie678' : (v == 8) ?
					' ie678' : (v > 8) ? ' ie9m' : '')) :
/* FF */
		(/firefox\/(\d+)\.(\d+)/.test(ua) && (re = RegExp)) ? g + ' ff ff' + re.$1 + ' ff' + re.$1 + '_' + re.$2 :
			is('gecko/') ? g :
/* Opera */
		is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 :
			(/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) :
/* K */
		is('konqueror') ? 'konqueror' :
/* Black Berry */
		is('blackberry') ? m + ' blackberry' :
/* Android */
		is('android') ? m + ' android' :
/* Chrome */
		is(c) ? w + ' ' + c :
			is('crios') ? w + ' ' + c :
/* Iron */
		is('iron') ? w + ' iron' :
/* Safari */
		is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') :
/* Mozilla */
		is('mozilla/') ? g : '',
/* Machine */
		is('j2me') ? m + ' j2me' :
		is('iphone') ? m + ' iphone' :
		is('ipod') ? m + ' ipod' :
		is('ipad') ? m + ' ipad' :
		is('mac') ? 'mac' :
		is('darwin') ? 'mac' :
		is('webtv') ? 'webtv' :
		is('win') ? 'win' + (is('windows nt 6.0') ? ' vista' : '') :
		is('freebsd') ? 'freebsd' :
		(is('x11') || is('linux')) ? 'linux' : '',
/* Ratio (Retina) */
		(r != '1') ? ' retina ratio' + r : '',
		'js portrait'].join(' ');
};
var _c = css_browser_selector(navigator.userAgent);
var de = document.documentElement;
de.className += ' ' + _c;
de.cbs = {};
var _d = _c.split(/ +/);
for(var i in _d) {
	de.cbs[_d[i]] = 1;
}
if(!!jQuery) {
	(function($) {
		var $h = $('html'), d = document, w = window;
		function CSSSelectorUpdateOrientation() {
			switch(w.orientation) {
				case 90:
				case -90:
					$h.removeClass('portrait').addClass('landscape');
					break;
				default:
					$h.removeClass('landscape').addClass('portrait');
					break;
			}
		}
		if($h.hasClass('mobile') && w.orientation != undefined) {
			$(w).on('orientationchange', CSSSelectorUpdateOrientation);
			CSSSelectorUpdateOrientation();
		}
		function CSSSelectorUpdateSize() {
			var c = d.documentElement.clientWidth || d.body.clientWidth;
			var m = 'smart', mw = 'smartwide', t = 'tablet', tw = 'tabletwide';
			$h.removeClass(m).removeClass(mw).removeClass(t).removeClass(tw).removeClass('pc');
			$h.addClass(
				(c <= 360) ? m :
				(c <= 640) ? mw :
				(c <= 768) ? t :
				(c <= 1024) ? tw : 'pc'
			);
		}
		$(w).on('resize', CSSSelectorUpdateSize);
		CSSSelectorUpdateSize();
	})(jQuery);
}

<commit_msg>for jquery 1.9 browser<commit_after>/*
CSS Browser Selector v0.4.5 (Jan 21, 2012)

-- original --
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
-- /original --

Fork project: http://code.google.com/p/css-browser-selector/
Song Hyo-Jin (shj at xenosi.de)
*/
function css_browser_selector(u) {
	var ua = u.toLowerCase(),
		is = function (t) {
			return ua.indexOf(t) > -1
		},
		g = 'gecko',
		w = 'webkit',
		s = 'safari',
		c = 'chrome',
		o = 'opera',
		m = 'mobile',
		r = window.devicePixelRatio ? (window.devicePixelRatio + '').replace('.', '_') : '1';
	return [
/* IE */
		(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua) && (v = RegExp.$1 * 1)) ?
			('ie ie' + v + ((v == 6 || v == 7) ?
				' ie67 ie678' : (v == 8) ?
					' ie678' : (v > 8) ? ' ie9m' : '')) :
/* FF */
		(/firefox\/(\d+)\.(\d+)/.test(ua) && (re = RegExp)) ? g + ' ff ff' + re.$1 + ' ff' + re.$1 + '_' + re.$2 :
			is('gecko/') ? g :
/* Opera */
		is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 :
			(/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) :
/* K */
		is('konqueror') ? 'konqueror' :
/* Black Berry */
		is('blackberry') ? m + ' blackberry' :
/* Android */
		is('android') ? m + ' android' :
/* Chrome */
		is(c) ? w + ' ' + c :
			is('crios') ? w + ' ' + c :
/* Iron */
		is('iron') ? w + ' iron' :
/* Safari */
		is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') :
/* Mozilla */
		is('mozilla/') ? g : '',
/* Machine */
		is('j2me') ? m + ' j2me' :
		is('iphone') ? m + ' iphone' :
		is('ipod') ? m + ' ipod' :
		is('ipad') ? m + ' ipad' :
		is('mac') ? 'mac' :
		is('darwin') ? 'mac' :
		is('webtv') ? 'webtv' :
		is('win') ? 'win' + (is('windows nt 6.0') ? ' vista' : '') :
		is('freebsd') ? 'freebsd' :
		(is('x11') || is('linux')) ? 'linux' : '',
/* Ratio (Retina) */
		(r != '1') ? ' retina ratio' + r : '',
		'js portrait'].join(' ');
};
var _c = css_browser_selector(navigator.userAgent);
var d = document, w = window;
var h = d.documentElement;
h.className += ' ' + _c;
w.cbs = {};
var _d = _c.split(/ +/);
for(var i in _d) {
	w.cbs[_d[i]] = 1;
}
if(!!jQuery) {
	(function($) {
		var $h = $(h);
		function CSSSelectorUpdateOrientation() {
			switch(w.orientation) {
				case 90:
				case -90:
					$h.removeClass('portrait').addClass('landscape');
					break;
				default:
					$h.removeClass('landscape').addClass('portrait');
					break;
			}
		}
		if($h.hasClass('mobile') && w.orientation != undefined) {
			$(w).on('orientationchange', CSSSelectorUpdateOrientation);
			CSSSelectorUpdateOrientation();
		}
		function CSSSelectorUpdateSize() {
			var c = d.documentElement.clientWidth || d.body.clientWidth;
			var m = 'smart', mw = 'smartwide', t = 'tablet', tw = 'tabletwide';
			$h.removeClass(m).removeClass(mw).removeClass(t).removeClass(tw).removeClass('pc');
			$h.addClass(
				(c <= 360) ? m :
				(c <= 640) ? mw :
				(c <= 768) ? t :
				(c <= 1024) ? tw : 'pc'
			);
		}
		$(w).on('resize', CSSSelectorUpdateSize);
		CSSSelectorUpdateSize();
	})(jQuery);
}

<|endoftext|>


<commit_before>module.exports = {
  components: {
    Dropzone: require('vue2-dropzone')  //https://github.com/rowanwins/vue-dropzone
  },
  props: {
    url: {
      type: String,
      required: true
    },
    model: {
      type: String,
      required: true
    },
    collection: {
    	type: String,
      required: true
    },
    maxNumberOfFiles:{
      type: Number,
      required: false,
      default: 1
    },
    maxFileSizeInMb:{
      type: Number,
      required: false,
      default: 2
    },
    acceptedFileTypes: {
      type: String,
      required: false
    },
    thumbnailWidth: {
      type: Number,
      required: false,
      default: 200
    },
    uploadedImages : {
      type: Array,
      required: false,
      default: function () { return [] }
    },
  },
  data: function () {
    return {
      mutableUploadedImages: this.uploadedImages
    }
  },
  template: `<dropzone :id="collection"
                       :url="url"
                       v-bind:preview-template="template"
                       v-on:vdropzone-success="onSuccess"
                       v-on:vdropzone-error="onUploadError"
                       v-on:vdropzone-removed-file="onFileDelete"
                       v-on:vdropzone-file-added="onFileAdded"
                       :useFontAwesome="true"
                       :ref="collection"
                       :maxNumberOfFiles="maxNumberOfFiles"
                       :maxFileSizeInMB="maxFileSizeInMb"
                       :acceptedFileTypes="acceptedFileTypes"
                       :thumbnailWidth="thumbnailWidth">

                <input type="hidden" name="model" :value="model">
                <input type="hidden" name="collection" :value="collection">
            </dropzone>`,
  mounted: function () {
    this.attachAlreadyUploadedMedia();
  },
  methods: {
    onSuccess: function (file, response) {
      if(!file.type.includes('image')) {
        setTimeout(function() {
            //FIXME jquery
            $(file.previewElement).removeClass('dz-file-preview');
        }, 3000);
      }
    },

    onUploadError: function (file) {
      // if(file.xhr) {
      //   alert(JSON.parse(file.xhr.response));
      // }
    },

    onFileAdded: function(file) {
      this.placeIcon(file);
    },

    onFileDelete: function (file, error, xhr) {
      var deletedFileIndex = _.findIndex(this.mutableUploadedImages, {url: file.url});
      if(this.mutableUploadedImages[deletedFileIndex]) {
        this.mutableUploadedImages[deletedFileIndex]['deleted'] = true;
      }
    },

    attachAlreadyUploadedMedia: function() {
      this.$nextTick( () => {
        if(this.mutableUploadedImages) {
          _.each(this.mutableUploadedImages, (file, key) => {

            this.$refs[this.collection].manuallyAddFile({ name: file['name'],
                                                          size: file['size'],
                                                          type: file['type'],
                                                          url: file['url'],
                                                        }, file['thumb_url'],
                                                        false,
                                                        false,
                                                        {
                                                          dontSubstractMaxFiles: false,
                                                          addToFiles: true
                                                        });
          });
        }
      })
    },

    getFiles: function() {
      var files = this.mutableUploadedImages;

      _.each(this.$refs[this.collection].getAcceptedFiles(), (file, key) => {
        var response = JSON.parse(file.xhr.response);

        if(response.path) {
          files.push({
              collection: this.collection,
              name: file.name,  //TODO: editable in the future
              file_name: file.name,
              width: file.width,
              height: file.height,
              model: this.model,
              path: response.path
          });
        }
      });

    	return files;
    },

    placeIcon: function(file) {
      //FIXME iconStyleString, nameStyleString, linkStyleString
      //FIXME cele to je jqueryoidne, asi si budeme musiet spravit vlastny vue wrapper, tento je zbugovany
      var iconStyleString = 'width:'+this.thumbnailWidth+'px; height:'+this.thumbnailWidth+'px; font-size: '+this.thumbnailWidth/2+'px; line-height: '+this.thumbnailWidth+'px; text-align: center',
          nameStyleString =  'position: absolute;bottom: 0px;width: 100%;text-align: center;height: 20px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;font-size: 12px;line-height: 1.2;padding: 0 15px;';
          linkStyleString = 'cursor: pointer;color:white;',
          $previewElement = $(file.previewElement);

      if(file.url) {
        $previewElement.find('.dz-filename').html(''+file.name+'');
      }

      if(file.type.includes('image')) {
        //nothing, default thumb
      }
      else if(file.type.includes('pdf')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('word')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('spreadsheet') || file.type.includes('csv')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('presentation')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('video')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('text')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('zip') || file.type.includes('rar')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
    },

    template: function() {
      return `

          `;
    }
  }
}<commit_msg>ugly error msgs position fix<commit_after>module.exports = {
  components: {
    Dropzone: require('vue2-dropzone')  //https://github.com/rowanwins/vue-dropzone
  },
  props: {
    url: {
      type: String,
      required: true
    },
    model: {
      type: String,
      required: true
    },
    collection: {
    	type: String,
      required: true
    },
    maxNumberOfFiles:{
      type: Number,
      required: false,
      default: 1
    },
    maxFileSizeInMb:{
      type: Number,
      required: false,
      default: 2
    },
    acceptedFileTypes: {
      type: String,
      required: false
    },
    thumbnailWidth: {
      type: Number,
      required: false,
      default: 200
    },
    uploadedImages : {
      type: Array,
      required: false,
      default: function () { return [] }
    },
  },
  data: function () {
    return {
      mutableUploadedImages: this.uploadedImages
    }
  },
  template: `<dropzone :id="collection"
                       :url="url"
                       v-bind:preview-template="template"
                       v-on:vdropzone-success="onSuccess"
                       v-on:vdropzone-error="onUploadError"
                       v-on:vdropzone-removed-file="onFileDelete"
                       v-on:vdropzone-file-added="onFileAdded"
                       :useFontAwesome="true"
                       :ref="collection"
                       :maxNumberOfFiles="maxNumberOfFiles"
                       :maxFileSizeInMB="maxFileSizeInMb"
                       :acceptedFileTypes="acceptedFileTypes"
                       :thumbnailWidth="thumbnailWidth">

                <input type="hidden" name="model" :value="model">
                <input type="hidden" name="collection" :value="collection">
            </dropzone>`,
  mounted: function () {
    //FIXME: temporary ugly fix until is fixed in package https://github.com/rowanwins/vue-dropzone/issues/127
    $('head').append('');

    this.attachAlreadyUploadedMedia();
  },
  methods: {
    onSuccess: function (file, response) {
      if(!file.type.includes('image')) {
        setTimeout(function() {
            //FIXME jquery
            $(file.previewElement).removeClass('dz-file-preview');
        }, 3000);
      }
    },

    onUploadError: function (file) {
      // if(file.xhr) {
      //   alert(JSON.parse(file.xhr.response));
      // }
    },

    onFileAdded: function(file) {
      this.placeIcon(file);
    },

    onFileDelete: function (file, error, xhr) {
      var deletedFileIndex = _.findIndex(this.mutableUploadedImages, {url: file.url});
      if(this.mutableUploadedImages[deletedFileIndex]) {
        this.mutableUploadedImages[deletedFileIndex]['deleted'] = true;
      }
    },

    attachAlreadyUploadedMedia: function() {
      this.$nextTick( () => {
        if(this.mutableUploadedImages) {
          _.each(this.mutableUploadedImages, (file, key) => {

            this.$refs[this.collection].manuallyAddFile({ name: file['name'],
                                                          size: file['size'],
                                                          type: file['type'],
                                                          url: file['url'],
                                                        }, file['thumb_url'],
                                                        false,
                                                        false,
                                                        {
                                                          dontSubstractMaxFiles: false,
                                                          addToFiles: true
                                                        });
          });
        }
      })
    },

    getFiles: function() {
      var files = this.mutableUploadedImages;

      _.each(this.$refs[this.collection].getAcceptedFiles(), (file, key) => {
        var response = JSON.parse(file.xhr.response);

        if(response.path) {
          files.push({
              collection: this.collection,
              name: file.name,  //TODO: editable in the future
              file_name: file.name,
              width: file.width,
              height: file.height,
              model: this.model,
              path: response.path
          });
        }
      });

    	return files;
    },

    placeIcon: function(file) {
      //FIXME iconStyleString, nameStyleString, linkStyleString
      //FIXME cele to je jqueryoidne, asi si budeme musiet spravit vlastny vue wrapper, tento je zbugovany
      var iconStyleString = 'width:'+this.thumbnailWidth+'px; height:'+this.thumbnailWidth+'px; font-size: '+this.thumbnailWidth/2+'px; line-height: '+this.thumbnailWidth+'px; text-align: center',
          nameStyleString =  'position: absolute;bottom: 0px;width: 100%;text-align: center;height: 20px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;font-size: 12px;line-height: 1.2;padding: 0 15px;';
          linkStyleString = 'cursor: pointer;color:white;',
          $previewElement = $(file.previewElement);

      if(file.url) {
        $previewElement.find('.dz-filename').html(''+file.name+'');
      }

      if(file.type.includes('image')) {
        //nothing, default thumb
      }
      else if(file.type.includes('pdf')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('word')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('spreadsheet') || file.type.includes('csv')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('presentation')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('video')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('text')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else if(file.type.includes('zip') || file.type.includes('rar')) {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
      else {
        $previewElement.find('.dz-image').html('
'+file.name+'
');
      }
    },

    template: function() {
      return `

          `;
    }
  }
}<|endoftext|>


<commit_before>/*

*/

var moment = require('moment');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;
var ParsedComponents = require('../../result').ParsedComponents;

var FIRST_REG_PATTERN  = new RegExp("(^|\\s|T)" +
    "(?:(?:at|from)\\s*)??" +
    "(\\d{1,4}|noon|midnight)" +
    "(?:" +
        "(?:\\.|\\:|\\：)(\\d{1,2})" +
        "(?:" +
            "(?:\\:|\\：)(\\d{2})" +
        ")?" +
    ")?" +
    "(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?" +
    "(?=\\W|$)", 'i');

var SECOND_REG_PATTERN = new RegExp("^\\s*" +
    "(\\-|\\–|\\~|\\〜|to|\\?)\\s*" +
    "(\\d{1,4})" +
    "(?:" +
        "(?:\\.|\\:|\\：)(\\d{1,2})" +
        "(?:" +
            "(?:\\.|\\:|\\：)(\\d{1,2})" +
        ")?" +
    ")?" +
    "(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?" +
    "(?=\\W|$)", 'i');

var HOUR_GROUP    = 2;
var MINUTE_GROUP  = 3;
var SECOND_GROUP  = 4;
var AM_PM_HOUR_GROUP = 5;

exports.Parser = function ENTimeExpressionParser(){
    Parser.apply(this, arguments);

    this.pattern = function() { return FIRST_REG_PATTERN; }

    this.extract = function(text, ref, match, opt){

        // This pattern can be overlaped Ex. [12] AM, 1[2] AM
        if (match.index > 0 && text[match.index-1].match(/\w/)) return null;
        var refMoment = moment(ref);
        var result = new ParsedResult();
        result.ref = ref;
        result.index = match.index + match[1].length;
        result.text  = match[0].substring(match[1].length);
        result.tags['ENTimeExpressionParser'] = true;

        result.start.imply('day',   refMoment.date());
        result.start.imply('month', refMoment.month()+1);
        result.start.imply('year',  refMoment.year());

        var hour = 0;
        var minute = 0;
        var meridiem = -1;

        // ----- Second
        if(match[SECOND_GROUP] != null){
            var second = parseInt(match[SECOND_GROUP]);
            if(second >= 60) return null;

            result.start.assign('second', second);
        }

        // ----- Hours
        if (match[HOUR_GROUP].toLowerCase() == "noon"){
            meridiem = 1;
            hour = 12;
        } else if (match[HOUR_GROUP].toLowerCase() == "midnight") {
            meridiem = 0;
            hour = 0;
        } else {
            hour = parseInt(match[HOUR_GROUP]);
        }

        // ----- Minutes
        if(match[MINUTE_GROUP] != null){
            minute = parseInt(match[MINUTE_GROUP]);
        } else if(hour > 100) {
            minute = hour%100;
            hour   = parseInt(hour/100);
        }

        if(minute >= 60) {
            return null;
        }

        if(hour > 24) {
            return null;
        }
        if (hour >= 12) {
            meridiem = 1;
        }

        // ----- AM & PM
        if(match[AM_PM_HOUR_GROUP] != null) {
            if(hour > 12) return null;
            var ampm = match[AM_PM_HOUR_GROUP][0].toLowerCase();
            if(ampm == "a"){
                meridiem = 0;
                if(hour == 12) hour = 0;
            }

            if(ampm == "p"){
                meridiem = 1;
                if(hour != 12) hour += 12;
            }
        }

        result.start.assign('hour', hour);
        result.start.assign('minute', minute);

        if (meridiem >= 0) {
            result.start.assign('meridiem', meridiem);
        } else {
            if (hour < 12) {
                result.start.imply('meridiem', 0);
            } else {
                result.start.imply('meridiem', 1);
            }
        }

        // ==============================================================
        //                  Extracting the 'to' chunk
        // ==============================================================
        match = SECOND_REG_PATTERN.exec(text.substring(result.index + result.text.length));
        if (!match) {
            // Not accept number only result
            if (result.text.match(/^\d+$/)) {
                return null;
            }
            return result;
        }

        // Pattern "YY.YY -XXXX" is more like timezone offset
        if (match[0].match(/^\s*(\+|\-)\s*\d{3,4}$/)) {
            return result;
        }

        if(result.end == null){
            result.end = new ParsedComponents(null, result.start.date());
        }

        var hour = 0;
        var minute = 0;
        var meridiem = -1;

        // ----- Second
        if(match[SECOND_GROUP] != null){
            var second = parseInt(match[SECOND_GROUP]);
            if(second >= 60) return null;

            result.end.assign('second', second);
        }

        hour = parseInt(match[2]);

        // ----- Minute
        if (match[MINUTE_GROUP]!= null) {

            minute = parseInt(match[MINUTE_GROUP]);
            if(minute >= 60) return result;

        } else if (hour > 100) {

            minute = hour%100;
            hour   = parseInt(hour/100);
        }

        if(minute >= 60) {
            return null;
        }

        if(hour > 24) {
            return null;
        }
        if (hour >= 12) {
            meridiem = 1;
        }

        // ----- AM & PM
        if (match[AM_PM_HOUR_GROUP] != null){

            if (hour > 12) return null;

            var ampm = match[AM_PM_HOUR_GROUP][0].toLowerCase();
            if(ampm == "a"){
                meridiem = 0;
                if(hour == 12) {
                    hour = 0;
                    if (!result.end.isCertain('day')) {
                        result.end.imply('day', result.end.get('day') + 1);
                    }
                }
            }

            if(ampm == "p"){
                meridiem = 1;
                if(hour != 12) hour += 12;
            }

            if (!result.start.isCertain('meridiem')) {
                if (meridiem == 0) {

                    result.start.imply('meridiem', 0);

                    if (result.start.get('hour') == 12) {
                        result.start.assign('hour', 0);
                    }

                } else {

                    result.start.imply('meridiem', 1);

                    if (result.start.get('hour') != 12) {
                        result.start.assign('hour', result.start.get('hour') + 12);
                    }
                }
            }
        }

        result.text = result.text + match[0];
        result.end.assign('hour', hour);
        result.end.assign('minute', minute);
        if (meridiem >= 0) {
            result.end.assign('meridiem', meridiem);
        } else {
            var startAtPM = result.start.isCertain('meridiem') && result.start.get('meridiem') == 1;
            if (startAtPM && result.start.get('hour') > hour) {
                // 10pm - 1 (am)
                result.end.imply('meridiem', 0);

            } else if (hour > 12) {
                result.end.imply('meridiem', 1);
            }
        }

        if (result.end.date().getTime() < result.start.date().getTime()) {
            result.end.imply('day', result.end.get('day') + 1)
        }

        return result;
    }
}
<commit_msg>Update ENTimeExpressionParser.js<commit_after>/*

What did Travis CI do?

*/

var moment = require('moment');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;
var ParsedComponents = require('../../result').ParsedComponents;

var FIRST_REG_PATTERN  = new RegExp("(^|\\s|T)" +
    "(?:(?:at|from)\\s*)??" +
    "(\\d{1,4}|noon|midnight)" +
    "(?:" +
        "(?:\\.|\\:|\\：)(\\d{1,2})" +
        "(?:" +
            "(?:\\:|\\：)(\\d{2})" +
        ")?" +
    ")?" +
    "(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?" +
    "(?=\\W|$)", 'i');

var SECOND_REG_PATTERN = new RegExp("^\\s*" +
    "(\\-|\\–|\\~|\\〜|to|\\?)\\s*" +
    "(\\d{1,4})" +
    "(?:" +
        "(?:\\.|\\:|\\：)(\\d{1,2})" +
        "(?:" +
            "(?:\\.|\\:|\\：)(\\d{1,2})" +
        ")?" +
    ")?" +
    "(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?" +
    "(?=\\W|$)", 'i');

var HOUR_GROUP    = 2;
var MINUTE_GROUP  = 3;
var SECOND_GROUP  = 4;
var AM_PM_HOUR_GROUP = 5;

exports.Parser = function ENTimeExpressionParser(){
    Parser.apply(this, arguments);

    this.pattern = function() { return FIRST_REG_PATTERN; }

    this.extract = function(text, ref, match, opt){

        // This pattern can be overlaped Ex. [12] AM, 1[2] AM
        if (match.index > 0 && text[match.index-1].match(/\w/)) return null;
        var refMoment = moment(ref);
        var result = new ParsedResult();
        result.ref = ref;
        result.index = match.index + match[1].length;
        result.text  = match[0].substring(match[1].length);
        result.tags['ENTimeExpressionParser'] = true;

        result.start.imply('day',   refMoment.date());
        result.start.imply('month', refMoment.month()+1);
        result.start.imply('year',  refMoment.year());

        var hour = 0;
        var minute = 0;
        var meridiem = -1;

        // ----- Second
        if(match[SECOND_GROUP] != null){
            var second = parseInt(match[SECOND_GROUP]);
            if(second >= 60) return null;

            result.start.assign('second', second);
        }

        // ----- Hours
        if (match[HOUR_GROUP].toLowerCase() == "noon"){
            meridiem = 1;
            hour = 12;
        } else if (match[HOUR_GROUP].toLowerCase() == "midnight") {
            meridiem = 0;
            hour = 0;
        } else {
            hour = parseInt(match[HOUR_GROUP]);
        }

        // ----- Minutes
        if(match[MINUTE_GROUP] != null){
            minute = parseInt(match[MINUTE_GROUP]);
        } else if(hour > 100) {
            minute = hour%100;
            hour   = parseInt(hour/100);
        }

        if(minute >= 60) {
            return null;
        }

        if(hour > 24) {
            return null;
        }
        if (hour >= 12) {
            meridiem = 1;
        }

        // ----- AM & PM
        if(match[AM_PM_HOUR_GROUP] != null) {
            if(hour > 12) return null;
            var ampm = match[AM_PM_HOUR_GROUP][0].toLowerCase();
            if(ampm == "a"){
                meridiem = 0;
                if(hour == 12) hour = 0;
            }

            if(ampm == "p"){
                meridiem = 1;
                if(hour != 12) hour += 12;
            }
        }

        result.start.assign('hour', hour);
        result.start.assign('minute', minute);

        if (meridiem >= 0) {
            result.start.assign('meridiem', meridiem);
        } else {
            if (hour < 12) {
                result.start.imply('meridiem', 0);
            } else {
                result.start.imply('meridiem', 1);
            }
        }

        // ==============================================================
        //                  Extracting the 'to' chunk
        // ==============================================================
        match = SECOND_REG_PATTERN.exec(text.substring(result.index + result.text.length));
        if (!match) {
            // Not accept number only result
            if (result.text.match(/^\d+$/)) {
                return null;
            }
            return result;
        }

        // Pattern "YY.YY -XXXX" is more like timezone offset
        if (match[0].match(/^\s*(\+|\-)\s*\d{3,4}$/)) {
            return result;
        }

        if(result.end == null){
            result.end = new ParsedComponents(null, result.start.date());
        }

        var hour = 0;
        var minute = 0;
        var meridiem = -1;

        // ----- Second
        if(match[SECOND_GROUP] != null){
            var second = parseInt(match[SECOND_GROUP]);
            if(second >= 60) return null;

            result.end.assign('second', second);
        }

        hour = parseInt(match[2]);

        // ----- Minute
        if (match[MINUTE_GROUP]!= null) {

            minute = parseInt(match[MINUTE_GROUP]);
            if(minute >= 60) return result;

        } else if (hour > 100) {

            minute = hour%100;
            hour   = parseInt(hour/100);
        }

        if(minute >= 60) {
            return null;
        }

        if(hour > 24) {
            return null;
        }
        if (hour >= 12) {
            meridiem = 1;
        }

        // ----- AM & PM
        if (match[AM_PM_HOUR_GROUP] != null){

            if (hour > 12) return null;

            var ampm = match[AM_PM_HOUR_GROUP][0].toLowerCase();
            if(ampm == "a"){
                meridiem = 0;
                if(hour == 12) {
                    hour = 0;
                    if (!result.end.isCertain('day')) {
                        result.end.imply('day', result.end.get('day') + 1);
                    }
                }
            }

            if(ampm == "p"){
                meridiem = 1;
                if(hour != 12) hour += 12;
            }

            if (!result.start.isCertain('meridiem')) {
                if (meridiem == 0) {

                    result.start.imply('meridiem', 0);

                    if (result.start.get('hour') == 12) {
                        result.start.assign('hour', 0);
                    }

                } else {

                    result.start.imply('meridiem', 1);

                    if (result.start.get('hour') != 12) {
                        result.start.assign('hour', result.start.get('hour') + 12);
                    }
                }
            }
        }

        result.text = result.text + match[0];
        result.end.assign('hour', hour);
        result.end.assign('minute', minute);
        if (meridiem >= 0) {
            result.end.assign('meridiem', meridiem);
        } else {
            var startAtPM = result.start.isCertain('meridiem') && result.start.get('meridiem') == 1;
            if (startAtPM && result.start.get('hour') > hour) {
                // 10pm - 1 (am)
                result.end.imply('meridiem', 0);

            } else if (hour > 12) {
                result.end.imply('meridiem', 1);
            }
        }

        if (result.end.date().getTime() < result.start.date().getTime()) {
            result.end.imply('day', result.end.get('day') + 1)
        }

        return result;
    }
}
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
    angular.module('socialPluginWidget', ['ngRoute', 'infinite-scroll', 'ngAnimate', 'socialModals', 'ngFileUpload', 'socialPluginFilters'])
        .config(['$routeProvider', '$compileProvider', '$httpProvider', function ($routeProvider, $compileProvider, $httpProvider) {

            /**
             * To make href urls safe on mobile
             */
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile|file):/);

            $routeProvider
                .when('/', {
                    template: '

'
                })
                .when('/thread/:threadId', {
                    templateUrl: 'templates/thread.html',
                    controllerAs: 'Thread',
                    controller: 'ThreadCtrl'
                })
                .otherwise('/');

            var interceptor = ['$q', function ($q) {
                var counter = 0;

                function increaseCounter() {
                    counter = counter + 1;
                }

                function decreaseCounter() {
                    counter = Math.max(counter - 1, 0);
                }

                function toggleSpinner() {
                    if (counter > 0)
                        buildfire.spinner.show();
                    else {
                        buildfire.spinner.hide();
                    }
                }

                return {

                    request: function (config) {
                        console.log('config-------------------------', config, config.url.indexOf('threadLikes'));
                        if (config.url.indexOf('threadLikes') == -1 && config.url.indexOf('thread/add') == -1 && config.url.indexOf('Image/upload') == -1) {
                            increaseCounter();
                            toggleSpinner();
                        }
                        return config;
                    },
                    response: function (response) {
                        console.log('Counter----------------------------------', counter, 'rseponse--------------------', response);
                        decreaseCounter();
                        toggleSpinner();
                        return response;
                    },
                    responseError: function (rejection) {
                        console.log('Counter----------------------------------', counter, 'error------------------', rejection);
                        decreaseCounter();
                        toggleSpinner();
                        return $q.reject(rejection);
                    }
                };
            }];

            $httpProvider.interceptors.push(interceptor);
        }])
        .run(['$location', '$rootScope', 'Location', 'Buildfire', function ($location, $rootScope, Location, Buildfire) {
            Buildfire.navigation.onBackButtonClick = function () {
                var path = $location.path();
                if (path.indexOf('/thread') == 0) {
                    $rootScope.showThread = true;
                    $location.path('/');
                    $rootScope.$digest();
                }
                else
                    Buildfire.navigation._goBackOne();
            }
        }])
        .directive('handlePhoneSubmit', function () {
            return function (scope, element, attr) {
                var textFields = $(element).children('textarea[name="text"]');
                console.log("---------------------------------->",textFields);
                $(element).submit(function() {
                    console.log('form was submitted');
                    textFields.blur();
                });
            };
        })
        .filter('getUserImage', ['Buildfire', function (Buildfire) {
            filter.$stateful = true;
            function filter (usersData, userId) {
                var userImageUrl = '';
                usersData.some(function (userData) {
                    if (userData.userObject._id == userId) {
                        if(userData.userObject.imageUrl) {
                            userImageUrl = userData.userObject.imageUrl;
                        } else {
                            userImageUrl = '';
                        }
                        return true;
                    }
                });
                return userImageUrl;
            }
            return filter;
        }])
        .directive("loadImage", function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

                    var _img = attrs.finalSrc;
                    if (attrs.cropType == 'resize') {
                        buildfire.imageLib.local.resizeImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    } else if (attrs.cropType == 'default') {
                        replaceImg(_img);
                    } else {
                        buildfire.imageLib.local.cropImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    }

                    function replaceImg(finalSrc) {
                        var elem = $("");
                        elem[0].onload = function () {
                            element.attr("src", finalSrc);
                            elem.remove();
                        };
                        elem.attr("src", finalSrc);
                    }
                }
            };
        });
})(window.angular, window.buildfire);<commit_msg>Fixed image not updating issue, #128643775<commit_after>'use strict';

(function (angular, buildfire) {
    angular.module('socialPluginWidget', ['ngRoute', 'infinite-scroll', 'ngAnimate', 'socialModals', 'ngFileUpload', 'socialPluginFilters'])
        .config(['$routeProvider', '$compileProvider', '$httpProvider', function ($routeProvider, $compileProvider, $httpProvider) {

            /**
             * To make href urls safe on mobile
             */
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile|file):/);

            $routeProvider
                .when('/', {
                    template: '

'
                })
                .when('/thread/:threadId', {
                    templateUrl: 'templates/thread.html',
                    controllerAs: 'Thread',
                    controller: 'ThreadCtrl'
                })
                .otherwise('/');

            var interceptor = ['$q', function ($q) {
                var counter = 0;

                function increaseCounter() {
                    counter = counter + 1;
                }

                function decreaseCounter() {
                    counter = Math.max(counter - 1, 0);
                }

                function toggleSpinner() {
                    if (counter > 0)
                        buildfire.spinner.show();
                    else {
                        buildfire.spinner.hide();
                    }
                }

                return {

                    request: function (config) {
                        console.log('config-------------------------', config, config.url.indexOf('threadLikes'));
                        if (config.url.indexOf('threadLikes') == -1 && config.url.indexOf('thread/add') == -1 && config.url.indexOf('Image/upload') == -1) {
                            increaseCounter();
                            toggleSpinner();
                        }
                        return config;
                    },
                    response: function (response) {
                        console.log('Counter----------------------------------', counter, 'rseponse--------------------', response);
                        decreaseCounter();
                        toggleSpinner();
                        return response;
                    },
                    responseError: function (rejection) {
                        console.log('Counter----------------------------------', counter, 'error------------------', rejection);
                        decreaseCounter();
                        toggleSpinner();
                        return $q.reject(rejection);
                    }
                };
            }];

            $httpProvider.interceptors.push(interceptor);
        }])
        .run(['$location', '$rootScope', 'Location', 'Buildfire', function ($location, $rootScope, Location, Buildfire) {
            Buildfire.navigation.onBackButtonClick = function () {
                var path = $location.path();
                if (path.indexOf('/thread') == 0) {
                    $rootScope.showThread = true;
                    $location.path('/');
                    $rootScope.$digest();
                }
                else
                    Buildfire.navigation._goBackOne();
            }
        }])
        .directive('handlePhoneSubmit', function () {
            return function (scope, element, attr) {
                var textFields = $(element).children('textarea[name="text"]');
                console.log("---------------------------------->",textFields);
                $(element).submit(function() {
                    console.log('form was submitted');
                    textFields.blur();
                });
            };
        })
        .filter('getUserImage', ['Buildfire', function (Buildfire) {
            filter.$stateful = true;
            function filter (usersData, userId) {
                var userImageUrl = '';
                usersData.some(function (userData) {
                    if (userData.userObject._id == userId) {
                        if(userData.userObject.imageUrl) {
                            userImageUrl = userData.userObject.imageUrl;
                        } else {
                            userImageUrl = '';
                        }
                        return true;
                    }
                });
                return userImageUrl;
            }
            return filter;
        }])
        .directive("loadImage", function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

                    attrs.$observe('finalSrc', function() {
                        var _img = attrs.finalSrc;

                        if (attrs.cropType == 'resize') {
                            buildfire.imageLib.local.resizeImage(_img, {
                                width: attrs.cropWidth,
                                height: attrs.cropHeight
                            }, function (err, imgUrl) {
                                _img = imgUrl;
                                replaceImg(_img);
                            });
                        } else {
                            buildfire.imageLib.local.cropImage(_img, {
                                width: attrs.cropWidth,
                                height: attrs.cropHeight
                            }, function (err, imgUrl) {
                                _img = imgUrl;
                                replaceImg(_img);
                            });
                        }
                    });

                    function replaceImg(finalSrc) {
                        var elem = $("");
                        elem[0].onload = function () {
                            element.attr("src", finalSrc);
                            elem.remove();
                        };
                        elem.attr("src", finalSrc);
                    }
                }
            };
        });
})(window.angular, window.buildfire);<|endoftext|>