<commit_before>var React = require('react');
var ReactNative = require('react-native');
var PropTypes = require('prop-types');
var createReactClass = require('create-react-class');

var {
  PanResponder,
  View,
  TouchableHighlight,
  Animated,
} = ReactNative;

var MaterialSwitch = createReactClass({
  padding: 8,

  propTypes: {
    active: PropTypes.bool,
    style: View.propTypes.style,
    inactiveButtonColor: PropTypes.string,
    inactiveButtonPressedColor: PropTypes.string,
    activeButtonColor: PropTypes.string,
    activeButtonPressedColor: PropTypes.string,
    buttonShadow: View.propTypes.style,
    activeBackgroundColor: PropTypes.string,
    inactiveBackgroundColor: PropTypes.string,
    buttonRadius: PropTypes.number,
    switchWidth: PropTypes.number,
    switchHeight: PropTypes.number,
    buttonContent: PropTypes.element,
    enableSlide: PropTypes.bool,
    switchAnimationTime: PropTypes.number,
    onActivate: PropTypes.func,
    onDeactivate: PropTypes.func,
    onChangeState: PropTypes.func,
  },

  getDefaultProps() {
    return {
      active: false,
      style: {},
      inactiveButtonColor: '#2196F3',
      inactiveButtonPressedColor: '#42A5F5',
      activeButtonColor: '#FAFAFA',
      activeButtonPressedColor: '#F5F5F5',
      buttonShadow: {
        elevation: 3,
        shadowColor: '#000',
        shadowOpacity: 0.5,
        shadowRadius: 1,
        shadowOffset: { height: 1, width: 0 },
      },
      activeBackgroundColor: 'rgba(255,255,255,.5)',
      inactiveBackgroundColor: 'rgba(0,0,0,.5)',
      buttonRadius: 15,
      switchWidth: 40,
      switchHeight: 20,
      buttonContent: null,
      buttonOffset: 0,
      enableSlide: true,
      switchAnimationTime: 200,
      onActivate: function() {},
      onDeactivate: function() {},
      onChangeState: function() {},
    };
  },

  getInitialState() {
    var w = (this.props.switchWidth - Math.min(this.props.switchHeight, this.props.buttonRadius*2) - this.props.buttonOffset);

    return {
      width: w,
      state: this.props.active,
      position: new Animated.Value(this.props.active? w : this.props.buttonOffset),
    };
  },

  start: {},

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

      onPanResponderGrant: (evt, gestureState) => {
        if (!this.props.enableSlide) return;

        this.setState({pressed: true});
        this.start.x0 = gestureState.x0;
        this.start.pos = this.state.position._value;
        this.start.moved = false;
        this.start.state = this.state.state;
        this.start.stateChanged = false;
      },
      onPanResponderMove: (evt, gestureState) => {
        if (!this.props.enableSlide) return;

        this.start.moved = true;
        if (this.start.pos == 0) {
          if (gestureState.dx <= this.state.width && gestureState.dx >= 0) {
            this.state.position.setValue(gestureState.dx);
          }
          if (gestureState.dx > this.state.width) {
            this.state.position.setValue(this.state.width);
          }
          if (gestureState.dx < 0) {
            this.state.position.setValue(0);
          }
        }
        if (this.start.pos == this.state.width) {
          if (gestureState.dx >= -this.state.width && gestureState.dx <= 0) {
            this.state.position.setValue(this.state.width+gestureState.dx);
          }
          if (gestureState.dx > 0) {
            this.state.position.setValue(this.state.width);
          }
          if (gestureState.dx < -this.state.width) {
            this.state.position.setValue(0);
          }
        }
        var currentPos = this.state.position._value;
        this.onSwipe(currentPos, this.start.pos,
          () => {
            if (!this.start.state) this.start.stateChanged = true;
            this.setState({state: true})
          },
          ()=>{
            if (this.start.state) this.start.stateChanged = true;
            this.setState({state: false})
          });
      },
      onPanResponderTerminationRequest: (evt, gestureState) => true,
      onPanResponderRelease: (evt, gestureState) => {
        this.setState({pressed: false});
        var currentPos = this.state.position._value;
        if (!this.start.moved || (Math.abs(currentPos-this.start.pos)<5 && !this.start.stateChanged)) {
          this.toggle();
          return;
        }
        this.onSwipe(currentPos, this.start.pos, this.activate, this.deactivate);
      },
      onPanResponderTerminate: (evt, gestureState) => {
        var currentPos = this.state.position._value;
        this.setState({pressed: false});
        this.onSwipe(currentPos, this.start.pos, this.activate, this.deactivate);
      },
      onShouldBlockNativeResponder: (evt, gestureState) => true,
    });
  },

  componentWillReceiveProps: function(nextProps){
    if(this.state.state !== nextProps.active){
      nextProps.active ? this.activate() : this.deactivate()
    }
  },

  onSwipe(currentPosition, startingPosition, onChange, onTerminate) {
    if (currentPosition-startingPosition >= 0) {
      if (currentPosition-startingPosition > this.state.width/2 || startingPosition == this.state.width) {
        onChange();
      } else {
        onTerminate();
      }
    } else {
      if (currentPosition-startingPosition < -this.state.width/2) {
        onTerminate();
      } else {
        onChange();
      }
    }
  },

  activate() {
    Animated.timing(
      this.state.position,
      {
        toValue: this.state.width,
        duration: this.props.switchAnimationTime,
        useNativeDriver: true,
      }
    ).start();
    this.changeState(true);
  },

  deactivate() {
    Animated.timing(
      this.state.position,
      {
        toValue: this.props.buttonOffset,
        duration: this.props.switchAnimationTime,
        useNativeDriver: true,
      }
    ).start();
    this.changeState(false);
  },

  changeState(state) {
    var callHandlers = this.start.state != state;
    setTimeout(() => {
      this.setState({state : state});
      if (callHandlers) {
        this.callback();
      }
    }, this.props.switchAnimationTime/2);
  },

  callback() {
    var state = this.state.state;
    if (state) {
      this.props.onActivate();
    } else {
      this.props.onDeactivate();
    }
    this.props.onChangeState(state);
  },

  toggle() {
    if (!this.props.enableSlide) return;

    if (this.state.state) {
      this.deactivate();
    } else {
      this.activate();
    }
  },

  render() {
    var doublePadding = this.padding*2-2;
    var halfPadding = doublePadding/2;
    return (
      <View
        {...this._panResponder.panHandlers}
        style={[{padding: this.padding, position: 'relative'}, this.props.style]}>
        <View
          style={{
            backgroundColor: this.state.state ? this.props.activeBackgroundColor : this.props.inactiveBackgroundColor,
            height: this.props.switchHeight,
            width: this.props.switchWidth,
            borderRadius: this.props.switchHeight/2,
          }}/>
        <TouchableHighlight underlayColor='transparent' activeOpacity={1} style={{
            height: Math.max(this.props.buttonRadius*2+doublePadding, this.props.switchHeight+doublePadding),
            width: this.props.switchWidth+doublePadding,
            position: 'absolute',
            top: 1,
            left: 1
          }}>
          <Animated.View style={[{
              backgroundColor:
                this.state.state
                  ? (this.state.pressed? this.props.activeButtonPressedColor : this.props.activeButtonColor)
                  : (this.state.pressed? this.props.inactiveButtonPressedColor : this.props.inactiveButtonColor),
              height: this.props.buttonRadius*2,
              width: this.props.buttonRadius*2,
              borderRadius: this.props.buttonRadius,
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: 'row',
              position: 'absolute',
              top: halfPadding + this.props.switchHeight/2 - this.props.buttonRadius,
              left: this.props.switchHeight/2 > this.props.buttonRadius ? halfPadding : halfPadding + this.props.switchHeight/2 - this.props.buttonRadius,
              transform: [{ translateX: this.state.position }]
            },
            this.props.buttonShadow]}
          >
            {this.props.buttonContent}
          </Animated.View>
        </TouchableHighlight>
      </View>
    )
  }
});

module.exports = MaterialSwitch;
<commit_msg>proptypes<commit_after>var React = require('react');
var ReactNative = require('react-native');
var PropTypes = require('prop-types');
var createReactClass = require('create-react-class');

var {
  PanResponder,
  View,
  TouchableHighlight,
  Animated,
  ViewPropTypes,
} = ReactNative;

