<commit_before>/* global Hammer */

(function(factory) {
  // expose Heidelberg
  if (typeof module === 'object' && module.exports) {
    require('browsernizr/test/css/transformstylepreserve3d');
    require('browsernizr/test/css/transforms3d');

    module.exports = factory(require('jquery'), require('browsernizr'));
  } else {
    // Check for Modernizr, if not available assume modern browser
    var Modernizr = window.Modernizr || { csstransforms3d: true };
    if (typeof Modernizr.preserve3d !== 'boolean') {
      Modernizr.preserve3d = true;
    }

    window.Heidelberg = factory(window.jQuery, Modernizr);
  }
})(function ($, Modernizr) {
  'use strict';

  function Heidelberg(el, options) {

    // Allow developer to omit new when instantiating
    if (!(this instanceof Heidelberg)) {
      if (el.length) {
        Array.prototype.forEach.call(el, function(n) {
          return new Heidelberg(n, options);
        });
      } else {
        return new Heidelberg(el, options);
      }
    }

    // OPTIONS
    var defaults = {
      nextButton: $(),
      previousButton: $(),
      hasSpreads: false,
      canClose: false,
      arrowKeys: true,
      concurrentAnimations: null,
      limitPageTurns: true,
      initialActivePage: 0,
      onPageTurn: function() {},
      onSpreadSetup: function() {}
    };

    this.options = $.extend({}, defaults, options);

    // PRIVATE VARIABLES
    // Main element always a jQuery object
    this.el = (el instanceof $) ? el : $(el);
    this.el.attr('data-useragent', navigator.userAgent); // Add user agent attribute to HTMLElement - used in CSS selection ( for IE10 detection )
    // RUN
    this.init();

  }

  Heidelberg.prototype.init = function() {

    var el      = this.el;
    var els     = {};
    var options = this.options;

    setTimeout(function() {
      el.addClass('is-ready');
    }, 0);

    if(options.hasSpreads) {
      this.setupSpreads();
    }

    var leftFunction  = options.canClose ? 'even' : 'odd';
    var rightFunction = options.canClose ? 'odd' : 'even';

    els.pages      = $('.Heidelberg-Page', this.el);
    els.pagesLeft  = $('.Heidelberg-Page:nth-child('+leftFunction+')', el);
    els.pagesRight = $('.Heidelberg-Page:nth-child('+rightFunction+')', el);

    // if initialActivePage is odd, we substract one.
    var initialActivePage = options.initialActivePage & 1
      ? options.initialActivePage - 1
      : options.initialActivePage;

    if(!options.canClose) {
      var coverEl = $('<div />').addClass('Heidelberg-HiddenCover');
      el.prepend(coverEl.clone());
      el.append(coverEl.clone());

      els.pages.eq(initialActivePage).add(
        els.pages.eq(initialActivePage + 1)).addClass('is-active');
    }
    else {
      if (options.initialActivePage !== 0) {
        els.pages.eq(initialActivePage).add(
          els.pages.eq(initialActivePage + 1)).addClass('is-active');
      } else {
        els.pages.eq(0).addClass('is-active');
      }
    }

    els.previousTrigger = els.pagesLeft.add(options.previousButton);
    els.nextTrigger     = els.pagesRight.add(options.nextButton);

    els.previousTrigger.on('click', function() {
      this.turnPage('back');
    }.bind(this));

    els.nextTrigger.on('click', function() {
      this.turnPage('forwards');
    }.bind(this));

    if(typeof Hammer !== 'undefined') {
      var opts = {
        drag_min_distance: 5,
        swipe_velocity: 0.3
      };

      Hammer(els.pagesLeft, opts).on("dragright", function(evt) {
        this.turnPage('back');
        evt.gesture.stopDetect();
      }.bind(this));

      Hammer(els.pagesRight, opts).on("dragleft", function(evt) {
        this.turnPage('forwards');
        evt.gesture.stopDetect();
      }.bind(this));
    }

    var forwardsKeycode = 37;
    var backKeycode = 39;

    if((!Modernizr.csstransforms3d)) {
      forwardsKeycode = 39;
      backKeycode = 37;
    }

    if(options.arrowKeys) {
      $(document).keydown(function(e){
        if (e.keyCode == forwardsKeycode) {
          this.turnPage('forwards');
          return false;
        }
        if (e.keyCode == backKeycode) {
          this.turnPage('back');
          return false;
        }
      }.bind(this));
    }
  };

  Heidelberg.prototype.turnPage = function(arg) {

    var el        = this.el;
    var els       = {};
    var options   = this.options;
    var index     = {};
    var direction = arg;

    els.pages          = $('.Heidelberg-Page', el);
    els.pagesActive    = $('.Heidelberg-Page.is-active', el);
    els.pagesAnimating = $('.Heidelberg-Page.is-animating', el);
    els.children       = $('.Heidelberg-Page, .Heidelberg-HiddenCover', el);

    var maxAnimations = options.concurrentAnimations && els.pagesAnimating.length > options.concurrentAnimations;
    var maxAnimationsBrowser = !Modernizr.preserve3d && els.pagesAnimating.length > 2 && options.limitPageTurns;

    if(maxAnimations || maxAnimationsBrowser) {
      return;
    }

    if ( options.hasSpreads ) {
      index.activeRight = els.pagesActive.eq(1).index();
      index.activeLeft  = index.activeRight - 1;
    } else {// Single page spreads ( JHome )
      index.activeLeft  = els.pagesActive.eq(0).index(); // Note about fix: the double spread code above caused code to wrap to bottom of array . This is the fix for double spreads.
      index.activeRight = index.activeLeft + 1;
    }

    var isFirstPage = els.pages.first().index() == index.activeLeft && direction == 'back';
    var isLastPage  = els.pages.last().index() == index.activeRight && direction == 'forwards';

    if(isFirstPage || isLastPage) {
      return;
    }

    if(typeof arg == 'number') {
      var isOdd         = arg & 1;
      var isRight       = options.canClose ? isOdd : !isOdd;

      index.targetRight = isRight ? arg : arg + 1;
      index.targetLeft  = index.targetRight - 1;

      if (index.targetLeft == index.activeLeft) {
        return;
      }
      else if(index.targetLeft > index.activeRight) {
        direction           = 'forwards';
        index.target        = index.targetLeft;
        index.targetSibling = index.target + 1;
      }
      else {
        direction           = 'back';
        index.target        = index.targetRight;
        index.targetSibling = index.target - 1;
      }

      if ( ! options.hasSpreads )
      {
        index.target = index.target - 1;
        index.targetSibling = index.targetSibling - 1;
      }

    }
    else {
      index.target        = direction == 'forwards' ? index.activeRight + 1 : index.activeLeft - 1;
      index.targetSibling = direction == 'forwards' ? index.activeRight + 2 : index.activeLeft - 2;
    }

    // JHome - double spreads - Fix for 'is-active' pages not being correctly offset from the stars
    if ( ! options.hasSpreads && direction == 'forwards' && index.target == 2 ) {
      index.target = 1;
      index.targetSibling = 2;
    }

    els.pagesAnimatingOut = (direction == 'back') ? els.pagesActive.first() : els.pagesActive.last();
    els.pagesAnimatingIn  = els.children.eq(index.target);
    els.pagesTarget       = els.pagesAnimatingIn.add(els.children.eq(index.targetSibling));
    els.pagesAnimating    = els.pagesAnimatingIn.add(els.pagesAnimatingOut);

    els.pagesActive.removeClass('is-active').addClass('was-active');
    els.pagesTarget.addClass('is-active');

    if((Modernizr.csstransforms3d)) {
      els.pagesAnimating.addClass('is-animating');
    }

    els.pagesAnimating.on('webkitTransitionEnd oTransitionEnd msTransitionEnd transitionend', function () {
      els.pagesAnimating.removeClass('is-animating');
      els.pagesActive.removeClass('was-active');
    }.bind(document));

    options.onPageTurn(el, els);
    $(this).trigger('pageTurn.heidelberg', [el, els]);

  };

  Heidelberg.prototype.setupSpreads = function() {

    var el      = this.el;
    var options = this.options;

    $('.Heidelberg-Spread', el).each(function() {
      var spreadEl = $(this);
      var pageEl   = $('<div />').addClass('Heidelberg-Page with-Spread').html(spreadEl.clone());
      spreadEl.after(pageEl);
      spreadEl.replaceWith(pageEl.clone());
    });

    options.onSpreadSetup(el);
    $(this).trigger('spreadSetup.heidelberg', el);
  };
  return Heidelberg;
});
<commit_msg>Remove domain specific comments<commit_after>/* global Hammer */

