<commit_before>import Translatable from '~mixins/translatable'

export default {
  name: 'v-parallax',

  mixins: [Translatable],

  props: {
    height: {
      type: [String, Number],
      default: 500
    },
    src: {
      type: String,
      required: true
    }
  },

  computed: {
    styles () {
      return {
        display: 'block',
        transform: `translate3d(-50%, ${this.parallax}px, 0)`
      }
    }
  },

  methods: {
    init () {
      if (this.$refs.img.complete) {
        this.translate()
        this.listeners()
      } else {
        this.$refs.img.addEventListener('load', () => {
          this.translate()
          this.listeners()
        }, false)
      }
    },
    objHeight () {
      return this.$refs.img.naturalHeight
    },
    elOffsetTop () {
      return this.$el.offsetTop
    }
  },

  render (h) {
    const container = h('div', {
      staticClass: 'parallax__image-container'
    }, [
      h('img', {
        staticClass: 'parallax__image',
        style: this.styles,
        attrs: {
          src: this.src
        },
        ref: 'img'
      })
    ])

    const content = h('div', {
      staticClass: 'parallax__content'
    }, this.$slots.default)

    return h('div', {
      staticClass: 'parallax',
      style: {
        height: `${parseInt(this.normalizedHeight)}px`
      },
      on: this.$listeners
    }, [container, content])
  }
}
<commit_msg>fix for #1029<commit_after>import Translatable from '~mixins/translatable'