var MaterialSwitch = createReactClass({
  padding: 8,

  propTypes: {
    active: PropTypes.bool,
    style: ViewPropTypes.style,
    inactiveButtonColor: PropTypes.string,
    inactiveButtonPressedColor: PropTypes.string,
    activeButtonColor: PropTypes.string,
    activeButtonPressedColor: PropTypes.string,
    buttonShadow: ViewPropTypes.style,
    activeBackgroundColor: PropTypes.string,
    inactiveBackgroundColor: PropTypes.string,
    buttonRadius: PropTypes.number,
    switchWidth: PropTypes.number,
    switchHeight: PropTypes.number,
    buttonContent: PropTypes.element,
    enableSlide: PropTypes.bool,
    switchAnimationTime: PropTypes.number,
    onActivate: PropTypes.func,
    onDeactivate: PropTypes.func,
    onChangeState: PropTypes.func,
  },

  getDefaultProps() {
    return {
      active: false,
      style: {},
      inactiveButtonColor: '#2196F3',
      inactiveButtonPressedColor: '#42A5F5',
      activeButtonColor: '#FAFAFA',
      activeButtonPressedColor: '#F5F5F5',
      buttonShadow: {
        elevation: 3,
        shadowColor: '#000',
        shadowOpacity: 0.5,
        shadowRadius: 1,
        shadowOffset: { height: 1, width: 0 },
      },
      activeBackgroundColor: 'rgba(255,255,255,.5)',
      inactiveBackgroundColor: 'rgba(0,0,0,.5)',
      buttonRadius: 15,
      switchWidth: 40,
      switchHeight: 20,
      buttonContent: null,
      buttonOffset: 0,
      enableSlide: true,
      switchAnimationTime: 200,
      onActivate: function() {},
      onDeactivate: function() {},
      onChangeState: function() {},
    };
  },

  getInitialState() {
    var w = (this.props.switchWidth - Math.min(this.props.switchHeight, this.props.buttonRadius*2) - this.props.buttonOffset);

    return {
      width: w,
      state: this.props.active,
      position: new Animated.Value(this.props.active? w : this.props.buttonOffset),
    };
  },

  start: {},

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

      onPanResponderGrant: (evt, gestureState) => {
        if (!this.props.enableSlide) return;

        this.setState({pressed: true});
        this.start.x0 = gestureState.x0;
        this.start.pos = this.state.position._value;
        this.start.moved = false;
        this.start.state = this.state.state;
        this.start.stateChanged = false;
      },
      onPanResponderMove: (evt, gestureState) => {
        if (!this.props.enableSlide) return;

        this.start.moved = true;
        if (this.start.pos == 0) {
          if (gestureState.dx <= this.state.width && gestureState.dx >= 0) {
            this.state.position.setValue(gestureState.dx);
          }
          if (gestureState.dx > this.state.width) {
            this.state.position.setValue(this.state.width);
          }
          if (gestureState.dx < 0) {
            this.state.position.setValue(0);
          }
        }
        if (this.start.pos == this.state.width) {
          if (gestureState.dx >= -this.state.width && gestureState.dx <= 0) {
            this.state.position.setValue(this.state.width+gestureState.dx);
          }
          if (gestureState.dx > 0) {
            this.state.position.setValue(this.state.width);
          }
          if (gestureState.dx < -this.state.width) {
            this.state.position.setValue(0);
          }
        }
        var currentPos = this.state.position._value;
        this.onSwipe(currentPos, this.start.pos,
          () => {
            if (!this.start.state) this.start.stateChanged = true;
            this.setState({state: true})
          },
          ()=>{
            if (this.start.state) this.start.stateChanged = true;
            this.setState({state: false})
          });
      },
      onPanResponderTerminationRequest: (evt, gestureState) => true,
      onPanResponderRelease: (evt, gestureState) => {
        this.setState({pressed: false});
        var currentPos = this.state.position._value;
        if (!this.start.moved || (Math.abs(currentPos-this.start.pos)<5 && !this.start.stateChanged)) {
          this.toggle();
          return;
        }
        this.onSwipe(currentPos, this.start.pos, this.activate, this.deactivate);
      },
      onPanResponderTerminate: (evt, gestureState) => {
        var currentPos = this.state.position._value;
        this.setState({pressed: false});
        this.onSwipe(currentPos, this.start.pos, this.activate, this.deactivate);
      },
      onShouldBlockNativeResponder: (evt, gestureState) => true,
    });
  },

  componentWillReceiveProps: function(nextProps){
    if(this.state.state !== nextProps.active){
      nextProps.active ? this.activate() : this.deactivate()
    }
  },

  onSwipe(currentPosition, startingPosition, onChange, onTerminate) {
    if (currentPosition-startingPosition >= 0) {
      if (currentPosition-startingPosition > this.state.width/2 || startingPosition == this.state.width) {
        onChange();
      } else {
        onTerminate();
      }
    } else {
      if (currentPosition-startingPosition < -this.state.width/2) {
        onTerminate();
      } else {
        onChange();
      }
    }
  },

  activate() {
    Animated.timing(
      this.state.position,
      {
        toValue: this.state.width,
        duration: this.props.switchAnimationTime,
        useNativeDriver: true,
      }
    ).start();
    this.changeState(true);
  },

  deactivate() {
    Animated.timing(
      this.state.position,
      {
        toValue: this.props.buttonOffset,
        duration: this.props.switchAnimationTime,
        useNativeDriver: true,
      }
    ).start();
    this.changeState(false);
  },

  changeState(state) {
    var callHandlers = this.start.state != state;
    setTimeout(() => {
      this.setState({state : state});
      if (callHandlers) {
        this.callback();
      }
    }, this.props.switchAnimationTime/2);
  },

  callback() {
    var state = this.state.state;
    if (state) {
      this.props.onActivate();
    } else {
      this.props.onDeactivate();
    }
    this.props.onChangeState(state);
  },

  toggle() {
    if (!this.props.enableSlide) return;

    if (this.state.state) {
      this.deactivate();
    } else {
      this.activate();
    }
  },

  render() {
    var doublePadding = this.padding*2-2;
    var halfPadding = doublePadding/2;
    return (
      <View
        {...this._panResponder.panHandlers}
        style={[{padding: this.padding, position: 'relative'}, this.props.style]}>
        <View
          style={{
            backgroundColor: this.state.state ? this.props.activeBackgroundColor : this.props.inactiveBackgroundColor,
            height: this.props.switchHeight,
            width: this.props.switchWidth,
            borderRadius: this.props.switchHeight/2,
          }}/>
        <TouchableHighlight underlayColor='transparent' activeOpacity={1} style={{
            height: Math.max(this.props.buttonRadius*2+doublePadding, this.props.switchHeight+doublePadding),
            width: this.props.switchWidth+doublePadding,
            position: 'absolute',
            top: 1,
            left: 1
          }}>
          <Animated.View style={[{
              backgroundColor:
                this.state.state
                  ? (this.state.pressed? this.props.activeButtonPressedColor : this.props.activeButtonColor)
                  : (this.state.pressed? this.props.inactiveButtonPressedColor : this.props.inactiveButtonColor),
              height: this.props.buttonRadius*2,
              width: this.props.buttonRadius*2,
              borderRadius: this.props.buttonRadius,
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: 'row',
              position: 'absolute',
              top: halfPadding + this.props.switchHeight/2 - this.props.buttonRadius,
              left: this.props.switchHeight/2 > this.props.buttonRadius ? halfPadding : halfPadding + this.props.switchHeight/2 - this.props.buttonRadius,
              transform: [{ translateX: this.state.position }]
            },
            this.props.buttonShadow]}
          >
            {this.props.buttonContent}
          </Animated.View>
        </TouchableHighlight>
      </View>
    )
  }
});

module.exports = MaterialSwitch;
<|endoftext|>


<commit_before>var checksum = require('checksum');