(function(factory) {
  // expose Heidelberg
  if (typeof module === 'object' && module.exports) {
    require('browsernizr/test/css/transformstylepreserve3d');
    require('browsernizr/test/css/transforms3d');

    module.exports = factory(require('jquery'), require('browsernizr'));
  } else {
    // Check for Modernizr, if not available assume modern browser
    var Modernizr = window.Modernizr || { csstransforms3d: true };
    if (typeof Modernizr.preserve3d !== 'boolean') {
      Modernizr.preserve3d = true;
    }

    window.Heidelberg = factory(window.jQuery, Modernizr);
  }
})(function ($, Modernizr) {
  'use strict';

  function Heidelberg(el, options) {

    // Allow developer to omit new when instantiating
    if (!(this instanceof Heidelberg)) {
      if (el.length) {
        Array.prototype.forEach.call(el, function(n) {
          return new Heidelberg(n, options);
        });
      } else {
        return new Heidelberg(el, options);
      }
    }

    // OPTIONS
    var defaults = {
      nextButton: $(),
      previousButton: $(),
      hasSpreads: false,
      canClose: false,
      arrowKeys: true,
      concurrentAnimations: null,
      limitPageTurns: true,
      initialActivePage: 0,
      onPageTurn: function() {},
      onSpreadSetup: function() {}
    };

    this.options = $.extend({}, defaults, options);

    // PRIVATE VARIABLES
    // Main element always a jQuery object
    this.el = (el instanceof $) ? el : $(el);
    this.el.attr('data-useragent', navigator.userAgent); // Add user agent attribute to HTMLElement - used in CSS selection ( for IE10 detection )
    // RUN
    this.init();

  }

  Heidelberg.prototype.init = function() {

    var el      = this.el;
    var els     = {};
    var options = this.options;

    setTimeout(function() {
      el.addClass('is-ready');
    }, 0);

    if(options.hasSpreads) {
      this.setupSpreads();
    }

    var leftFunction  = options.canClose ? 'even' : 'odd';
    var rightFunction = options.canClose ? 'odd' : 'even';

    els.pages      = $('.Heidelberg-Page', this.el);
    els.pagesLeft  = $('.Heidelberg-Page:nth-child('+leftFunction+')', el);
    els.pagesRight = $('.Heidelberg-Page:nth-child('+rightFunction+')', el);

    // if initialActivePage is odd, we substract one.
    var initialActivePage = options.initialActivePage & 1
      ? options.initialActivePage - 1
      : options.initialActivePage;

    if(!options.canClose) {
      var coverEl = $('<div />').addClass('Heidelberg-HiddenCover');
      el.prepend(coverEl.clone());
      el.append(coverEl.clone());

      els.pages.eq(initialActivePage).add(
        els.pages.eq(initialActivePage + 1)).addClass('is-active');
    }
    else {
      if (options.initialActivePage !== 0) {
        els.pages.eq(initialActivePage).add(
          els.pages.eq(initialActivePage + 1)).addClass('is-active');
      } else {
        els.pages.eq(0).addClass('is-active');
      }
    }

    els.previousTrigger = els.pagesLeft.add(options.previousButton);
    els.nextTrigger     = els.pagesRight.add(options.nextButton);

    els.previousTrigger.on('click', function() {
      this.turnPage('back');
    }.bind(this));

    els.nextTrigger.on('click', function() {
      this.turnPage('forwards');
    }.bind(this));

    if(typeof Hammer !== 'undefined') {
      var opts = {
        drag_min_distance: 5,
        swipe_velocity: 0.3
      };

      Hammer(els.pagesLeft, opts).on("dragright", function(evt) {
        this.turnPage('back');
        evt.gesture.stopDetect();
      }.bind(this));

      Hammer(els.pagesRight, opts).on("dragleft", function(evt) {
        this.turnPage('forwards');
        evt.gesture.stopDetect();
      }.bind(this));
    }

    var forwardsKeycode = 37;
    var backKeycode = 39;

    if((!Modernizr.csstransforms3d)) {
      forwardsKeycode = 39;
      backKeycode = 37;
    }

    if(options.arrowKeys) {
      $(document).keydown(function(e){
        if (e.keyCode == forwardsKeycode) {
          this.turnPage('forwards');
          return false;
        }
        if (e.keyCode == backKeycode) {
          this.turnPage('back');
          return false;
        }
      }.bind(this));
    }
  };

  Heidelberg.prototype.turnPage = function(arg) {

    var el        = this.el;
    var els       = {};
    var options   = this.options;
    var index     = {};
    var direction = arg;

    els.pages          = $('.Heidelberg-Page', el);
    els.pagesActive    = $('.Heidelberg-Page.is-active', el);
    els.pagesAnimating = $('.Heidelberg-Page.is-animating', el);
    els.children       = $('.Heidelberg-Page, .Heidelberg-HiddenCover', el);

    var maxAnimations = options.concurrentAnimations && els.pagesAnimating.length > options.concurrentAnimations;
    var maxAnimationsBrowser = !Modernizr.preserve3d && els.pagesAnimating.length > 2 && options.limitPageTurns;

    if(maxAnimations || maxAnimationsBrowser) {
      return;
    }

    if ( options.hasSpreads ) {
      index.activeRight = els.pagesActive.eq(1).index();
      index.activeLeft  = index.activeRight - 1;
    } else {// Single page spreads
      index.activeLeft  = els.pagesActive.eq(0).index(); // Note about fix: the double spread code above caused code to wrap to bottom of array . This is the fix for double spreads.
      index.activeRight = index.activeLeft + 1;
    }

    var isFirstPage = els.pages.first().index() == index.activeLeft && direction == 'back';
    var isLastPage  = els.pages.last().index() == index.activeRight && direction == 'forwards';

    if(isFirstPage || isLastPage) {
      return;
    }

    if(typeof arg == 'number') {
      var isOdd         = arg & 1;
      var isRight       = options.canClose ? isOdd : !isOdd;

      index.targetRight = isRight ? arg : arg + 1;
      index.targetLeft  = index.targetRight - 1;

      if (index.targetLeft == index.activeLeft) {
        return;
      }
      else if(index.targetLeft > index.activeRight) {
        direction           = 'forwards';
        index.target        = index.targetLeft;
        index.targetSibling = index.target + 1;
      }
      else {
        direction           = 'back';
        index.target        = index.targetRight;
        index.targetSibling = index.target - 1;
      }

      if ( ! options.hasSpreads )
      {
        index.target = index.target - 1;
        index.targetSibling = index.targetSibling - 1;
      }

    }
    else {
      index.target        = direction == 'forwards' ? index.activeRight + 1 : index.activeLeft - 1;
      index.targetSibling = direction == 'forwards' ? index.activeRight + 2 : index.activeLeft - 2;
    }

    if ( ! options.hasSpreads && direction == 'forwards' && index.target == 2 ) {
      index.target = 1;
      index.targetSibling = 2;
    }

    els.pagesAnimatingOut = (direction == 'back') ? els.pagesActive.first() : els.pagesActive.last();
    els.pagesAnimatingIn  = els.children.eq(index.target);
    els.pagesTarget       = els.pagesAnimatingIn.add(els.children.eq(index.targetSibling));
    els.pagesAnimating    = els.pagesAnimatingIn.add(els.pagesAnimatingOut);

    els.pagesActive.removeClass('is-active').addClass('was-active');
    els.pagesTarget.addClass('is-active');

    if((Modernizr.csstransforms3d)) {
      els.pagesAnimating.addClass('is-animating');
    }

    els.pagesAnimating.on('webkitTransitionEnd oTransitionEnd msTransitionEnd transitionend', function () {
      els.pagesAnimating.removeClass('is-animating');
      els.pagesActive.removeClass('was-active');
    }.bind(document));

    options.onPageTurn(el, els);
    $(this).trigger('pageTurn.heidelberg', [el, els]);

  };

  Heidelberg.prototype.setupSpreads = function() {

    var el      = this.el;
    var options = this.options;

    $('.Heidelberg-Spread', el).each(function() {
      var spreadEl = $(this);
      var pageEl   = $('<div />').addClass('Heidelberg-Page with-Spread').html(spreadEl.clone());
      spreadEl.after(pageEl);
      spreadEl.replaceWith(pageEl.clone());
    });

    options.onSpreadSetup(el);
    $(this).trigger('spreadSetup.heidelberg', el);
  };
  return Heidelberg;
});
<|endoftext|>


<commit_before>'use strict';

var sensors = require('ds18x20'),
    intervalId;

sensors.getAll(function (err, results) { if (err) throw err;

    var list = Object.keys(results),
        results = list.map(function (item) { return results[item]; });

    intervalId = setInterval(function () {
        sensors.get(list, function (err, newResults) { if (err) throw err;

            var diff = newResults.map(function (temp, i) { return Math.abs(temp - results[i]); });

            console.log(diff);
            process.exit();
        });
    }, 500);

});

<commit_msg>Added some more functionality to util<commit_after>'use strict';

var logger = {
    levels: { debug: 0, info: 1, warn: 2, error: 3 },

    _level: 1,

    setLevel: function (level) { this._level = level; },

    debug: function () { this._log(0, 'DEBUG', arguments); },
    info: function () { this._log(1, 'INFO ', arguments); },
    log: function () { this._log(1, 'INFO ', arguments); },
    warn: function () { this._log(2, 'WARN ', arguments); },
    error: function () { this._log(3, 'ERROR', arguments); },

    _log: function (level, txt, args) {
        args = Object.keys(args).map(function (x) { return args[x]; });
        if (level >= this._level) {
            args.unshift(txt);
            console.log.apply(this, args);
        }
    }
}
    ,
    sensors = require('ds18x20'),
    intervalId;

