<commit_before>import React from 'react';
import {StyleSheet, ScrollView, Text, View, Platform, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';
import {RightBarIOS, BarButtonIOS, SharedElementAndroid} from 'navigation-react-native';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

export default ({color}) => (
  <NavigationContext.Consumer>
    {({stateNavigator}) => (
      <ScrollView contentInsetAdjustmentBehavior="automatic">
          <RightBarIOS>
            <BarButtonIOS systemItem="cancel" onPress={() => {
              stateNavigator.navigateBack(1);
            }} />
          </RightBarIOS>
          {Platform.OS === 'android' && <TouchableHighlight
            underlayColor="#fff"
            onPress={() => {
              stateNavigator.navigateBack(1);
            }}>
            <Text style={styles.back}>X</Text>
          </TouchableHighlight>}
          <SharedElementAndroid name={color} style={styles.color} transition="overshoot">
            <View style={{backgroundColor: color, flex: 1}} />
          </SharedElementAndroid>
          <Text style={styles.text}>{color}</Text>
          <View style={styles.colors}>
            {[1,2,3].map(i => colors[(colors.indexOf(color) + i) % 15])
              .map(subcolor => (
                <TouchableHighlight
                  key={subcolor}
                  style={[styles.subcolor, {backgroundColor: subcolor}]}
                  underlayColor={subcolor}
                  onPress={() => {
                    stateNavigator.navigate('detail', {
                      color: subcolor, sharedElements: [subcolor]
                    });
                  }}>
                    <View />
                </TouchableHighlight>
              )
            )}
          </View>
        </ScrollView>
    )}
  </NavigationContext.Consumer>
);

const styles = StyleSheet.create({
  back: {
    fontSize: 20,
    color: '#000',
    fontWeight: 'bold',
    paddingLeft: 20,
    paddingTop: 10,
  },
  color: {
    height: 300,
    marginTop: 10,
    marginLeft: 15,
    marginRight: 15,
  },
  text:{
    fontSize: 80,
    color: '#000',
    textAlign:'center',
    fontWeight: 'bold',
  },
  colors: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20,
  },
  subcolor: {
    width: 100,
    height: 50,
    marginLeft: 4,
    marginRight: 4,
    marginBottom: 10,
  },
});<commit_msg>Tweaked format<commit_after>import React from 'react';
import {StyleSheet, ScrollView, Text, View, Platform, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';
import {RightBarIOS, BarButtonIOS, SharedElementAndroid} from 'navigation-react-native';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

export default ({color}) => (
  <NavigationContext.Consumer>
    {({stateNavigator}) => (
      <ScrollView contentInsetAdjustmentBehavior="automatic">
          <RightBarIOS>
            <BarButtonIOS systemItem="cancel" onPress={() => {
              stateNavigator.navigateBack(1);
            }} />
          </RightBarIOS>
          {Platform.OS === 'android' && <TouchableHighlight
            underlayColor="#fff"
            onPress={() => {
              stateNavigator.navigateBack(1);
            }}>
            <Text style={styles.back}>X</Text>
          </TouchableHighlight>}
          <SharedElementAndroid
            name={color}
            style={styles.color}
            transition="overshoot">
            <View style={{backgroundColor: color, flex: 1}} />
          </SharedElementAndroid>
          <Text style={styles.text}>{color}</Text>
          <View style={styles.colors}>
            {[1,2,3].map(i => colors[(colors.indexOf(color) + i) % 15])
              .map(subcolor => (
                <TouchableHighlight
                  key={subcolor}
                  style={[styles.subcolor, {backgroundColor: subcolor}]}
                  underlayColor={subcolor}
                  onPress={() => {
                    stateNavigator.navigate('detail', {
                      color: subcolor, sharedElements: [subcolor]
                    });
                  }}>
                    <View />
                </TouchableHighlight>
              )
            )}
          </View>
        </ScrollView>
    )}
  </NavigationContext.Consumer>
);

const styles = StyleSheet.create({
  back: {
    fontSize: 20,
    color: '#000',
    fontWeight: 'bold',
    paddingLeft: 20,
    paddingTop: 10,
  },
  color: {
    height: 300,
    marginTop: 10,
    marginLeft: 15,
    marginRight: 15,
  },
  text:{
    fontSize: 80,
    color: '#000',
    textAlign:'center',
    fontWeight: 'bold',
  },
  colors: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20,
  },
  subcolor: {
    width: 100,
    height: 50,
    marginLeft: 4,
    marginRight: 4,
    marginBottom: 10,
  },
});<|endoftext|>


<commit_before>Ti.include('/Metal/config.js');

/**
 *
 */
(function() {

  this.metal = this.metal || {};

  // Check if global configuration is set
  // If not, set default values
  if (typeof metal.config == "undefined") {
    metal.config = {
      serverDomain : 'myDomain.com',
      serverPath: '/myServerPath',
      debugState: 3, // DEBUG
      cloudebug: false // Set Cloud debugging mode
    };
  }

  /**
   * Set debug state threshold level:
   * 0 - NONE
   * 1 - ERROR
   * 2 - INFO
   * 3 - DEBUG
   *
   * @property {Integer} DEBUG_STATE
   */
  metal.DEBUG_STATE = metal.config.debugState;

  /**
   * Set cloud debugging state
   *
   * @property {Boolean} CLOUD_DEBUG
   */
  metal.CLOUD_DEBUG = metal.config.cloudebug;

  /**
   * @param {String}
   *            namespace1
   * @param {String}
   *            namespace2
   * @param {String}
   *            etc
   * @return {Object} The namespace object. (If multiple arguments are passed,
   *         this will be the last namespace created)
   * @method createNameSpace
   */
   metal.createNameSpace = function() {
    var ln = arguments.length, i, value, split, x, xln, parts, object;

    for (i = 0; i < ln; i++) {
      value = arguments[i];
      parts = value.split(".");
      /*
      if (typeof this[parts[0]] == 'undefined') {
        Ti.API.info('[metal] ' + parts[0] + ' was undefined');
        this[parts[0]] = Object(parts[0]);
      }
      */
      object = metal;

      //Ti.API.info('[metal] value: ' + value);
      for (x = 1, xln = parts.length; x < xln; x++) {
        object = object[parts[x]] = Object(object[parts[x]]);
        //Ti.API.info('[metal] object: ' + JSON.stringify(object));
      }
    }

    //Ti.API.info('[metal] object: ' + JSON.stringify(object));
    return object;
  };

  // Define an alias
  metal.ns = metal.createNameSpace;

  /**
   * Copies all the properties of config to obj.
   *
   * @param {Object}
   *            object The receiver of the properties
   * @param {Object}
   *            config The source of the properties
   * @param {Object}
   *            defaults A different object that will also be applied for
   *            default values
   * @method apply
   * @return {Object} returns obj
   */
  metal.apply = function(object, config, defaults) {
    // no "this" reference for friendly out of scope calls
    if (defaults) {
      metal.apply(object, defaults);
    }
    if (object && config && typeof config == 'object') {
      for ( var key in config) {
        object[key] = config[key];
      }
    }
    return object;
  };

  /**
   * Secure apply. Acts exactly like {metal.apply} with one change:
   * if config.properties/config.items were not found then
   * it will apply config only of object.properties (used mainly in classes)
   *
   * @method overrideClass
   * @param {Object} object
   * @param {Object} config
   */
  metal.overrideClass = function(object, config) {
    config = config || {};
    if (config.properties != undefined ||
        config.items != undefined) {
      metal.apply(object, config);
    } else {
      metal.apply(object.properties, config);
    }
  };

  /**
   * Safe Apply
   * Acts the same as apply with only one difference:
   * it doesn't overrides any keys in <object>
   *
   * @method sApply
   * @param {Object} object
   * @param {Object} config
   */
  metal.sApply = function(object, config) {
    if (object && config && typeof config == 'object') {
      for (var key in config) {
        if (!(key in object)) {
          object[key] = config[key];
        }
      }
    }
  }

  // Empty object
  var empty = {};

  /**
   * Extend an object with the properties from another
   * (thanks Dojo - http://docs.dojocampus.org/dojo/mixin)
   *
   * @param {Object} target
   * @param {Object} source
   */
  function mixin(target, source){
    var name, s, i;
    for(name in source){
      if (source.hasOwnProperty(name)) {
        s = source[name];
        if(!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))){
          target[name] = s;
        }
      }
    }
    return target; // Object
  };

  /**
   * Copies all fields in "props" to "obj"
   *
   * @param {Object} obj
   * @param {Object...} props
   */
  metal.mixin = function(obj, props){
    if(!obj){ obj = {}; }
    for(var i=1, l=arguments.length; i<l; i++){
      mixin(obj, arguments[i]);
    }
    return obj; // Object
  };

  /**
   * create a new object, combining the properties of the passed objects with the last arguments having
   * priority over the first ones
   *
   * @param {Object} obj
   * @param {Object...} props
   */
  metal.combine = function(obj, props) {
    var newObj = {};
    for(var i=0, l=arguments.length; i<l; i++){
      mixin(newObj, arguments[i]);
    }
    return newObj;
  };

  /**
   * Override functions in a class
   *
   * @method override
   * @param originclass
   *            {Object} The class to override
   * @param overrides
   *            {Object} The overrides
   */
  metal.override = function(origclass, overrides) {
    metal.apply(origclass.prototype, overrides);
    return;
  };

  /**
   * @method urlEncode
   * @param {Object} object Creates an object that is
   */
  metal.urlEncode = function(object) {
    var val = "";
    var i = 0;
    for ( var key in object) {
      val = val + (i == 0 ? "" : "&") + encodeURI(key) + "="
          + encodeURI(object[key]);
      i++;
    }
    return val;
  };

  /**
   * isArray
   * Checks if the object is an array
   * @method isArray
   * @param {Object} The object to check if it is an array
   */
  metal.isArray = function isArray(obj) {
    // TODO [metal] :: isArray function is not working
    if (typeof obj.pop == 'undefined' || typeof obj.push == 'undefined')
      return false;
    else
      return true;
  };

  /**
   * @method isNumber
   * Checks if n is a number
   * @param {Object} n The object to sjek.
   */
  metal.isNumber = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  };

  /**
   * @method isObject
   * Check if an object is an object *_* fun.
   * @param {Object} v Something to sjek.
   */
  metal.isObject = function(v) {
    return !!v && Object.prototype.toString.call(v) === '[object Object]';
  };

  /**
   * Extend class
   * @method extend
   * @return {Object} The new class
   */
  metal.extend = function() {
    // inline overrides
    var inlineOverrides = function(o) {
      for ( var m in o) {
        if (!o.hasOwnProperty(m)) {
          continue;
        }
        this[m] = o[m];
      }
    };

    var objectConstructor = Object.prototype.constructor;

    return function(subclass, superclass, overrides) {
      // First we check if the user passed in just the superClass with
      // overrides
      if (metal.isObject(superclass)) {
        overrides = superclass;
        superclass = subclass;
        subclass = overrides.constructor != objectConstructor ? overrides.constructor
            : function() {
              superclass.apply(this, arguments);
            };
      }

      if (!superclass) {
        throw "Attempting to extend from a class which has not been loaded on the page.";
      }

      // We create a new temporary class
      var F = function() {
      }, subclassProto, superclassProto = superclass.prototype;

      F.prototype = superclassProto;
      subclassProto = subclass.prototype = new F();
      subclassProto.constructor = subclass;
      subclass.superclass = superclassProto;

      if (superclassProto.constructor == objectConstructor) {
        superclassProto.constructor = superclass;
      }

      subclass.override = function(overrides) {
        metal.override(subclass, overrides);
      };

      subclassProto.superclass = subclassProto.supr = (function() {
        return superclassProto;
      });

      subclassProto.base = superclassProto.constructor;
      subclassProto.override = inlineOverrides;
      subclassProto.proto = subclassProto;

      subclass.override(overrides);
      subclass.extend = function(o) {
        return metal.extend(subclass, o);
      };

      return subclass;
    };
  }();

  /**
   * Screen dimensions
   */
  metal.height = Ti.Platform.displayCaps.platformHeight;
  metal.width = Ti.Platform.displayCaps.platformWidth;

  Ti.API.info('[metal] Device height: ' + metal.height + ', width: ' + metal.width);

  /**
   * Get the values needed to align the component to the right
   *
   * @param {Integer} numOfComponents
   * @param {Integer} substract
   * @param [optional] {Integer} optPadding
   */
  metal.getRightAlign = function(numOfComponents, substract, optPadding) {
    var padding = optPadding || 5;
    return metal.width - substract - padding - padding * numOfComponents;
  };

  /**
   * Register a global event
   *
   * @method on
   * @param {String} event
   * @param {Function} cb The callback function
   */
  metal.on = function(event, cb) {
    Ti.App.addEventListener(event, cb);
  };

  /**
   * Dismisses a global event
   *
   * @method dismiss
   * @param {String} event
   * @param {Function} cb The callback function
   */
  metal.dismiss = function(event, cb) {
    Ti.App.removeEventListener(event, cb);
  };

  /**
   * Fires a global event
   *
   * @method fire
   * @param {String} event The event name
   * @param {Function} obj The event parameter sent to listener
   */
  metal.fire = function(event, obj) {
    Ti.App.fireEvent(event, obj);
  };

})();