module.exports = {

	website: {
		assets: "./book",
		css: [
			"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css",
			"fbqx.css"
		],
		js: [
			"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js",
			"fbqx.js",
			"js.cookie.js"
		]
	},

	blocks: {
		fbq: {
			process: function(blk) {
                if(this.generator === 'website'){

                    var para = blk.body;
                    var substr = para.split("$$");
                    var ans = [];

                    for(var i = 1; i<substr.length; i++){
                        ans.push(substr[i].split("##", 1));
                        var str = '$$' + ans[i-1].toString() + '##';
                        para = para.replace(str, "
<input type='text' class='form-control input-sm'/>
");
                    }

				    return "
" + para + "
<button class='btn btn-default btn-sm FBQsubmit'>Submit</button>
";
                }
                else {

                    var para = blk.body;
                    var substr = para.split("$$");
                    var ans = [];

                    for(var i = 1; i<substr.length; i++){
                        ans.push(substr[i].split("##", 1));
                        var str = '$$' + ans[i-1].toString() + '##';
                        para = para.replace(str, "______");
                    }

                    var ansString = ans.join(',');

                    return "
"+ para +"
ans: "+ansString+"
";
                }
			}
		}
	}
};
<commit_msg>making ans text smaller<commit_after>var checksum = require('checksum');

module.exports = {

	website: {
		assets: "./book",
		css: [
			"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css",
			"fbqx.css"
		],
		js: [
			"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js",
			"fbqx.js",
			"js.cookie.js"
		]
	},

	blocks: {
		fbq: {
			process: function(blk) {
                if(this.generator === 'website'){

                    var para = blk.body;
                    var substr = para.split("$$");
                    var ans = [];

                    for(var i = 1; i<substr.length; i++){
                        ans.push(substr[i].split("##", 1));
                        var str = '$$' + ans[i-1].toString() + '##';
                        para = para.replace(str, "
<input type='text' class='form-control input-sm'/>
");
                    }

				    return "
" + para + "
<button class='btn btn-default btn-sm FBQsubmit'>Submit</button>
";
                }
                else {

                    var para = blk.body;
                    var substr = para.split("$$");
                    var ans = [];

                    for(var i = 1; i<substr.length; i++){
                        ans.push(substr[i].split("##", 1));
                        var str = '$$' + ans[i-1].toString() + '##';
                        para = para.replace(str, "______");
                    }

                    var ansString = ans.join(',');

                    return "
"+ para +"
ans: "+ansString+"
";
                }
			}
		}
	}
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var Funnel = require('broccoli-funnel');
var MergeTrees = require('broccoli-merge-trees');
var SVGOptimizer = require('broccoli-svg-optimizer');
var Symbolizer = require('broccoli-symbolizer');
var InlinePacker = require('./lib/inline-packer');
var ViewerAssetsBuilder = require('./lib/viewer-assets-builder');
var ViewerBuilder = require('./lib/viewer-builder');
var defaultGenerators = require('./lib/generators');

var symbolsLoaderScript = fs.readFileSync(
  path.join(__dirname, 'symbols-loader.html'), 'utf8'
);

function mergeTreesIfNeeded(trees, options) {
  return trees.length === 1 ? trees[0] : new MergeTrees(trees, options);
}

module.exports = {
  name: 'ember-svg-jar',

  isDevelopingAddon: function() {
    return false;
  },

  included: function(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    this.initializeOptions(app.options.svgJar, app.env);
  },

  treeForPublic: function() {
    var trees = [];

    if (this.options.viewer.enabled) {
      trees.push(this.getViewerTree());

      if (this.options.viewer.embed) {
        trees.push(this._super.treeForPublic.apply(this, arguments));
      }
    }

    if (this.hasSymbolStrategy()) {
      trees.push(this.getSymbolStrategyTree());
    }

    return mergeTreesIfNeeded(trees);
  },

  treeForApp: function(appTree) {
    var trees = [appTree];

    if (this.hasInlineStrategy()) {
      trees.push(this.getInlineStrategyTree());
    }

    return mergeTreesIfNeeded(trees, { overwrite: true });
  },

  contentFor: function(type) {
    var includeLoader =
        this.hasSymbolStrategy() && this.options.symbol.includeLoader;

    if (type === 'body' && includeLoader) {
      return symbolsLoaderScript
        .replace('{{FILE_PATH}}', this.options.symbol.outputFile);
    }

    return '';
  },

  initializeOptions: function(options, env) {
    this.options = _.merge({
      strategy: 'inline',
      persist: true,
      optimizer: {},

      viewer: {
        enabled: env === 'development',
        embed: env === 'development'
      },

      inline: {
        sourceDirs: ['public'],
        idGen: defaultGenerators.inlineIDGen,
        copypastaGen: defaultGenerators.inlineCopypastaGen
      },

      symbol: {
        sourceDirs: ['public'],
        outputFile: '/assets/symbols.svg',
        prefix: '',
        idGen: defaultGenerators.symbolIDGen,
        copypastaGen: defaultGenerators.symbolCopypastaGen,
        includeLoader: true
      }
    }, options || {});

    if (_.isString(this.options.strategy)) {
      this.options.strategy = [this.options.strategy];
    }
  },

  svgFilesFor: function(strategy) {
    this.svgFilesCache = this.svgFilesCache || {};

    if (this.svgFilesCache[strategy]) {
      return this.svgFilesCache[strategy];
    }

    var sourceDirs = this.options[strategy].sourceDirs
      .filter(function(sourceDir) {
        return fs.existsSync(sourceDir);
      });

    var svgFiles = new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg']
    });

    if (this.options.optimizer) {
      svgFiles = new SVGOptimizer(svgFiles, {
        svgoConfig: this.options.optimizer,
        persist: this.options.persist
      });
    }

    this.svgFilesCache[strategy] = svgFiles;

    return svgFiles;
  },

  getViewerTree: function() {
    var idGenOptions = {
      symbol: { prefix: this.options.symbol.prefix }
    };

    var viewerInputNodes = this.options.strategy.map(function(strategy) {
      return new ViewerAssetsBuilder(this.svgFilesFor(strategy), {
        outputFile: strategy + '.json',
        strategy: strategy,
        idGen: this.options[strategy].idGen,
        idGenOptions: idGenOptions[strategy],
        copypastaGen: this.options[strategy].copypastaGen
      });
    }.bind(this));

    return new ViewerBuilder(mergeTreesIfNeeded(viewerInputNodes), {
      outputFile: 'svg-jar.json'
    });
  },

  getSymbolStrategyTree: function() {
    return new Symbolizer(this.svgFilesFor('symbol'), {
      outputFile: this.options.symbol.outputFile,
      idGen: this.options.symbol.idGen,
      prefix: this.options.symbol.prefix,
      persist: this.options.persist
    });
  },

  getInlineStrategyTree: function() {
    return new InlinePacker(this.svgFilesFor('inline'), {
      outputFile: 'svgs.js',
      idGen: this.options.inline.idGen
    });
  },

  hasSymbolStrategy: function() {
    return this.options.strategy.indexOf('symbol') !== -1;
  },

  hasInlineStrategy: function() {
    return this.options.strategy.indexOf('inline') !== -1;
  }
};
<commit_msg>Add global sourceDirs option<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var Funnel = require('broccoli-funnel');
var MergeTrees = require('broccoli-merge-trees');
var SVGOptimizer = require('broccoli-svg-optimizer');
var Symbolizer = require('broccoli-symbolizer');
var InlinePacker = require('./lib/inline-packer');
var ViewerAssetsBuilder = require('./lib/viewer-assets-builder');
var ViewerBuilder = require('./lib/viewer-builder');
var defaultGenerators = require('./lib/generators');

var symbolsLoaderScript = fs.readFileSync(
  path.join(__dirname, 'symbols-loader.html'), 'utf8'
);

function mergeTreesIfNeeded(trees, options) {
  return trees.length === 1 ? trees[0] : new MergeTrees(trees, options);
}

module.exports = {
  name: 'ember-svg-jar',

  isDevelopingAddon: function() {
    return false;
  },

  included: function(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    this.initializeOptions(app.options.svgJar, app.env);
  },

  treeForPublic: function() {
    var trees = [];

    if (this.options.viewer.enabled) {
      trees.push(this.getViewerTree());

      if (this.options.viewer.embed) {
        trees.push(this._super.treeForPublic.apply(this, arguments));
      }
    }

    if (this.hasSymbolStrategy()) {
      trees.push(this.getSymbolStrategyTree());
    }

    return mergeTreesIfNeeded(trees);
  },

  treeForApp: function(appTree) {
    var trees = [appTree];

    if (this.hasInlineStrategy()) {
      trees.push(this.getInlineStrategyTree());
    }

    return mergeTreesIfNeeded(trees, { overwrite: true });
  },

  contentFor: function(type) {
    var includeLoader =
        this.hasSymbolStrategy() && this.options.symbol.includeLoader;

    if (type === 'body' && includeLoader) {
      return symbolsLoaderScript
        .replace('{{FILE_PATH}}', this.options.symbol.outputFile);
    }

    return '';
  },

  initializeOptions: function(options, env) {
    this.options = _.merge({
      sourceDirs: ['public'],
      strategy: 'inline',
      persist: true,
      optimizer: {},

      viewer: {
        enabled: env === 'development',
        embed: env === 'development'
      },

      inline: {
        idGen: defaultGenerators.inlineIDGen,
        copypastaGen: defaultGenerators.inlineCopypastaGen
      },

      symbol: {
        outputFile: '/assets/symbols.svg',
        prefix: '',
        idGen: defaultGenerators.symbolIDGen,
        copypastaGen: defaultGenerators.symbolCopypastaGen,
        includeLoader: true
      }
    }, options || {});

    if (_.isString(this.options.strategy)) {
      this.options.strategy = [this.options.strategy];
    }
  },

  sourceDirsFor: function(strategy) {
    var sourceDirs =
      this.options[strategy].sourceDirs || this.options.sourceDirs;

    return sourceDirs.filter(function(sourceDir) {
      return fs.existsSync(sourceDir);
    });
  },

  svgFilesFor: function(strategy) {
    this.svgFilesCache = this.svgFilesCache || {};

    if (this.svgFilesCache[strategy]) {
      return this.svgFilesCache[strategy];
    }

    var sourceDirs = this.sourceDirsFor(strategy);
    var svgFiles = new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg']
    });

    if (this.options.optimizer) {
      svgFiles = new SVGOptimizer(svgFiles, {
        svgoConfig: this.options.optimizer,
        persist: this.options.persist
      });
    }

    this.svgFilesCache[strategy] = svgFiles;

    return svgFiles;
  },

  getViewerTree: function() {
    var idGenOptions = {
      symbol: { prefix: this.options.symbol.prefix }
    };

    var viewerInputNodes = this.options.strategy.map(function(strategy) {
      return new ViewerAssetsBuilder(this.svgFilesFor(strategy), {
        outputFile: strategy + '.json',
        strategy: strategy,
        idGen: this.options[strategy].idGen,
        idGenOptions: idGenOptions[strategy],
        copypastaGen: this.options[strategy].copypastaGen
      });
    }.bind(this));

    return new ViewerBuilder(mergeTreesIfNeeded(viewerInputNodes), {
      outputFile: 'svg-jar.json'
    });
  },

  getSymbolStrategyTree: function() {
    return new Symbolizer(this.svgFilesFor('symbol'), {
      outputFile: this.options.symbol.outputFile,
      idGen: this.options.symbol.idGen,
      prefix: this.options.symbol.prefix,
      persist: this.options.persist
    });
  },

  getInlineStrategyTree: function() {
    return new InlinePacker(this.svgFilesFor('inline'), {
      outputFile: 'svgs.js',
      idGen: this.options.inline.idGen
    });
  },

  hasSymbolStrategy: function() {
    return this.options.strategy.indexOf('symbol') !== -1;
  },

  hasInlineStrategy: function() {
    return this.options.strategy.indexOf('inline') !== -1;
  }
};
<|endoftext|>


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