sensors.getAll(function (err, results) { if (err) throw err;

    var list = Object.keys(results),
        results = list.map(function (item) { return results[item]; });

    if (list.length <= 1) {
        if (list.length === 0) { logger.warn('No devices found'); }
        else                   { logger.info('Only one device found'); }
        process.exit();
    }

    intervalId = setInterval(function () {
        sensors.get(list, function (err, newResults) { if (err) throw err;

            var finding = findDeviantDevice(list, results, newResults);

            results = newResults;

            // No deviant sensor detected
            if (finding === false) { logger.info('No deviant sensor found.'); return; }

            clearInterval(intervalId);

            logger.info('Found deviant device:', finding);
        });
    }, 1000);

});

function findDeviantDevice(ids, previousResults, newResults) {

    var diff = diffOfArray(previousResults, newResults),
        median = medianOfArray(diff),
        threshold = median * 10,
        findings = [];

    logger.debug('median:', median, 'threshold:', threshold)

    diff.forEach(function (value, index) {
        if (value > threshold) {
            logger.debug('OJOJ, found one!', ids[index], 'with difference:', value);
            findings.push(ids[index]);
        }
    });

    if (findings.length > 1) logger.warn('Found more than one deviant device. Ignoring readout!')

    return (findings.length === 1) ? findings[0] : false;
}

function diffOfArray(a, b) {
    return a.map(function (item, index) { return Math.abs(item - b[index]); });
}

function medianOfArray(values) {

    var l = values.length,
        m = Math.floor(l / 2),
        v = values
            .map(function (x) { return x; })
            .sort();

    return (l % 2) ? v[m] : (v[m - 1] + v[m]) / 2.0;
}

//logger.setLevel(logger.levels.debug);
//
//var finding = findDeviantDevice(
//    ['a', 'b', 'c', 'd', 'e'],
//    [1.0, 2.0, 3.0, 4.0, 5.0],
//    [5.1, 2.3, 3.2, 4.1, 5.3]
//);
//
//logger.info('finding:', finding);<|endoftext|>


<commit_before>import loggerCreator from "app/utils/logger";
//noinspection JSUnresolvedVariable
var moduleLogger = loggerCreator("Sidebar");

import React, { Component } from "react";
import { Image, StyleSheet, Text, View, Animated, PanResponder } from "react-native";
import { observer } from "mobx-react";
import { colors } from "app/styles/styles";

const styles = StyleSheet.create({
  sidebar: {
    position: "absolute",
    backgroundColor: colors.CONTAINER_BACKGROUND_NORMAL,
    top: 54,
    bottom: -1,
    borderColor: colors.CYAN_BRIGHT,
    borderStyle: "solid",
    borderWidth: 1,
  },
});

@observer
export default class Sidebar extends Component {
  componentWillMount() {
    this.openPosition = -2;
    this.closePosition = this.openPosition - this.props.width;
    this.state = { positionAnimation: new Animated.Value(this.props.isOpen ? this.openPosition : this.closePosition) };

    this.panResponder = PanResponder.create({
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,
      onPanResponderGrant: this.onPanResponderGrant,
      onPanResponderMove: this.onPanResponderMove,
      onPanResponderRelease: this.onPanResponderRelease,
    });
  }

  componentWillReceiveProps(nextProps) {
    loggerCreator("componentWillReceiveProps", moduleLogger);

    Animated.timing(this.state.positionAnimation, {
      toValue: nextProps.isOpen ? this.openPosition : this.closePosition,
      duration: 200,
    }).start();
  }

  onMoveShouldSetPanResponder = (evt, gestureState) => {
    return gestureState.numberActiveTouches > 0 && Math.abs(gestureState.dx) > 10;
  };

  onPanResponderGrant = () => {
    loggerCreator("onPanResponderGrant", moduleLogger);
    this.state.positionAnimation.setOffset(this.state.positionAnimation._value);
    this.state.positionAnimation.setValue(0);
  };

  onPanResponderMove = (evt, gestureState) => {
    this.state.positionAnimation.setValue(gestureState.dx);
  };

  onPanResponderRelease = (evt, gestureState) => {
    loggerCreator("onPanResponderRelease", moduleLogger);

    this.state.positionAnimation.flattenOffset();
    this.props.onChangeOpen(gestureState.vx > 0);
  };

  render() {
    const targetSide = this.props.fromLeft ? "left" : "right";
    const targetRoundedCorner = this.props.fromLeft ? "borderTopRightRadius" : "borderTopLeftRadius";

    return (
      <Animated.View
        style={[
          styles.sidebar,
          {
            width: this.props.width,
            [targetRoundedCorner]: 5,
            [targetSide]: this.state.positionAnimation.interpolate({
              inputRange: [this.closePosition, this.openPosition],
              outputRange: [this.closePosition, this.openPosition],
              extrapolate: "clamp",
            }),
          },
        ]}
        {...this.panResponder.panHandlers}>
        {this.props.children}
      </Animated.View>
    );
  }
}

Sidebar.propTypes = {
  width: React.PropTypes.number.isRequired,
  fromLeft: React.PropTypes.bool.isRequired,

  isOpen: React.PropTypes.bool.isRequired,
  onChangeOpen: React.PropTypes.func.isRequired,
};
<commit_msg>sidebar scrubs - allow you to open a sidebar without a button<commit_after>import loggerCreator from "app/utils/logger";
//noinspection JSUnresolvedVariable
var moduleLogger = loggerCreator("Sidebar");

import React, { Component } from "react";
import { Image, StyleSheet, Text, View, Animated, PanResponder } from "react-native";
import { observer } from "mobx-react";
import { colors } from "app/styles/styles";

const SCRUB_WIDTH = 30;

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    top: 54,
    bottom: -1,
    flexDirection: "row",
  },
  scrub: {
    width: SCRUB_WIDTH,
    backgroundColor: "transparent",
  },
  sidebar: {
    borderWidth: 1,
    borderColor: colors.CYAN_BRIGHT,
    borderStyle: "solid",
    backgroundColor: colors.CONTAINER_BACKGROUND_NORMAL,
  },
});

@observer
export default class Sidebar extends Component {
  componentWillMount() {
    this.openPosition = -2 - SCRUB_WIDTH;
    this.closePosition = this.openPosition - this.props.width;
    this.state = { positionAnimation: new Animated.Value(this.props.isOpen ? this.openPosition : this.closePosition) };

    this.panResponder = PanResponder.create({
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,
      onPanResponderGrant: this.onPanResponderGrant,
      onPanResponderMove: this.onPanResponderMove,
      onPanResponderRelease: this.onPanResponderRelease,
    });
  }

  componentWillReceiveProps(nextProps) {
    loggerCreator("componentWillReceiveProps", moduleLogger);

    Animated.timing(this.state.positionAnimation, {
      toValue: nextProps.isOpen ? this.openPosition : this.closePosition,
      duration: 200,
    }).start();
  }

  onMoveShouldSetPanResponder = (evt, gestureState) => {
    return gestureState.numberActiveTouches > 0 && Math.abs(gestureState.dx) > 1;
  };

  onPanResponderGrant = () => {
    loggerCreator("onPanResponderGrant", moduleLogger);
    this.state.positionAnimation.setOffset(this.state.positionAnimation._value);
    this.state.positionAnimation.setValue(0);
  };

  onPanResponderMove = (evt, gestureState) => {
    this.state.positionAnimation.setValue(gestureState.dx);
  };

  onPanResponderRelease = (evt, gestureState) => {
    loggerCreator("onPanResponderRelease", moduleLogger);

    this.state.positionAnimation.flattenOffset();
    this.props.onChangeOpen(gestureState.vx > 0);
  };

  render() {
    const targetSide = this.props.fromLeft ? "left" : "right";
    const targetRoundedCorner = this.props.fromLeft ? "borderTopRightRadius" : "borderTopLeftRadius";

    return (
      <Animated.View
        style={[
          styles.container,
          {
            [targetSide]: this.state.positionAnimation.interpolate({
              inputRange: [this.closePosition, this.openPosition],
              outputRange: [this.closePosition, this.openPosition],
              extrapolate: "clamp",
            }),
          },
        ]}
        {...this.panResponder.panHandlers}>
        <View style={styles.scrub} />
        <View
          style={[
            styles.sidebar,
            {
              width: this.props.width,
              [targetRoundedCorner]: 5,
            },
          ]}>
          {this.props.children}
        </View>
        <View style={styles.scrub} />
      </Animated.View>
    );
  }
}

Sidebar.propTypes = {
  width: React.PropTypes.number.isRequired,
  fromLeft: React.PropTypes.bool.isRequired,

  isOpen: React.PropTypes.bool.isRequired,
  onChangeOpen: React.PropTypes.func.isRequired,
};
<|endoftext|>