Ti.include(

  // Debug
  '/Metal/debug/debug.js',

  // Core
  //'/Metal/core/auth.js',
  '/Metal/core/control.js',

  // Util
  '/Metal/util/net.js',
  '/Metal/util/location.js',

  // UI
  '/Metal/ui/AbstractMetalView.js',
  '/Metal/ui/Window.js',
  '/Metal/ui/TabGroup.js',
  '/Metal/ui/Tab.js',
  '/Metal/ui/View.js',
  '/Metal/ui/TableView.js',
  '/Metal/ui/TableRow.js',
  '/Metal/ui/TableSection.js',

  // Custom UI
  //'/Metal/customUI/simpleWindow.js',
  //'/Metal/customUI/login.js',

  // Tests
  '/Metal/test/net.js'

);
<commit_msg>Added a TODO for generic register namespaces<commit_after>Ti.include('/Metal/config.js');

/**
 *
 */
(function() {

  this.metal = this.metal || {};

  // Check if global configuration is set
  // If not, set default values
  if (typeof metal.config == "undefined") {
    metal.config = {
      serverDomain : 'myDomain.com',
      serverPath: '/myServerPath',
      debugState: 3, // DEBUG
      cloudebug: false // Set Cloud debugging mode
    };
  }

  /**
   * Set debug state threshold level:
   * 0 - NONE
   * 1 - ERROR
   * 2 - INFO
   * 3 - DEBUG
   *
   * @property {Integer} DEBUG_STATE
   */
  metal.DEBUG_STATE = metal.config.debugState;

  /**
   * Set cloud debugging state
   *
   * @property {Boolean} CLOUD_DEBUG
   */
  metal.CLOUD_DEBUG = metal.config.cloudebug;

  /**
   * @param {String}
   *            namespace1
   * @param {String}
   *            namespace2
   * @param {String}
   *            etc
   * @return {Object} The namespace object. (If multiple arguments are passed,
   *         this will be the last namespace created)
   * @method createNameSpace
   */
   metal.createNameSpace = function() {
    var ln = arguments.length, i, value, split, x, xln, parts, object;

    for (i = 0; i < ln; i++) {
      value = arguments[i];
      parts = value.split(".");
      /*
      if (typeof this[parts[0]] == 'undefined') {
        Ti.API.info('[metal] ' + parts[0] + ' was undefined');
        this[parts[0]] = Object(parts[0]);
      }
      */
      // TODO [metal::createNameSpace] We need to make this generic and not only work for metal namespace!
      object = metal;

      //Ti.API.info('[metal] value: ' + value);
      for (x = 1, xln = parts.length; x < xln; x++) {
        object = object[parts[x]] = Object(object[parts[x]]);
        //Ti.API.info('[metal] object: ' + JSON.stringify(object));
      }
    }

    //Ti.API.info('[metal] object: ' + JSON.stringify(object));
    return object;
  };

  // Define an alias
  metal.ns = metal.createNameSpace;

  /**
   * Copies all the properties of config to obj.
   *
   * @param {Object}
   *            object The receiver of the properties
   * @param {Object}
   *            config The source of the properties
   * @param {Object}
   *            defaults A different object that will also be applied for
   *            default values
   * @method apply
   * @return {Object} returns obj
   */
  metal.apply = function(object, config, defaults) {
    // no "this" reference for friendly out of scope calls
    if (defaults) {
      metal.apply(object, defaults);
    }
    if (object && config && typeof config == 'object') {
      for ( var key in config) {
        object[key] = config[key];
      }
    }
    return object;
  };

  /**
   * Secure apply. Acts exactly like {metal.apply} with one change:
   * if config.properties/config.items were not found then
   * it will apply config only of object.properties (used mainly in classes)
   *
   * @method overrideClass
   * @param {Object} object
   * @param {Object} config
   */
  metal.overrideClass = function(object, config) {
    config = config || {};
    if (config.properties != undefined ||
        config.items != undefined) {
      metal.apply(object, config);
    } else {
      metal.apply(object.properties, config);
    }
  };

  /**
   * Safe Apply
   * Acts the same as apply with only one difference:
   * it doesn't overrides any keys in <object>
   *
   * @method sApply
   * @param {Object} object
   * @param {Object} config
   */
  metal.sApply = function(object, config) {
    if (object && config && typeof config == 'object') {
      for (var key in config) {
        if (!(key in object)) {
          object[key] = config[key];
        }
      }
    }
  }

  // Empty object
  var empty = {};

  /**
   * Extend an object with the properties from another
   * (thanks Dojo - http://docs.dojocampus.org/dojo/mixin)
   *
   * @param {Object} target
   * @param {Object} source
   */
  function mixin(target, source){
    var name, s, i;
    for(name in source){
      if (source.hasOwnProperty(name)) {
        s = source[name];
        if(!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))){
          target[name] = s;
        }
      }
    }
    return target; // Object
  };

  /**
   * Copies all fields in "props" to "obj"
   *
   * @param {Object} obj
   * @param {Object...} props
   */
  metal.mixin = function(obj, props){
    if(!obj){ obj = {}; }
    for(var i=1, l=arguments.length; i<l; i++){
      mixin(obj, arguments[i]);
    }
    return obj; // Object
  };

  /**
   * create a new object, combining the properties of the passed objects with the last arguments having
   * priority over the first ones
   *
   * @param {Object} obj
   * @param {Object...} props
   */
  metal.combine = function(obj, props) {
    var newObj = {};
    for(var i=0, l=arguments.length; i<l; i++){
      mixin(newObj, arguments[i]);
    }
    return newObj;
  };

  /**
   * Override functions in a class
   *
   * @method override
   * @param originclass
   *            {Object} The class to override
   * @param overrides
   *            {Object} The overrides
   */
  metal.override = function(origclass, overrides) {
    metal.apply(origclass.prototype, overrides);
    return;
  };

  /**
   * @method urlEncode
   * @param {Object} object Creates an object that is
   */
  metal.urlEncode = function(object) {
    var val = "";
    var i = 0;
    for ( var key in object) {
      val = val + (i == 0 ? "" : "&") + encodeURI(key) + "="
          + encodeURI(object[key]);
      i++;
    }
    return val;
  };

  /**
   * isArray
   * Checks if the object is an array
   * @method isArray
   * @param {Object} The object to check if it is an array
   */
  metal.isArray = function isArray(obj) {
    // TODO [metal] :: isArray function is not working
    if (typeof obj.pop == 'undefined' || typeof obj.push == 'undefined')
      return false;
    else
      return true;
  };

  /**
   * @method isNumber
   * Checks if n is a number
   * @param {Object} n The object to sjek.
   */
  metal.isNumber = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  };

  /**
   * @method isObject
   * Check if an object is an object *_* fun.
   * @param {Object} v Something to sjek.
   */
  metal.isObject = function(v) {
    return !!v && Object.prototype.toString.call(v) === '[object Object]';
  };

  /**
   * Extend class
   * @method extend
   * @return {Object} The new class
   */
  metal.extend = function() {
    // inline overrides
    var inlineOverrides = function(o) {
      for ( var m in o) {
        if (!o.hasOwnProperty(m)) {
          continue;
        }
        this[m] = o[m];
      }
    };

    var objectConstructor = Object.prototype.constructor;

    return function(subclass, superclass, overrides) {
      // First we check if the user passed in just the superClass with
      // overrides
      if (metal.isObject(superclass)) {
        overrides = superclass;
        superclass = subclass;
        subclass = overrides.constructor != objectConstructor ? overrides.constructor
            : function() {
              superclass.apply(this, arguments);
            };
      }

      if (!superclass) {
        throw "Attempting to extend from a class which has not been loaded on the page.";
      }

      // We create a new temporary class
      var F = function() {
      }, subclassProto, superclassProto = superclass.prototype;

      F.prototype = superclassProto;
      subclassProto = subclass.prototype = new F();
      subclassProto.constructor = subclass;
      subclass.superclass = superclassProto;

      if (superclassProto.constructor == objectConstructor) {
        superclassProto.constructor = superclass;
      }

      subclass.override = function(overrides) {
        metal.override(subclass, overrides);
      };

      subclassProto.superclass = subclassProto.supr = (function() {
        return superclassProto;
      });

      subclassProto.base = superclassProto.constructor;
      subclassProto.override = inlineOverrides;
      subclassProto.proto = subclassProto;

      subclass.override(overrides);
      subclass.extend = function(o) {
        return metal.extend(subclass, o);
      };

      return subclass;
    };
  }();

  /**
   * Screen dimensions
   */
  metal.height = Ti.Platform.displayCaps.platformHeight;
  metal.width = Ti.Platform.displayCaps.platformWidth;

  Ti.API.info('[metal] Device height: ' + metal.height + ', width: ' + metal.width);

  /**
   * Get the values needed to align the component to the right
   *
   * @param {Integer} numOfComponents
   * @param {Integer} substract
   * @param [optional] {Integer} optPadding
   */
  metal.getRightAlign = function(numOfComponents, substract, optPadding) {
    var padding = optPadding || 5;
    return metal.width - substract - padding - padding * numOfComponents;
  };

  /**
   * Register a global event
   *
   * @method on
   * @param {String} event
   * @param {Function} cb The callback function
   */
  metal.on = function(event, cb) {
    Ti.App.addEventListener(event, cb);
  };

  /**
   * Dismisses a global event
   *
   * @method dismiss
   * @param {String} event
   * @param {Function} cb The callback function
   */
  metal.dismiss = function(event, cb) {
    Ti.App.removeEventListener(event, cb);
  };

  /**
   * Fires a global event
   *
   * @method fire
   * @param {String} event The event name
   * @param {Function} obj The event parameter sent to listener
   */
  metal.fire = function(event, obj) {
    Ti.App.fireEvent(event, obj);
  };

})();