"use strict";

var ExecutionEnvironment = require('ExecutionEnvironment');

var contentKey = null;

/**
 * Gets the key used to access text content on a DOM node.
 *
 * @return {?string} Key used to access text content.
 * @internal
 */
function getTextContentAccessor() {
  if (!contentKey && ExecutionEnvironment.canUseDOM) {
    // Prefer textContent to innerText because many browsers support both but
    // SVG <text> elements don't support innerText even when <div> does.
    contentKey = 'textContent' in document.createElement('div') ?
      'textContent' :
      'innerText';
  }
  return contentKey;
}

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

"use strict";

var ExecutionEnvironment = require('ExecutionEnvironment');

var contentKey = null;

/**
 * Gets the key used to access text content on a DOM node.
 *
 * @return {?string} Key used to access text content.
 * @internal
 */
function getTextContentAccessor() {
  if (!contentKey && ExecutionEnvironment.canUseDOM) {
    contentKey = 'innerText' in document.createElement('div') ?
      'innerText' :
      'textContent';
  }
  return contentKey;
}

module.exports = getTextContentAccessor;
<|endoftext|>


<commit_before>/*!
 * morgan
 * Copyright(c) 2010 Sencha Inc.
 * Copyright(c) 2011 TJ Holowaychuk
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module dependencies.
 * @private
 */

var auth = require('basic-auth')
var debug = require('debug')('morgan')
var deprecate = require('depd')('morgan')
var onFinished = require('on-finished')
var onHeaders = require('on-headers')

/**
 * Array of CLF month names.
 * @private
 */

var clfmonth = [
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]

/**
 * Default log buffer duration.
 * @private
 */

var defaultBufferDuration = 1000;

/**
 * Create a logger middleware.
 *
 * @public
 * @param {String|Function} format
 * @param {Object} [options]
 * @return {Function} middleware
 */

exports = module.exports = function morgan(format, options) {
  var fmt = format
  var opts = options || {}

  if (format && typeof format === 'object') {
    opts = format
    fmt = opts.format || 'default'

    // smart deprecation message
    deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead')
  }

  if (fmt === undefined) {
    deprecate('undefined format: specify a format')
  }

  // output on request instead of response
  var immediate = opts.immediate

  // check if log entry should be skipped
  var skip = opts.skip || false

  // format function
  var formatLine = typeof fmt !== 'function'
    ? getFormatFunction(fmt)
    : fmt

  // stream
  var buffer = opts.buffer
  var stream = opts.stream || process.stdout

  // buffering support
  if (buffer) {
    deprecate('buffer option')

    var realStream = stream
    var buf = []
    var timer = null
    var interval = 'number' == typeof buffer
      ? buffer
      : defaultBufferDuration

    // flush function
    var flush = function(){
      timer = null
      realStream.write(buf.join(''))
      buf.length = 0
    }

    // swap the stream
    stream = {
      write: function(str){
        if (timer === null) {
          timer = setTimeout(flush, interval)
        }

        buf.push(str);
      }
    };
  }

  return function logger(req, res, next) {
    // request data
    req._startAt = undefined
    req._startTime = undefined
    req._remoteAddress = getip(req)

    // response data
    res._startAt = undefined
    res._startTime = undefined

    // record request start
    recordStartTime.call(req)

    function logRequest() {
      if (skip !== false && skip(req, res)) {
        debug('skip request')
        return
      }

      var line = formatLine(exports, req, res)

      if (null == line) {
        debug('skip line')
        return
      }

      debug('log request')
      stream.write(line + '\n')
    };

    if (immediate) {
      // immediate log
      logRequest()
    } else {
      // record response start
      onHeaders(res, recordStartTime)

      // log when response finished
      onFinished(res, logRequest)
    }

    next();
  };
};

/**
 * Define a token function with the given `name`,
 * and callback `fn(req, res)`.
 *
 * @public
 * @param {String} name
 * @param {Function} fn
 * @return {Object} exports for chaining
 */

exports.token = function(name, fn) {
  exports[name] = fn;
  return this;
};

/**
 * Define a `fmt` with the given `name`.
 *
 * @public
 * @param {String} name
 * @param {String|Function} fmt
 * @return {Object} exports for chaining
 */

exports.format = function(name, fmt){
  exports[name] = fmt;
  return this;
};

/**
 * Apache combined log format.
 */

exports.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')

/**
 * Apache common log format.
 */

exports.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]')

/**
 * Default format.
 */

exports.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"');
deprecate.property(exports, 'default', 'default format: use combined format')

/**
 * Short format.
 */

exports.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms');

/**
 * Tiny format.
 */

exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms');

/**
 * dev (colored)
 */

exports.format('dev', function(tokens, req, res){
  var color = 32; // green
  var status = res.statusCode;

  if (status >= 500) color = 31; // red
  else if (status >= 400) color = 33; // yellow
  else if (status >= 300) color = 36; // cyan

  var fn = compile('\x1b[0m:method :url \x1b[' + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m');

  return fn(tokens, req, res);
});

/**
 * request url
 */

exports.token('url', function(req){
  return req.originalUrl || req.url;
});

/**
 * request method
 */

exports.token('method', function(req){
  return req.method;
});

/**
 * response time in milliseconds
 */

exports.token('response-time', function getResponseTimeToken(req, res) {
  if (!req._startAt || !res._startAt) {
    // missing request and/or response start time
    return
  }

  // calculate diff
  var ms = (res._startAt[0] - req._startAt[0]) * 1e3
    + (res._startAt[1] - req._startAt[1]) * 1e-6

  // return truncated value
  return ms.toFixed(3)
})

/**
 * current date
 */

exports.token('date', function(req, res, format){
  format = format || 'web'

  var date = new Date()

  switch (format) {
    case 'clf':
      return clfdate(date)
    case 'iso':
      return date.toISOString()
    case 'web':
      return date.toUTCString()
  }
});

/**
 * response status code
 */

exports.token('status', function(req, res){
  return res._header ? res.statusCode : null;
});

/**
 * normalized referrer
 */

exports.token('referrer', function(req){
  return req.headers['referer'] || req.headers['referrer'];
});

/**
 * remote address
 */

exports.token('remote-addr', getip);

/**
 * remote user
 */

exports.token('remote-user', function (req) {
  var creds = auth(req)
  var user = (creds && creds.name) || '-'
  return user;
})

/**
 * HTTP version
 */

exports.token('http-version', function(req){
  return req.httpVersionMajor + '.' + req.httpVersionMinor;
});

/**
 * UA string
 */

exports.token('user-agent', function(req){
  return req.headers['user-agent'];
});

/**
 * request header
 */

exports.token('req', function(req, res, field){
  return req.headers[field.toLowerCase()];
});

/**
 * response header
 */

exports.token('res', function(req, res, field){
  return (res._headers || {})[field.toLowerCase()];
});

/**
 * Format a Date in the common log format.
 *
 * @private
 * @param {Date} dateTime
 * @return {string}
 */

function clfdate(dateTime) {
  var date = dateTime.getUTCDate()
  var hour = dateTime.getUTCHours()
  var mins = dateTime.getUTCMinutes()
  var secs = dateTime.getUTCSeconds()
  var year = dateTime.getUTCFullYear()

  var month = clfmonth[dateTime.getUTCMonth()]

  return pad2(date) + '/' + month + '/' + year
    + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs)
    + ' +0000'
}