<commit_before>OMAR.views.FederatedRasterSearch = Backbone.View.extend({
    el:"#rasterSearchPageId",
    bboxView:null,
    initialize:function(params){
        this.bboxView = new OMAR.views.BBOX();
        this.bboxModel = this.bboxView.model;
        this.dateTimeRangeView = new OMAR.views.SimpleDateRangeView();
        this.dateTimeRangeModel = this.dateTimeRangeView.model;
        this.omarServerCollectionView = new OMAR.views.OmarServerCollectionView(
            {model:new OMAR.models.OmarServerCollection()}
        );
        this.mapView = new OMAR.views.Map(params.map);
        this.mapView.setBboxModel(this.bboxModel);
        this.mapView.setServerCollection(this.omarServerCollectionView.model);
        this.setElement(this.el);

        this.dateTimeRangeModel.bind('change', this.updateFootprintCql, this)
    },
    events: {
        "click #SearchRasterId": "searchRaster"
    },
    render:function(){
        if(this.bboxView)
        {
            this.bboxView.render();
        }
        if(this.pointView)
        {
            this.pointView.render();
        }
        if(this.dateTimeRangeView)
        {
            this.dateTimeRangeView.render();
        }

        if(this.mapView)
        {
            this.mapView.render();
        }
        // lets make sure that that the map object exists
        // before we start the AJAX calls for fetching the server lists
        //
        if(this.omarServerCollectionView)
        {
            var collection =  this.omarServerCollectionView;

            collection.model.fetch({success:function(){collection.render()},
                update: true, remove: false,date:{cache:false}});
            window.setTimeout(this.updateServers.bind(this),5000);
        }
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateFootprintCql:function(){
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateServers:function(){
        var collection =  this.omarServerCollectionView;
        collection.model.fetch({success:function(){},
            update: true, remove: false,date:{cache:false}});
        window.setTimeout(this.updateServers.bind(this),5000);
    },
    toCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");
        var bboxQueryCql = this.bboxModel.toCql("ground_geom");
        if(timeQueryCql&&bboxQueryCql)
        {
            result = "(("+bboxQueryCql+")AND(" +timeQueryCql+"))";
        }
        else if(bboxQueryCql)
        {
            result=bboxQueryCql;
        }
        else
        {
            result = timeQueryCql;
        }

        return result;
    },
    centerResize:function(){
        var tabHeight = $(".ui-tabs-nav").height()*2;
        var tabWidth = 0;//$("#tabView ul:first li").width();
        var innerHeight = $(".inner-center").height();
        var innerWidth = $(".inner-center").width();
        var toolBarHeight = $("#mapToolBar").height();
        var mapReadoutsHeight = $("#mapReadouts").height();
        var mapContainerWidth = innerWidth;
        var mapHeight = innerHeight - (toolBarHeight+
                                       mapReadoutsHeight+
                                        tabHeight);
        var mapContainerHeight = mapHeight + toolBarHeight+mapReadoutsHeight;
        $("#map").height(mapHeight);
        $("#map").width(innerWidth-4);
        $("#mapContainer").height(mapContainerHeight);
        $("#mapContainer").width(mapContainerWidth-4);

        this.mapView.mapResize();
    },
    toFootprintCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");

        // add all criteria here later.   Fo now we will just do time
        //
        result = timeQueryCql;

        return result;
    },
    searchRaster:function(){
        var wfs = new OMAR.models.Wfs({"resultType":"hits"});
        var cqlFilter = this.toCql();
        wfs.set("filter",cqlFilter);

        for(var idx = 0; idx <this.omarServerCollectionView.model.size();++idx )
        {
            var model = this.omarServerCollectionView.model.at(idx);
            if(model.get("enabled"))
            {
                this.omarServerCollectionView.setBusy(model.id, true);
                wfs.set("url",model.get("url")+"/wfs");
                $.ajax({
                    url: wfs.toUrl()+"&callback=?",
                    cache:false,
                    type: "GET",
                    crossDomain:true,
                    dataType: "json",
                    timeout: 60000,
                    modelId:model.id,
                    scopePtr:this,
                    success: function(response) {
                        if(response.numberOfFeatures!=null)
                        {
                            var numberOfFeatures = response.numberOfFeatures;
                            this.scopePtr.omarServerCollectionView.setBusy(this.modelId, false);
                            var tempModel = this.scopePtr.omarServerCollectionView.model.get(this.modelId);
                            if(tempModel)
                            {
                                tempModel.set({"count":numberOfFeatures});
                            }
                        }
                    },
                    error: function(x, t, m) {
                        var count = "Error";
                        if(t==="timeout") {
                            count = "Timeout"
                        } else {
                            //alert(JSON.stringify(x)+ " " +t + " " + m);
                        }
                        var tempModel = this.scopePtr.omarServerCollectionView.model.get(this.modelId);
                        this.scopePtr.omarServerCollectionView.setBusy(this.modelId, false);
                        if(tempModel)
                        {
                            tempModel.get(this.modelId).set({"count":count});
                        }
                    }
                });
            }
            else
            {

            }
        }
    }
});

OMAR.federatedRasterSearch = null;
OMAR.pages.FederatedRasterSearch = (function($, params){
    OMAR.federatedRasterSearch = new OMAR.views.FederatedRasterSearch(params);
    return OMAR.federatedRasterSearch;
});

$(document).ready(function () {

    // OUTER-LAYOUT

    $('body').layout({
        center__paneSelector:	".outer-center"
        ,	west__paneSelector:		".outer-west"
        ,	east__paneSelector:		".outer-east"
        ,	west__size:				125
        ,	east__size:				125
        ,	spacing_open:			8  // ALL panes
        ,	spacing_closed:			12 // ALL panes
        //,	north__spacing_open:	0
        //,	south__spacing_open:	0
        ,	north__maxSize:			50
        ,   north__minSize:         50
        ,	south__maxSize:			50
        ,   south__minSize:         50

        // MIDDLE-LAYOUT (child of outer-center-pane)
        ,	center__childOptions: {
            center__paneSelector:	".middle-center"
            ,	west__paneSelector:		".middle-west"
            ,	east__paneSelector:		".middle-east"
            ,	west__size:				100
            ,	east__size:				100
            ,	spacing_open:			0  // ALL panes
            ,	spacing_closed:			0 // ALL panes

            // INNER-LAYOUT (child of middle-center-pane)
            ,	center__childOptions: {
                center__paneSelector:	".inner-center"
                ,	west__paneSelector:		".inner-west"
                ,	east__paneSelector:		".inner-east"
                ,	west__size:				250
                ,   west__minSize:          250
                ,	east__size:				75
                ,	spacing_open:			8  // ALL panes
                ,	spacing_closed:			8  // ALL panes
                ,	west__spacing_closed:	8
                ,	east__spacing_closed:	8
                ,onresize_end:function(){
                    OMAR.federatedRasterSearch.centerResize();
                }
            }
        }
    });

    init();
    OMAR.federatedRasterSearch.centerResize();
    //$( "#accordion" ).accordion();
});

function generateKmlQuery() {
    alert("kml query code goes here.")
}

function refreshFootprints() {
    alert("refresh footprints code goes here.")
}

function search() {
    alert("search code goes here.")
}