export default {
  name: 'v-parallax',

  mixins: [Translatable],

  props: {
    height: {
      type: [String, Number],
      default: 500
    },
    src: {
      type: String,
      required: true
    }
  },

  computed: {
    styles () {
      return {
        display: 'block',
        transform: `translate3d(-50%, ${this.parallax}px, 0)`
      }
    }
  },

  methods: {
    init () {
      if (!this.$refs.img) {
        return
      } else if (this.$refs.img.complete) {
        this.translate()
        this.listeners()
      } else {
        this.$refs.img.addEventListener('load', () => {
          this.translate()
          this.listeners()
        }, false)
      }
    },
    objHeight () {
      return this.$refs.img.naturalHeight
    },
    elOffsetTop () {
      return this.$el.offsetTop
    }
  },

  render (h) {
    const container = h('div', {
      staticClass: 'parallax__image-container'
    }, [
      h('img', {
        staticClass: 'parallax__image',
        style: this.styles,
        attrs: {
          src: this.src
        },
        ref: 'img'
      })
    ])

    const content = h('div', {
      staticClass: 'parallax__content'
    }, this.$slots.default)

    return h('div', {
      staticClass: 'parallax',
      style: {
        height: `${parseInt(this.normalizedHeight)}px`
      },
      on: this.$listeners
    }, [container, content])
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env nodejs
var _ = require('lodash');
var Promise = require('bluebird');
var debug = require('debug')('parserectomy');
var moment = require('moment');
var nconf = require('nconf');

var mongo = require('../lib/mongo');
var timutils = require('../lib/timeutils');

var cfgFile = "config/settings.json";
nconf.argv().env().file({ file: cfgFile });

/*
 * example:
 *
 * mongodb="mongodb://10.0.2.2/facebook" KEYS="interactions-interactions,rmap" DEBUG=* START=2017-10-01 mongo-scripts/parserctomy.js
 *
 */

function cleanABlock(keyinfo, std, blockSize) {
    var discrimK = keyinfo.discrimK;
    var tbremK = keyinfo.tbremK;

    var selector = {
        "savingTime": { "$gt": new Date(std) }
    }
    _.set(selector, discrimK, { "$exists": true });

    return mongo
        .readLimit(nconf.get('schema').htmls, selector, {}, blockSize, 0)
        .map(function(he) {
            return _.omit(he, tbremK);
        })
        .then(function(htelems) {
            if(_.size(htelems)) {
                debug("First elements processed now is from %s and has %d fields",
                    htelems[0].savingTime, _.size(htelems[0]));
                return mongo
                    .updateMany(nconf.get('schema').htmls, htelems);
            }
        })
        .then(function(htelems) {
            return _.size(htelems);
        });
}

function recursiveRemoval(k, std, blockSize) {

    return cleanABlock(k, std, blockSize)
        .then(function(numbers) {
            if(numbers < blockSize) {
                debug("Process completed!");
                return;
            } else {
                return recursiveRemoval(k, std, blockSize);
            }
        });
};

function removeParserData(k, std) {
    var blockSize = 2000;
    debug("Removing keys %j starting since %s, processin %d block per time",
        k, std, blockSize);
    return recursiveRemoval(k, std, blockSize);
};

/* comma separared string, like: "postType,type" */
function importKeys(csStr) {
    debug("Splitting string KEYS [%s] expecting a string with 0 or more commas and 0 or more dash", csStr);
    var f = csStr.split('-');
    var alls = f[1].split(',');
    return {
        discrimK: f[0],
        tbremK: alls
    };
};

/* YYYY-MM-DD expected here */
function importStartDate(dateStr) {
    debug("Parsing string START [%s] expecting a YYYY-MM-DD", dateStr);
    var dat = moment(dateStr);
    return dat;
};

var keys = importKeys(nconf.get('KEYS'));
var startDay = importStartDate(nconf.get('START'));

debug("Addressing keys: %j since %s", keys, startDay);

return removeParserData(keys, startDay);
<commit_msg>as said, coherence of mongo-script interface<commit_after>#!/usr/bin/env nodejs
var _ = require('lodash');
var Promise = require('bluebird');
var debug = require('debug')('parserectomy');
var moment = require('moment');
var nconf = require('nconf');

var mongo = require('../lib/mongo');
var timutils = require('../lib/timeutils');

var cfgFile = "config/settings.json";
nconf.argv().env().file({ file: cfgFile });

/*
 * example:
 *
 * mongodb="mongodb://10.0.2.2/facebook" KEYS="interactions-interactions,rmap" DEBUG=* START=2017-10-01 mongo-scripts/parserctomy.js
 *
 */

function cleanABlock(keyinfo, std, blockSize) {
    var discrimK = keyinfo.discrimK;
    var tbremK = keyinfo.tbremK;

    var selector = {
        "savingTime": { "$gt": new Date(std) }
    }
    _.set(selector, discrimK, { "$exists": true });

    return mongo
        .readLimit(nconf.get('schema').htmls, selector, {}, blockSize, 0)
        .map(function(he) {
            return _.omit(he, tbremK);
        })
        .then(function(htelems) {
            if(_.size(htelems)) {
                debug("First elements processed now is from %s and has %d fields",
                    htelems[0].savingTime, _.size(htelems[0]));
                return mongo
                    .updateMany(nconf.get('schema').htmls, htelems);
            }
        })
        .then(function(htelems) {
            return _.size(htelems);
        });
}

function recursiveRemoval(k, std, blockSize) {

    return cleanABlock(k, std, blockSize)
        .then(function(numbers) {
            if(numbers < blockSize) {
                debug("Process completed!");
                return;
            } else {
                return recursiveRemoval(k, std, blockSize);
            }
        });
};

function removeParserData(k, std) {
    var blockSize = 2000;
    debug("Removing keys %j starting since %s, processin %d block per time",
        k, std, blockSize);
    return recursiveRemoval(k, std, blockSize);
};

/* comma separared string, like: "postType,type" */
function importKeys(csStr) {
    debug("Splitting string KEYS [%s] expecting a string with 0 or more commas and 0 or more dash", csStr);
    var f = csStr.split('-');
    var alls = f[1].split(',');
    return {
        discrimK: f[0],
        tbremK: alls
    };
};

/* YYYY-MM-DD expected here */
function importStartDate(dateStr) {
    debug("Parsing string $since [%s] expecting a YYYY-MM-DD", dateStr);
    var dat = moment(dateStr);
    return dat;
};

debug("KEYS format is discrimKey-keytoremove1,keytoremove2");
var keys = importKeys(nconf.get('KEYS'));
var startDay = importStartDate(nconf.get('since'));

debug("Addressing keys: %j since %s", keys, startDay);

return removeParserData(keys, startDay);
<|endoftext|>


<commit_before>// @flow
import React, { createFactory, Component } from "react";
import "./ManagedTree.css";

import { Tree as _Tree } from "devtools-components";
const Tree = createFactory(_Tree);

export type Item = {
  contents: any,
  name: string,
  path: string
};

type Props = {
  autoExpandAll: boolean,
  autoExpandDepth: number,
  getChildren: Item => Item[],
  getPath: Item => string,
  getParent: () => any,
  getRoots: () => any,
  highlightItems?: Array<Item>,
  itemHeight: number,
  listItems?: Array<Item>,
  onFocus?: (item: any) => void,
  onExpand?: (item: any, expanded: Set<Item>) => void,
  onCollapse?: (item: any, expanded: Set<Item>) => void,
  renderItem: any,
  disabledFocus?: boolean,
  focused?: any,
  expanded?: any
};

type ManagedTreeState = {
  expanded: any,
  focusedItem: ?Item
};

class ManagedTree extends Component {
  state: ManagedTreeState;
  props: Props;

  constructor(props: Props) {
    super();

    this.state = {
      expanded: props.expanded || git  to new Set(),
      focusedItem: null
    };

    const self: any = this;
    self.setExpanded = this.setExpanded.bind(this);
    self.focusItem = this.focusItem.bind(this);
  }

  componentWillReceiveProps(nextProps: Props) {
    const listItems = nextProps.listItems;
    if (listItems && listItems != this.props.listItems && listItems.length) {
      this.expandListItems(listItems);
    }

    const highlightItems = nextProps.highlightItems;
    if (
      highlightItems &&
      highlightItems != this.props.highlightItems &&
      highlightItems.length
    ) {
      this.highlightItem(highlightItems);
    }

    if (nextProps.focused && nextProps.focused !== this.props.focused) {
      this.focusItem(nextProps.focused);
    }
  }

  setExpanded(item: Item, isExpanded: boolean) {
    const expanded = this.state.expanded;
    const itemPath = this.props.getPath(item);
    if (isExpanded) {
      expanded.add(itemPath);
    } else {
      expanded.delete(itemPath);
    }
    this.setState({ expanded });

    if (isExpanded && this.props.onExpand) {
      this.props.onExpand(item, expanded);
    } else if (!isExpanded && this.props.onCollapse) {
      this.props.onCollapse(item, expanded);
    }
  }

  expandListItems(listItems: Array<Item>) {
    const expanded = this.state.expanded;
    listItems.forEach(item => expanded.add(this.props.getPath(item)));
    this.focusItem(listItems[0]);
    this.setState({ expanded });
  }

  highlightItem(highlightItems: Array<Item>) {
    const expanded = this.state.expanded;

    // This file is visible, so we highlight it.
    if (expanded.has(this.props.getPath(highlightItems[0]))) {
      this.focusItem(highlightItems[0]);
    } else {
      // Look at folders starting from the top-level until finds a
      // closed folder and highlights this folder
      const index = highlightItems
        .reverse()
        .findIndex(item => !expanded.has(this.props.getPath(item)));
      this.focusItem(highlightItems[index]);
    }
  }

  focusItem(item: Item) {
    if (!this.props.disabledFocus && this.state.focusedItem !== item) {
      this.setState({ focusedItem: item });

      if (this.props.onFocus) {
        this.props.onFocus(item);
      }
    }
  }

  render() {
    const { expanded, focusedItem } = this.state;

    const overrides = {
      isExpanded: item => expanded.has(this.props.getPath(item)),
      focused: focusedItem,
      getKey: this.props.getPath,
      onExpand: item => this.setExpanded(item, true),
      onCollapse: item => this.setExpanded(item, false),
      onFocus: this.focusItem,
      renderItem: (...args) =>
        this.props.renderItem(...args, {
          setExpanded: this.setExpanded
        })
    };

    const props = { ...this.props, ...overrides };
    return (

        <Tree {...props} />

    );
  }
}

ManagedTree.displayName = "ManagedTree";

ManagedTree.propTypes = Object.assign({}, Tree.propTypes);

export default ManagedTree;
<commit_msg>remove rouge text<commit_after>// @flow
import React, { createFactory, Component } from "react";
import "./ManagedTree.css";

import { Tree as _Tree } from "devtools-components";
const Tree = createFactory(_Tree);

export type Item = {
  contents: any,
  name: string,
  path: string
};

type Props = {
  autoExpandAll: boolean,
  autoExpandDepth: number,
  getChildren: Item => Item[],
  getPath: Item => string,
  getParent: () => any,
  getRoots: () => any,
  highlightItems?: Array<Item>,
  itemHeight: number,
  listItems?: Array<Item>,
  onFocus?: (item: any) => void,
  onExpand?: (item: any, expanded: Set<Item>) => void,
  onCollapse?: (item: any, expanded: Set<Item>) => void,
  renderItem: any,
  disabledFocus?: boolean,
  focused?: any,
  expanded?: any
};

type ManagedTreeState = {
  expanded: any,
  focusedItem: ?Item
};

class ManagedTree extends Component {
  state: ManagedTreeState;
  props: Props;

  constructor(props: Props) {
    super();

    this.state = {
      expanded: props.expanded || new Set(),
      focusedItem: null
    };

    const self: any = this;
    self.setExpanded = this.setExpanded.bind(this);
    self.focusItem = this.focusItem.bind(this);
  }

  componentWillReceiveProps(nextProps: Props) {
    const listItems = nextProps.listItems;
    if (listItems && listItems != this.props.listItems && listItems.length) {
      this.expandListItems(listItems);
    }

    const highlightItems = nextProps.highlightItems;
    if (
      highlightItems &&
      highlightItems != this.props.highlightItems &&
      highlightItems.length
    ) {
      this.highlightItem(highlightItems);
    }

    if (nextProps.focused && nextProps.focused !== this.props.focused) {
      this.focusItem(nextProps.focused);
    }
  }

  setExpanded(item: Item, isExpanded: boolean) {
    const expanded = this.state.expanded;
    const itemPath = this.props.getPath(item);
    if (isExpanded) {
      expanded.add(itemPath);
    } else {
      expanded.delete(itemPath);
    }
    this.setState({ expanded });

    if (isExpanded && this.props.onExpand) {
      this.props.onExpand(item, expanded);
    } else if (!isExpanded && this.props.onCollapse) {
      this.props.onCollapse(item, expanded);
    }
  }

  expandListItems(listItems: Array<Item>) {
    const expanded = this.state.expanded;
    listItems.forEach(item => expanded.add(this.props.getPath(item)));
    this.focusItem(listItems[0]);
    this.setState({ expanded });
  }

  highlightItem(highlightItems: Array<Item>) {
    const expanded = this.state.expanded;

    // This file is visible, so we highlight it.
    if (expanded.has(this.props.getPath(highlightItems[0]))) {
      this.focusItem(highlightItems[0]);
    } else {
      // Look at folders starting from the top-level until finds a
      // closed folder and highlights this folder
      const index = highlightItems
        .reverse()
        .findIndex(item => !expanded.has(this.props.getPath(item)));
      this.focusItem(highlightItems[index]);
    }
  }

  focusItem(item: Item) {
    if (!this.props.disabledFocus && this.state.focusedItem !== item) {
      this.setState({ focusedItem: item });

      if (this.props.onFocus) {
        this.props.onFocus(item);
      }
    }
  }

  render() {
    const { expanded, focusedItem } = this.state;

    const overrides = {
      isExpanded: item => expanded.has(this.props.getPath(item)),
      focused: focusedItem,
      getKey: this.props.getPath,
      onExpand: item => this.setExpanded(item, true),
      onCollapse: item => this.setExpanded(item, false),
      onFocus: this.focusItem,
      renderItem: (...args) =>
        this.props.renderItem(...args, {
          setExpanded: this.setExpanded
        })
    };

    const props = { ...this.props, ...overrides };
    return (

        <Tree {...props} />

    );
  }
}

ManagedTree.displayName = "ManagedTree";

ManagedTree.propTypes = Object.assign({}, Tree.propTypes);

export default ManagedTree;
<|endoftext|>


<commit_before>import ReactHighcharts from 'react-highcharts';
import highchartsTreemap from 'highcharts-treemap';

let hasBeenInitialized = false;

// wrapper to make sure we only initialize the highcharts component once
function initHighcharts() {
  if (!hasBeenInitialized) {
    highchartsTreemap(ReactHighcharts.Highcharts);
    hasBeenInitialized = true;
  }
}

export default initHighcharts;
<commit_msg>Add highcharts exporting back in #1328<commit_after>import ReactHighcharts from 'react-highcharts';
import highchartsTreemap from 'highcharts-treemap';
import highchartsExporting from 'highcharts/modules/exporting';

let hasBeenInitialized = false;

// wrapper to make sure we only initialize the highcharts component once
function initHighcharts() {
  if (!hasBeenInitialized) {
    highchartsTreemap(ReactHighcharts.Highcharts);
    highchartsExporting(ReactHighcharts.Highcharts);
    hasBeenInitialized = true;
  }
}

export default initHighcharts;
<|endoftext|>


<commit_before>define(function(require) {

  var _ = require('underscore');
  var Backbone = require('backbone');

  var SearchView = Backbone.View.extend({

    initialize: function () {

      _.bindAll(this, 'toggle');

      this.render();

      this.collection
        .on('add', this.toggle)
        .on('remove', this.toggle);

    },

    el: '#search',

    events: {
      'search': 'search',
      'keyup': 'handleKey',
      'focus': 'triggerFocus',
      'blur': 'triggerBlur'
    },

    serialize: function () {
      return this.model.get('query');
    },

    render: function () {
      this.$el.val( this.serialize() );
    },

    search: function() {
      var query = this.$el.val();
      this.model.save( 'query', query );
    },

    handleKey: function(e) {
      if (e.which === 27) { // ESC
        e.preventDefault();
        return this.triggerBlur();
      }
      this.search();
    },

    focus: function() {
      this.$el.focus();
    },

    triggerFocus: function() {
      this.trigger('focus');
    },

    triggerBlur: function() {
      this.trigger('blur');
    },

    toggle: function() {
      this.collection.length > 7 ? this.show() : this.hide();
    },

    show: function() {
      this.$el.removeClass('hide');
    },

    hide: function() {
      this.$el.addClass('hide');
    }

  });

  return SearchView;

});
<commit_msg>use enter instead of escape to leave search<commit_after>define(function(require) {

  var _ = require('underscore');
  var Backbone = require('backbone');

  var SearchView = Backbone.View.extend({

    initialize: function () {

      _.bindAll(this, 'toggle');

      this.render();

      this.collection
        .on('add', this.toggle)
        .on('remove', this.toggle);

    },

    el: '#search',

    events: {
      'search': 'search',
      'keyup': 'handleKey',
      'focus': 'triggerFocus',
      'blur': 'triggerBlur'
    },

    serialize: function () {
      return this.model.get('query');
    },

    render: function () {
      this.$el.val( this.serialize() );
    },

    search: function() {
      var query = this.$el.val();
      this.model.save( 'query', query );
    },

    handleKey: function(e) {
      if (e.which === 27) { // ESC
      if (e.which === 13) { // ENTER
        e.preventDefault();
        return this.triggerBlur();
      }
      this.search();
    },

    focus: function() {
      this.$el.focus();
    },

    triggerFocus: function() {
      this.trigger('focus');
    },

    triggerBlur: function() {
      this.trigger('blur');
    },

    toggle: function() {
      this.collection.length > 7 ? this.show() : this.hide();
    },

    show: function() {
      this.$el.removeClass('hide');
    },

    hide: function() {
      this.$el.addClass('hide');
    }

  });

  return SearchView;

});
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('/t/:test')
		.get( function(req, res) {
			res.send('test: ' + req.params.test);
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);
};
<commit_msg>Updated for Timestamp Microservice<commit_after>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var moment = require('moment');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get( function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('/:thetime')
		.get( function(req, res) {
			var time = { "unix": null, "natural": null };
			var toConvert = req.params.thetime;

			if( isNaN(toConvert) && moment(toConvert, "MMMM DD, YYYY").isValid() ) {
				time.natural = toConvert;
				time.unix = moment(toConvert).unix();
			}
			else if( moment.unix(Number(toConvert)).isValid() ) {
				time.unix = Number(toConvert);
				time.natural = moment.unix(time.unix).format("MMMM DD, YYYY");
			}
			res.send(time);
		});

	/*app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/
};
<|endoftext|>


<commit_before>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err)
				}
			User.polls.push(poll._id);
				res.redirect('/poll/' + poll._id)
			});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{poll:poll});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	/*app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.redirect('/poll');
				})
				//console.log(poll.poll.choices);
			});*/

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

//	app.route('/createpoll')
	//	.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<commit_msg>displaying polls<commit_after>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/poll')
		.post(isLoggedIn, function (req, res) {
			console.log(req.body);
			var newpoll = {question : req.body.question};
			newpoll.choices = {};
			var choices = req.body.choices.split(',');
			choices.forEach(function(item) {
				newpoll.choices[item]=0;
			})
			newpoll.creator = req.user._id;
			console.log(newpoll);
			Poll.create(newpoll, function(err, poll) {
				if (err) {
					console.log(err)
				}
			User.findById(req.user._id, function(err, user){
				console.log(user);
				user.polls.push(poll._id);
    			user.save();
				res.redirect('/poll/' + poll._id)
			});
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findById(req.params.id, function(err, poll){
				console.log(poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{poll:poll});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
			User.findById(req.user._id, function(err, user){
				console.log(user);
				var index = user.polls.indexOf(req.params.id);
				console.log(index);
				if (index > -1) {
    				user.polls.splice(index, 1);
    				user.save();
				}
				res.redirect('/profile');
			})
			})
		})
		.post(function (req, res) {
			console.log(req.body);
			if (req.body.choice) {
				Poll.findOne({"_id": req.params.id}, function(err, poll) {
					poll.choices[req.body.choice]++;
					console.log(poll);
					poll.markModified('choices');
					poll.save();
					res.redirect('/poll/' + poll._id);
				})
			}
		});

	/*app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.redirect('/poll');
				})
				//console.log(poll.poll.choices);
			});*/

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

//	app.route('/createpoll')
	//	.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<|endoftext|>


<commit_before>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function GenieMini(id) {
    this.btServiceIds = ['f000474d04514000b000000000000000'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._angle = null;
    this._position = 0;
    this._currentMove = null;
    this._stepsPerDegree = 186.56716418;
    this._backlash = 0;
    this._lastDirection = 0;

    this.orientation = null;
}

util.inherits(GenieMini, EventEmitter);

GenieMini.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('GenieMini(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._gmCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            console.log("ch.uuid", ch.uuid);
                            if (ch.uuid == "2") {
                                self._gmCh = ch;
                            }
                        }
                        if (self._gmCh) {
                            try {
                                self._gmCh.write(new Buffer("012600", 'hex'));
                                self._gmCh.subscribe(function(){
                                    self._dev = btPeripheral;
                                    self._dev.connected = true;
                                    self.connected = true;
                                    self._dev.type = "bt";
                                    self._gmCh.on('data', function(data, isNotification) {
                                        self._parseIncoming(data);
                                    });
                                    console.log("GenieMini(" + self._id + "): connected!");
                                    self._init();
                                    if (callback) callback(true);
                                });
                            } catch(err3) {
                                btPeripheral.disconnect();
                                console.log("GenieMini(" + self._id + "): exception while connecting: ", err3);
                                if (callback) callback(false);
                            }
                        } else {
                            console.log("GenieMini(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("GenieMini(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("GenieMini(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

GenieMini.prototype._init = function() {
    var self = this;
    var dataBuf = new Buffer(4);
    dataBuf.fill(0);
    dataBuf.writeInt32LE(0x000B, 0);
    //self.statusIntervalHandle = setInterval(function(){
    self._write(0x001E, dataBuf, function(err) { // checks orientation
        var tries = 0;
        var waitForOrientation = function() {
            tries++;
            if(self.orientation || tries > 5) {
                self.emit("status", self.getStatus());
            } else {
                setTimeout(waitForOrientation, 500);
            }
        }
        waitForOrientation();
    });
    //}, 5000);
}

GenieMini.prototype._parseIncoming = function(data) {
    var id = data.readUInt16LE(1);
    if(id == 0x0060 || id == 0x0061) { // moving steps
        var state = data.readUInt8(7);
        var steps = data.readInt16LE(3);
        this._moving = (state == 0x01);
        //if(this._newMove) {
        //    this._newMove = false;
        //    this._moving = true;
        //}
        console.log("GenieMini(" + this._id + "): moving: ", this._moving, ", steps:", steps, "id:", id);
    } else if(id == 0x000B || id == 0x0052) { // current state
        var state = data.readUInt8(4);
        var angle = data.readUInt16LE(12);
        this._angle = angle;
        this._moving = (state == 0x01);
        console.log("GenieMini(" + this._id + "): moving: ", this._moving, ", angle:", angle, "id:", id);
        if(this._currentMove != null && this._lastAngle != null) {
            if(Math.abs(angle - this._lastAngle) < 180) {
                this._currentMove += angle - this._lastAngle;
            } else {
                if(this._lastAngle < angle) {
                    this._currentMove += 359 - (angle - this._lastAngle);
                } else {
                    this._currentMove -= 359 - (this._lastAngle - angle);
                }
            }
            console.log("GenieMini(" + this._id + "): _currentMove", this._currentMove);
        }
        this._lastAngle = angle;
    } else if(id == 0x0025) {
        var orientationCode = data.readUInt8(3);
        console.log("GenieMini(" + this._id + "): orientationCode:", orientationCode);
        var origOrientation = this.orientation;
        if(orientationCode & 0x4) this.orientation = 'tilt'; else this.orientation = 'pan'; // pan = 0x90, 0x80, tilt = 0x94, 0x84
        if(origOrientation != this.orientation) {
            console.log("GenieMini(" + this._id + "): orientation:", this.orientation);
            this.emit("status", this.getStatus());
        }
    } else if(id == 0x004E) {
        this._init(); // update orientation on change
    } else {
        console.log("GenieMini(" + this._id + "): unknown id", id, "data", data);
    }
}

GenieMini.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("GenieMini(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("GenieMini(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

GenieMini.prototype.disconnect = function() {
    console.log("GenieMini(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

GenieMini.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        motor1: this._dev && this._dev.connected,
        motor1pos: this._position / this._stepsPerDegree,
        orientation: this.orientation
    }
}

GenieMini.prototype.disable = function(motor) {
    this._enabled = false;
}

GenieMini.prototype.enable = function(motor) {
    this._enabled = true;
}

GenieMini.prototype.move = function(motor, degrees, callback) {
    if (this._moving) {
        if (callback) callback("GenieMini(" + this._id + "): motor already running");
        return console.log("GenieMini(" + this._id + "): motor already running");
    }
    var sign = 0;
    if(degrees > 0) sign = 1;
    if(degrees < 0) sign = -1;

    if(sign && this._lastDirection != sign) {
        this._lastDirection = sign;
        degrees += this._backlash * sign;
    }
    var steps = Math.round(degrees * this._stepsPerDegree);
    if(!steps) {
        console.log("GenieMini(" + this._id + "): NOT moving motor", steps, "steps, (", degrees, " degrees)");
        return callback && callback(null, this._position / this._stepsPerDegree);
    }
    console.log("GenieMini(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    var dataBuf = new Buffer(4);
    dataBuf.fill(0);
    dataBuf.writeInt32LE(steps, 0);
    this._moving = true;

    var self = this;
    //this._newMove = true;
    self._write(0x005E, dataBuf, function(err) {
        self._moving = true;
        if (!err) {
            var check = function() {
                setTimeout(function() {
                    if(self._moving === undefined) return check();;
                    if(self._moving) {
                        check(); // keep checking until stop
                    } else {
                        self._position += steps;
                        console.log("GenieMini(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerDegree);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}
//<Buffer 01 5e 00 00 00 03 a4 00>
GenieMini.prototype._write = function(command, dataBuf, callback) {
    var template = new Buffer("010000", 'hex');
    var len = dataBuf ? dataBuf.length : 0;
    var COMMAND = 0;

    template.writeUInt16LE(parseInt(command), 1);

    var cmd;
    if (dataBuf) {
        cmd = Buffer.concat([template, dataBuf]);
    } else {
        cmd = template;
    }

    //console.log("GenieMini(" + this._id + "): sending data", cmd);

    try {
        this._gmCh.write(cmd);
        callback && callback();
    } catch(err) {
        callback && callback(err);
    }
}

GenieMini.prototype.constantMove = function(motor, speed, callback) {
    console.log("GenieMini(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var dataBuf = new Buffer(3);
    var self = this;
    dataBuf.fill(0);
    dataBuf.writeInt8(Math.round(speed), 0);
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 1);
    this._moving = true;

    if(this._watchdog) {
        clearTimeout(this._watchdog);
        this._watchdog = null;
    }
    if(speed) {
        this._watchdog = setTimeout(function(){
            console.log("GenieMini(" + self._id + "): stopping via watchdog");
            self.constantMove(motor, 0);
        }, 3000);
    }

    var sendMove = function() {
        self._write(0x003F, dataBuf, function(err) {
            if (!err) {
                var check = function() {
                    if(this._endTimer) clearTimeout(this._endTimer);
                    if(!speed) {
                        self._endTimer = setTimeout(function() {
                            if(self._moving === undefined) return;
                            if(self._moving) {
                                check(); // keep checking until stop
                            } else {
                                console.log("GenieMini(" + self._id + "): adding", self._currentMove, "° to position");
                                self._position += self._currentMove * self._stepsPerDegree;
                                self._currentMove = null;
                                if (callback) callback(null, self._position / self._stepsPerDegree);
                            }
                        }, 200);
                    } else {
                        if (callback) callback(null, null);
                    }
                }
                check();
            } else {
                if (callback) callback(err);
                self._moving = false;
            }
        });
    }

    var self = this;
    if(this._endTimer) clearTimeout(this._endTimer);
    if(self._currentMove == null) {
        self._lastAngle = null;
        self._currentMove = 0;
        console.log("GenieMini(" + self._id + "): starting move at speed, saving position");
        var d = new Buffer(2);
        d.fill(0);
        d.writeUInt16LE(0x000B, 0);
        this._moving = true;
        self._write(0x001E, d, function(err) {
            sendMove();
        });
    } else {
        sendMove();
    }
}

GenieMini.prototype.resetMotorPosition = function(motor, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            self._position = 0;
            if (callback) callback();
        }
    }
    check();
}

GenieMini.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

GenieMini.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = GenieMini;
<commit_msg>motion backlash calibration testing<commit_after>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function GenieMini(id) {
    this.btServiceIds = ['f000474d04514000b000000000000000'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._angle = null;
    this._position = 0;
    this._currentMove = null;
    this._stepsPerDegree = 186.56716418;
    this._backlash = 0;
    this._lastDirection = 0;

    this.orientation = null;
}

util.inherits(GenieMini, EventEmitter);

GenieMini.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('GenieMini(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._gmCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            console.log("ch.uuid", ch.uuid);
                            if (ch.uuid == "2") {
                                self._gmCh = ch;
                            }
                        }
                        if (self._gmCh) {
                            try {
                                self._gmCh.write(new Buffer("012600", 'hex'));
                                self._gmCh.subscribe(function(){
                                    self._dev = btPeripheral;
                                    self._dev.connected = true;
                                    self.connected = true;
                                    self._dev.type = "bt";
                                    self._gmCh.on('data', function(data, isNotification) {
                                        self._parseIncoming(data);
                                    });
                                    console.log("GenieMini(" + self._id + "): connected!");
                                    self._init();
                                    if (callback) callback(true);
                                });
                            } catch(err3) {
                                btPeripheral.disconnect();
                                console.log("GenieMini(" + self._id + "): exception while connecting: ", err3);
                                if (callback) callback(false);
                            }
                        } else {
                            console.log("GenieMini(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("GenieMini(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("GenieMini(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

GenieMini.prototype._init = function() {
    var self = this;
    var dataBuf = new Buffer(4);
    dataBuf.fill(0);
    dataBuf.writeInt32LE(0x000B, 0);
    //self.statusIntervalHandle = setInterval(function(){
    self._write(0x001E, dataBuf, function(err) { // checks orientation
        var tries = 0;
        var waitForOrientation = function() {
            tries++;
            if(self.orientation || tries > 5) {
                self.emit("status", self.getStatus());
            } else {
                setTimeout(waitForOrientation, 500);
            }
        }
        waitForOrientation();
    });
    //}, 5000);
}

GenieMini.prototype._parseIncoming = function(data) {
    var id = data.readUInt16LE(1);
    if(id == 0x0060 || id == 0x0061) { // moving steps
        var state = data.readUInt8(7);
        var steps = data.readInt16LE(3);
        this._moving = (state == 0x01);
        if(this._newMove) {
            this._newMove = false;
            this._moving = true;
        }
        console.log("GenieMini(" + this._id + "): moving: ", this._moving, ", steps:", steps, "id:", id);
    } else if(id == 0x000B || id == 0x0052) { // current state
        var state = data.readUInt8(4);
        var angle = data.readUInt16LE(12);
        this._angle = angle;
        this._moving = (state == 0x01);
        console.log("GenieMini(" + this._id + "): moving: ", this._moving, ", angle:", angle, "id:", id);
        if(this._currentMove != null && this._lastAngle != null) {
            if(Math.abs(angle - this._lastAngle) < 180) {
                this._currentMove += angle - this._lastAngle;
            } else {
                if(this._lastAngle < angle) {
                    this._currentMove += 359 - (angle - this._lastAngle);
                } else {
                    this._currentMove -= 359 - (this._lastAngle - angle);
                }
            }
            console.log("GenieMini(" + this._id + "): _currentMove", this._currentMove);
        }
        this._lastAngle = angle;
    } else if(id == 0x0025) {
        var orientationCode = data.readUInt8(3);
        console.log("GenieMini(" + this._id + "): orientationCode:", orientationCode);
        var origOrientation = this.orientation;
        if(orientationCode & 0x4) this.orientation = 'tilt'; else this.orientation = 'pan'; // pan = 0x90, 0x80, tilt = 0x94, 0x84
        if(origOrientation != this.orientation) {
            console.log("GenieMini(" + this._id + "): orientation:", this.orientation);
            this.emit("status", this.getStatus());
        }
    } else if(id == 0x004E) {
        this._init(); // update orientation on change
    } else {
        console.log("GenieMini(" + this._id + "): unknown id", id, "data", data);
    }
}

GenieMini.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("GenieMini(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("GenieMini(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

GenieMini.prototype.disconnect = function() {
    console.log("GenieMini(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

GenieMini.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        motor1: this._dev && this._dev.connected,
        motor1pos: this._position / this._stepsPerDegree,
        orientation: this.orientation
    }
}

GenieMini.prototype.disable = function(motor) {
    this._enabled = false;
}

GenieMini.prototype.enable = function(motor) {
    this._enabled = true;
}

GenieMini.prototype.move = function(motor, degrees, callback) {
    if (this._moving) {
        if (callback) callback("GenieMini(" + this._id + "): motor already running");
        return console.log("GenieMini(" + this._id + "): motor already running");
    }
    var sign = 0;
    if(degrees > 0) sign = 1;
    if(degrees < 0) sign = -1;

    if(sign && this._lastDirection != sign) {
        this._lastDirection = sign;
        degrees += this._backlash * sign;
    }
    var steps = Math.round(degrees * this._stepsPerDegree);
    if(!steps) {
        console.log("GenieMini(" + this._id + "): NOT moving motor", steps, "steps, (", degrees, " degrees)");
        return callback && callback(null, this._position / this._stepsPerDegree);
    }
    console.log("GenieMini(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    var dataBuf = new Buffer(4);
    dataBuf.fill(0);
    dataBuf.writeInt32LE(steps, 0);
    this._moving = true;

    var self = this;
    this._newMove = true;
    self._write(0x005E, dataBuf, function(err) {
        self._moving = true;
        if (!err) {
            var check = function() {
                setTimeout(function() {
                    if(self._moving === undefined) return check();;
                    if(self._moving) {
                        check(); // keep checking until stop
                    } else {
                        self._position += steps;
                        console.log("GenieMini(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerDegree);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}
//<Buffer 01 5e 00 00 00 03 a4 00>
GenieMini.prototype._write = function(command, dataBuf, callback) {
    var template = new Buffer("010000", 'hex');
    var len = dataBuf ? dataBuf.length : 0;
    var COMMAND = 0;

    template.writeUInt16LE(parseInt(command), 1);

    var cmd;
    if (dataBuf) {
        cmd = Buffer.concat([template, dataBuf]);
    } else {
        cmd = template;
    }

    //console.log("GenieMini(" + this._id + "): sending data", cmd);

    try {
        this._gmCh.write(cmd);
        callback && callback();
    } catch(err) {
        callback && callback(err);
    }
}

GenieMini.prototype.constantMove = function(motor, speed, callback) {
    console.log("GenieMini(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var dataBuf = new Buffer(3);
    var self = this;
    dataBuf.fill(0);
    dataBuf.writeInt8(Math.round(speed), 0);
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 1);
    this._moving = true;

    if(this._watchdog) {
        clearTimeout(this._watchdog);
        this._watchdog = null;
    }
    if(speed) {
        this._watchdog = setTimeout(function(){
            console.log("GenieMini(" + self._id + "): stopping via watchdog");
            self.constantMove(motor, 0);
        }, 3000);
    }

    var sendMove = function() {
        self._write(0x003F, dataBuf, function(err) {
            if (!err) {
                var check = function() {
                    if(this._endTimer) clearTimeout(this._endTimer);
                    if(!speed) {
                        self._endTimer = setTimeout(function() {
                            if(self._moving === undefined) return;
                            if(self._moving) {
                                check(); // keep checking until stop
                            } else {
                                console.log("GenieMini(" + self._id + "): adding", self._currentMove, "° to position");
                                self._position += self._currentMove * self._stepsPerDegree;
                                self._currentMove = null;
                                if (callback) callback(null, self._position / self._stepsPerDegree);
                            }
                        }, 200);
                    } else {
                        if (callback) callback(null, null);
                    }
                }
                check();
            } else {
                if (callback) callback(err);
                self._moving = false;
            }
        });
    }

    var self = this;
    if(this._endTimer) clearTimeout(this._endTimer);
    if(self._currentMove == null) {
        self._lastAngle = null;
        self._currentMove = 0;
        console.log("GenieMini(" + self._id + "): starting move at speed, saving position");
        var d = new Buffer(2);
        d.fill(0);
        d.writeUInt16LE(0x000B, 0);
        this._moving = true;
        self._write(0x001E, d, function(err) {
            sendMove();
        });
    } else {
        sendMove();
    }
}

GenieMini.prototype.resetMotorPosition = function(motor, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            self._position = 0;
            if (callback) callback();
        }
    }
    check();
}

GenieMini.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

GenieMini.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = GenieMini;
<|endoftext|>


<commit_before>import Ember from 'ember';
import bbox from 'npm:@turf/bbox'; // eslint-disable-line

export default Ember.Route.extend({
  mapState: Ember.inject.service(),

  model() {
    return this.modelFor('application');
  },

  afterModel(districts) {
    const mapState = this.get('mapState');
    mapState.set('bounds', bbox(districts));
  },

  actions: {
    didTransition() {
      let mapState = this.get('mapState');
      let mapInstance = mapState.get('mapInstance');

      mapState.set('currentlySelected', null);
    }
  }
});
<commit_msg>MapState sets bbox of geojson-ified collection<commit_after>import Ember from 'ember';
import bbox from 'npm:@turf/bbox'; // eslint-disable-line
import toGeojson from '../utils/to-geojson';

export default Ember.Route.extend({
  mapState: Ember.inject.service(),

  model() {
    return this.modelFor('application');
  },

  afterModel(districts) {
    const mapState = this.get('mapState');
    const geojsonDistricts = toGeojson(districts);
    mapState.set('bounds', bbox(geojsonDistricts));
  },

  actions: {
    didTransition() {
      let mapState = this.get('mapState');

      mapState.set('currentlySelected', null);
    },
  },
});
<|endoftext|>


<commit_before>import fse from 'fs-extra';
import path from 'path';
import glob from 'glob';
import R from 'ramda';
import Promise from 'bluebird';

const fs = Promise.promisifyAll(require('fs'));
const fseCopy = Promise.promisify(fse.copy);
const PromisifiedGlob = Promise.promisify(glob);

function copySingleFile(src, dest, newFileName) {
  const promise = fseCopy(src, path.join(dest, newFileName));
  return promise;
}

// will need refactoring - good enough for POC
// ain't not much consistency in file naming tho, gotta have to make it work
// with:
//  - x = reference

  //  - y = number from 0 to 9
//  - Q = quality (caps) from A to G

        //  - q = quality (min) from a to g
//
//  match:
//  - xq.jpg          [xa.jpg ... xg.jpg]
//  - x.y.jpg         [x.1.jpg ... x.9.jpg]
//  - x.q.jpg         [x.a.jpg ... x.g.jpg]
//  - xQ.y.jpg        [xA.1.jpg ... xA.9.jpg ... xG.1.jpg ... xG.9.jpg]
//  - xQ.q.jpg        [xA.a.jpg ... xA.g.jpg ... xG.a.jpg ... xG.g.jpg]
//  - xBis.y.jpg      [xBis.1.jpg ... xBis.9.jpg]
//  - xBis.q.jpg      [xBis.a.jpg ... xBis.g.jpg]
export function copyFiles(src, dest, files, cb) {

  cb(`Starting copy process`);
  cb(`Starting async copy process for ${files.length} file(s): ${files}`);

  const promise = new Promise((resolve, reject) => {
    let counter = 0;

    Promise.each(files, file => {

      const wildcard = path.join(src, '**', `${file}?(?|?(|Bis|A|B|C|D|E|G).??(|.?)).+(jpg|jpeg|JPG|JPEG)`);

      return new PromisifiedGlob(wildcard, {})
        .then(matchingFiles => {

          return Promise
            .filter(matchingFiles, matchingFile => !R.test(new RegExp(dest), matchingFile)) // don't copy from subfolder
            .then(matchingFiles => {
              cb(`Start processing input file ${file}`);
              cb(`Found ${matchingFiles.length} matching file(s) : ${matchingFiles}`);
              return matchingFiles;
            })
            .filter(matchingFile => {
              // remove files with the term 'copy' in the name
              if (/copy/i.test(matchingFile)) {
                cb(`Decided not to process following file: ${matchingFile}`);
                return false;
              } else {
                return true;
              }

            })
            .each(fileToCopy => {
              const fileName = R.last(fileToCopy.split('/'));

              return copySingleFile(fileToCopy, dest, fileName)
                .then(data => {
                  counter++;
                  cb('Done copying ' + fileName)
                })
                .catch(err => cb('ERROR copying ' + fileName))
            })
            .then(data => cb(`Done processing input file ${file}`))
            .catch(err => {
              debugger;
              console.error(err)
              cb(`Error processing input file ${file} - ${err}`)
            })
          });
    })
    .then(data => {
      cb(`A total of ${counter} file(s) have been copied`);
      resolve();
    })
    .catch(err => {
      cb(`Copy process ERROR: ${err}`);
      reject(err);
    });
  })
  .then(data => cb('Copy process terminated succesfully'))
  .catch(err => cb('Copy process terminated with ERROR'))
  .finally(() => cb('Shutting system down\n\n'));

  return promise;
}
<commit_msg>remove now obsolete file filter<commit_after>import fse from 'fs-extra';
import path from 'path';
import glob from 'glob';
import R from 'ramda';
import Promise from 'bluebird';

const fs = Promise.promisifyAll(require('fs'));
const fseCopy = Promise.promisify(fse.copy);
const PromisifiedGlob = Promise.promisify(glob);

function copySingleFile(src, dest, newFileName) {
  const promise = fseCopy(src, path.join(dest, newFileName));
  return promise;
}

// will need refactoring - good enough for POC
// ain't not much consistency in file naming tho, gotta have to make it work
// with:
//  - x = reference

  //  - y = number from 0 to 9
//  - Q = quality (caps) from A to G

        //  - q = quality (min) from a to g
//
//  match:
//  - xq.jpg          [xa.jpg ... xg.jpg]
//  - x.y.jpg         [x.1.jpg ... x.9.jpg]
//  - x.q.jpg         [x.a.jpg ... x.g.jpg]
//  - xQ.y.jpg        [xA.1.jpg ... xA.9.jpg ... xG.1.jpg ... xG.9.jpg]
//  - xQ.q.jpg        [xA.a.jpg ... xA.g.jpg ... xG.a.jpg ... xG.g.jpg]
//  - xBis.y.jpg      [xBis.1.jpg ... xBis.9.jpg]
//  - xBis.q.jpg      [xBis.a.jpg ... xBis.g.jpg]
export function copyFiles(src, dest, files, cb) {

  cb(`Starting copy process`);
  cb(`Starting async copy process for ${files.length} file(s): ${files}`);

  const promise = new Promise((resolve, reject) => {
    let counter = 0;

    Promise.each(files, file => {

      const wildcard = path.join(src, '**', `${file}?(?|?(|Bis|A|B|C|D|E|G).??(|.?)).+(jpg|jpeg|JPG|JPEG)`);

      return new PromisifiedGlob(wildcard, {})
        .then(matchingFiles => {

          return Promise
            .filter(matchingFiles, matchingFile => !R.test(new RegExp(dest), matchingFile)) // don't copy from subfolder
            .then(matchingFiles => {
              cb(`Start processing input file ${file}`);
              cb(`Found ${matchingFiles.length} matching file(s) : ${matchingFiles}`);
              return matchingFiles;
            })
            .each(fileToCopy => {
              const fileName = R.last(fileToCopy.split('/'));

              return copySingleFile(fileToCopy, dest, fileName)
                .then(data => {
                  counter++;
                  cb('Done copying ' + fileName)
                })
                .catch(err => cb('ERROR copying ' + fileName))
            })
            .then(data => cb(`Done processing input file ${file}`))
            .catch(err => {
              debugger;
              console.error(err)
              cb(`Error processing input file ${file} - ${err}`)
            })
          });
    })
    .then(data => {
      cb(`A total of ${counter} file(s) have been copied`);
      resolve();
    })
    .catch(err => {
      cb(`Copy process ERROR: ${err}`);
      reject(err);
    });
  })
  .then(data => cb('Copy process terminated succesfully'))
  .catch(err => cb('Copy process terminated with ERROR'))
  .finally(() => cb('Shutting system down\n\n'));

  return promise;
}
<|endoftext|>


<commit_before>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = (/\.svg$/.test(_cachedItem));
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          injectHTML(inlineContent);
          localStorage.setItem(_cachedItem, inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<commit_msg>加入 cacheOnly 選項至 injectInline function，可略過 inject HTML<commit_after>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = (/\.svg$/.test(_cachedItem));
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          localStorage.setItem(_cachedItem, inlineContent);

          if ($specilOption && $specilOption.cacheOnly) {
            return;
          }

          injectHTML(inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<|endoftext|>


<commit_before>/* global d3:true */
/* global RSVP:true */
/* global SW:true */
'use strict';

///////////////////////////////////////////////////////////////////////////////
// START TICKET FILTERING
var assigneeIds     = [],
    dataArray       = [], // this will be passed to D3
    ticketsToChart  = [];

var callSW = function(){
  var promise = new RSVP.Promise(function(resolve, reject){
    var card = new SW.Card();
    var helpdesk = card.services('helpdesk');
    helpdesk.request('tickets')
      .then(function(data) {
        if (data.tickets.length > 0){
          resolve(data.tickets);
        } else {
          reject('err');
        }
      });
    });
  return promise;
};

////////////////////////////////////
// Get the tickets we want to chart
callSW().then(function(allTickets){
  ticketsToChart = allTickets.filter(function(ticket, index, arr){
    if (ticket.status === 'open' && ticket.assignee) { return ticket; }
  });
  ////////////////////////////////
  // Get an array of the assignees
  assigneeIds = ticketsToChart.map(function(ticket, index, arr){
    return ticket.assignee.id;
  });
  // http://stackoverflow.com/a/9229821/2276791
  var uniqIds = function(a) {
    var seen  = {},
        out   = [],
        len   = a.length,
        j     = 0;
    for(var i = 0; i < len; i++) {
      var item = a[i];
      if(seen[item] !== 1) {
        seen[item] = 1;
        out[j++] = item;
      }
    }
    return out;
  };
  assigneeIds = uniqIds(assigneeIds);

  // Calculate the days a ticket has been open
  var calcDaysOpen = function(time){
    var floatDays = (Date.now() - new Date(time))/(1000*60*60*24);
    return Math.floor(floatDays);
  };

  // Pull out relevant bits of the ticket in question
  var getTicketData = function(t){
    var info = {};
    info.ticketId = t.id;
    info.priority = t.priority;
    info.daysOpen = calcDaysOpen(t.created_at);
    info.reopened = t.reopened;
    return info;
  };

  // Used for splitting out each assignee's tickets...
  var theirTickets = function(assigneeId){
    return ticketsToChart.filter(function(t, index, arr){
      if (assigneeId === t.assignee.id){
        return t;
      }
    });
  };
  // ...done here.
  assigneeIds.forEach(function(a){
    var bucket = {
                  'assigneeId': a,
                  'assigneeName': '',
                  'tickets': []
                };
    var theseTickets = theirTickets(a);
    theseTickets.forEach(function(t){
      bucket.tickets.push(getTicketData(t));
    });
    dataArray.push(bucket);
    bucket = {};
  });

  // Prioritizing the tickets
  var priorities = []; // PRIORITIES!

  priorities.push(
    { priority: 'Low',
      data: []
    },
    { priority: 'Medium',
      data: []
    },
    { priority: 'High',
      data: []}
    );

  var getCount = function (data, priorityInt) {
    return data.tickets.filter( function(t,index,arr) {
      if ( t.priority === priorityInt ){ return 1; }
    }).length;
  };

  var assignPriorities = function(d, lowCount, medCount, highCount){
    priorities.forEach(function(p){
      if (p.priority === 'Low'){
        p.data.push({'assId': d.assigneeId, 'count': lowCount });
      } else if (p.priority === 'Medium'){
        p.data.push({'assId': d.assigneeId, 'count': medCount });
      } else if (p.priority === 'High'){
        p.data.push({'assId': d.assigneeId, 'count': highCount });
      } else {
        console.error('No priority noted for ticket ' + d);
      }
    });
  };

  // Prepare the data for processing by D3, here...
  dataArray.forEach(function(d){
    var lowCount = getCount(d, 1),
        medCount = getCount(d, 2),
        highCount = getCount(d, 3);

    assignPriorities(d, lowCount, medCount, highCount);
  });

  console.log(priorities);

  // ...and here
  var stackData = priorities.map(function (d){
    return d.data.map(function (t, i){
      return {
        y: t.count,
        x: t.assId
      };
    });
  });

  var priorityLevels = priorities.map(function (t){
    return t.priority;
  });

  ///////////////////////////////////////////////////////////////////////////////
  // GRAPH MAKING
  var width = 600,
      height = 500;

  var stack = d3.layout.stack();

  stack(stackData);

  stackData = stackData.map(function (group) {
    return group.map(function (d) {
      // Invert the x and y values, and y0 becomes x0
      return {
        x: d.y,
        y: d.x,
        x0: d.y0
      };
    });
  });

  //Set up scales
  var xMax = d3.max(stackData, function (group) {
      return d3.max(group, function (d) {
        return d.x + d.x0;
      });
  });

  var xScale = d3.scale.linear()
          .domain([0, xMax])
          .range([0, width]);

  // todo: programatically get names into an array
  var names = [29, 3, 2];
  // var names = ['Alice', 'Bob', 'Carol'];

  var yScale = d3.scale.ordinal()
          .domain(names)
          .rangeRoundBands([0, height], 0.1);

  var colors = d3.scale.category10();

  var canvas = d3.select('.jumbotron')
                  .append('svg')
                  .attr('width', width + 60)
                  .attr('height', height)
                  .append('g') //group the rects on the canvas
                  .attr('transform', 'translate(20, 0)');

  // Add a group for each row of data
  var groups = canvas.selectAll('g')
                  .data(stackData)
                  .enter()
                  .append('g')
                  .style('fill', function(d, i) {
                    return colors(i);
                  });

  var rects = groups.selectAll('rect')
          .data(function(d) { return d; })
          .enter()
          .append('rect')
          .attr('x', function(d) {
                  return xScale(d.x0);
          })
          .attr('y', function(d) {
                  return yScale(d.y);
          })
          .attr('height', function (d) {
            return yScale.rangeBand();
          })
          .attr('width', function(d) {
                  return xScale(d.x);
          })
          .on('mouseover', function (d) {
            var xPos = parseFloat(d3.select(this).attr('x')) + width;
            var yPos = parseFloat(d3.select(this).attr('y')) + yScale.rangeBand();
            console.log(xPos);
            console.log(yPos);
            d3.select('#d3-tooltip')
                .style('left', (xPos - (width / 2)) + 'px')
                .style('top', yPos + 'px')
                .select('#value')
                .text(d.x);
            d3.select('#d3-tooltip').classed('hidden', false);
        })
        .on('mouseout', function () {
          d3.select('#d3-tooltip').classed('hidden', true);
        });

  // Axis, no Allies
  var xAxis = d3.svg.axis()
      .scale(xScale)
      .ticks(stackData[0].length)
      .orient('bottom');

  var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient('left');

  canvas.append('g')
      .attr('class', 'axis')
      .attr('transform', 'translate(0,' + (height - 17) + ')')
      .call(xAxis);

  canvas.append('g')
      .attr('class', 'axis')
      .call(yAxis);
});
<commit_msg>Add note and sample code for iterating over user ids to get first names.<commit_after>/* global d3:true */
/* global RSVP:true */
/* global SW:true */
'use strict';

///////////////////////////////////////////////////////////////////////////////
// START TICKET FILTERING
var assigneeIds     = [],
    dataArray       = [], // this will be passed to D3
    ticketsToChart  = [];

var callSW = function(){
  var promise = new RSVP.Promise(function(resolve, reject){
    var card = new SW.Card();
    var helpdesk = card.services('helpdesk');
    helpdesk.request('tickets')
      .then(function(data) {
        if (data.tickets.length > 0){
          resolve(data.tickets);
        } else {
          reject('err');
        }
      });
    });
  return promise;
};

////////////////////////////////////
// Get the tickets we want to chart
callSW().then(function(allTickets){
  ticketsToChart = allTickets.filter(function(ticket, index, arr){
    if (ticket.status === 'open' && ticket.assignee) { return ticket; }
  });
  ////////////////////////////////
  // Get an array of the assignees
  assigneeIds = ticketsToChart.map(function(ticket, index, arr){
    return ticket.assignee.id;
  });
  // http://stackoverflow.com/a/9229821/2276791
  var uniqIds = function(a) {
    var seen  = {},
        out   = [],
        len   = a.length,
        j     = 0;
    for(var i = 0; i < len; i++) {
      var item = a[i];
      if(seen[item] !== 1) {
        seen[item] = 1;
        out[j++] = item;
      }
    }
    return out;
  };
  assigneeIds = uniqIds(assigneeIds);

  // Calculate the days a ticket has been open
  var calcDaysOpen = function(time){
    var floatDays = (Date.now() - new Date(time))/(1000*60*60*24);
    return Math.floor(floatDays);
  };

  // Pull out relevant bits of the ticket in question
  var getTicketData = function(t){
    var info = {};
    info.ticketId = t.id;
    info.priority = t.priority;
    info.daysOpen = calcDaysOpen(t.created_at);
    info.reopened = t.reopened;
    return info;
  };

  // Used for splitting out each assignee's tickets...
  var theirTickets = function(assigneeId){
    return ticketsToChart.filter(function(t, index, arr){
      if (assigneeId === t.assignee.id){
        return t;
      }
    });
  };
  // ...done here.
  assigneeIds.forEach(function(a){
    var bucket = {
                  'assigneeId': a,
                  'assigneeName': '',
                  'tickets': []
                };
    var theseTickets = theirTickets(a);
    theseTickets.forEach(function(t){
      bucket.tickets.push(getTicketData(t));
    });
    dataArray.push(bucket);
    bucket = {};
  });

  // Prioritizing the tickets
  var priorities = []; // PRIORITIES!

  priorities.push(
    { priority: 'Low',
      data: []
    },
    { priority: 'Medium',
      data: []
    },
    { priority: 'High',
      data: []}
    );

  var getCount = function (data, priorityInt) {
    return data.tickets.filter( function(t,index,arr) {
      if ( t.priority === priorityInt ){ return 1; }
    }).length;
  };

  var assignPriorities = function(d, lowCount, medCount, highCount){
    priorities.forEach(function(p){
      if (p.priority === 'Low'){
        p.data.push({'assId': d.assigneeId, 'count': lowCount });
      } else if (p.priority === 'Medium'){
        p.data.push({'assId': d.assigneeId, 'count': medCount });
      } else if (p.priority === 'High'){
        p.data.push({'assId': d.assigneeId, 'count': highCount });
      } else {
        console.error('No priority noted for ticket ' + d);
      }
    });
  };

  // Prepare the data for processing by D3, here...
  dataArray.forEach(function(d){
    var lowCount = getCount(d, 1),
        medCount = getCount(d, 2),
        highCount = getCount(d, 3);

    assignPriorities(d, lowCount, medCount, highCount);
  });

  console.log(priorities);

  // ...and here
  var stackData = priorities.map(function (d){
    return d.data.map(function (t, i){
      return {
        y: t.count,
        x: t.assId
      };
    });
  });

  var priorityLevels = priorities.map(function (t){
    return t.priority;
  });

  ///////////////////////////////////////////////////////////////////////////////
  // GRAPH MAKING
  var width = 600,
      height = 500;

  var stack = d3.layout.stack();

  stack(stackData);

  stackData = stackData.map(function (group) {
    return group.map(function (d) {
      // Invert the x and y values, and y0 becomes x0
      return {
        x: d.y,
        y: d.x,
        x0: d.y0
      };
    });
  });

  //Set up scales
  var xMax = d3.max(stackData, function (group) {
      return d3.max(group, function (d) {
        return d.x + d.x0;
      });
  });

  var xScale = d3.scale.linear()
          .domain([0, xMax])
          .range([0, width]);

  // todo: programatically get names into an array
  var names = [29, 3, 2];
  // var names = ['Alice', 'Bob', 'Carol'];

  // todo: implement this to get the names and stuff:
  // card.services('environment').request('user', 2).then(function(data){console.log(data.first_name)})

  var yScale = d3.scale.ordinal()
          .domain(names)
          .rangeRoundBands([0, height], 0.1);

  var colors = d3.scale.category10();

  var canvas = d3.select('.jumbotron')
                  .append('svg')
                  .attr('width', width + 60)
                  .attr('height', height)
                  .append('g') //group the rects on the canvas
                  .attr('transform', 'translate(20, 0)');

  // Add a group for each row of data
  var groups = canvas.selectAll('g')
                  .data(stackData)
                  .enter()
                  .append('g')
                  .style('fill', function(d, i) {
                    return colors(i);
                  });

  var rects = groups.selectAll('rect')
          .data(function(d) { return d; })
          .enter()
          .append('rect')
          .attr('x', function(d) {
                  return xScale(d.x0);
          })
          .attr('y', function(d) {
                  return yScale(d.y);
          })
          .attr('height', function (d) {
            return yScale.rangeBand();
          })
          .attr('width', function(d) {
                  return xScale(d.x);
          })
          .on('mouseover', function (d) {
            var xPos = parseFloat(d3.select(this).attr('x')) + width;
            var yPos = parseFloat(d3.select(this).attr('y')) + yScale.rangeBand();
            console.log(xPos);
            console.log(yPos);
            d3.select('#d3-tooltip')
                .style('left', (xPos - (width / 2)) + 'px')
                .style('top', yPos + 'px')
                .select('#value')
                .text(d.x);
            d3.select('#d3-tooltip').classed('hidden', false);
        })
        .on('mouseout', function () {
          d3.select('#d3-tooltip').classed('hidden', true);
        });

  // Axis, no Allies
  var xAxis = d3.svg.axis()
      .scale(xScale)
      .ticks(stackData[0].length)
      .orient('bottom');

  var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient('left');

  canvas.append('g')
      .attr('class', 'axis')
      .attr('transform', 'translate(0,' + (height - 17) + ')')
      .call(xAxis);

  canvas.append('g')
      .attr('class', 'axis')
      .call(yAxis);
});
<|endoftext|>


<commit_before>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll.min',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',
    QBNotification: '../bower_components/web-notifications/qbNotification',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // events
    Events: 'events',
    // helpers
    Helpers: 'helpers',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone', 'QBNotification',
  'Helpers'
], function ($, QMCONFIG, minEmoji, QM, Backbone, QBNotification, Helpers) {
  var APP;

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      Helpers.showInConsole('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      if (QMCONFIG.notification && QBNotification.isSupported()) {
        QBNotification.requestPermission();
      }

      APP = new QM();
      APP.init();
    });

    $.getScript('https://cdn.flurry.com/js/flurry.js', function() {
      FlurryAgent.startSession('ZJQZKGMMMFTWMBRZ7G63');
    });
  });

});
<commit_msg>changed apiKey<commit_after>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll.min',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',
    QBNotification: '../bower_components/web-notifications/qbNotification',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // events
    Events: 'events',
    // helpers
    Helpers: 'helpers',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone', 'QBNotification',
  'Helpers'
], function ($, QMCONFIG, minEmoji, QM, Backbone, QBNotification, Helpers) {
  var APP;

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      Helpers.showInConsole('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      if (QMCONFIG.notification && QBNotification.isSupported()) {
        QBNotification.requestPermission();
      }

      APP = new QM();
      APP.init();
    });

    $.getScript('https://cdn.flurry.com/js/flurry.js', function() {
      FlurryAgent.startSession('P8NWM9PBFCK2CWC8KZ59');
    });
  });

});
<|endoftext|>


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

  var querySelector = document.querySelector.bind(document);

  var navdrawerContainer = querySelector('.navdrawer-container');
  var body = document.body;
  var appbarElement = querySelector('.app-bar');
  var menuBtn = querySelector('.menu');
  var main = querySelector('main');

  function closeMenu() {
    body.classList.remove('open');
    appbarElement.classList.remove('open');
    navdrawerContainer.classList.remove('open');
  }

  function toggleMenu() {
    body.classList.toggle('open');
    appbarElement.classList.toggle('open');
    navdrawerContainer.classList.toggle('open');
  }

  main.addEventListener('click', closeMenu);
  menuBtn.addEventListener('click', toggleMenu);
  navdrawerContainer.addEventListener('click', function (event) {
    if (event.target.nodeName === 'A' || event.target.nodeName === 'LI') {
      closeMenu();
    }
  });

  var map = L.map('map').setView([51.505, -0.09], 13);
  L.tileLayer('http://{s}.tiles.mapbox.com/v3/MapID/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    maxZoom: 18
  }).addTo(map);

})();
<commit_msg>add geolocation request<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
(function () {
  'use strict';

  var querySelector = document.querySelector.bind(document);

  var navdrawerContainer = querySelector('.navdrawer-container');
  var body = document.body;
  var appbarElement = querySelector('.app-bar');
  var menuBtn = querySelector('.menu');
  var main = querySelector('main');

  function closeMenu() {
    body.classList.remove('open');
    appbarElement.classList.remove('open');
    navdrawerContainer.classList.remove('open');
  }

  function toggleMenu() {
    body.classList.toggle('open');
    appbarElement.classList.toggle('open');
    navdrawerContainer.classList.toggle('open');
  }

  main.addEventListener('click', closeMenu);
  menuBtn.addEventListener('click', toggleMenu);
  navdrawerContainer.addEventListener('click', function (event) {
    if (event.target.nodeName === 'A' || event.target.nodeName === 'LI') {
      closeMenu();
    }
  });

  var map = L.map('map');

  L.tileLayer('http://{s}.tiles.mapbox.com/v3/MapID/997/256/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    maxZoom: 18
  }).addTo(map);

  map.locate({setView: true, maxZoom: 16});

})();
<|endoftext|>