/**
 * Compile a format string into a function.
 *
 * @param {string} format
 * @return {function}
 * @private
 */

function compile(format) {
  if (typeof format !== 'string') {
    throw new TypeError('argument format must be a string')
  }

  var fmt = format.replace(/"/g, '\\"')
  var js = '  return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg) {
    return '"\n    + (tokens["' + name + '"](req, res, ' + String(JSON.stringify(arg)) + ') || "-") + "'
  }) + '";'

  return new Function('tokens, req, res', js)
}

/**
 * Lookup and compile a named format function.
 *
 * @param {string} name
 * @return {function}
 * @public
 */

function getFormatFunction(name) {
  // lookup format
  var fmt = exports[name] || name || exports.default

  // return compiled format
  return typeof fmt !== 'function'
    ? compile(fmt)
    : fmt
}

/**
 * Get request IP address.
 *
 * @private
 * @param {IncomingMessage} req
 * @return {string}
 */

function getip(req) {
  return req.ip
    || req._remoteAddress
    || (req.connection && req.connection.remoteAddress)
    || undefined;
}

/**
 * Pad number to two digits.
 *
 * @private
 * @param {number} num
 * @return {string}
 */

function pad2(num) {
  var str = String(num)

  return (str.length === 1 ? '0' : '')
    + str
}

/**
 * Record the start time.
 * @private
 */

function recordStartTime() {
  this._startAt = process.hrtime()
  this._startTime = new Date()
}
<commit_msg>Reorganize the export definitions<commit_after>/*!
 * morgan
 * Copyright(c) 2010 Sencha Inc.
 * Copyright(c) 2011 TJ Holowaychuk
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module exports.
 * @public
 */

module.exports = morgan
module.exports.format = format
module.exports.token = token

/**
 * Module dependencies.
 * @private
 */

var auth = require('basic-auth')
var debug = require('debug')('morgan')
var deprecate = require('depd')('morgan')
var onFinished = require('on-finished')
var onHeaders = require('on-headers')

/**
 * Array of CLF month names.
 * @private
 */

var clfmonth = [
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]

/**
 * Default log buffer duration.
 * @private
 */

var defaultBufferDuration = 1000;

/**
 * Create a logger middleware.
 *
 * @public
 * @param {String|Function} format
 * @param {Object} [options]
 * @return {Function} middleware
 */

function morgan(format, options) {
  var fmt = format
  var opts = options || {}

  if (format && typeof format === 'object') {
    opts = format
    fmt = opts.format || 'default'

    // smart deprecation message
    deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead')
  }

  if (fmt === undefined) {
    deprecate('undefined format: specify a format')
  }

  // output on request instead of response
  var immediate = opts.immediate

  // check if log entry should be skipped
  var skip = opts.skip || false

  // format function
  var formatLine = typeof fmt !== 'function'
    ? getFormatFunction(fmt)
    : fmt

  // stream
  var buffer = opts.buffer
  var stream = opts.stream || process.stdout

  // buffering support
  if (buffer) {
    deprecate('buffer option')

    var realStream = stream
    var buf = []
    var timer = null
    var interval = 'number' == typeof buffer
      ? buffer
      : defaultBufferDuration

    // flush function
    var flush = function(){
      timer = null
      realStream.write(buf.join(''))
      buf.length = 0
    }

    // swap the stream
    stream = {
      write: function(str){
        if (timer === null) {
          timer = setTimeout(flush, interval)
        }

        buf.push(str);
      }
    };
  }

  return function logger(req, res, next) {
    // request data
    req._startAt = undefined
    req._startTime = undefined
    req._remoteAddress = getip(req)

    // response data
    res._startAt = undefined
    res._startTime = undefined

    // record request start
    recordStartTime.call(req)

    function logRequest() {
      if (skip !== false && skip(req, res)) {
        debug('skip request')
        return
      }

      var line = formatLine(morgan, req, res)

      if (null == line) {
        debug('skip line')
        return
      }

      debug('log request')
      stream.write(line + '\n')
    };

    if (immediate) {
      // immediate log
      logRequest()
    } else {
      // record response start
      onHeaders(res, recordStartTime)

      // log when response finished
      onFinished(res, logRequest)
    }

    next();
  };
}

/**
 * Apache combined log format.
 */

morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')

/**
 * Apache common log format.
 */

morgan.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]')

/**
 * Default format.
 */

morgan.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
deprecate.property(morgan, 'default', 'default format: use combined format')

/**
 * Short format.
 */

morgan.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')

/**
 * Tiny format.
 */

morgan.format('tiny', ':method :url :status :res[content-length] - :response-time ms')

/**
 * dev (colored)
 */

morgan.format('dev', function developmentFormatLine(tokens, req, res) {
  var color = 32; // green
  var status = res.statusCode;

  if (status >= 500) color = 31; // red
  else if (status >= 400) color = 33; // yellow
  else if (status >= 300) color = 36; // cyan

  var fn = compile('\x1b[0m:method :url \x1b[' + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m');

  return fn(tokens, req, res);
});

/**
 * request url
 */

morgan.token('url', function getUrlToken(req) {
  return req.originalUrl || req.url;
});

/**
 * request method
 */

morgan.token('method', function getMethodToken(req) {
  return req.method;
});

/**
 * response time in milliseconds
 */

morgan.token('response-time', function getResponseTimeToken(req, res) {
  if (!req._startAt || !res._startAt) {
    // missing request and/or response start time
    return
  }

  // calculate diff
  var ms = (res._startAt[0] - req._startAt[0]) * 1e3
    + (res._startAt[1] - req._startAt[1]) * 1e-6

  // return truncated value
  return ms.toFixed(3)
})

/**
 * current date
 */

morgan.token('date', function getDateToken(req, res, format) {
  format = format || 'web'

  var date = new Date()

  switch (format) {
    case 'clf':
      return clfdate(date)
    case 'iso':
      return date.toISOString()
    case 'web':
      return date.toUTCString()
  }
});

/**
 * response status code
 */

morgan.token('status', function getStatusToken(req, res) {
  return res._header ? res.statusCode : null;
});

/**
 * normalized referrer
 */

morgan.token('referrer', function getReferrerToken(req) {
  return req.headers['referer'] || req.headers['referrer'];
});

/**
 * remote address
 */

morgan.token('remote-addr', getip)

/**
 * remote user
 */

morgan.token('remote-user', function getRemoteUserToken(req) {
  var creds = auth(req)
  var user = (creds && creds.name) || '-'
  return user;
})

/**
 * HTTP version
 */

morgan.token('http-version', function getHttpVersionToken(req) {
  return req.httpVersionMajor + '.' + req.httpVersionMinor;
});

/**
 * UA string
 */

morgan.token('user-agent', function getUserAgentToken(req) {
  return req.headers['user-agent'];
});

/**
 * request header
 */

morgan.token('req', function getRequestToken(req, res, field) {
  return req.headers[field.toLowerCase()];
});

/**
 * response header
 */

morgan.token('res', function getResponseTime(req, res, field) {
  return (res._headers || {})[field.toLowerCase()];
});

/**
 * Format a Date in the common log format.
 *
 * @private
 * @param {Date} dateTime
 * @return {string}
 */

function clfdate(dateTime) {
  var date = dateTime.getUTCDate()
  var hour = dateTime.getUTCHours()
  var mins = dateTime.getUTCMinutes()
  var secs = dateTime.getUTCSeconds()
  var year = dateTime.getUTCFullYear()

  var month = clfmonth[dateTime.getUTCMonth()]

  return pad2(date) + '/' + month + '/' + year
    + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs)
    + ' +0000'
}

/**
 * Compile a format string into a function.
 *
 * @param {string} format
 * @return {function}
 * @private
 */

function compile(format) {
  if (typeof format !== 'string') {
    throw new TypeError('argument format must be a string')
  }

  var fmt = format.replace(/"/g, '\\"')
  var js = '  return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg) {
    return '"\n    + (tokens["' + name + '"](req, res, ' + String(JSON.stringify(arg)) + ') || "-") + "'
  }) + '";'

  return new Function('tokens, req, res', js)
}

/**
 * Define a format with the given name.
 *
 * @param {string} name
 * @param {string|function} fmt
 * @public
 */

function format(name, fmt) {
  this[name] = fmt
  return this
}

/**
 * Lookup and compile a named format function.
 *
 * @param {string} name
 * @return {function}
 * @public
 */

function getFormatFunction(name) {
  // lookup format
  var fmt = morgan[name] || name || morgan.default

  // return compiled format
  return typeof fmt !== 'function'
    ? compile(fmt)
    : fmt
}

/**
 * Get request IP address.
 *
 * @private
 * @param {IncomingMessage} req
 * @return {string}
 */