function foo() {
    alert("search code goes here.")
}
<commit_msg>Updating sizes<commit_after>OMAR.views.FederatedRasterSearch = Backbone.View.extend({
    el:"#rasterSearchPageId",
    bboxView:null,
    initialize:function(params){
        this.bboxView = new OMAR.views.BBOX();
        this.bboxModel = this.bboxView.model;
        this.dateTimeRangeView = new OMAR.views.SimpleDateRangeView();
        this.dateTimeRangeModel = this.dateTimeRangeView.model;
        this.omarServerCollectionView = new OMAR.views.OmarServerCollectionView(
            {model:new OMAR.models.OmarServerCollection()}
        );
        this.mapView = new OMAR.views.Map(params.map);
        this.mapView.setBboxModel(this.bboxModel);
        this.mapView.setServerCollection(this.omarServerCollectionView.model);
        this.setElement(this.el);

        this.dateTimeRangeModel.bind('change', this.updateFootprintCql, this)
    },
    events: {
        "click #SearchRasterId": "searchRaster"
    },
    render:function(){
        if(this.bboxView)
        {
            this.bboxView.render();
        }
        if(this.pointView)
        {
            this.pointView.render();
        }
        if(this.dateTimeRangeView)
        {
            this.dateTimeRangeView.render();
        }

        if(this.mapView)
        {
            this.mapView.render();
        }
        // lets make sure that that the map object exists
        // before we start the AJAX calls for fetching the server lists
        //
        if(this.omarServerCollectionView)
        {
            var collection =  this.omarServerCollectionView;

            collection.model.fetch({success:function(){collection.render()},
                update: true, remove: false,date:{cache:false}});
            window.setTimeout(this.updateServers.bind(this),5000);
        }
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateFootprintCql:function(){
        this.mapView.setCqlFilterToFootprintLayers(this.toFootprintCql());
    },
    updateServers:function(){
        var collection =  this.omarServerCollectionView;
        collection.model.fetch({success:function(){},
            update: true, remove: false,date:{cache:false}});
        window.setTimeout(this.updateServers.bind(this),5000);
    },
    toCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");
        var bboxQueryCql = this.bboxModel.toCql("ground_geom");
        if(timeQueryCql&&bboxQueryCql)
        {
            result = "(("+bboxQueryCql+")AND(" +timeQueryCql+"))";
        }
        else if(bboxQueryCql)
        {
            result=bboxQueryCql;
        }
        else
        {
            result = timeQueryCql;
        }

        return result;
    },
    centerResize:function(){
        var tabHeight = $(".ui-tabs-nav").height()*1.5;
        var tabWidth = 0;//$("#tabView ul:first li").width();
        var innerHeight = $(".inner-center").height();
        var innerWidth = $(".inner-center").width();
        var toolBarHeight = $("#mapToolBar").height();
        var mapReadoutsHeight = $("#mapReadouts").height();
        var mapContainerWidth = innerWidth;
        var mapHeight = innerHeight - (toolBarHeight+
                                       mapReadoutsHeight+
                                        tabHeight);
        var mapContainerHeight = mapHeight + toolBarHeight+mapReadoutsHeight;
        $("#map").height(mapHeight);
        $("#map").width(innerWidth-4);
        $("#mapContainer").height(mapContainerHeight);
        $("#mapContainer").width(mapContainerWidth-4);

        this.mapView.mapResize();
    },
    toFootprintCql:function(){
        var result = "";
        var timeQueryCql = this.dateTimeRangeModel.toCql("acquisition_date");

        // add all criteria here later.   Fo now we will just do time
        //
        result = timeQueryCql;

        return result;
    },
    searchRaster:function(){
        var wfs = new OMAR.models.Wfs({"resultType":"hits"});
        var cqlFilter = this.toCql();
        wfs.set("filter",cqlFilter);

        for(var idx = 0; idx <this.omarServerCollectionView.model.size();++idx )
        {
            var model = this.omarServerCollectionView.model.at(idx);
            if(model.get("enabled"))
            {
                this.omarServerCollectionView.setBusy(model.id, true);
                wfs.set("url",model.get("url")+"/wfs");
                $.ajax({
                    url: wfs.toUrl()+"&callback=?",
                    cache:false,
                    type: "GET",
                    crossDomain:true,
                    dataType: "json",
                    timeout: 60000,
                    modelId:model.id,
                    scopePtr:this,
                    success: function(response) {
                        if(response.numberOfFeatures!=null)
                        {
                            var numberOfFeatures = response.numberOfFeatures;
                            this.scopePtr.omarServerCollectionView.setBusy(this.modelId, false);
                            var tempModel = this.scopePtr.omarServerCollectionView.model.get(this.modelId);
                            if(tempModel)
                            {
                                tempModel.set({"count":numberOfFeatures});
                            }
                        }
                    },
                    error: function(x, t, m) {
                        var count = "Error";
                        if(t==="timeout") {
                            count = "Timeout"
                        } else {
                            //alert(JSON.stringify(x)+ " " +t + " " + m);
                        }
                        var tempModel = this.scopePtr.omarServerCollectionView.model.get(this.modelId);
                        this.scopePtr.omarServerCollectionView.setBusy(this.modelId, false);
                        if(tempModel)
                        {
                            tempModel.get(this.modelId).set({"count":count});
                        }
                    }
                });
            }
            else
            {

            }
        }
    }
});

OMAR.federatedRasterSearch = null;
OMAR.pages.FederatedRasterSearch = (function($, params){
    OMAR.federatedRasterSearch = new OMAR.views.FederatedRasterSearch(params);
    return OMAR.federatedRasterSearch;
});

$(document).ready(function () {

    // OUTER-LAYOUT

    $('body').layout({
        center__paneSelector:	".outer-center"
        ,	west__paneSelector:		".outer-west"
        ,	east__paneSelector:		".outer-east"
        ,	west__size:				125
        ,	east__size:				125
        ,	spacing_open:			8  // ALL panes
        ,	spacing_closed:			12 // ALL panes
        //,	north__spacing_open:	0
        //,	south__spacing_open:	0
        ,	north__maxSize:			50
        ,   north__minSize:         50
        ,	south__maxSize:			50
        ,   south__minSize:         50

        // MIDDLE-LAYOUT (child of outer-center-pane)
        ,	center__childOptions: {
            center__paneSelector:	".middle-center"
            ,	west__paneSelector:		".middle-west"
            ,	east__paneSelector:		".middle-east"
            ,	west__size:				100
            ,	east__size:				100
            ,	spacing_open:			0  // ALL panes
            ,	spacing_closed:			0 // ALL panes

            // INNER-LAYOUT (child of middle-center-pane)
            ,	center__childOptions: {
                center__paneSelector:	".inner-center"
                ,	west__paneSelector:		".inner-west"
                ,	east__paneSelector:		".inner-east"
                ,	west__size:				250
                ,   west__minSize:          250
                ,	east__size:				75
                ,	spacing_open:			8  // ALL panes
                ,	spacing_closed:			8  // ALL panes
                ,	west__spacing_closed:	8
                ,	east__spacing_closed:	8
                ,onresize_end:function(){
                    OMAR.federatedRasterSearch.centerResize();
                }
            }
        }
    });

    init();
    OMAR.federatedRasterSearch.centerResize();
    $( "#accordion" ).accordion();
});

function generateKmlQuery() {
    alert("kml query code goes here.")
}

function refreshFootprints() {
    alert("refresh footprints code goes here.")
}

function search() {
    alert("search code goes here.")
}

function foo() {
    alert("search code goes here.")
}
<|endoftext|>


<commit_before>import perdido from 'perdido'; // eslint-disable-line import/no-unresolved
import {jssSetup, jssReset, testMethod} from './helpers';

afterEach(jssReset);
beforeEach(jssSetup);

/* eslint-disable max-len */
describe('Perdido Utilities', () => {
  testMethod('can support applying edit indicator', perdido.utils.edit, [
    'a {\n}',
    'a *:not(input):not(textarea):not(select) {',
    '  background-color: rgba(0, 0, 255, 0.1);\n}'
  ]);

  testMethod('can support applying clearfix', perdido.utils.clearFix, [
    'a {\n  *zoom: 1;\n}',
    'a:before {\n  content: \'\';\n  display: table;\n}',
    'a:after {\n  content: \'\';\n  display: table;\n  clear: both;\n}'
  ]);
});
/* eslint-enable max-len */
<commit_msg>fixed remaining test - output appears to be correct and assertion didn't make sense (needs review)<commit_after>import perdido from 'perdido'; // eslint-disable-line import/no-unresolved
import {jssSetup, jssReset, testMethod} from './helpers';

afterEach(jssReset);
beforeEach(jssSetup);

/* eslint-disable max-len */
describe('Perdido Utilities', () => {
  testMethod('can support applying edit indicator', perdido.utils.edit, [
    'a *:not(input):not(textarea):not(select) {',
    '  background-color: rgba(0, 0, 255, 0.1);\n}'
  ]);

  testMethod('can support applying clearfix', perdido.utils.clearFix, [
    'a {\n  *zoom: 1;\n}',
    'a:before {\n  content: \'\';\n  display: table;\n}',
    'a:after {\n  content: \'\';\n  display: table;\n  clear: both;\n}'
  ]);
});
/* eslint-enable max-len */
<|endoftext|>


<commit_before>window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

 // taken from
 // http://stackoverflow.com/questions/7799722/how-do-i-implement-move-forward-action-for-google-street-view
 function difference(link, angle) {

    var diff = Math.abs((svl.panorama.pov.heading % 360) - link.heading + angle);
    if(diff>180)
        diff=Math.abs(360-diff);

    return diff;

}

function movePano(angle) {
  var curr;
  var found = false;
  for(var i = 0; i < svl.panorama.links.length; i++) {
    var diffLast = difference(svl.panorama.links[i], angle);
    if(curr == undefined) {
      curr = svl.panorama.links[i];
    }
    if(diffLast <= 45){
        found = true;
    }
    var diffCurr = difference(curr, angle);
    if(diffCurr > diffLast && diffLast <= 45 ) {
        curr = svl.panorama.links[i];
        found = true;
    }
  }
  if(found){
    svl.panorama.setPano(curr.pano);
    }
}

/**
 * A Keyboard module
 * @param $ jQuery
 * @returns {{className: string}}
 * @constructor
 * @memberof svl
 */