Ti.include(

  // Debug
  '/Metal/debug/debug.js',

  // Core
  //'/Metal/core/auth.js',
  '/Metal/core/control.js',

  // Util
  '/Metal/util/net.js',
  '/Metal/util/location.js',

  // UI
  '/Metal/ui/AbstractMetalView.js',
  '/Metal/ui/Window.js',
  '/Metal/ui/TabGroup.js',
  '/Metal/ui/Tab.js',
  '/Metal/ui/View.js',
  '/Metal/ui/TableView.js',
  '/Metal/ui/TableRow.js',
  '/Metal/ui/TableSection.js',

  // Custom UI
  //'/Metal/customUI/simpleWindow.js',
  //'/Metal/customUI/login.js',

  // Tests
  '/Metal/test/net.js'

);
<|endoftext|>


<commit_before>var React = require('react');
var { array, func, number, object, oneOf, string } = React.PropTypes;
var Interaction = require('../constants/interaction');
var classNames = require('classnames');
var VerticalBar = require('./vertical-bar');
var { values } = require('../utils/object-util');
var d3 = require('d3');
var GetActive = require('../mixins/get-active');
var GetBarHeight = require('../mixins/get-bar-height');
var GetBarWidth = require('../mixins/get-bar-width');
var GetBarY = require('../mixins/get-bar-y');
var SeriesMouseInteraction = require('../mixins/series-mouse-interaction');

module.exports = React.createClass({

  propTypes: {
    barSpacing: number.isRequired,
    className: string,
    data: array.isRequired,
    dispatcher: object.isRequired,

    height: number.isRequired,
    id: string.isRequired,
    interaction: oneOf(values(Interaction)),
    scaleY: func.isRequired,
    style: object,
    tickWidth: number.isRequired,
    width: number.isRequired,
    zeroY: number.isRequired
  },

  mixins: [
    GetActive,
    GetBarHeight,
    GetBarWidth,
    GetBarY,
    SeriesMouseInteraction
  ],

  getDefaultProps() {
    return {
      barSpacing: 2,
      className: '',
      data: [],
      dispatcher: d3.dispatch(),
      height: 0,
      id: '',
      interaction: Interaction.MOUSE_OVER,
      scaleY: Function,
      style: {},
      tickWidth: 0,
      width: 0,
      zeroY: 0
    };
  },

  getInitialState() {
    return {
      activeDatum: {},
      activeIndex: -1
    };
  },

  getBarProps(props, state, datum, index) {
    var active = this.getActive(
      state.activeIndex,
      index);
    var height = this.getBarHeight(
      props.zeroY,
      props.scaleY,
      datum.value);
    var width = this.getBarWidth(
      props.tickWidth,
      props.barSpacing);
    var x = this.getBarX(
      props.tickWidth,
      index);
    var y = this.getBarY(
      datum.value,
      props.zeroY,
      height);
    return {
      active: active,
      height: height,
      width: width,
      x: x,
      y: y
    };
  },

  getBarX(tickWidth, index) {
    return Math.floor(tickWidth * index);
  },

  render() {
    return (
      <g
        className={classNames(
          'bar-series',
          this.props.className
        )}
        style={this.props.style}>

        {this.props.data.map((datum, index) => {
          var barProps = this.getBarProps(
            this.props, this.state, datum, index);
          return (
            <VerticalBar
              active={barProps.active}
              className={datum.className}
              height={barProps.height}
              key={index}
              style={datum.style}
              value={datum.value}
              width={barProps.width}
              x={barProps.x}
              y={barProps.y} />
          );
        })}
      </g>
    );
  }
});
<commit_msg>removed extraneous line break in bar series<commit_after>var React = require('react');
var { array, func, number, object, oneOf, string } = React.PropTypes;
var Interaction = require('../constants/interaction');
var classNames = require('classnames');
var VerticalBar = require('./vertical-bar');
var { values } = require('../utils/object-util');
var d3 = require('d3');
var GetActive = require('../mixins/get-active');
var GetBarHeight = require('../mixins/get-bar-height');
var GetBarWidth = require('../mixins/get-bar-width');
var GetBarY = require('../mixins/get-bar-y');
var SeriesMouseInteraction = require('../mixins/series-mouse-interaction');

module.exports = React.createClass({

  propTypes: {
    barSpacing: number.isRequired,
    className: string,
    data: array.isRequired,
    dispatcher: object.isRequired,
    height: number.isRequired,
    id: string.isRequired,
    interaction: oneOf(values(Interaction)),
    scaleY: func.isRequired,
    style: object,
    tickWidth: number.isRequired,
    width: number.isRequired,
    zeroY: number.isRequired
  },

  mixins: [
    GetActive,
    GetBarHeight,
    GetBarWidth,
    GetBarY,
    SeriesMouseInteraction
  ],

  getDefaultProps() {
    return {
      barSpacing: 2,
      className: '',
      data: [],
      dispatcher: d3.dispatch(),
      height: 0,
      id: '',
      interaction: Interaction.MOUSE_OVER,
      scaleY: Function,
      style: {},
      tickWidth: 0,
      width: 0,
      zeroY: 0
    };
  },

  getInitialState() {
    return {
      activeDatum: {},
      activeIndex: -1
    };
  },

  getBarProps(props, state, datum, index) {
    var active = this.getActive(
      state.activeIndex,
      index);
    var height = this.getBarHeight(
      props.zeroY,
      props.scaleY,
      datum.value);
    var width = this.getBarWidth(
      props.tickWidth,
      props.barSpacing);
    var x = this.getBarX(
      props.tickWidth,
      index);
    var y = this.getBarY(
      datum.value,
      props.zeroY,
      height);
    return {
      active: active,
      height: height,
      width: width,
      x: x,
      y: y
    };
  },

  getBarX(tickWidth, index) {
    return Math.floor(tickWidth * index);
  },

  render() {
    return (
      <g
        className={classNames(
          'bar-series',
          this.props.className
        )}
        style={this.props.style}>

        {this.props.data.map((datum, index) => {
          var barProps = this.getBarProps(
            this.props, this.state, datum, index);
          return (
            <VerticalBar
              active={barProps.active}
              className={datum.className}
              height={barProps.height}
              key={index}
              style={datum.style}
              value={datum.value}
              width={barProps.width}
              x={barProps.x}
              y={barProps.y} />
          );
        })}
      </g>
    );
  }
});
<|endoftext|>


<commit_before>document.addEventListener("touchstart",on_touch);
document.addEventListener("mousedown",on_touch);

var recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.maxAlternatives =5;

function on_touch()
{
	if(recognition.start){
		recognition.start();
		recognition_started = true;
	}

}
function onend()
{
	recognition.stop();
	recognition_started = false;
}
recognition.onend = onend;
recognition.onsoundend = onend;
recognition.onspeechend = onend;
recognition.onresult =on_results;