function getip(req) {
  return req.ip
    || req._remoteAddress
    || (req.connection && req.connection.remoteAddress)
    || undefined;
}

/**
 * Pad number to two digits.
 *
 * @private
 * @param {number} num
 * @return {string}
 */

function pad2(num) {
  var str = String(num)

  return (str.length === 1 ? '0' : '')
    + str
}

/**
 * Record the start time.
 * @private
 */

function recordStartTime() {
  this._startAt = process.hrtime()
  this._startTime = new Date()
}

/**
 * Define a token function with the given name,
 * and callback fn(req, res).
 *
 * @param {string} name
 * @param {function} fn
 * @public
 */

function token(name, fn) {
  this[name] = fn
  return this
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Philippe Leefsma 2014 - ADN/Developer Technical Services
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////////////////
var credentials= {
	BaseUrl: 'https://developer.api.autodesk.com',

	credentials: {
		client_id: process.env.CONSUMERKEY || '<test>',
		client_secret: process.env.CONSUMERSECRET || '<replace with your consumer secret>',
		grant_type: 'client_credentials'
	}
} ;
module.exports =credentials ;<commit_msg>test after add 2<commit_after>/////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Philippe Leefsma 2014 - ADN/Developer Technical Services
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////////////////
var credentials= {
	BaseUrl: 'https://developer.api.autodesk.com',

	credentials: {
		client_id: process.env.CONSUMERKEY || '<test after add 2>',
		client_secret: process.env.CONSUMERSECRET || '<replace with your consumer secret>',
		grant_type: 'client_credentials'
	}
} ;
module.exports =credentials ;<|endoftext|>


<commit_before>// @flow
import { api, type Claims } from 'neon-js'
import { map, reduce } from 'lodash'

import {
  showErrorNotification,
  showSuccessNotification,
  showInfoNotification
} from './notifications'
import {
  getNetwork,
  getWIF,
  getAddress,
  getSigningFunction,
  getPublicKey,
  getIsHardwareLogin,
  getNEO
} from '../core/deprecated'
import { toBigNumber, toNumber } from '../core/math'
import { ASSETS } from '../core/constants'
import { FIVE_MINUTES_MS } from '../core/time'
import poll from '../util/poll'

const POLL_ATTEMPTS = 50
const POLL_FREQUENCY = 5000

const fetchClaims = async ({ net, address }) => {
  api.setApiSwitch(0)
  const response = await api.loadBalance(api.getClaimsFrom, { net, address })
  api.setApiSwitch(0.5)
  const { claims } = response.claims
  return map(claims, 'claim')
}

const calculateClaimableAmount = (claims: Claims) => {
  return reduce(claims, (sum, claim) => claim.plus(sum), 0).toString()
}

const getClaimableAmount = async ({ net, address }) => {
  const claims = await fetchClaims({ net, address })
  return calculateClaimableAmount(claims)
}

const updateClaimableAmount = async ({ net, address, publicKey, privateKey, signingFunction, balance }) => {
  const { response } = await api.sendAsset({
    net,
    address,
    publicKey,
    privateKey,
    signingFunction,
    intents: api.makeIntent({ [ASSETS.NEO]: toNumber(balance) }, address)
  })

  if (!response.result || !response.txid) {
    throw new Error('Transaction failed!')
  }

  return response.result.response
}

const pollForUpdatedClaimableAmount = async ({ net, address, claimableAmount }) => {
  return poll(async () => {
    const updatedClaimableAmount = await getClaimableAmount({ net, address })

    if (toBigNumber(updatedClaimableAmount).eq(claimableAmount)) {
      throw new Error('Waiting for updated claims')
    }

    return updatedClaimableAmount
  }, { attempts: POLL_ATTEMPTS, frequency: POLL_FREQUENCY })
}

const getUpdatedClaimableAmount = async ({ net, address, balance, publicKey, privateKey, signingFunction }) => {
  const claimableAmount = await getClaimableAmount({ net, address })

  if (toBigNumber(balance).eq(0)) {
    return claimableAmount
  } else {
    await updateClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
    return pollForUpdatedClaimableAmount({ net, address, claimableAmount })
  }
}

export const doGasClaim = () => async (dispatch: DispatchType, getState: GetStateType) => {
  const state = getState()
  const address = getAddress(state)
  const net = getNetwork(state)
  const balance = getNEO(state)
  const publicKey = getPublicKey(state)
  const privateKey = getWIF(state)
  const signingFunction = getSigningFunction(state)
  const isHardwareClaim = getIsHardwareLogin(state)

  dispatch(disableClaim(true))

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 1 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Calculating claimable GAS...' }))
  }

  // step 1: update available claims
  try {
    await getUpdatedClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Calculating claimable GAS failed.' }))
    return
  }

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 2 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Claiming GAS...' }))
  }

  // step 2: send claim request
  try {
    api.setApiSwitch(0)
    const { response } = await api.claimGas({ net, address, publicKey, privateKey, signingFunction })
    api.setApiSwitch(0.5)

    if (!response.result) {
      throw new Error('Claiming GAS failed')
    }
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Claiming GAS failed.' }))
    return
  }

  dispatch(showSuccessNotification({
    message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
  }))
  setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
}

// Constants
export const DISABLE_CLAIM = 'DISABLE_CLAIM'

// Actions
export function disableClaim (disableClaimButton: boolean) {
  return {
    type: DISABLE_CLAIM,
    payload: { disableClaimButton }
  }
}

// State Getters
export const getDisableClaimButton = (state: Object) => state.claim.disableClaimButton

const initialState = {
  disableClaimButton: false
}

export default (state: Object = initialState, action: ReduxAction) => {
  switch (action.type) {
    case DISABLE_CLAIM:
      const { disableClaimButton } = action.payload
      return {
        ...state,
        disableClaimButton
      }
    default:
      return state
  }
}
<commit_msg>limit ledger claims to 25<commit_after>// @flow
import { api, type Claims } from 'neon-js'
import { map, reduce } from 'lodash'

import {
  showErrorNotification,
  showSuccessNotification,
  showInfoNotification
} from './notifications'
import {
  getNetwork,
  getWIF,
  getAddress,
  getSigningFunction,
  getPublicKey,
  getIsHardwareLogin,
  getNEO
} from '../core/deprecated'
import { toBigNumber, toNumber } from '../core/math'
import { ASSETS } from '../core/constants'
import { FIVE_MINUTES_MS } from '../core/time'
import poll from '../util/poll'

const POLL_ATTEMPTS = 50
const POLL_FREQUENCY = 5000

const fetchClaims = async ({ net, address }) => {
  api.setApiSwitch(0)
  const response = await api.loadBalance(api.getClaimsFrom, { net, address })
  api.setApiSwitch(0.5)
  const { claims } = response.claims
  return map(claims, 'claim')
}

const calculateClaimableAmount = (claims: Claims) => {
  return reduce(claims, (sum, claim) => claim.plus(sum), 0).toString()
}

const getClaimableAmount = async ({ net, address }) => {
  const claims = await fetchClaims({ net, address })
  return calculateClaimableAmount(claims)
}

const updateClaimableAmount = async ({ net, address, publicKey, privateKey, signingFunction, balance }) => {
  const { response } = await api.sendAsset({
    net,
    address,
    publicKey,
    privateKey,
    signingFunction,
    intents: api.makeIntent({ [ASSETS.NEO]: toNumber(balance) }, address)
  })

  if (!response.result || !response.txid) {
    throw new Error('Transaction failed!')
  }

  return response.result.response
}

const pollForUpdatedClaimableAmount = async ({ net, address, claimableAmount }) => {
  return poll(async () => {
    const updatedClaimableAmount = await getClaimableAmount({ net, address })

    if (toBigNumber(updatedClaimableAmount).eq(claimableAmount)) {
      throw new Error('Waiting for updated claims')
    }

    return updatedClaimableAmount
  }, { attempts: POLL_ATTEMPTS, frequency: POLL_FREQUENCY })
}

const getUpdatedClaimableAmount = async ({ net, address, balance, publicKey, privateKey, signingFunction }) => {
  const claimableAmount = await getClaimableAmount({ net, address })

  if (toBigNumber(balance).eq(0)) {
    return claimableAmount
  } else {
    await updateClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
    return pollForUpdatedClaimableAmount({ net, address, claimableAmount })
  }
}