function Keyboard ($) {
    var self = {
            className : 'Keyboard'
        };
    var status = {
        focusOnTextField: false,
        shiftDown: false
    };

    var $textareaComment;

    function init () {
        if ('ui' in svl && 'form' in svl.ui) {
            $textareaComment = (svl.ui.form.commentField.length) > 0 ? svl.ui.form.commentField : null;
        }

        if ($textareaComment) {
          $textareaComment.bind('focus', textFieldFocus);
          $textareaComment.bind('blur', textFieldBlur);
        }

        $(document).bind('keyup', documentKeyUp);
        $(document).bind('keydown', documentKeyDown);
    }

    /**
     * This is a callback for a key down event
     * @param {object} e An event object
     * @private
     */
    function documentKeyDown(e) {
        // The callback method that is triggered with a keyUp event.
        if (!status.focusOnTextField) {
            switch (e.keyCode) {
                case 16:
                    // "Shift"
                    status.shiftDown = true;
                    break;
            }
        }
    }

    /**
     * This is a callback for a key up event.
     * @param {object} e An event object
     * @private
     */
    function documentKeyUp (e) {
        switch (e.keyCode) {
            // "left"
            case 37:
                movePano(270);
                break;
            // "up"
            case 38:
                movePano(0);
                break;
            // "right"
            case 39:
                movePano(90);
                break;
            // "down"
            case 40:
                movePano(180);
                break;
        }
        if ("onboarding" in svl && svl.onboarding && svl.onboarding.isOnboarding()) {
            // Don't allow users to use keyboard shortcut during the onboarding.
            return;
        }

        // This is a callback method that is triggered when a keyDown event occurs.
        if (!status.focusOnTextField) {
            // if ("contextMenu" in svl && svl.contextMenu) {
            //     svl.contextMenu.hide();
            // }

            switch (e.keyCode) {
                // "Enter"
                case 13:
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.contextMenu.hide();
                    }
                    break;
                case 16:
                    // "Shift"
                    status.shiftDown = false;
                    break;
                case 27:
                    // "Escape"
                    if (svl.canvas.getStatus('drawing')) {
                        svl.canvas.cancelDrawing();
                    } else {
                        svl.ribbon.backToWalk();
                    }
                    break;
                    case 49:
                    // "1"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='1'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("CurbRamp");
                        break;
                    }
                    break;
                case 50:
                    // "2"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='2'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("NoCurbRamp");
                    }
                    break;
                case 51:
                    // "3"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='3'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("Obstacle");
                    }
                    break;
                case 52:
                    // "4"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='4'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("SurfaceProblem");
                    }
                    break;
                case 53:
                    // "5"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='5'}).prop("checked", true).trigger("click");
                    }
                    else{

                    }
                    break;
                case 66:
                    // "b" for a blocked view
                    svl.ribbon.modeSwitch("Occlusion");
                    break;
                case 67:
                    // "c" for CurbRamp. Switch the mode to the CurbRamp labeling mode.
                    svl.ribbon.modeSwitch("CurbRamp");
                    break;
                case 69:
                    // "e" for Explore. Switch the mode to Walk (camera) mode.
                    svl.ribbon.modeSwitch("Walk");
                    break;
                case 77:
                    // "m" for MissingCurbRamp. Switch the mode to the MissingCurbRamp labeling mode.
                    svl.ribbon.modeSwitch("NoCurbRamp");
                    break;
                case 78:
                    svl.ribbon.modeSwitch("NoSidewalk");
                    break;
                case 79:
                    // "o" for Obstacle
                    svl.ribbon.modeSwitch("Obstacle");
                    break;
                case 83:
                    svl.ribbon.modeSwitch("SurfaceProblem");
                    break;
                case 90:
                    // "z" for zoom. By default, it will zoom in. If "shift" is down, it will zoom out.
                    if (status.shiftDown) {
                        // Zoom out
                        if ("zoomControl" in svl) {
                            svl.zoomControl.zoomOut();
                        }
                    } else {
                        // Zoom in
                        if ("zoomControl" in svl)
                            svl.zoomControl.zoomIn();
                    }
            }
        }
    }

    /**
     * This is a callback function called when any of the text field is blurred.
     * @private
     */
    function textFieldBlur () {
        status.focusOnTextField = false
    }

    /**
     * This is a callback function called when any of the text field is focused.
     * @private
     */
    function textFieldFocus () {
        status.focusOnTextField = true;
    }

    /**
     * Get status
     * @param {string} key Field name
     * @returns {*}
     */
    function getStatus (key) {
        if (!(key in status)) {
            console.warn("You have passed an invalid key for status.")
        }
        return status[key];
    }

    /**
     * This method returns whether a shift key is currently pressed or not.
     * @returns {boolean}
     */
    function isShiftDown () {
        return status.shiftDown;
    }

    /**
     * Set status
     * @param key Field name
     * @param value Field value
     * @returns {setStatus}
     */
    function setStatus (key, value) {
        if (key in status) {
            status[key] = value;
        }
        return this;
    }

    self.getStatus = getStatus;
    self.isShiftDown = isShiftDown;
    self.setStatus = setStatus;

    init();
    return self;
}
<commit_msg>Moving and Rotating with Arrow Keys<commit_after>/**
 * A Keyboard module
 * @param $ jQuery
 * @returns {{className: string}}
 * @constructor
 * @memberof svl
 */

function Keyboard ($) {
    var self = {
            className : 'Keyboard'
        };
    var status = {
        focusOnTextField: false,
        shiftDown: false
    };

    var $textareaComment;

    function init () {
        if ('ui' in svl && 'form' in svl.ui) {
            $textareaComment = (svl.ui.form.commentField.length) > 0 ? svl.ui.form.commentField : null;
        }

        if ($textareaComment) {
          $textareaComment.bind('focus', textFieldFocus);
          $textareaComment.bind('blur', textFieldBlur);
        }

        $(document).bind('keyup', documentKeyUp);
        $(document).bind('keydown', documentKeyDown);
    }
     // taken from
    // http://stackoverflow.com/questions/7799722/how-do-i-implement-move-forward-action-for-google-street-view
    function headingDifference(link, angle) {

        var diff = Math.abs((svl.panorama.pov.heading % 360) - link.heading + angle);
        if(diff>180)
            diff=Math.abs(360-diff);

        return diff;

    }

    function movePano(angle) {
        var curr;
        var found = false;
        var len =  svl.panorama.links.length;
        for(var i = 0; i < len; i++) {
            var diffLast = headingDifference(svl.panorama.links[i], angle);
            if(curr == undefined) {
                curr = svl.panorama.links[i];
            }
            if(diffLast <= 90){
                found = true;
            }
            var diffCurr = headingDifference(curr, angle);
            if(diffCurr > diffLast && diffLast <= 90) {
                curr = svl.panorama.links[i];
                found = true;
            }
        }
        if(found){
            svl.panorama.setPano(curr.pano);
        }
    }

    function rotatePov(degree){
        var heading =  svl.panorama.pov.heading;
        var pitch = svl.panorama.pov.pitch;
        var zoom = svl.panorama.pov.zoom;
        heading += degree;
        if(heading < 0)
            heading += 360;
        heading = heading % 360;
        svl.panorama.setPov({heading: heading, pitch: pitch, zoom: zoom});

    }

    /**
     * This is a callback for a key down event
     * @param {object} e An event object
     * @private
     */
    function documentKeyDown(e) {
        if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
            e.preventDefault();
        }

        switch (e.keyCode) {
            // "left"
            // rotate pano
            case 37:
                rotatePov(-2);
                break;
             // "right"
            // rotate pano
            case 39:
                rotatePov(2);
                break;

        }
        // The callback method that is triggered with a keyUp event.
        if (!status.focusOnTextField) {
            switch (e.keyCode) {
                case 16:
                    // "Shift"
                    status.shiftDown = true;
                    break;
            }
        }
    }

    function documentKeyPress (e) {

    }
    /**
     * This is a callback for a key up event.
     * @param {object} e An event object
     * @private
     */
    function documentKeyUp (e) {
        switch (e.keyCode) {
            // "up"
            case 38:
                movePano(0);
                break;
            // "down"
            case 40:
                movePano(180);
                break;
        }
        if ("onboarding" in svl && svl.onboarding && svl.onboarding.isOnboarding()) {
            // Don't allow users to use keyboard shortcut during the onboarding.
            return;
        }

        // This is a callback method that is triggered when a keyDown event occurs.
        if (!status.focusOnTextField) {
            // if ("contextMenu" in svl && svl.contextMenu) {
            //     svl.contextMenu.hide();
            // }

            switch (e.keyCode) {
                // "Enter"
                case 13:
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.contextMenu.hide();
                    }
                    break;
                case 16:
                    // "Shift"
                    status.shiftDown = false;
                    break;
                case 27:
                    // "Escape"
                    if (svl.canvas.getStatus('drawing')) {
                        svl.canvas.cancelDrawing();
                    } else {
                        svl.ribbon.backToWalk();
                    }
                    break;
                    case 49:
                    // "1"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='1'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("CurbRamp");
                        break;
                    }
                    break;
                case 50:
                    // "2"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='2'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("NoCurbRamp");
                    }
                    break;
                case 51:
                    // "3"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='3'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("Obstacle");
                    }
                    break;
                case 52:
                    // "4"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='4'}).prop("checked", true).trigger("click");
                    }
                    else{
                        svl.ribbon.modeSwitchClick("SurfaceProblem");
                    }
                    break;
                case 53:
                    // "5"
                    if ('contextMenu' in svl && svl.contextMenu.isOpen()) {
                        svl.ui.contextMenu.radioButtons.filter(function(){return this.value=='5'}).prop("checked", true).trigger("click");
                    }
                    else{

                    }
                    break;
                case 66:
                    // "b" for a blocked view
                    svl.ribbon.modeSwitch("Occlusion");
                    break;
                case 67:
                    // "c" for CurbRamp. Switch the mode to the CurbRamp labeling mode.
                    svl.ribbon.modeSwitch("CurbRamp");
                    break;
                case 69:
                    // "e" for Explore. Switch the mode to Walk (camera) mode.
                    svl.ribbon.modeSwitch("Walk");
                    break;
                case 77:
                    // "m" for MissingCurbRamp. Switch the mode to the MissingCurbRamp labeling mode.
                    svl.ribbon.modeSwitch("NoCurbRamp");
                    break;
                case 78:
                    svl.ribbon.modeSwitch("NoSidewalk");
                    break;
                case 79:
                    // "o" for Obstacle
                    svl.ribbon.modeSwitch("Obstacle");
                    break;
                case 83:
                    svl.ribbon.modeSwitch("SurfaceProblem");
                    break;
                case 90:
                    // "z" for zoom. By default, it will zoom in. If "shift" is down, it will zoom out.
                    if (status.shiftDown) {
                        // Zoom out
                        if ("zoomControl" in svl) {
                            svl.zoomControl.zoomOut();
                        }
                    } else {
                        // Zoom in
                        if ("zoomControl" in svl)
                            svl.zoomControl.zoomIn();
                    }
            }
        }
    }

    /**
     * This is a callback function called when any of the text field is blurred.
     * @private
     */
    function textFieldBlur () {
        status.focusOnTextField = false
    }

    /**
     * This is a callback function called when any of the text field is focused.
     * @private
     */
    function textFieldFocus () {
        status.focusOnTextField = true;
    }

    /**
     * Get status
     * @param {string} key Field name
     * @returns {*}
     */
    function getStatus (key) {
        if (!(key in status)) {
            console.warn("You have passed an invalid key for status.")
        }
        return status[key];
    }

    /**
     * This method returns whether a shift key is currently pressed or not.
     * @returns {boolean}
     */
    function isShiftDown () {
        return status.shiftDown;
    }

    /**
     * Set status
     * @param key Field name
     * @param value Field value
     * @returns {setStatus}
     */
    function setStatus (key, value) {
        if (key in status) {
            status[key] = value;
        }
        return this;
    }

    self.getStatus = getStatus;
    self.isShiftDown = isShiftDown;
    self.setStatus = setStatus;

    init();
    return self;
}
<|endoftext|>