function on_results(e)
{
	var alternatives = e.results[2];
	for (var i=0; i<alternatives.length; i++)
		document.getElementById("text").innerHTML += alternatives[i].transcript
	//document.getElementById("text").innerHTML += "Ati rostit cuvantul: "+ alternatives[i].transcript + ", acuratete: "+alternatives[i].confidence + "
" ;
}
<commit_msg>Update speech.js<commit_after>document.addEventListener("touchstart",on_touch);
document.addEventListener("mousedown",on_touch);

var recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.maxAlternatives =5;

function on_touch()
{
	if(recognition.start){
		recognition.start();
		recognition_started = true;
	}

}
function onend()
{
	recognition.stop();
	recognition_started = false;
}
recognition.onend = onend;
recognition.onsoundend = onend;
recognition.onspeechend = onend;
recognition.onresult =on_results;

function on_results(e)
{
	var alternatives = e.results[0];
	for (var i=0; i<alternatives.length; i++)
		document.getElementById("text").innerHTML += alternatives[i].transcript
	//document.getElementById("text").innerHTML += "Ati rostit cuvantul: "+ alternatives[i].transcript + ", acuratete: "+alternatives[i].confidence + "
" ;
}
<|endoftext|>


<commit_before>var ModelUpdateNothing = 0
var ModelUpdateInsert = 1
var ModelUpdateUpdate = 2

var ModelUpdateRange = function(type, length) {
	this.type = type
	this.length = length
}

exports.ModelUpdate = function() {
	this.count = 0
	this._reset()
}
exports.ModelUpdate.prototype.constructor = exports.ModelUpdate

exports.ModelUpdate.prototype._reset = function() {
	this._ranges = [new ModelUpdateRange(ModelUpdateNothing, this.count)]
	this._updateIndex = this.count
}

exports.ModelUpdate.prototype._setUpdateIndex = function(begin) {
	if (begin < this._updateIndex)
		this._updateIndex = begin
}

exports.ModelUpdate.prototype._find = function(index) {
	var ranges = this._ranges
	var i
	for(i = 0; i < ranges.length; ++i) {
		var range = ranges[i]
		if (index < range.length)
			return { index: i, offset: index }
		if (range.length > 0)
			index -= range.length
	}
	if (index != 0)
		throw new Error('invalid index ' + index)

	return { index: i - 1, offset: range.length }
}

exports.ModelUpdate.prototype.reset = function(model) {
	this.update(model, 0, Math.min(model.count, this.count))
	if (this.count < model.count) {
		this.insert(model, this.count, model.count)
	} else {
		this.remove(model, model.count, this.count)
	}
}

exports.ModelUpdate.prototype._merge = function() {
	var ranges = this._ranges
	for(var index = 1; index < ranges.length; ) {
		var range = ranges[index - 1]
		var nextRange = ranges[index]
		if (range.type === nextRange.type) {
			range.length += nextRange.length
			ranges.splice(index, 1)
		} else
			++index
	}
}

exports.ModelUpdate.prototype._split = function(index, offset, type, length) {
	var ranges = this._ranges
	if (offset == 0) {
		ranges.splice(index, 0, new ModelUpdateRange(type, length))
		return index + 1
	} else {
		var range = ranges[index]
		var right = range.length - offset
		range.length = offset
		if (right != 0) {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length),
				new ModelUpdateRange(range.type, right))
			return index + 2
		} else {
			ranges.splice(index, 0,
				new ModelUpdateRange(type, length))
			return index + 1
		}
	}
}

exports.ModelUpdate.prototype.insert = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count += d
	if (this.count != model.count)
		throw new Error('unbalanced insert ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]
	if (range.length == 0) { //first insert
		range.type = ModelUpdateInsert
		range.length += d
	} else if (range.type == ModelUpdateInsert) {
		range.length += d
	} else {
		this._split(res.index, res.offset, ModelUpdateInsert, d)
	}
	this._merge()
}