export const doGasClaim = () => async (dispatch: DispatchType, getState: GetStateType) => {
  const state = getState()
  const address = getAddress(state)
  const net = getNetwork(state)
  const balance = getNEO(state)
  const publicKey = getPublicKey(state)
  const privateKey = getWIF(state)
  const signingFunction = getSigningFunction(state)
  const isHardwareClaim = getIsHardwareLogin(state)

  dispatch(disableClaim(true))

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 1 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Calculating claimable GAS...' }))
  }

  // step 1: update available claims
  try {
    await getUpdatedClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Calculating claimable GAS failed.' }))
    return
  }

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 2 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Claiming GAS...' }))
  }

  // step 2: send claim request
  try {
    var {claims} = await api.getClaimsFrom({net, address}, api.neoscan)
    if (isHardwareClaim) claims = claims.slice(0, 25)
    api.setApiSwitch(0)
    const { response } = await api.claimGas({ net, address, claims, publicKey, privateKey, signingFunction })
    api.setApiSwitch(0.5)

    if (!response.result) {
      throw new Error('Claiming GAS failed')
    }
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: `Claiming GAS failed: ${err}` }))
    return
  }

  dispatch(showSuccessNotification({
    message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
  }))
  setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
}

// Constants
export const DISABLE_CLAIM = 'DISABLE_CLAIM'

// Actions
export function disableClaim (disableClaimButton: boolean) {
  return {
    type: DISABLE_CLAIM,
    payload: { disableClaimButton }
  }
}

// State Getters
export const getDisableClaimButton = (state: Object) => state.claim.disableClaimButton

const initialState = {
  disableClaimButton: false
}

export default (state: Object = initialState, action: ReduxAction) => {
  switch (action.type) {
    case DISABLE_CLAIM:
      const { disableClaimButton } = action.payload
      return {
        ...state,
        disableClaimButton
      }
    default:
      return state
  }
}
<|endoftext|>


<commit_before>Z.chart = (function () {

var data;

var width = 800, height = 600, margin = 50;

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var xAccessor = function (d) { return x(d.date); };
var yAccessor = function (d) { return y(d.relative); };

x.domain([ new Date(2000,0,1), new Date(2040,0,1) ]);
y.domain([ 0, 1 ]);

var xAxis = d3.svg.axis().scale(x).orient('bottom');
var yAxis = d3.svg.axis().scale(y).orient('left');

var yearlySamples = [];
for (
	// Yes, I'm a horrible person for hardcoding this
	var date=x.domain()[0], last=x.domain()[1], quarter=-6;
	date<=last;
	date.setFullYear(date.getFullYear()+1)
) {
	yearlySamples.push([new Date(+date), quarter+=4]);
}

var line = d3.svg.line().x(xAccessor).y(yAccessor);
function exponentialLine (reg) {
		return (d3.svg.line()
		.x(function (x0) { return x(x0[0]); })
		.y(function (x0) { return y(reg.first.relative * Math.exp(reg.lambda*x0[1])); })
		(yearlySamples)
	);
}

function numberFormat (n) {
	// <3 http://stackoverflow.com/questions/2901102/
	return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}

var viewBox = [ 0, 0, width + 2*margin, height + 2*margin ];
var svg = d3.select('#main-chart')
.attr('width', viewBox[2]).attr('height', viewBox[3])
.attr('viewBox', viewBox.join(' '));

svg = svg.append('g').attr('transform', 'translate('+margin+','+margin+')');

svg.append('g').attr('class', 'x axis').call(xAxis).attr('transform', 'translate(0,'+height+')');
svg.append('g').attr('class', 'y axis').call(yAxis);

var publicationLine, regressionLine, maxLabel, minLabel;
var isInitialized = false;
function init () {
	if (isInitialized) return false;
	isInitialized = true;

	svg.append('path')
	.attr('class', 'line data foreground');

	publicationLine = svg.selectAll('.data');

	svg.append('path')
	.attr('class', 'line prediction foreground');

	regressionLine = svg.selectAll('.prediction');

	svg.append('text')
	.attr('class', 'data-label max')
	.attr('text-anchor', 'start')
	.attr('dx', 10)
	.attr('dy', -10);

	svg.append('circle')
	.attr('r', 8)
	.attr('class', 'data-label max');

	svg.append('text')
	.attr('class', 'data-label min')
	.attr('text-anchor', 'end')
	.attr('dx', -10)
	.attr('dy', 35);

	svg.append('circle')
	.attr('r', 8)
	.attr('class', 'data-label min');

	maxLabel = svg.selectAll('.data-label.max');
	minLabel = svg.selectAll('.data-label.min');

	var $header = $('form');
	$(window).on('resize keyup typeahead:closed', function () {
		var bottom = $header.outerHeight();
		var availableHeight = $(window).height() - bottom;
		$('#main-chart').css('max-height', availableHeight);
	});

	return true;
}

function update () {
	var duration = $('body').hasClass('photogenic')? 0 : 200;

	var halfLife = (data.regression.halfLife === Infinity)? 'keine' : (Math.round(data.regression.halfLife) + ' Jahre');

	// A warning will be shown if the data is for a publication
	// is more than a year old. This is mainly intended to compensate the fact
	// that we do not research which papers have ceased to be published, but
	// is also nice as the visualisation ages.
	var dataIsOld = new Date() - data.newest.date >= 1.57788e10;

	// Text eleements
	$('.data-sheet').removeClass('hidden').toggleClass('toggle-animation');
	$('.js-publication-title').text(data.title);
	$('.js-publication-halflife').text(halfLife);
	$('.js-old-data-warning').toggleClass('hidden', !dataIsOld);
	$('.js-old-data-value').text(data.newest.quarterString());

	// Chart
	publicationLine.datum(data).transition().duration(duration)
	.attr('d', function (d) { return line(d.copies); });
	regressionLine.transition().duration(duration)
	.attr('d', exponentialLine(data.regression));
	//.style('opacity', function (d) { return +(data.regression.halfLife !== Infinity); });

	maxLabel.datum(data)
	.transition().duration(duration)
	.attr('cx', function (d) { return xAccessor(d.max); })
	.attr( 'x', function (d) { return xAccessor(d.max); })
	.attr('cy', function (d) { return yAccessor(d.max); })
	.attr( 'y', function (d) { return yAccessor(d.max); })
	.text(function (d) { return numberFormat(d.max.absolute); });

	minLabel.datum(data)
	.transition().duration(duration)
	.attr('cx', function (d) { return xAccessor(d.min); })
	.attr( 'x', function (d) { return xAccessor(d.min); })
	.attr('cy', function (d) { return yAccessor(d.min); })
	.attr( 'y', function (d) { return yAccessor(d.min); })
	.text(function (d) { return numberFormat(d.min.absolute); });

	$(Z).trigger('Z:chartdrawn');
}

function draw (newData) {
	data = newData;
	init();
	update();
}

return {
	draw: draw
}

})();
<commit_msg>Autoscale chart height relative to body, not document<commit_after>Z.chart = (function () {

var data;

var width = 800, height = 600, margin = 50;

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var xAccessor = function (d) { return x(d.date); };
var yAccessor = function (d) { return y(d.relative); };

x.domain([ new Date(2000,0,1), new Date(2040,0,1) ]);
y.domain([ 0, 1 ]);

var xAxis = d3.svg.axis().scale(x).orient('bottom');
var yAxis = d3.svg.axis().scale(y).orient('left');

var yearlySamples = [];
for (
	// Yes, I'm a horrible person for hardcoding this
	var date=x.domain()[0], last=x.domain()[1], quarter=-6;
	date<=last;
	date.setFullYear(date.getFullYear()+1)
) {
	yearlySamples.push([new Date(+date), quarter+=4]);
}

var line = d3.svg.line().x(xAccessor).y(yAccessor);
function exponentialLine (reg) {
		return (d3.svg.line()
		.x(function (x0) { return x(x0[0]); })
		.y(function (x0) { return y(reg.first.relative * Math.exp(reg.lambda*x0[1])); })
		(yearlySamples)
	);
}

function numberFormat (n) {
	// <3 http://stackoverflow.com/questions/2901102/
	return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}

var viewBox = [ 0, 0, width + 2*margin, height + 2*margin ];
var svg = d3.select('#main-chart')
.attr('width', viewBox[2]).attr('height', viewBox[3])
.attr('viewBox', viewBox.join(' '));

svg = svg.append('g').attr('transform', 'translate('+margin+','+margin+')');

svg.append('g').attr('class', 'x axis').call(xAxis).attr('transform', 'translate(0,'+height+')');
svg.append('g').attr('class', 'y axis').call(yAxis);

var publicationLine, regressionLine, maxLabel, minLabel;
var isInitialized = false;
function init () {
	if (isInitialized) return false;
	isInitialized = true;

	svg.append('path')
	.attr('class', 'line data foreground');

	publicationLine = svg.selectAll('.data');

	svg.append('path')
	.attr('class', 'line prediction foreground');

	regressionLine = svg.selectAll('.prediction');

	svg.append('text')
	.attr('class', 'data-label max')
	.attr('text-anchor', 'start')
	.attr('dx', 10)
	.attr('dy', -10);

	svg.append('circle')
	.attr('r', 8)
	.attr('class', 'data-label max');

	svg.append('text')
	.attr('class', 'data-label min')
	.attr('text-anchor', 'end')
	.attr('dx', -10)
	.attr('dy', 35);

	svg.append('circle')
	.attr('r', 8)
	.attr('class', 'data-label min');

	maxLabel = svg.selectAll('.data-label.max');
	minLabel = svg.selectAll('.data-label.min');

	var $header = $('form');
	$(window).on('resize keyup typeahead:closed', function () {
		var bottom = $header.outerHeight();
		var availableHeight = $('body').outerHeight() - bottom;
		$('#main-chart').css('max-height', availableHeight*.98);
	});

	return true;
}

function update () {
	var duration = $('body').hasClass('photogenic')? 0 : 200;

	var halfLife = (data.regression.halfLife === Infinity)? 'keine' : (Math.round(data.regression.halfLife) + ' Jahre');

	// A warning will be shown if the data is for a publication
	// is more than a year old. This is mainly intended to compensate the fact
	// that we do not research which papers have ceased to be published, but
	// is also nice as the visualisation ages.
	var dataIsOld = new Date() - data.newest.date >= 1.57788e10;

	// Text eleements
	$('.data-sheet').removeClass('hidden').toggleClass('toggle-animation');
	$('.js-publication-title').text(data.title);
	$('.js-publication-halflife').text(halfLife);
	$('.js-old-data-warning').toggleClass('hidden', !dataIsOld);
	$('.js-old-data-value').text(data.newest.quarterString());

	// Chart
	publicationLine.datum(data).transition().duration(duration)
	.attr('d', function (d) { return line(d.copies); });
	regressionLine.transition().duration(duration)
	.attr('d', exponentialLine(data.regression));
	//.style('opacity', function (d) { return +(data.regression.halfLife !== Infinity); });

	maxLabel.datum(data)
	.transition().duration(duration)
	.attr('cx', function (d) { return xAccessor(d.max); })
	.attr( 'x', function (d) { return xAccessor(d.max); })
	.attr('cy', function (d) { return yAccessor(d.max); })
	.attr( 'y', function (d) { return yAccessor(d.max); })
	.text(function (d) { return numberFormat(d.max.absolute); });

	minLabel.datum(data)
	.transition().duration(duration)
	.attr('cx', function (d) { return xAccessor(d.min); })
	.attr( 'x', function (d) { return xAccessor(d.min); })
	.attr('cy', function (d) { return yAccessor(d.min); })
	.attr( 'y', function (d) { return yAccessor(d.min); })
	.text(function (d) { return numberFormat(d.min.absolute); });

	$(Z).trigger('Z:chartdrawn');
}

function draw (newData) {
	data = newData;
	init();
	update();
}

return {
	draw: draw
}

})();
<|endoftext|>