<commit_before>'use strict';

// Config HTTP Error Handling
angular.module('users').config(['$httpProvider',
	function($httpProvider) {
		// Set the httpProvider "not authorized" interceptor
		$httpProvider.interceptors.push(['$q', '$location', 'Authentication', '$window',
			function($q, $location, Authentication, $window) {
				return {
					responseError: function(rejection) {
						console.log(rejection);
						switch (rejection.status) {
							case 401:
								/**
								* 401 errors are handled specially.  They can mean the user is not logged
								* in or that the user does not have permission to do the action they were
								* trying to do.  Also, the user could try to access something without
								* selecting an event, which will cause a 401, but may not require a
								* redirection.
								*/
								if(rejection.data.message === "User not logged in.") {
									//Deauthenticate the global user
									Authentication.user = null;
									$window.user = null;

									//Redirect the user to the signin page
									$location.path('/signin');
								} else if(rejection.data.message === "User does not have permission.") {
									//Redirect the user to the home page
									$location.path('/');
								}

								break;
							case 403:
								// Add unauthorized behaviour
								break;
						}

						return $q.reject(rejection);
					}
				};
			}
		]);
	}
]);<commit_msg>Removed printing rejections to console.<commit_after>'use strict';

// Config HTTP Error Handling
angular.module('users').config(['$httpProvider',
	function($httpProvider) {
		// Set the httpProvider "not authorized" interceptor
		$httpProvider.interceptors.push(['$q', '$location', 'Authentication', '$window',
			function($q, $location, Authentication, $window) {
				return {
					responseError: function(rejection) {
						switch (rejection.status) {
							case 401:
								/**
								* 401 errors are handled specially.  They can mean the user is not logged
								* in or that the user does not have permission to do the action they were
								* trying to do.  Also, the user could try to access something without
								* selecting an event, which will cause a 401, but may not require a
								* redirection.
								*/
								if(rejection.data.message === "User not logged in.") {
									//Deauthenticate the global user
									Authentication.user = null;
									$window.user = null;

									//Redirect the user to the signin page
									$location.path('/signin');
								} else if(rejection.data.message === "User does not have permission.") {
									//Redirect the user to the home page
									$location.path('/');
								}

								break;
							case 403:
								// Add unauthorized behaviour
								break;
						}

						return $q.reject(rejection);
					}
				};
			}
		]);
	}
]);<|endoftext|>


<commit_before>/* The following three functions can, and maybe should be overwritten with custom functions for a particular site. */
jQuery.adjax_callbacks = {
    /* Display the given message as a notification (passive non-vital information) */
    show_message: function(message) {
        msg_html = jQuery('
'+message.content+'
');
        // Show the messages by sliding down.
        msg_html.hide();
        jQuery('#messages').prepend(msg_html);
        msg_html.slideDown('slow');
        // Hide unimportant messages after a few seconds
        if (message.level < 40) { msg_html.wait(2000).slideUp('slow') }
        }
    }

/* This factory generates a speical processor for handling form responses
   It is currently hardwired to handle Djangos standard form html.
   TODO: Allow this to be overridden.
   TODO: How are multiple forms handled?
*/
form_processor_factory = function(form_obj, callback) {
  if (!form_obj) { form_obj = jQuery; }

  return function(json) {
    /* Process the json, like links do */
    process_json_response(json);
    var errors = json.forms

    /* Remove all preexisting error messages */
    form_obj.find('.errorlist').remove();
    form_obj.find('.error').removeClass('error');
    for (error in errors) {
        /* Generate the error message html */
        var html = '
';
        for (msg in errors[error]) { html += '
'+errors[error][msg]+'
'; }
        html += '
';

        /* Attach the messages somewhere and add classes */
        if (error == '__all__') {
            form_obj.prepend(html); }
        else {
            form_obj.find('#form-error-'+error).each(function() {
                jQuery(this).addClass('error');
                jQuery(this).after(html); });
            form_obj.find('#'+error).each(function() {
                jQuery(this).addClass('error');
                jQuery(this).after(html); });
            }
        }
    if (callback) {
        callback(json);
        }
    }
  }

/* Function to process json response. This is the main switchboard, routing the
   specific top-level json items to handler functions.
*/
process_json_response = function(json) {
    /* Process any redirection first */
    /* TODO, recognise 3XX responses and redirect the entire window (may be impossible with js/jQuery) */
    // Redirect leaving an entry in the browser's history (ie back button)
    if (json.redirect) { window.location.href = json.redirect; }
    /* Process single notifications, messages and errors */
    if (json.messages) { for (var msg in json.messages) { jQuery.adjax_callbacks.show_message(json.messages[msg]); } }
    /* If any update data have been provided, update the relevant elements */
    if (json.replace) {
        for (index in json.replace) {
            // TODO: Need to determine whether it is a class or an id. For now i'm passing this in the DJANGO code itself.
            jQuery(index).html(json.replace[index]).show();
            }
        /* If a function is defined for document.ready, reapply that.  TODO: Document this feature. */
        if (json.document_ready) { document_ready() }
        }

    /* Hide any elements listed here */
    if (json.hide) {
        for (element in json.hide) {
            // TODO: Allow this functionality to be overridden, like message display
            // to let developers eg fade or slide or display a message etc
            jQuery(json.hide[element]).hide();
            }
        }
    /* Replace content for elements with the given class (handled by ) */
    if (json.update) {
        for (index in json.update) {
            jQuery("." + index).html(json.update[index]);
            }
        }
    }

/* Call a url that is served by an adjax decorated view.
 * Note that caching is turned off as Adjax usually runs through a Django view.
 * IE is known to otherwise automatically cache Ajax responses.
 */
jQuery.adjax = function(url, data, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'json',
        data: data,
        cache: false,
        success: function(json) { process_json_response(json); if (callback) { callback(json); }}
    });
    /* Return false to prevent any links from being followed */
    return false;
    }

/* Make an ajax call (immediately) to the given url or object's href
 * attribute, or post to the form's target.
 * USAGE:   $('#vote').adjax()
 */
jQuery.fn.adjax = function(data, callback) {
    this.each(function() {
        if (jQuery(this).attr('href')) {
            var url = jQuery(this).attr('href').split("?")[0];
            jQuery.adjax(url, data, callback);
            return false;
        } else if (jQuery(this).attr('action')) {
            var form_processor = form_processor_factory(obj, callback);
            jQuery(this).ajaxSubmit({success:form_processor, dataType:'json'});
            return false;
        }
        });

    /* Return false to avoid the link being followed or form submitted */
    return false;
    }