exports.ModelUpdate.prototype.remove = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count -= d
	if (this.count != model.count)
		throw new Error('unbalanced remove ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]

	if (range.type == ModelUpdateInsert) {
		range.length -= d
	} else {
		var index = this._split(res.index, res.offset, ModelUpdateInsert, -d)
		while(d > 0) {
			var range = ranges[index]
			if (range.length <= d) {
				ranges.splice(index, 1)
				d -= range.length
			} else {
				range.length -= d
			}
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.update = function(model, begin, end) {
	if (begin >= end)
		return

	var ranges = this._ranges
	var n = end - begin
	var res = this._find(begin)
	var index = res.index

	var range = ranges[index]
	if (res.offset > 0) {
		ranges.splice(index + 1, 0, new ModelUpdateRange(ModelUpdateNothing, range.length - res.offset))
		range.length = res.offset
		++index
		if (range.length == 0)
			throw new Error('invalid offset')
	}

	while(n > 0) {
		var range = ranges[index]
		var length = range.length
		switch(range.type) {
			case ModelUpdateNothing:
				if (length > n) {
					//range larger than needed
					range.length -= n
					ranges.splice(index, 0, new ModelUpdateRange(ModelUpdateUpdate, n))
					n -= length
				} else { //length <= n
					range.type = ModelUpdateUpdate
					n -= length
				}
				break
			case ModelUpdateInsert:
				if (length > 0) {
					n -= length
					++index
				}
				break
			case ModelUpdateUpdate:
				n -= length
				++index
				break
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.apply = function(view) {
	var index = 0
	this._ranges.forEach(
		function(range) {
			var n = range.length
			switch(range.type) {
				case ModelUpdateInsert:
					if (n > 0) {
						view._insertItems(index, index + n)
						index += n
					} else {
						view._removeItems(index, index - n)
					}
					break
				case ModelUpdateUpdate:
					view._updateItems(index, index + n)
					index += n
					break
				default:
					index += range.length
			}
		}
	)
	if (view._items.length != this.count)
		throw new Error('unbalanced items update, view: ' + view._items.length + ', update:' + this.count)

	for(var i = this._updateIndex; i < this.count; ++i)
		view._updateDelegateIndex(i)
	this._reset()
}
<commit_msg>fixed invalid offset in split-right<commit_after>var ModelUpdateNothing = 0
var ModelUpdateInsert = 1
var ModelUpdateUpdate = 2

var ModelUpdateRange = function(type, length) {
	this.type = type
	this.length = length
}

exports.ModelUpdate = function() {
	this.count = 0
	this._reset()
}
exports.ModelUpdate.prototype.constructor = exports.ModelUpdate

exports.ModelUpdate.prototype._reset = function() {
	this._ranges = [new ModelUpdateRange(ModelUpdateNothing, this.count)]
	this._updateIndex = this.count
}

exports.ModelUpdate.prototype._setUpdateIndex = function(begin) {
	if (begin < this._updateIndex)
		this._updateIndex = begin
}

exports.ModelUpdate.prototype._find = function(index) {
	var ranges = this._ranges
	var i
	for(i = 0; i < ranges.length; ++i) {
		var range = ranges[i]
		if (index < range.length)
			return { index: i, offset: index }
		if (range.length > 0)
			index -= range.length
	}
	if (index != 0)
		throw new Error('invalid index ' + index)

	return { index: i - 1, offset: range.length }
}

exports.ModelUpdate.prototype.reset = function(model) {
	this.update(model, 0, Math.min(model.count, this.count))
	if (this.count < model.count) {
		this.insert(model, this.count, model.count)
	} else {
		this.remove(model, model.count, this.count)
	}
}

exports.ModelUpdate.prototype._merge = function() {
	var ranges = this._ranges
	for(var index = 1; index < ranges.length; ) {
		var range = ranges[index - 1]
		var nextRange = ranges[index]
		if (range.type === nextRange.type) {
			range.length += nextRange.length
			ranges.splice(index, 1)
		} else
			++index
	}
}

exports.ModelUpdate.prototype._split = function(index, offset, type, length) {
	var ranges = this._ranges
	if (offset == 0) {
		ranges.splice(index, 0, new ModelUpdateRange(type, length))
		return index + 1
	} else {
		var range = ranges[index]
		var right = range.length - offset
		range.length = offset
		if (right != 0) {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length),
				new ModelUpdateRange(range.type, right))
			return index + 2
		} else {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length))
			return index + 2
		}
	}
}

exports.ModelUpdate.prototype.insert = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count += d
	if (this.count != model.count)
		throw new Error('unbalanced insert ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]
	if (range.length == 0) { //first insert
		range.type = ModelUpdateInsert
		range.length += d
	} else if (range.type == ModelUpdateInsert) {
		range.length += d
	} else {
		this._split(res.index, res.offset, ModelUpdateInsert, d)
	}
	this._merge()
}

exports.ModelUpdate.prototype.remove = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count -= d
	if (this.count != model.count)
		throw new Error('unbalanced remove ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]

	if (range.type == ModelUpdateInsert) {
		range.length -= d
	} else {
		var index = this._split(res.index, res.offset, ModelUpdateInsert, -d)
		while(d > 0) {
			var range = ranges[index]
			if (range.length <= d) {
				ranges.splice(index, 1)
				d -= range.length
			} else {
				range.length -= d
			}
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.update = function(model, begin, end) {
	if (begin >= end)
		return

	var ranges = this._ranges
	var n = end - begin
	var res = this._find(begin)
	var index = res.index

	var range = ranges[index]
	if (res.offset > 0) {
		ranges.splice(index + 1, 0, new ModelUpdateRange(ModelUpdateNothing, range.length - res.offset))
		range.length = res.offset
		++index
		if (range.length == 0)
			throw new Error('invalid offset')
	}

	while(n > 0) {
		var range = ranges[index]
		var length = range.length
		switch(range.type) {
			case ModelUpdateNothing:
				if (length > n) {
					//range larger than needed
					range.length -= n
					ranges.splice(index, 0, new ModelUpdateRange(ModelUpdateUpdate, n))
					n -= length
				} else { //length <= n
					range.type = ModelUpdateUpdate
					n -= length
				}
				break
			case ModelUpdateInsert:
				if (length > 0) {
					n -= length
					++index
				}
				break
			case ModelUpdateUpdate:
				n -= length
				++index
				break
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.apply = function(view) {
	var index = 0
	this._ranges.forEach(
		function(range) {
			var n = range.length
			switch(range.type) {
				case ModelUpdateInsert:
					if (n > 0) {
						view._insertItems(index, index + n)
						index += n
					} else {
						view._removeItems(index, index - n)
					}
					break
				case ModelUpdateUpdate:
					view._updateItems(index, index + n)
					index += n
					break
				default:
					index += range.length
			}
		}
	)
	if (view._items.length != this.count)
		throw new Error('unbalanced items update, view: ' + view._items.length + ', update:' + this.count)

	for(var i = this._updateIndex; i < this.count; ++i)
		view._updateDelegateIndex(i)
	this._reset()
}
<|endoftext|>


<commit_before>import THREE from 'three';
import raf from 'raf-loop';
import Clock from '../helpers/Clock';
import Cube from '../meshes/cube';
import PostProcessing from '../postProcessing/PostProcessing';

/**
 * Scene class
 */
class Scene extends THREE.Scene {

  /**
   * Constructor function
   * @param {Renderer} Renderer Renderer instance
   * @param {Camera}   Camera   Camera instance
   */
  constructor( Renderer, Camera ) {
    super();

    this.renderer = Renderer;
    this.camera = Camera;
    this.postProcessing = new PostProcessing( this, this.renderer, this.camera );

    this.clock = new Clock();

    this.createScene();
  }

  /**
   * CreateScene function
   */
  createScene() {

    this.cube = new Cube();
    this.add( this.cube );

    this.raf = raf( ::this.render ).start();
  }

  /**
   * Render function
   */
  render() {

    this.cube.rotation.x += 0.01;
    this.cube.rotation.y += 0.02;

    this.cube.update( this.clock.time );

    this.postProcessing.update();
    this.camera.update( this.clock.delta );
  };
}

export default Scene;<commit_msg>Global - Fix uppercase name<commit_after>import THREE from 'three';
import raf from 'raf-loop';
import Clock from '../helpers/Clock';
import Cube from '../meshes/Cube';
import PostProcessing from '../postProcessing/PostProcessing';

/**
 * Scene class
 */
class Scene extends THREE.Scene {

  /**
   * Constructor function
   * @param {Renderer} Renderer Renderer instance
   * @param {Camera}   Camera   Camera instance
   */
  constructor( Renderer, Camera ) {
    super();

    this.renderer = Renderer;
    this.camera = Camera;
    this.postProcessing = new PostProcessing( this, this.renderer, this.camera );

    this.clock = new Clock();

    this.createScene();
  }

  /**
   * CreateScene function
   */
  createScene() {

    this.cube = new Cube();
    this.add( this.cube );

    this.raf = raf( ::this.render ).start();
  }

  /**
   * Render function
   */
  render() {

    this.cube.rotation.x += 0.01;
    this.cube.rotation.y += 0.02;

    this.cube.update( this.clock.time );

    this.postProcessing.update();
    this.camera.update( this.clock.delta );
  };
}

export default Scene;<|endoftext|>


<commit_before>var ModelUpdateNothing = 0
var ModelUpdateInsert = 1
var ModelUpdateUpdate = 2

var ModelUpdateRange = function(type, length) {
	this.type = type
	this.length = length
}

exports.ModelUpdate = function() {
	this.count = 0
	this._reset()
}
exports.ModelUpdate.prototype.constructor = exports.ModelUpdate

exports.ModelUpdate.prototype._reset = function() {
	this._ranges = [new ModelUpdateRange(ModelUpdateNothing, this.count)]
	this._updateIndex = this.count
}

exports.ModelUpdate.prototype._setUpdateIndex = function(begin) {
	if (begin < this._updateIndex)
		this._updateIndex = begin
}

exports.ModelUpdate.prototype._find = function(index) {
	var ranges = this._ranges
	var i
	for(i = 0; i < ranges.length; ++i) {
		var range = ranges[i]
		if (index < range.length)
			return { index: i, offset: index }
		if (range.length > 0)
			index -= range.length
	}
	if (index != 0)
		throw new Error('invalid index ' + index)

	return { index: i - 1, offset: range.length }
}

exports.ModelUpdate.prototype.reset = function(model) {
	this.update(model, 0, Math.min(model.count, this.count))
	if (this.count < model.count) {
		this.insert(model, this.count, model.count)
	} else {
		this.remove(model, model.count, this.count)
	}
}

exports.ModelUpdate.prototype._merge = function() {
	var ranges = this._ranges
	for(var index = 1; index < ranges.length; ) {
		var range = ranges[index - 1]
		var nextRange = ranges[index]
		if (range.type === nextRange.type) {
			if (range.type === ModelUpdateInsert && range.length < 0 && nextRange.length > 0) {
				//removed + inserted rows reappers as updated
				var updated = Math.min(-range.length, nextRange.length)
				range.type = ModelUpdateUpdate
				nextRange.length += range.length
				range.length = updated
				if (index > 1)
					--index
			} else {
				range.length += nextRange.length
				ranges.splice(index, 1)
			}
		} else if (range.type === ModelUpdateInsert && range.length === 0) {
			ranges.splice(index, 1)
		} else
			++index
	}
}

exports.ModelUpdate.prototype._split = function(index, offset, type, length) {
	var ranges = this._ranges
	if (offset === 0) {
		ranges.splice(index, 0, new ModelUpdateRange(type, length))
		return index + 1
	} else {
		var range = ranges[index]
		var right = range.length - offset
		range.length = offset
		if (right != 0) {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length),
				new ModelUpdateRange(range.type, right))
			return index + 2
		} else {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length))
			return index + 2
		}
	}
}

exports.ModelUpdate.prototype.insert = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count += d
	if (this.count != model.count)
		throw new Error('unbalanced insert ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]
	if (range.length === 0) { //first insert
		range.type = ModelUpdateInsert
		range.length += d
	} else {
		if (res.offset >= 0)
			this._split(res.index, res.offset, ModelUpdateInsert, d)
		else
			this._split(res.index + 1, 0, ModelUpdateInsert, d)
	}
	this._merge()
}

exports.ModelUpdate.prototype.remove = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count -= d
	if (this.count != model.count)
		throw new Error('unbalanced remove ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]

	if (range.type === ModelUpdateInsert) {
		range.length -= d
	} else {
		var index = this._split(res.index, res.offset, ModelUpdateInsert, -d)
		while(d > 0) {
			var range = ranges[index]
			if (range.length <= d) {
				ranges.splice(index, 1)
				d -= range.length
			} else {
				range.length -= d
				d = 0
			}
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.update = function(model, begin, end) {
	if (begin >= end)
		return

	var ranges = this._ranges
	var n = end - begin
	var res = this._find(begin)
	var index = res.index

	var range = ranges[index]
	if (res.offset > 0) {
		ranges.splice(index + 1, 0, new ModelUpdateRange(range.type, range.length - res.offset))
		range.length = res.offset
		++index
		if (range.length === 0)
			throw new Error('invalid offset')
	}

	while(n > 0) {
		var range = ranges[index]
		var length = range.length
		switch(range.type) {
			case ModelUpdateNothing:
				if (length > n) {
					//range larger than needed
					range.length -= n
					ranges.splice(index, 0, new ModelUpdateRange(ModelUpdateUpdate, n))
					n -= length
				} else { //length <= n
					range.type = ModelUpdateUpdate
					n -= length
				}
				break
			case ModelUpdateInsert:
				if (length > 0)
					n -= length
				++index
				break
			case ModelUpdateUpdate:
				n -= length
				++index
				break
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.clear = function() {
	this.count = 0
	this._reset()
}

exports.ModelUpdate.prototype.apply = function(view, skipCheck) {
	var index = 0
	this._ranges.forEach(
		function(range) {
			var n = range.length
			switch(range.type) {
				case ModelUpdateInsert:
					if (n > 0) {
						view._insertItems(index, index + n)
						index += n
					} else if (n < 0) {
						view._removeItems(index, index - n)
					}
					break
				case ModelUpdateUpdate:
					view._updateItems(index, index + n)
					index += n
					break
				default:
					index += range.length
			}
		}
	)
	if (!skipCheck && view._items.length != this.count)
		throw new Error('unbalanced items update, view: ' + view._items.length + ', update:' + this.count)

	for(var i = this._updateIndex; i < this.count; ++i)
		view._updateDelegateIndex(i)
	this._reset()
}

var ArrayModelWrapper = exports.ArrayModelWrapper = function (data) { this.data = data; this.count = data.length }
ArrayModelWrapper.prototype.get = function(idx)  { return { value: this.data[idx] } }
ArrayModelWrapper.prototype.on = function() { }
ArrayModelWrapper.prototype.removeListener = function() { }
<commit_msg>fix typo<commit_after>var ModelUpdateNothing = 0
var ModelUpdateInsert = 1
var ModelUpdateUpdate = 2

var ModelUpdateRange = function(type, length) {
	this.type = type
	this.length = length
}

exports.ModelUpdate = function() {
	this.count = 0
	this._reset()
}
exports.ModelUpdate.prototype.constructor = exports.ModelUpdate

exports.ModelUpdate.prototype._reset = function() {
	this._ranges = [new ModelUpdateRange(ModelUpdateNothing, this.count)]
	this._updateIndex = this.count
}

exports.ModelUpdate.prototype._setUpdateIndex = function(begin) {
	if (begin < this._updateIndex)
		this._updateIndex = begin
}

exports.ModelUpdate.prototype._find = function(index) {
	var ranges = this._ranges
	var i
	for(i = 0; i < ranges.length; ++i) {
		var range = ranges[i]
		if (index < range.length)
			return { index: i, offset: index }
		if (range.length > 0)
			index -= range.length
	}
	if (index != 0)
		throw new Error('invalid index ' + index)

	return { index: i - 1, offset: range.length }
}

exports.ModelUpdate.prototype.reset = function(model) {
	this.update(model, 0, Math.min(model.count, this.count))
	if (this.count < model.count) {
		this.insert(model, this.count, model.count)
	} else {
		this.remove(model, model.count, this.count)
	}
}

exports.ModelUpdate.prototype._merge = function() {
	var ranges = this._ranges
	for(var index = 1; index < ranges.length; ) {
		var range = ranges[index - 1]
		var nextRange = ranges[index]
		if (range.type === nextRange.type) {
			if (range.type === ModelUpdateInsert && range.length < 0 && nextRange.length > 0) {
				//removed + inserted rows reappears as updated
				var updated = Math.min(-range.length, nextRange.length)
				range.type = ModelUpdateUpdate
				nextRange.length += range.length
				range.length = updated
				if (index > 1)
					--index
			} else {
				range.length += nextRange.length
				ranges.splice(index, 1)
			}
		} else if (range.type === ModelUpdateInsert && range.length === 0) {
			ranges.splice(index, 1)
		} else
			++index
	}
}

exports.ModelUpdate.prototype._split = function(index, offset, type, length) {
	var ranges = this._ranges
	if (offset === 0) {
		ranges.splice(index, 0, new ModelUpdateRange(type, length))
		return index + 1
	} else {
		var range = ranges[index]
		var right = range.length - offset
		range.length = offset
		if (right != 0) {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length),
				new ModelUpdateRange(range.type, right))
			return index + 2
		} else {
			ranges.splice(index + 1, 0,
				new ModelUpdateRange(type, length))
			return index + 2
		}
	}
}

exports.ModelUpdate.prototype.insert = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count += d
	if (this.count != model.count)
		throw new Error('unbalanced insert ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]
	if (range.length === 0) { //first insert
		range.type = ModelUpdateInsert
		range.length += d
	} else {
		if (res.offset >= 0)
			this._split(res.index, res.offset, ModelUpdateInsert, d)
		else
			this._split(res.index + 1, 0, ModelUpdateInsert, d)
	}
	this._merge()
}

exports.ModelUpdate.prototype.remove = function(model, begin, end) {
	if (begin >= end)
		return

	this._setUpdateIndex(begin)
	var ranges = this._ranges
	var d = end - begin
	this.count -= d
	if (this.count != model.count)
		throw new Error('unbalanced remove ' + this.count + ' + [' + begin + '-' + end + '], model reported ' + model.count)

	var res = this._find(begin)
	var range = ranges[res.index]

	if (range.type === ModelUpdateInsert) {
		range.length -= d
	} else {
		var index = this._split(res.index, res.offset, ModelUpdateInsert, -d)
		while(d > 0) {
			var range = ranges[index]
			if (range.length <= d) {
				ranges.splice(index, 1)
				d -= range.length
			} else {
				range.length -= d
				d = 0
			}
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.update = function(model, begin, end) {
	if (begin >= end)
		return

	var ranges = this._ranges
	var n = end - begin
	var res = this._find(begin)
	var index = res.index

	var range = ranges[index]
	if (res.offset > 0) {
		ranges.splice(index + 1, 0, new ModelUpdateRange(range.type, range.length - res.offset))
		range.length = res.offset
		++index
		if (range.length === 0)
			throw new Error('invalid offset')
	}

	while(n > 0) {
		var range = ranges[index]
		var length = range.length
		switch(range.type) {
			case ModelUpdateNothing:
				if (length > n) {
					//range larger than needed
					range.length -= n
					ranges.splice(index, 0, new ModelUpdateRange(ModelUpdateUpdate, n))
					n -= length
				} else { //length <= n
					range.type = ModelUpdateUpdate
					n -= length
				}
				break
			case ModelUpdateInsert:
				if (length > 0)
					n -= length
				++index
				break
			case ModelUpdateUpdate:
				n -= length
				++index
				break
		}
	}
	this._merge()
}

exports.ModelUpdate.prototype.clear = function() {
	this.count = 0
	this._reset()
}

exports.ModelUpdate.prototype.apply = function(view, skipCheck) {
	var index = 0
	this._ranges.forEach(
		function(range) {
			var n = range.length
			switch(range.type) {
				case ModelUpdateInsert:
					if (n > 0) {
						view._insertItems(index, index + n)
						index += n
					} else if (n < 0) {
						view._removeItems(index, index - n)
					}
					break
				case ModelUpdateUpdate:
					view._updateItems(index, index + n)
					index += n
					break
				default:
					index += range.length
			}
		}
	)
	if (!skipCheck && view._items.length != this.count)
		throw new Error('unbalanced items update, view: ' + view._items.length + ', update:' + this.count)

	for(var i = this._updateIndex; i < this.count; ++i)
		view._updateDelegateIndex(i)
	this._reset()
}

var ArrayModelWrapper = exports.ArrayModelWrapper = function (data) { this.data = data; this.count = data.length }
ArrayModelWrapper.prototype.get = function(idx)  { return { value: this.data[idx] } }
ArrayModelWrapper.prototype.on = function() { }
ArrayModelWrapper.prototype.removeListener = function() { }
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {VelocityComponent} from 'velocity-react';
import styled from '@emotion/styled';

const Div = styled('div', {
    shouldForwardProp: prop => ['className', 'children'].indexOf(prop) !== -1
})((({style}) => style));
const Polygon = styled('polygon', {
    shouldForwardProp: prop => ['className', 'children', 'points'].indexOf(prop) !== -1
})((({style}) => style));

const Loading = styled(({ className }) => {
    return
loading...
;
})(({ style }) => style);

Loading.propTypes = {
    style: PropTypes.object
};

const Toggle = ({style}) => {
    const {height, width} = style;
    const midHeight = height * 0.5;
    const points = `0,0 0,${height} ${width},${midHeight}`;

    return (

                <svg height={height} width={width}>
                    <Polygon points={points}
                             style={style.arrow}/>
                </svg>

    );
};
Toggle.propTypes = {
    style: PropTypes.object
};

const Header = ({node, style}) => {
    return (

                {node.name}

    );
};
Header.propTypes = {
    style: PropTypes.object,
    node: PropTypes.object.isRequired
};

class Container extends React.Component {
    render() {
        const {style, decorators, terminal, onClick, node} = this.props;

        return (

 this.clickableRef = ref}
                 style={style.container}>
                {!terminal ? this.renderToggle() : null}

                <decorators.Header node={node}
                                   style={style.header}/>

        );
    }

    renderToggle() {
        const {animations} = this.props;

        if (!animations) {
            return this.renderToggleDecorator();
        }

        return (
            <VelocityComponent animation={animations.toggle.animation}
                               duration={animations.toggle.duration}
                               ref={ref => this.velocityRef = ref}>
                {this.renderToggleDecorator()}
            </VelocityComponent>
        );
    }

    renderToggleDecorator() {
        const {style, decorators} = this.props;

        return <decorators.Toggle style={style.toggle}/>;
    }
}
Container.propTypes = {
    style: PropTypes.object.isRequired,
    decorators: PropTypes.object.isRequired,
    terminal: PropTypes.bool.isRequired,
    onClick: PropTypes.func.isRequired,
    animations: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.bool
    ]).isRequired,
    node: PropTypes.object.isRequired
};

export default {
    Loading,
    Toggle,
    Header,
    Container
};
<commit_msg>fix a bug that activeLink does not work<commit_after>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {VelocityComponent} from 'velocity-react';
import styled from '@emotion/styled';

const Div = styled('div', {
    shouldForwardProp: prop => ['className', 'children'].indexOf(prop) !== -1
})((({style}) => style));
const Polygon = styled('polygon', {
    shouldForwardProp: prop => ['className', 'children', 'points'].indexOf(prop) !== -1
})((({style}) => style));

const Loading = styled(({ className }) => {
    return
loading...
;
})(({ style }) => style);

Loading.propTypes = {
    style: PropTypes.object
};

const Toggle = ({style}) => {
    const {height, width} = style;
    const midHeight = height * 0.5;
    const points = `0,0 0,${height} ${width},${midHeight}`;

    return (

                <svg height={height} width={width}>
                    <Polygon points={points}
                             style={style.arrow}/>
                </svg>

    );
};
Toggle.propTypes = {
    style: PropTypes.object
};

const Header = ({node, style}) => {
    return (

                {node.name}

    );
};
Header.propTypes = {
    style: PropTypes.object,
    node: PropTypes.object.isRequired
};

class Container extends React.Component {
    render() {
        const {style, decorators, terminal, onClick, node} = this.props;

        return (

 this.clickableRef = ref}
                 style={Object.assign({}, ...style.container)}>
                {!terminal ? this.renderToggle() : null}

                <decorators.Header node={node}
                                   style={style.header}/>

        );
    }

    renderToggle() {
        const {animations} = this.props;

        if (!animations) {
            return this.renderToggleDecorator();
        }

        return (
            <VelocityComponent animation={animations.toggle.animation}
                               duration={animations.toggle.duration}
                               ref={ref => this.velocityRef = ref}>
                {this.renderToggleDecorator()}
            </VelocityComponent>
        );
    }

    renderToggleDecorator() {
        const {style, decorators} = this.props;

        return <decorators.Toggle style={style.toggle}/>;
    }
}
Container.propTypes = {
    style: PropTypes.object.isRequired,
    decorators: PropTypes.object.isRequired,
    terminal: PropTypes.bool.isRequired,
    onClick: PropTypes.func.isRequired,
    animations: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.bool
    ]).isRequired,
    node: PropTypes.object.isRequired
};

export default {
    Loading,
    Toggle,
    Header,
    Container
};
<|endoftext|>


<commit_before>App.directive('choropleth', function($window) {

  var loader = $("#loader").clone();
  var hasLoader = loader.length > 0;

  if (hasLoader) {
      var choropleth = $("#choropleth");
          choropleth.append(loader.show());
  }

  var width = 600,
      height = 600;

  // D3 Array Object where the data is stored as key : value
  var rateById = d3.map();

  // Projection for Map
  var projection = d3.geo.transverseMercator()
      .rotate([100 + 20 / 60, -29 - 40 / 60])
      .scale(3000)
      .translate([285, 380]);

  // Declare the path object
  var path = d3.geo.path()
        .projection(projection);

  return {
    restrict: "E",
    scope: {
      dataset: '=',
      choropleth: '=',
      palette: '=',
    },
    link: function (scope, element, attrs) {
      var scale, svg, $svg;

      svg = d3.select(element[0]).append("svg")
        .attr("width", width)
        .attr("height", height);

      $svg = $('svg');

      hasLoader ? $svg.hide() : false;

      // Watch for changes in the dataset
      scope.$watch('dataset.records', function(newVals, oldVals) {
        updateData(newVals);
      }, true);

      scope.$watchCollection('[choropleth.scale, choropleth.data_classes, palette]', function(newVals, oldVals) {
        setScale(newVals[0]);
        updateData(scope.dataset.records);
      });

      function setScale(scaleId) {
        var range = scope.choropleth.data_classes;

        switch(scaleId) {
          // Quantize
          case 0:
            if (scope.palette && scope.choropleth.data_classes) {
              var min = scope.dataset.domain.min,
                  max = scope.dataset.domain.max;

              scale = d3.scale.quantize()
                .domain([min, max])
                .range(d3.range(range).map(function(i) {
                  return colorbrewer[scope.palette][range][i];
                }));
            }
            break;

          // Non-Quantize
          case 1:
            if (scope.palette && range) {
              var palette = colorbrewer[scope.palette][range];

              var color1 = palette[0];
                  color2 = palette[palette.length -1];

              var min = scope.dataset.domain.non_zero_min,
                  max = scope.dataset.domain.non_zero_max;

              scale = d3.scale.log()
                .domain([min, max])
                .range([color1, color2])
                .clamp(true);
            }
            break;

          // No scale
          default:
            scale = function() {
              return "none";
            };
        }
        return scale;
      }

      function updateData(data) {
        svg.select("#entities").selectAll("path")
          .attr('class', null)
          .attr('fill', function(d) {
            // Updates changes in the dataset
            // data.forEach(function(d) { rateById.set(d.cartogram_entity, d.value); });
            return fill(d);
          });
      }

      function fill(d) {
         value = rateById.get(d.properties.fips);
         if (value === null) {
           return 'none';
         }
         return scale(rateById.get(d.properties.fips));
      }

      function ready(error, texas) {
        svg.append("g")
          .attr("id", "entities")
        .selectAll("path")
         .data(topojson.feature(texas, texas.objects.counties).features)
        .enter().append("path")
          .attr("id", function(d) { return d.properties.fips; })
          .attr("fill", function(d) { return fill(d); })
          .attr("d", path);

        if (hasLoader) {
            choropleth.find('#loader').fadeOut('slow', function() {
              this.remove();
              $('svg').fadeIn('slow');
            });
        }
      }

      function render(data) {
        data.forEach(function(d) {rateById.set(d.cartogram_entity, d.value); });
        queue()
          .defer(d3.json, "/static/JSON/texas.json")
          .await(ready);
      }

      render(scope.dataset.records);
    }
  };
});

// Live edit and generic rendering directive for Markdown
App.directive('markdown', function($window) {
  var converter = new $window.Showdown.converter();
  return {
    restrict: 'E',
    scope: {
      description: '='
    },
    link: function(scope, element, attrs) {
      function markdownify(html) {
        var htmlText = converter.makeHtml(html);
        element.html(htmlText);
      }

      // For static viewing
      if (!scope.description) {
        markdownify(element.text());
      }

      // For live editing
      scope.$watch('description', function(newVal, oldVal) {
        if (newVal) {
          markdownify(newVal);
        }
      });
    }
  };
});

App.controller('AbstractController', function AbstractController ($scope, $http, Palettes) {

  $scope.tab = 1;

  $scope._success = function() {
    window.location = "/choropleths/";
  };

  $scope.schemes = [
    {name: "Sequential", id: 1},
    {name: "Diverging", id: 2},
    {name: "Qualitivative", id: 3}
  ];

  // Update the number data_classes available based on the current palette selection
  $scope.$watch('palette', function (palette) {
    var keys, min, max;

    keys = [];
    if (palette) {
      for (var index in colorbrewer[palette.class_name]) keys.push(index);
      min = Math.min.apply(null, keys);
      max = Math.max.apply(null, keys);
    }
    $scope.range = {
      options: keys,
      min: min,
      max: max
    };
  });

  $scope.getSchemePalettes = function(id) {
    Palettes.query({id: id}, function(data) {
      $scope.palettes = data;
      $scope.findPalette($scope.choropleth.palette);
    });
  };

  $scope.findPalette = function(id) {
    if (0 < $scope.palettes.length) {

      // Set defaults if the choropleth doesn't already have values
      $scope.palette = $scope.palettes[0];
      $scope.choropleth.palette = $scope.palette.id;

      // Set palette if the palette id is in the palettes array
      $scope.palettes.forEach(function (value, index, array) {
        if (value.id == id) {
          $scope.palette = value;
          $scope.choropleth.palette = value.id;
        }
      });
    }
  };
});

App.controller('ViewController', function ViewController ($scope, $controller, Choropleth, Dataset, Palettes ) {
  $controller('AbstractController', {$scope: $scope});

  $scope.init = function(id) {
    Choropleth.get({id: id}, function (data) {
      $scope.choropleth = data;

      Dataset.get({id: data.dataset}, function(data) {
        $scope.dataset = data;
        $scope.scales = data.scale_options;
        $scope.hasData = true;
      });

      Palettes.query({id: data.scheme}, function (data) {
        $scope.palettes = data;
        $scope.findPalette($scope.choropleth.palette);
      });
    });
  };
});

App.controller('EditController', function EditController ($scope, $controller, Choropleth, Dataset, Palettes) {
  $controller('ViewController', {$scope: $scope});

  $scope.submit = function() {
    $('#in-progress').modal();
    $scope.choropleth.$update($scope._success);
  };

  $scope.delete = function() {
    $scope.choropleth.$delete($scope._success);
  };
});

App.controller('MappCtrl', function MappCtrl ($scope, $controller, Choropleth, Dataset, Palettes) {
  $controller('AbstractController', {$scope: $scope});

  $scope.init = function(id) {
    $scope.choropleth = new Choropleth();

    Dataset.get({id: id}, function(data) {
      $scope.dataset = data;
      $scope.choropleth.dataset = data.id;
      $scope.choropleth.name = data.name;
      $scope.choropleth.data_classes = 3;
      $scope.scales = data.scale_options;
      $scope.hasData = true;
    });

    Palettes.query({id: 1}, function(data) {
      $scope.palettes = data;
    });
  };

  $scope.submit = function() {
    $('#in-progress').modal();
    $scope.choropleth.$save($scope._success);
  };
});

<commit_msg>Completely removed isolated scope. Now grabbing the entity selection and adding it to scope.<commit_after>App.directive('choropleth', function($window) {

  var loader = $("#loader").clone();
  var hasLoader = loader.length > 0;

  if (hasLoader) {
      var choropleth = $("#choropleth");
          choropleth.append(loader.show());
  }

  var width = 600,
      height = 600;

  // D3 Array Object where the data is stored as key : value
  var rateById = d3.map();

  // Projection for Map
  var projection = d3.geo.transverseMercator()
      .rotate([100 + 20 / 60, -29 - 40 / 60])
      .scale(3000)
      .translate([285, 380]);

  // Declare the path object
  var path = d3.geo.path()
        .projection(projection);

  return {
    restrict: "E",
    scope: true,
    link: function (scope, element, attrs) {
      var scale, svg, $svg, g;

      svg = d3.select(element[0]).append("svg")
        .attr("width", width)
        .attr("height", height);

      $svg = $('svg');

      hasLoader ? $svg.hide() : false;

      // Watch for changes in the dataset
      scope.$watch('dataset.records', function(newVals, oldVals) {
        updateData(newVals);
      }, true);

      scope.$watch('choropleth.selection.cartogram_entity', function(newVals, oldVals) {
          if (newVals !== oldVals) {
              var records = scope.dataset.records
              records.forEach(function(record) {
                  if (newVals === record.cartogram_entity) {
                      scope.choropleth.selection = JSON.parse(JSON.stringify(record))
                  }
              })
          }
      });

      scope.$watchCollection('[choropleth.scale, choropleth.data_classes, palette.class_name]', function(newVals, oldVals) {
        setScale(newVals[0]);
        updateData(scope.dataset.records);
      });

      function setScale(scaleId) {
        var range = scope.choropleth.data_classes;

        switch(scaleId) {
          // Quantize
          case 0:
            if (scope.palette && scope.choropleth.data_classes) {
              var min = scope.dataset.domain.min,
                  max = scope.dataset.domain.max;

              scale = d3.scale.quantize()
                .domain([min, max])
                .range(d3.range(range).map(function(i) {
                  return colorbrewer[scope.palette.class_name][range][i];
                }));
            }
            break;

          // Non-Quantize
          case 1:
            if (scope.palette && range) {
              var palette = colorbrewer[scope.palette.class_name][range];

              var color1 = palette[0];
                  color2 = palette[palette.length -1];

              var min = scope.dataset.domain.non_zero_min,
                  max = scope.dataset.domain.non_zero_max;

              scale = d3.scale.log()
                .domain([min, max])
                .range([color1, color2])
                .clamp(true);
            }
            break;

          // No scale
          default:
            scale = function() {
              return "none";
            };
        }
        return scale;
      }

      function updateData(data) {
        svg.select("#entities").selectAll("path")
          .attr('class', null)
          .attr('fill', function(d) {
            // Updates changes in the dataset
            // data.forEach(function(d) { rateById.set(d.cartogram_entity, d.value); });
            return fill(d);
          });
      }

      function fill(d) {
         value = rateById.get(d.properties.fips);
         if (value === null) {
           return 'none';
         }
         return scale(rateById.get(d.properties.fips));
      }

      function ready(error, texas) {
        svg.append("g")
          .attr("id", "entities")
        .selectAll("path")
         .data(topojson.feature(texas, texas.objects.counties).features)
        .enter().append("path")
          .attr("id", function(d) { return d.properties.fips; })
          .attr("fill", function(d) { return fill(d); })
          .on("click", function(d) {
            scope.choropleth.selection.cartogram_entity = d.properties.fips;
            scope.$apply();
          })
          .attr("d", path);

        if (hasLoader) {
            choropleth.find('#loader').fadeOut('slow', function() {
              this.remove();
              $('svg').fadeIn('slow');
            });
        }
      }

      function render(data) {
        data.forEach(function(d) {rateById.set(d.cartogram_entity, d.value); });
        queue()
          .defer(d3.json, "/static/JSON/texas.json")
          .await(ready);
      }

      render(scope.dataset.records);
    }
  };
});

// Live edit and generic rendering directive for Markdown
App.directive('markdown', function($window) {
  var converter = new $window.Showdown.converter();
  return {
    restrict: 'E',
    scope: {
      description: '='
    },
    link: function(scope, element, attrs) {
      function markdownify(html) {
        var htmlText = converter.makeHtml(html);
        element.html(htmlText);
      }

      // For static viewing
      if (!scope.description) {
        markdownify(element.text());
      }

      // For live editing
      scope.$watch('description', function(newVal, oldVal) {
        if (newVal) {
          markdownify(newVal);
        }
      });
    }
  };
});

App.controller('AbstractController', function AbstractController ($scope, $http, Palettes) {

  $scope.tab = 1;

  $scope._success = function() {
    window.location = "/choropleths/";
  };

  $scope.schemes = [
    {name: "Sequential", id: 1},
    {name: "Diverging", id: 2},
    {name: "Qualitivative", id: 3}
  ];

  // Update the number data_classes available based on the current palette selection
  $scope.$watch('palette', function (palette) {
    var keys, min, max;

    keys = [];
    if (palette) {
      for (var index in colorbrewer[palette.class_name]) keys.push(index);
      min = Math.min.apply(null, keys);
      max = Math.max.apply(null, keys);
    }
    $scope.range = {
      options: keys,
      min: min,
      max: max
    };
  });

  $scope.getSchemePalettes = function(id) {
    Palettes.query({id: id}, function(data) {
      $scope.palettes = data;
      $scope.findPalette($scope.choropleth.palette);
    });
  };

  $scope.findPalette = function(id) {
    if (0 < $scope.palettes.length) {

      // Set defaults if the choropleth doesn't already have values
      $scope.palette = $scope.palettes[0];
      $scope.choropleth.palette = $scope.palette.id;

      // Set palette if the palette id is in the palettes array
      $scope.palettes.forEach(function (value, index, array) {
        if (value.id == id) {
          $scope.palette = value;
          $scope.choropleth.palette = value.id;
        }
      });
    }
  };
});

App.controller('ViewController', function ViewController ($scope, $controller, Choropleth, Dataset, Palettes ) {
  $controller('AbstractController', {$scope: $scope});

  $scope.init = function(id) {
    Choropleth.get({id: id}, function (data) {
      $scope.choropleth = data;
      $scope.choropleth.selection = {};

      Dataset.get({id: data.dataset}, function(data) {
        $scope.dataset = data;
        $scope.scales = data.scale_options;
        $scope.hasData = true;
      });

      Palettes.query({id: data.scheme}, function (data) {
        $scope.palettes = data;
        $scope.findPalette($scope.choropleth.palette);
      });
    });
  };
});

App.controller('EditController', function EditController ($scope, $controller, Choropleth, Dataset, Palettes) {
  $controller('ViewController', {$scope: $scope});

  $scope.submit = function() {
    $('#in-progress').modal();
    $scope.choropleth.$update($scope._success);
  };

  $scope.delete = function() {
    $scope.choropleth.$delete($scope._success);
  };
});

App.controller('MappCtrl', function MappCtrl ($scope, $controller, Choropleth, Dataset, Palettes) {
  $controller('AbstractController', {$scope: $scope});

  $scope.init = function(id) {
    $scope.choropleth = new Choropleth();

    Dataset.get({id: id}, function(data) {
      $scope.dataset = data;
      $scope.choropleth.dataset = data.id;
      $scope.choropleth.name = data.name;
      $scope.choropleth.data_classes = 3;
      $scope.choropleth.selection = {};
      $scope.scales = data.scale_options;
      $scope.hasData = true;
    });

    Palettes.query({id: 1}, function(data) {
      $scope.palettes = data;
    });
  };

  $scope.submit = function() {
    $('#in-progress').modal();
    $scope.choropleth.$save($scope._success);
  };
});

<|endoftext|>


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

    var gameDetailsController = function gameDetailsController($location, $routeParams, identity, games, cards, notifier){
        var vm = this;
        vm.selections = [];

        var gameId = $location.absUrl().split('/').pop();
        games
            .getById(gameId)
            .then(function(resp){
                vm.game = resp.data;
                vm.userWhiteCards = vm.game.currentWhiteCards.slice(0, 4);
            });

        $('.noselect').on('click', function(event){
            var $target = $(event.target);
            if($target.hasClass('white-card-container')) {
                if ($target.hasClass('selected-white-card')) {
                    notifier.error('You cannot unselect a card');
                } else {
                    if (vm.selections.length < vm.blackCard.whiteCardsRequire) {
                        vm.selections.push($target.text());
                        $target.toggleClass('selected-white-card');
                        if (vm.selections.length === vm.blackCard.whiteCardsRequire) {
                            if (vm.isCzar) {
                                games
                                    .registerCzarCards(vm.game._id, vm.selections)
                                    .then(function () {
                                        notifier.success('Your choice has been submitted');
                                    });
                            } else {
                                games
                                    .registerUserCards(vm.game._id, vm.selections)
                                    .then(function () {
                                        notifier.success('Your choice has been submitted');
                                    });
                            }
                        }
                    } else {
                        notifier.error('You cannot select any more white cards');
                    }
                }
            }
        });

        var $seconds = $('.seconds');
        var updateState = setInterval(function(){
            games
                .getById(gameId)
                .then(function(resp){
                    vm.game = resp.data;
                    vm.userWhiteCards = vm.game.currentWhiteCards.slice(0, 4);
                    if(Number($seconds.text()) === 0){
                        // reset UI - white cards
                        $('.white-card-container').each(function(index, value){
                           $(value).removeClass('selected-white-card');
                        });
                    }
                })
                .then(function() {
                    cards
                        .getBlackCardById(vm.game.currentBlackCard)
                        .then(function (resp) {
                            vm.blackCard = resp.data;
                        });
                });
        }, 1000);
    };

    angular
        .module('cardsAgainstHumanity.controllers')
        .controller('GameDetailsPageController', ['$location','$routeParams', 'identity', 'games', 'cards', 'notifier', gameDetailsController]);
}());<commit_msg>Bug fix - white cards selection count in game-details-controller.js reset after end of round<commit_after>(function(){
    "use strict";

    var gameDetailsController = function gameDetailsController($location, $routeParams, identity, games, cards, notifier){
        var vm = this;
        vm.selections = [];

        var gameId = $location.absUrl().split('/').pop();
        games
            .getById(gameId)
            .then(function(resp){
                vm.game = resp.data;
                vm.userWhiteCards = vm.game.currentWhiteCards.slice(0, 4);
            });

        $('.noselect').on('click', function(event){
            var $target = $(event.target);
            if($target.hasClass('white-card-container')) {
                if ($target.hasClass('selected-white-card')) {
                    notifier.error('You cannot unselect a card');
                } else {
                    if (vm.selections.length < vm.blackCard.whiteCardsRequire) {
                        vm.selections.push($target.text());
                        $target.toggleClass('selected-white-card');
                        if (vm.selections.length === vm.blackCard.whiteCardsRequire) {
                            if (vm.isCzar) {
                                games
                                    .registerCzarCards(vm.game._id, vm.selections)
                                    .then(function () {
                                        notifier.success('Your choice has been submitted');
                                    });
                            } else {
                                games
                                    .registerUserCards(vm.game._id, vm.selections)
                                    .then(function () {
                                        notifier.success('Your choice has been submitted');
                                    });
                            }
                        }
                    } else {
                        notifier.error('You cannot select any more white cards');
                    }
                }
            }
        });

        var $seconds = $('.seconds');
        var updateState = setInterval(function(){
            games
                .getById(gameId)
                .then(function(resp){
                    vm.game = resp.data;
                    vm.userWhiteCards = vm.game.currentWhiteCards.slice(0, 4);
                    if(Number($seconds.text()) === 0){
                        // reset UI - white cards
                        vm.selections = [];
                        $('.white-card-container').each(function(index, value){
                           $(value).removeClass('selected-white-card');
                        });
                    }
                })
                .then(function() {
                    cards
                        .getBlackCardById(vm.game.currentBlackCard)
                        .then(function (resp) {
                            vm.blackCard = resp.data;
                        });
                });
        }, 1000);
    };

    angular
        .module('cardsAgainstHumanity.controllers')
        .controller('GameDetailsPageController', ['$location','$routeParams', 'identity', 'games', 'cards', 'notifier', gameDetailsController]);
}());<|endoftext|>


<commit_before>import {input, div} from '@cycle/dom'

const view = (state$) => {
  return state$.map(({value, placeholder, transition, className}) => {
    console.log(value, placeholder, transition)
    const cName = className ? '.' + className : ''
    return div('.cycle-input-wrapper', [
      input('.cycle-input' + cName, {
        attrs: {
          type: 'text',
          placeholder: placeholder,
          value: value,
        },
        style: {
          height: transition + '%',
          opacity: transition < 30 ? transition / 30 : 1,
        },
      })
    ])
  })
}
export default view
<commit_msg>removed comments<commit_after>import {input, div} from '@cycle/dom'

const view = (state$) => {
  return state$.map(({value, placeholder, transition, className}) => {
    const cName = className ? '.' + className : ''
    return div('.cycle-input-wrapper', [
      input('.cycle-input' + cName, {
        attrs: {
          type: 'text',
          placeholder: placeholder,
          value: value,
        },
        style: {
          height: transition + '%',
          opacity: transition < 30 ? transition / 30 : 1,
        },
      })
    ])
  })
}
export default view
<|endoftext|>