<commit_before>//Declare Variables
  var firebaseURL = "https://battleshipit.firebaseio.com/",
      fb          = new Firebase(firebaseURL),
      gamesURL    = new Firebase(firebaseURL + 'games/'),
      createGame,
      // array       = ['', '', '', '', '', '', '', '', '', ''],
      // array1      = ['', '', '', '', '', '', '', '', '', ''],
      board       = [['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', '']],
      player1,
      player2     = 'United States',
      playerTurn,
      index,
      myDingy     = 'D';

  // var currentGameRef = fb.child(uuid);

// function init() {
$('#submit-player').on('click', function() {
  event.preventDefault();
  var thisplayersname = $('.playerName').val(),
      uuid  = $('table').data('uuid');
    gamesURL.push({"player1board": board, "player2board": board, "player1name" : thisplayersname, "player2name": "", "player1turn" : "", "player2turn" : ""});
    createBoard(board);
    console.log("uuid");
    // console.log(snapshot.val());
});
// }

    gamesURL.once("value", function(snapshot){
      var games = (snapshot.val());

      Object.keys(games).forEach(function (uuid) {
        $('.board').attr("data-uuid", uuid);
        // console.log(games[uuid]);
      });
    });

    //   //     if (games[uuid].isOver === false) {
    //   // // load unfinished game
    //         createBoard(games[uuid].board);
    //         player = games[uuid].whoseTurn;
    //         $('table').attr("data-uuid", uuid);
        // });
// });
// };      // console.log(Object.keys().name);

//Begin Functions
  //createGame
  //   $('#newGame').on('click', function(event){
  //     event.preventDefault();
  //     createBoard(board);

  //   });
  // //createBoard ===== think about using using .oneClick() or .unbind()
    function createBoard(board) {
    var $table = $('

')              //Created table to append too
    board.forEach(function (createRow) {                              //For Each item in the board array and create a row for it
      var $tr = $('

');                                       //created table rows in table
      createRow.forEach(function (createTd){                          //For Each table row create a TD
        $tr.append('' + createTd + '	')      //Nested loop going through every '' within the array
      });
    $table.append($tr);                                               //Append the created Td's to the table
    });
    $('.board').append($table);
    clickHandlerForGameBoard();                                       //Append the tbale to the the actual game board
  };

  //createGame
  //addPlayer

  //appendDataToPage
  //pullDataFromFirbase
  //findCellIndex
  //turnCount

var clickTr;

  function clickHandlerForGameBoard() {
    $('td').on('click', function() {
      console.log($('td').index(this), $(this).closest('tr').index());
      //$(this).append(myDingy);
      clickTr = $(this).closest('tr').index();
      //board[clickTr].splice($(this).index(), myDingy.length, myDingy);

      for (var i=0; i < 3; i++) {
        var shipIndex = ($(this).index() + i);
        board[clickTr].splice($(this).index() + i, 1, myDingy);
      };

      createBoard(board);

    });
  }

<commit_msg>added data to correct index<commit_after>//Declare Variables
  var firebaseURL = "https://battleshipit.firebaseio.com/",
      fb          = new Firebase(firebaseURL),
      gamesURL    = new Firebase(firebaseURL + 'games/'),
      createGame,
      // array       = ['', '', '', '', '', '', '', '', '', ''],
      // array1      = ['', '', '', '', '', '', '', '', '', ''],
      board       = [['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', ''],
                     ['', '', '', '', '', '', '', '', '', '']],
      player1,
      player2     = 'United States',
      playerTurn,
      index,
      myDingy     = 'D';

  // var currentGameRef = fb.child(uuid);

// function init() {
$('#submit-player').on('click', function() {
  event.preventDefault();
  var thisplayersname = $('.playerName').val(),
      uuid  = $('table').data('uuid');
    gamesURL.push({"player1board": board, "player2board": board, "player1name" : thisplayersname, "player2name": "", "player1turn" : "", "player2turn" : ""});
    createBoard(board);
    console.log("uuid");
    // console.log(snapshot.val());
});
// }

    gamesURL.once("value", function(snapshot){
      var games = (snapshot.val());

      Object.keys(games).forEach(function (uuid) {
        $('.board').attr("data-uuid", uuid);
        // console.log(games[uuid]);
      });
    });

    //   //     if (games[uuid].isOver === false) {
    //   // // load unfinished game
    //         createBoard(games[uuid].board);
    //         player = games[uuid].whoseTurn;
    //         $('table').attr("data-uuid", uuid);
        // });
// });
// };      // console.log(Object.keys().name);

//Begin Functions
  //createGame
  //   $('#newGame').on('click', function(event){
  //     event.preventDefault();
  //     createBoard(board);

  //   });
  // //createBoard ===== think about using using .oneClick() or .unbind()
    function createBoard(board) {
    var $table = $('

')              //Created table to append too
    board.forEach(function (createRow) {                              //For Each item in the board array and create a row for it
      var $tr = $('

');                                       //created table rows in table
      createRow.forEach(function (createTd){                          //For Each table row create a TD
        $tr.append('' + createTd + '	')      //Nested loop going through every '' within the array
      });
    $table.append($tr);                                               //Append the created Td's to the table
    });
    $('.board').append($table);
    clickHandlerForGameBoard();                                       //Append the tbale to the the actual game board
  };

  //createGame
  //addPlayer

  //appendDataToPage
  //pullDataFromFirbase
  //findCellIndex
  //turnCount

var clickTr;

  function clickHandlerForGameBoard() {
    $('td').on('click', function() {
      console.log($('td').index(this), $(this).closest('tr').index());
      //$(this).append(myDingy);
      clickTr = $(this).closest('tr').index();
      //board[clickTr].splice($(this).index(), myDingy.length, myDingy);

      for (var i=0; i < 3; i++) {
        var shipIndex = ($(this).index() + i);
        board[clickTr].splice($(this).index() + i, 1, myDingy);
      };

      createBoard(board);

    });
  }

  //here

<|endoftext|>


<commit_before>DS.RESTAdapter.reopen({
  url: "http://messages-be2.azurewebsites.net"
});

App.Store = DS.Store.extend({
});
<commit_msg>use message-be as instance<commit_after>DS.RESTAdapter.reopen({
  url: "http://messages-be.azurewebsites.net"
});

App.Store = DS.Store.extend({
});
<|endoftext|>