/* Automatically take a clickable object, doing an ajax call on click. */
jQuery.fn.adjaxify = function(callback) {
    this.each(function() {
        var obj = jQuery(this);
        if (obj.attr('href')) {
            obj.click(function() { return obj.adjax(null,callback); });
            }
        else if (obj.attr('tagName') == 'FORM') {
            /* submits an ajax form and prevent reloading POST submit */
            submit_form = function() {
                obj.ajaxSubmit({success: form_processor_factory(obj, callback), dataType:'json'});
                return false; }
            // Bind the ajax submit to the submit signal, so that it can be called from the form.
            obj.submit(submit_form);
        }});
    }

/* Convenient function to get objects to pause/wait for certain amount of time. */
jQuery.fn.wait = function(time) {
    var obj = jQuery(this);
    obj.queue(function() { setTimeout(function() {obj.dequeue();}, time); });
    return obj;
    };
<commit_msg>Ran JSLint on library.<commit_after>
/* The following three functions can, and maybe should be overwritten with custom functions for a particular site. */
jQuery.adjax_callbacks = {
    /* Display the given message as a notification (passive non-vital information) */
    show_message: function(message) {
        var msg_html = jQuery('
'+message.content+'
');
        // Show the messages by sliding down.
        msg_html.hide();
        jQuery('#messages').prepend(msg_html);
        msg_html.slideDown('slow');
        // Hide unimportant messages after a few seconds
        if (message.level < 40) { msg_html.wait(2000).slideUp('slow'); }
        }
    };

/* Function to process json response. This is the main switchboard, routing the
   specific top-level json items to handler functions.
*/
var process_json_response = function(json) {
    /* Process any redirection first */
    /* TODO, recognise 3XX responses and redirect the entire window (may be impossible with js/jQuery) */
    // Redirect leaving an entry in the browser's history (ie back button)
    if (json.redirect) { window; window.location.href = json.redirect; }
    /* Process single notifications, messages and errors */
    if (json.messages) { for (var msg in json.messages) { jQuery.adjax_callbacks.show_message(json.messages[msg]); } }
    /* If any update data have been provided, update the relevant elements */
    if (json.replace) {
        for (var replace_idx in json.replace) {
            // TODO: Need to determine whether it is a class or an id. For now i'm passing this in the DJANGO code itself.
            jQuery(replace_idx).html(json.replace[replace_idx]).show();
            }
        /* If a function is defined for document.ready, reapply that.  TODO: Document this feature. */
        if (json.document_ready) { document_ready(); }
        }

    /* Hide any elements listed here */
    if (json.hide) {
        for (var element in json.hide) {
            // TODO: Allow this functionality to be overridden, like message display
            // to let developers eg fade or slide or display a message etc
            jQuery(json.hide[element]).hide();
            }
        }
    /* Replace content for elements with the given class (handled by ) */
    if (json.update) {
        for (var update_idx in json.update) {
            jQuery("." + update_idx).html(json.update[update_idx]);
            }
        }
    };

/* This factory generates a speical processor for handling form responses
   It is currently hardwired to handle Djangos standard form html.
   TODO: Allow this to be overridden.
   TODO: How are multiple forms handled?
*/
var form_processor_factory = function(form_obj, callback) {
  if (!form_obj) { form_obj = jQuery; }

  return function(json) {
    /* Process the json, like links do */
    process_json_response(json);
    var errors = json.forms;

    /* Remove all preexisting error messages */
    form_obj.find('.errorlist').remove();
    form_obj.find('.error').removeClass('error');
    var display_form_error = function() {
        jQuery(this).addClass('error');
        jQuery(this).after(html);
    };
    for (var error in errors) {
        /* Generate the error message html */
        var html = '
';
        for (var msg in errors[error]) { html += '
'+errors[error][msg]+'
'; }
        html += '
';

        /* Attach the messages somewhere and add classes */
        if (error == '__all__') {
            form_obj.prepend(html); }
        else {
            form_obj.find('#form-error-'+error).each(display_form_error);
            form_obj.find('#'+error).each(display_form_error);
            }
      }
    if (callback) { callback(json); }
    };
  };

/* Call a url that is served by an adjax decorated view.
 * Note that caching is turned off as Adjax usually runs through a Django view.
 * IE is known to otherwise automatically cache Ajax responses.
 */
jQuery.adjax = function(url, data, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'json',
        data: data,
        cache: false,
        success: function(json) { process_json_response(json); if (callback) { callback(json); }}
    });
    /* Return false to prevent any links from being followed */
    return false;
    };

/* Make an ajax call (immediately) to the given url or object's href
 * attribute, or post to the form's target.
 * USAGE:   $('#vote').adjax()
 */
jQuery.fn.adjax = function(data, callback) {
    this.each(function() {
        var obj = jQuery(this);
        if (obj.attr('href')) {
            var url = obj.attr('href').split("?")[0];
            jQuery.adjax(url, data, callback);
            return false;
        } else if (obj.attr('action')) {
            var form_processor = form_processor_factory(obj, callback);
            obj.ajaxSubmit({success:form_processor, dataType:'json'});
            return false;
        }
        });

    /* Return false to avoid the link being followed or form submitted */
    return false;
    };

/* Automatically take a clickable object, doing an ajax call on click. */
jQuery.fn.adjaxify = function(callback) {
    this.each(function() {
        var obj = jQuery(this);
        if (obj.attr('href')) {
            obj.click(function() { return obj.adjax(null,callback); });
            }
        else if (obj.attr('tagName') == 'FORM') {
            /* submits an ajax form and prevent reloading POST submit */
            var submit_form = function() {
                obj.ajaxSubmit({success: form_processor_factory(obj, callback), dataType:'json'});
                return false; };
            // Bind the ajax submit to the submit signal, so that it can be called from the form.
            obj.submit(submit_form);
        }});
    };

/* Convenient function to get objects to pause/wait for certain amount of time. */
jQuery.fn.wait = function(time) {
    var obj = jQuery(this);
    obj.queue(function() { setTimeout(function() {obj.dequeue();}, time); });
    return obj;
    };
<|endoftext|>


<commit_before>function request(url, method, payload, callback)
{
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function()
		{
			if(this.readyState === 4)
			{
				callback(JSON.parse(this.responseText));
			}
		}
	if(payload)
	{
		if(method === "GET" || method === "DELETE" || payload.toString() !== "[object FormData]")
		{
			var query = requestQueryBuilder(payload);
		}
		if(method === "GET" || method === "DELETE")
		{
			url += "?" + query;
		}
	}
	xhr.open(method, url, true);
	if(method === "GET" || method === "DELETE" || payload.toString() !== "[object FormData]")
	{
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	}
	if(method === "GET" || method === "DELETE")
	{
		xhr.send();
	}
	else if(payload.toString() !== "[object FormData]")
	{
		xhr.send(query);
	}
	else
	{
		xhr.send(payload);
	}
}

function requestQueryBuilder(payload)
{
	var query = "";
	var first = true;
	for(key in payload)
	{
		if(!payload.hasOwnProperty(key))
		{
			continue;
		}
		if(payload[key].constructor === Array)
		{
			for(var i = 0; i < payload[key].length; i++)
			{
				if(!first)
				{
					query += "&";
				}
				query += key + "[]=" + payload[key][i];
				first = false;
			}
		}
		else
		{
			if(!first)
			{
				query += "&";
			}
			query += key + "=" + payload[key];
		}
		first = false;
	}
	return query;
}
<commit_msg>Fixed request adding trailing ? with empty query<commit_after>function request(url, method, payload, callback)
{
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function()
		{
			if(this.readyState === 4)
			{
				callback(JSON.parse(this.responseText));
			}
		}
	if(payload)
	{
		if(method === "GET" || method === "DELETE" || payload.toString() !== "[object FormData]")
		{
			var query = requestQueryBuilder(payload);
		}
		if((method === "GET" || method === "DELETE") && query)
		{
			url += "?" + query;
		}
	}
	xhr.open(method, url, true);
	if(method === "GET" || method === "DELETE" || payload.toString() !== "[object FormData]")
	{
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	}
	if(method === "GET" || method === "DELETE")
	{
		xhr.send();
	}
	else if(payload.toString() !== "[object FormData]")
	{
		xhr.send(query);
	}
	else
	{
		xhr.send(payload);
	}
}

function requestQueryBuilder(payload)
{
	var query = "";
	var first = true;
	for(key in payload)
	{
		if(!payload.hasOwnProperty(key))
		{
			continue;
		}
		if(payload[key].constructor === Array)
		{
			for(var i = 0; i < payload[key].length; i++)
			{
				if(!first)
				{
					query += "&";
				}
				query += key + "[]=" + payload[key][i];
				first = false;
			}
		}
		else
		{
			if(!first)
			{
				query += "&";
			}
			query += key + "=" + payload[key];
		}
		first = false;
	}
	return query;
}
<|endoftext|>