<commit_before>var bodyParser = require('body-parser');
var logger = require('morgan');
var glob = require('glob');
var favicon = require('serve-favicon');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

var db, server;

module.exports = function (app, config) {
    app.use(logger('dev'));

    // connect to databse
    var url = config.db;
    MongoClient.connect(url, function(err, database) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            db = database;

            // insert status collection
            db.collection(CONSTANTS.COLLECTION.STATUS).findOne({
                name: "status"
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                } else if (!doc) {
                    db.collection(CONSTANTS.COLLECTION.STATUS).insertOne({
                        name: "status",
                        running: true
                    }, (err, result) => {
                        if (err) {
                            console.log(err);
                            db.close();
                            server.close();
                            process.exit(0);
                        }
                    });
                }
            });

            const controllers = glob.sync(config.root + '/controllers/*.js');
            controllers.forEach(controller => {
                require(controller)(app, db);
                // import {default as func} from controller

                console.log(">> Deployed controller: " + controller + "\n");
                // This means "for each controller file, load that file using require, then
                // call the default function that's exported, with app as a parameter.
                // Those default functions just say 'hey app, use these routes.'"
            });

            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({
                extended: true
            }));

            // external module for handling favourite icon
            app.use(favicon(__dirname + "/../public/img/favicon.ico"));

            // view engine
            app.set('views', config.root + '/public/views');
            app.set("view engine", "pug");

            // middleware for handling file downloads
            app.get("*", function(req, res, next) {
                if (fs.existsSync(config.root + req.url)) {
                    let file = config.root + req.url;
                    res.download(file);
                } else {
                    const err = new Error("Not Found");
                    res.status(404);
                    next(err);
                }
            });

            // middlewares for handling uncaught errors
            app.use((req, res, next) => {
                const err = new Error("Not Found");
                res.status(404);
                next(err);
            });

            app.use((err, req, res, next) => {
                console.log(err);
                res.status(err.status || 500);
                res.json({ error: error.message });
            });

            // listening on port 3000
            server = app.listen(3000, function () {
                console.log("Server listening on port 3000...\n");
            });
        }
    });

    // when ^C is pressed
    process.on('SIGINT', function() {
        const readline = require('readline');
        readline.clearLine(process.stdout, 0);

        console.log("\nDisconnecting from database...");
        db.close();

        console.log("Killing server...");
        server.close();

        console.log("Bye!");
        process.exit(0);
    })
}
<commit_msg>Added missing imports<commit_after>var bodyParser = require('body-parser');
var logger = require('morgan');
var glob = require('glob');
var favicon = require('serve-favicon');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

const CONSTANTS = require("../config/constants");

var db, server;

module.exports = function (app, config) {
    app.use(logger('dev'));

    // connect to databse
    var url = config.db;
    MongoClient.connect(url, function(err, database) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            db = database;

            // insert status collection
            db.collection(CONSTANTS.COLLECTION.STATUS).findOne({
                name: "status"
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                } else if (!doc) {
                    db.collection(CONSTANTS.COLLECTION.STATUS).insertOne({
                        name: "status",
                        running: true
                    }, (err, result) => {
                        if (err) {
                            console.log(err);
                            db.close();
                            server.close();
                            process.exit(0);
                        }
                    });
                }
            });

            const controllers = glob.sync(config.root + '/controllers/*.js');
            controllers.forEach(controller => {
                require(controller)(app, db);
                // import {default as func} from controller

                console.log(">> Deployed controller: " + controller + "\n");
                // This means "for each controller file, load that file using require, then
                // call the default function that's exported, with app as a parameter.
                // Those default functions just say 'hey app, use these routes.'"
            });

            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({
                extended: true
            }));

            // external module for handling favourite icon
            app.use(favicon(__dirname + "/../public/img/favicon.ico"));

            // view engine
            app.set('views', config.root + '/public/views');
            app.set("view engine", "pug");

            // middleware for handling file downloads
            app.get("*", function(req, res, next) {
                if (fs.existsSync(config.root + req.url)) {
                    let file = config.root + req.url;
                    res.download(file);
                } else {
                    const err = new Error("Not Found");
                    res.status(404);
                    next(err);
                }
            });

            // middlewares for handling uncaught errors
            app.use((req, res, next) => {
                const err = new Error("Not Found");
                res.status(404);
                next(err);
            });

            app.use((err, req, res, next) => {
                console.log(err);
                res.status(err.status || 500);
                res.json({ error: error.message });
            });

            // listening on port 3000
            server = app.listen(3000, function () {
                console.log("Server listening on port 3000...\n");
            });
        }
    });

    // when ^C is pressed
    process.on('SIGINT', function() {
        const readline = require('readline');
        readline.clearLine(process.stdout, 0);

        console.log("\nDisconnecting from database...");
        db.close();

        console.log("Killing server...");
        server.close();

        console.log("Bye!");
        process.exit(0);
    })
}
<|endoftext|>


<commit_before>/* eslint-env browser */

import React, { PureComponent } from 'react';
import { SpeedDial, SpeedDialItem } from 'react-mui-speeddial';
import Add from 'material-ui/svg-icons/content/add';
import Close from 'material-ui/svg-icons/navigation/close';
import Done from 'material-ui/svg-icons/action/done';
import LightbulbOutline from 'material-ui/svg-icons/action/lightbulb-outline';
import { green600, yellow800 } from 'material-ui/styles/colors';
import shortid from 'shortid';
import { HotKeys } from 'react-hotkeys';

import NewTaskDialog from './NewTaskDialog';
import NewIdeaDialog from './NewIdeaDialog';

class FAB extends PureComponent {
  constructor() {
    super();
    this.state = {
      taskDialogOpen: false,
      ideaDialogOpen: false,
    };
    this.keyMap = {
      addNewIdea: 'ctrl+i',
      addNewTask: 'ctrl+t',
    };
  }
  handleRequestClose = () => {
    this.setState({
      taskDialogOpen: false,
      ideaDialogOpen: false,
    });
  }
  handleRequestTaskDialogOpen = () => {
    this.setState({
      taskDialogOpen: true,
    });
  }
  handleRequestIdeaDialogOpen = () => {
    this.setState({
      ideaDialogOpen: true,
    });
  }
  handleRequestTaskAdd = (taskInfo) => {
    const repetitionDays = taskInfo.repetition * taskInfo.repetitionValue;
    const id = shortid.generate();
    let offset = 0;
    if (this.props.calendarSystem === 'fa-IR') {
      offset = 56429000;
    }
    this.props.addTask({
      task: taskInfo.task,
      start: taskInfo.start - offset,
      end: (taskInfo.end + 86400000) - offset,
      estimation: taskInfo.estimation * taskInfo.estimationValue,
      repetition: repetitionDays,
      done: false,
      id,
    });
  }
  handleRequestIdeaAdd = (ideaInfo) => {
    const id = shortid.generate();
    this.props.addIdea({
      idea: ideaInfo.idea,
      id,
    });
  }
  render() {
    const styles = {
      speedDial: {
        position: 'absolute',
        right: '20px',
        bottom: '20px',
        zIndex: 1000,
      },
      newTask: {
        color: green600,
      },
      newIdea: {
        color: yellow800,
      },
    };
    const handlers = {
      addNewIdea: this.handleRequestIdeaDialogOpen,
      addNewTask: this.handleRequestTaskDialogOpen,
    };
    return (
      <HotKeys
        focused
        attach={window}
        keyMap={this.keyMap}
        handlers={handlers}
      >
        <SpeedDial
          className="SpeedDial"
          fabContentOpen={<Add />}
          fabContentClose={<Close />}
          style={styles.speedDial}
        >
          <SpeedDialItem
            fabContent={<Done />}
            onTouchTap={this.handleRequestTaskDialogOpen}
          />
          <SpeedDialItem
            fabContent={<LightbulbOutline />}
            onTouchTap={this.handleRequestIdeaDialogOpen}
          />
          <NewTaskDialog
            open={this.state.taskDialogOpen}
            onRequestClose={this.handleRequestClose}
            onRequestAdd={this.handleRequestTaskAdd}
            calendarSystem={this.props.calendarSystem}
            firstDayOfWeek={this.props.firstDayOfWeek}
          />
          <NewIdeaDialog
            open={this.state.ideaDialogOpen}
            onRequestClose={this.handleRequestClose}
            onRequestAdd={this.handleRequestIdeaAdd}
          />
        </SpeedDial>
      </HotKeys>
    );
  }
}

export default FAB;
<commit_msg>Add FAB item labels<commit_after>/* eslint-env browser */

import React, { PureComponent } from 'react';
import { SpeedDial, SpeedDialItem } from 'react-mui-speeddial';
import Add from 'material-ui/svg-icons/content/add';
import Close from 'material-ui/svg-icons/navigation/close';
import Done from 'material-ui/svg-icons/action/done';
import LightbulbOutline from 'material-ui/svg-icons/action/lightbulb-outline';
import { green600, yellow800 } from 'material-ui/styles/colors';
import shortid from 'shortid';
import { HotKeys } from 'react-hotkeys';

import NewTaskDialog from './NewTaskDialog';
import NewIdeaDialog from './NewIdeaDialog';

class FAB extends PureComponent {
  constructor() {
    super();
    this.state = {
      taskDialogOpen: false,
      ideaDialogOpen: false,
    };
    this.keyMap = {
      addNewIdea: 'ctrl+i',
      addNewTask: 'ctrl+t',
    };
  }
  handleRequestClose = () => {
    this.setState({
      taskDialogOpen: false,
      ideaDialogOpen: false,
    });
  }
  handleRequestTaskDialogOpen = () => {
    this.setState({
      taskDialogOpen: true,
    });
  }
  handleRequestIdeaDialogOpen = () => {
    this.setState({
      ideaDialogOpen: true,
    });
  }
  handleRequestTaskAdd = (taskInfo) => {
    const repetitionDays = taskInfo.repetition * taskInfo.repetitionValue;
    const id = shortid.generate();
    let offset = 0;
    if (this.props.calendarSystem === 'fa-IR') {
      offset = 56429000;
    }
    this.props.addTask({
      task: taskInfo.task,
      start: taskInfo.start - offset,
      end: (taskInfo.end + 86400000) - offset,
      estimation: taskInfo.estimation * taskInfo.estimationValue,
      repetition: repetitionDays,
      done: false,
      id,
    });
  }
  handleRequestIdeaAdd = (ideaInfo) => {
    const id = shortid.generate();
    this.props.addIdea({
      idea: ideaInfo.idea,
      id,
    });
  }
  render() {
    const styles = {
      speedDial: {
        position: 'absolute',
        right: '20px',
        bottom: '20px',
        zIndex: 1000,
      },
      newTask: {
        color: green600,
      },
      newIdea: {
        color: yellow800,
      },
    };
    const handlers = {
      addNewIdea: this.handleRequestIdeaDialogOpen,
      addNewTask: this.handleRequestTaskDialogOpen,
    };
    return (
      <HotKeys
        focused
        attach={window}
        keyMap={this.keyMap}
        handlers={handlers}
      >
        <SpeedDial
          className="SpeedDial"
          fabContentOpen={<Add />}
          fabContentClose={<Close />}
          style={styles.speedDial}
        >
          <SpeedDialItem
            fabContent={<Done />}
            label="Task"
            onTouchTap={this.handleRequestTaskDialogOpen}
          />
          <SpeedDialItem
            fabContent={<LightbulbOutline />}
            label="Idea"
            onTouchTap={this.handleRequestIdeaDialogOpen}
          />
          <NewTaskDialog
            open={this.state.taskDialogOpen}
            onRequestClose={this.handleRequestClose}
            onRequestAdd={this.handleRequestTaskAdd}
            calendarSystem={this.props.calendarSystem}
            firstDayOfWeek={this.props.firstDayOfWeek}
          />
          <NewIdeaDialog
            open={this.state.ideaDialogOpen}
            onRequestClose={this.handleRequestClose}
            onRequestAdd={this.handleRequestIdeaAdd}
          />
        </SpeedDial>
      </HotKeys>
    );
  }
}

export default FAB;
<|endoftext|>


<commit_before>// Urls
const containsUrl = str => window.location.href.indexOf(str) > -1
const endsWithUrl = str => window.location.href.endsWith(str)

// Return url search keys and values
const urlString = Object.assign({}, ...window.location.search.slice(1).split('&').map(item => {
	const property = item.split('=')[0]
	return { [property]: item.split('=')[1] }
}))

// Page
const page = () => {
  if (containsUrl('/events/'))  					return 'Event'
  if (endsWithUrl('/update'))  						return 'Update'
  return null
}

// Form page
const isFormPage = () => page() === 'Event' || page() === 'Update'

// Event Reg Form
const webflowRegForm = getElementByClassName('event-registration', 0)
const regForm = getElementByClassName('container reg-form')

// Hidden fields
const eventCode = getText(getElementById('event-code')).toUpperCase(),
eventName = getText(getElementById('event-name')),
eventDates = getText(getElementById('event-dates')),
eventVenue = getText(getElementById('event-venue')),
eventDepositAmount = parseFloat(getText(getElementById('event-deposit-amount'))).toFixed(2),
eventDepositDate = getText(getElementById('event-deposit-date')),
eventBasePrice = parseFloat(getText(getElementById('event-base-price'))).toFixed(2),
eventBaseCost = parseFloat(getText(getElementById('event-base-cost'))).toFixed(2),
eventStatusRestriction = getText(getElementById('event-status-restriction'))

// Invite-only
const eventInviteButton = getElementById('event-invitecode-button'),
eventInviteBox = getElementById('event-invitecode-box'),
eventInviteCode = getElementById('event-invitecode-code'),
eventInvitePass = getElementById('event-invitecode-pass'),
eventInviteFail = getElementById('event-invitecode-fail')

// Personal
const eventFirstName = getElementById('event-firstname'),
eventLastName = getElementById('event-lastname'),
eventEmail = getElementById('event-email'),
eventMobile = getElementById('event-mobile'),
eventBirthdate = getElementById('event-birthdate'),
eventGenderValidation = getElementById('event-gender-validation'),
eventFemale = getElementById('event-gender-female'),
eventMale = getElementById('event-gender-male'),
eventOther = getElementById('event-gender-other')

// Details
const eventReferral = getElementById('event-referral'),
eventExperienceContainer = getElementByClassName('container experience'),
eventExperienceValidation = getElementById('event-experience-validation'),
eventExperienceYes = getElementById('event-experience-yes'),
eventExperienceNo = getElementById('event-experience-no'),
eventExperienceDetails = getElementById('event-experience-details'),
eventDietContainer = getElementByClassName('container diet'),
eventDietValidation = getElementById('event-diet-validation'),
eventDietYes = getElementById('event-diet-yes'),
eventDietNo = getElementById('event-diet-no'),
eventDietDetails = getElementById('event-diet-details'),
eventSpecialContainer = getElementByClassName('container special'),
eventSpecialValidation = getElementById('event-special-validation'),
eventSpecialYes = getElementById('event-special-yes'),
eventSpecialNo = getElementById('event-special-no'),
eventSpecialDetails = getElementById('event-special-details')

// Affiliate Code
const eventAffiliateContainer = getElementByClassName('container affiliate'),
eventAffiliateCodeContainer = getElementByClassName('container affiliate-code'),
eventAffiliateValidation = getElementById('event-affiliate-validation'),
eventAffiliateYes = getElementById('event-affiliate-yes'),
eventAffiliateNo = getElementById('event-affiliate-no'),
eventAffiliateCode = getElementById('event-affiliate-code'),
eventAffiliatePass = getElementById('event-affiliate-pass'),
eventAffiliateFail = getElementById('event-affiliate-fail')
const urlDiscountCode = urlString && urlString.affiliate
	? urlString.affiliate
	: null

// Event Status: Couples, Singles, Both
const eventStatus = getElementById('event-status'),
eventPartnerContainer = getElementByClassName('container partner'),
eventPartnerFirstName = getElementById('event-partner-firstname'),
eventPartnerLastName = getElementById('event-partner-lastname'),
eventPartnerGenderValidation = getElementById('event-partner-gender-validation'),
eventPartnerFemale = getElementById('event-partner-gender-female'),
eventPartnerMale = getElementById('event-partner-gender-male'),
eventPartnerOther = getElementById('event-partner-gender-other'),
eventPayValidation = getElementById('event-pay-validation'),
eventPayBoth = getElementById('event-pay-both'),
eventPayMe = getElementById('event-pay-me')

// Registration options
const eventOption = getElementById('event-option'),
eventOptions = getText(getElementById('event-options')).split(' | '),
eventNotes = getText(getElementById('event-notes')).includes('|')
	? getText(getElementById('event-notes')).split('|')
	: getText(getElementById('event-notes')).split(',')

// Pricing
const eventPrices = getText(getElementById('event-prices')).split(' | '),
eventDepositContainer = getElementByClassName('container deposit'),
eventDepositValidation = getElementById('event-deposit-validation'),
eventDepositText = getElementById('event-deposit-text'),
eventDepositFull = getElementById('event-deposit-full'),
eventDepositDeposit = getElementById('event-deposit-deposit'),
eventAmountContainer = getElementByClassName('container amount'),
eventAmountDisplay = getElementById('event-amount-display'),
eventAmountShow = getElementById('event-amount-show')

// Terms
const eventTermsValidation = getElementById('event-terms-validation'),
eventTerms = getElementById('event-terms')

// Stripe billing variables
const billingFirstName = getElementById('billing-firstname'),
billingLastName = getElementById('billing-lastname'),
billingStreet = getElementById('billing-street'),
billingCity = getElementById('billing-city'),
billingState = getElementById('billing-state'),
billingPostal = getElementById('billing-postal'),
billingCountry = getElementById('country'),
billingCard = getElementById('billing-card'),
billingCardError = getElementById('billing-card-error')

// Pay now
const paymentButton = getElementById('payment-button')<commit_msg>Reg form modal display.<commit_after>// Urls
const containsUrl = str => window.location.href.indexOf(str) > -1
const endsWithUrl = str => window.location.href.endsWith(str)

// Return url search keys and values
const urlString = Object.assign({}, ...window.location.search.slice(1).split('&').map(item => {
	const property = item.split('=')[0]
	return { [property]: item.split('=')[1] }
}))

// Page
const page = () => {
  if (containsUrl('/events/'))  					return 'Event'
  if (endsWithUrl('/update'))  						return 'Update'
  return null
}

// Form page
const isFormPage = () => page() === 'Event' || page() === 'Update'

// Event Reg Form
const webflowRegForm = getElementByClassName('reg-form', 0)
const regForm = getElementByClassName('container reg-form')

// Hidden fields
const eventCode = getText(getElementById('event-code')).toUpperCase(),
eventName = getText(getElementById('event-name')),
eventDates = getText(getElementById('event-dates')),
eventVenue = getText(getElementById('event-venue')),
eventDepositAmount = parseFloat(getText(getElementById('event-deposit-amount'))).toFixed(2),
eventDepositDate = getText(getElementById('event-deposit-date')),
eventBasePrice = parseFloat(getText(getElementById('event-base-price'))).toFixed(2),
eventBaseCost = parseFloat(getText(getElementById('event-base-cost'))).toFixed(2),
eventStatusRestriction = getText(getElementById('event-status-restriction'))

// Invite-only
const eventInviteButton = getElementById('event-invitecode-button'),
eventInviteBox = getElementById('event-invitecode-box'),
eventInviteCode = getElementById('event-invitecode-code'),
eventInvitePass = getElementById('event-invitecode-pass'),
eventInviteFail = getElementById('event-invitecode-fail')

// Personal
const eventFirstName = getElementById('event-firstname'),
eventLastName = getElementById('event-lastname'),
eventEmail = getElementById('event-email'),
eventMobile = getElementById('event-mobile'),
eventBirthdate = getElementById('event-birthdate'),
eventGenderValidation = getElementById('event-gender-validation'),
eventFemale = getElementById('event-gender-female'),
eventMale = getElementById('event-gender-male'),
eventOther = getElementById('event-gender-other')

// Details
const eventReferral = getElementById('event-referral'),
eventExperienceContainer = getElementByClassName('container experience'),
eventExperienceValidation = getElementById('event-experience-validation'),
eventExperienceYes = getElementById('event-experience-yes'),
eventExperienceNo = getElementById('event-experience-no'),
eventExperienceDetails = getElementById('event-experience-details'),
eventDietContainer = getElementByClassName('container diet'),
eventDietValidation = getElementById('event-diet-validation'),
eventDietYes = getElementById('event-diet-yes'),
eventDietNo = getElementById('event-diet-no'),
eventDietDetails = getElementById('event-diet-details'),
eventSpecialContainer = getElementByClassName('container special'),
eventSpecialValidation = getElementById('event-special-validation'),
eventSpecialYes = getElementById('event-special-yes'),
eventSpecialNo = getElementById('event-special-no'),
eventSpecialDetails = getElementById('event-special-details')

// Affiliate Code
const eventAffiliateContainer = getElementByClassName('container affiliate'),
eventAffiliateCodeContainer = getElementByClassName('container affiliate-code'),
eventAffiliateValidation = getElementById('event-affiliate-validation'),
eventAffiliateYes = getElementById('event-affiliate-yes'),
eventAffiliateNo = getElementById('event-affiliate-no'),
eventAffiliateCode = getElementById('event-affiliate-code'),
eventAffiliatePass = getElementById('event-affiliate-pass'),
eventAffiliateFail = getElementById('event-affiliate-fail')
const urlDiscountCode = urlString && urlString.affiliate
	? urlString.affiliate
	: null

// Event Status: Couples, Singles, Both
const eventStatus = getElementById('event-status'),
eventPartnerContainer = getElementByClassName('container partner'),
eventPartnerFirstName = getElementById('event-partner-firstname'),
eventPartnerLastName = getElementById('event-partner-lastname'),
eventPartnerGenderValidation = getElementById('event-partner-gender-validation'),
eventPartnerFemale = getElementById('event-partner-gender-female'),
eventPartnerMale = getElementById('event-partner-gender-male'),
eventPartnerOther = getElementById('event-partner-gender-other'),
eventPayValidation = getElementById('event-pay-validation'),
eventPayBoth = getElementById('event-pay-both'),
eventPayMe = getElementById('event-pay-me')

// Registration options
const eventOption = getElementById('event-option'),
eventOptions = getText(getElementById('event-options')).split(' | '),
eventNotes = getText(getElementById('event-notes')).includes('|')
	? getText(getElementById('event-notes')).split('|')
	: getText(getElementById('event-notes')).split(',')

// Pricing
const eventPrices = getText(getElementById('event-prices')).split(' | '),
eventDepositContainer = getElementByClassName('container deposit'),
eventDepositValidation = getElementById('event-deposit-validation'),
eventDepositText = getElementById('event-deposit-text'),
eventDepositFull = getElementById('event-deposit-full'),
eventDepositDeposit = getElementById('event-deposit-deposit'),
eventAmountContainer = getElementByClassName('container amount'),
eventAmountDisplay = getElementById('event-amount-display'),
eventAmountShow = getElementById('event-amount-show')

// Terms
const eventTermsValidation = getElementById('event-terms-validation'),
eventTerms = getElementById('event-terms')

// Stripe billing variables
const billingFirstName = getElementById('billing-firstname'),
billingLastName = getElementById('billing-lastname'),
billingStreet = getElementById('billing-street'),
billingCity = getElementById('billing-city'),
billingState = getElementById('billing-state'),
billingPostal = getElementById('billing-postal'),
billingCountry = getElementById('country'),
billingCard = getElementById('billing-card'),
billingCardError = getElementById('billing-card-error')

// Pay now
const paymentButton = getElementById('payment-button')<|endoftext|>


<commit_before>module.exports = {
	views: [{
		"name": "Match Strategy Profile",
		"views": [
            {
                "name": "stratAverages",
                "disableInfo": true,
                "disablePaging": true,
                "colorcode": true
            },
            {
                "name": "matches",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            },
            {
                "name": "comments",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            }
        ]
	},{
		"name": "Alliance Selection Profile",
		"views": [
            {
                "name": "selecAverages",
                "disableInfo": true,
                "disablePaging": true,
                "colorcode": true
            },
            {
                "name": "matches",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            },
            {
                "name": "comments",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            }
        ]
	},{
		"name": "Raw Match Data",
		"views": [
            {
                "name": "matches",
                "disableInfo": true,
                "disablePaging": true
            }
        ]
	}],

    query: [
      {
          $match: {"competition": 2017}
      },
      {
          $group: {
              _id: {
                  "team": '$team',
                  "event": '$event'
              },

              "baseline": { $avg: '$baseline' },

              "auto-low-kPa": { $avg: '$auto-low-kPa' },
              "teleop-low-kPa": { $avg: '$teleop-low-kPa' },

              "auto-high-kPa": { $avg: '$auto-high-kPa' },
              "teleop-high-kPa": { $avg: '$teleop-high-kPa' },

              "auto-gears": { $avg: '$auto-gears' },
              "teleop-gears": { $avg: '$teleop-gears' },

              "auto-max-gears": { $max: '$auto-gears' },
              "teleop-max-gears": { $max: '$teleop-gears' },

              "auto-drop-gears": { $avg: '$auto-drop-gears' },
              "teleop-drop-gears": { $avg: '$teleop-drop-gears' },

              "touchpad": { $avg: '$touchpad' },
              "touchpad-attempted": { $avg: '$touchpad-attempted' }
          }
      },
      {
         $addFields: {
           "touchpad-success": {
               $cond: [
                   { "$eq": ["$touchpad", 0] },
                   0,
                   { "$divide": ['$touchpad', '$touchpad-attempted']}
               ]
           },
           "auto-success-gears": {
               $cond: [
                   { "$eq": ["$auto-gears", 0] },
                   0,
                   { "$divide": ['$auto-gears', { "$sum": ["$auto-gears", "$auto-drop-gears"]}]}
               ]
           },
           "teleop-success-gears": {
               $cond: [
                   { "$eq": [{ "$sum": ["$teleop-gears", "$teleop-gears-dropped"]}, 0] },
                   0,
                   { "$divide": ['$teleop-gears', { "$sum": ["$teleop-gears", "$teleop-drop-gears"]}]}
               ]
           }
         }
      },
      {
         $addFields: {
           "total-gears-score": {
                "$multiply": [
                    { "$sum": ["$auto-gears", "$teleop-gears"] },
                    12.3
                ]
           },

           "total-kPa": { "$sum": [
                "$auto-low-kPa", "$teleop-low-kPa","$auto-high-kPa","teleop-high-kPa"
           ]},

           "total-gears": { "$sum": [
                "$auto-gears", "$teleop-gears"
           ]},
           "total-max-gears": { "$sum": [
                "$auto-max-gears", "$teleop-max-gears"
           ]},
           "total-drop-gears": { "$sum": [
                "$auto-drop-gears", "$teleop-drop-gears"
           ]},
         }
      },
      {
         $addFields: {
            "total-score": { "$sum": [
                    {"$multiply": [5, "$baseline"]},
                    "$total-gears-score",
                    "$total-kPa",
                    {"$multiply": [50, "$touchpad"]},
            ]}
         }
      },
      {
         $addFields: {
           "team": {"$substr":["$_id.team", 0, -1 ]},
           "event": "$_id.event",
           "baseline": { "$divide": [ { "$trunc": { "$multiply": ["$baseline", 20] } }, 20] },
           "auto-low-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$auto-low-kPa", 20] } }, 20] },
           "teleop-low-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-low-kPa", 20] } }, 20] },
           "auto-high-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$auto-high-kPa", 20] } }, 20] },
           "teleop-high-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-high-kPa", 20] } }, 20] },
           "total-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$total-kPa", 20] } }, 20] },
           "auto-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-gears", 20] } }, 20] },
           "teleop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-gears", 20] } }, 20] },
           "auto-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-drop-gears", 20] } }, 20] },
           "teleop-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-drop-gears", 20] } }, 20] },
           "total-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-drop-gears", 20] } }, 20] },
           "auto-success-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-drop-gears", 20] } }, 20] },
           "teleop-success-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-drop-gears", 20] } }, 20] },
           "total-gears-score": { "$divide": [ { "$trunc": { "$multiply": ["$total-gears-score", 20] } }, 20] },
           "total-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-gears", 20] } }, 20] },
           "total-max-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-max-gears", 20] } }, 20] },
           "total-score": { "$divide": [ { "$trunc": { "$multiply": ["$total-score", 20] } }, 20] },
           "touchpad": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad", 20] } }, 20] },
           "touchpad-attempted": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad-attempted", 20] } }, 20] },
           "touchpad-success": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad-success", 20] } }, 20] }
         }
      },
      {
          $project: {
              "_id": 0,
              "team": 1,
              "event": 1,
              "auto-gears": 1, // Avg. Auto Gears / Match
              "total-gears": 1, // Avg. Gears / Match
              "total-max-gears": 1, // Max. Gears / Match
              "total-drop-gears": 1, // Dropped Gears / Match
              "total-kPa": 1, // Avg. kPa / Match
              "touchpad": 1, // Avg. Climb / Match
              "touchpad-success": 1, // Avg. Climb / Attempt
              "total-score": 1 // Calculated Score
          }
      }
    ],

	matches: function (mongoCollection, callback) {
		mongoCollection
			.find({"competition": 2017})
			.sort({"_id": -1})
			.toArray(function (err, matches) {
				callback([
					{
                        name: "Team Matches",
                        cols: [2,3,4,5,6,7,8,9,10,11],
                        headers: [
                            {
                                text: "Team",
                                value: "team"
                            },
                            {
                                text: "Event",
                                value: "event"
                            },
                            {
                                text: "Baseline",
                                value: "baseline"
                            },
                            {
                                text: "Auto. Low Goal kPa",
                                value: "auto-low-kPa"
                            },
                            {
                                text: "Auto. High Goal kPa",
                                value: "auto-high-kPa"
                            },
                            {
                                text: "Auto. Gears Placed",
                                value: "auto-gears"
                            },
                            {
                                text: "Auto. Gears Dropped",
                                value: "auto-drop-gears"
                            },
                            {
                                text: "Teleop. Low Goal kPa",
                                value: "teleop-low-kPa"
                            },
                            {
                                text: "Teleop. High Goal kPa",
                                value: "teleop-high-kPa"
                            },
                            {
                                text: "Teleop. Gears Placed",
                                value: "teleop-gears"
                            },
                            {
                                text: "Teleop. Gears Dropped",
                                value: "teleop-drop-gears"
                            },
                            {
                                text: "Attempted Touchpad",
                                value: "touchpad-attempted"
                            },
                            {
                                text: "Pressed Touchpad",
                                value: "touchpad"
                            },
                            {
                                text: "Comments",
                                value: "comments"
                            }
                        ],
                        data: matches
					}
				]);

				db.close();
			});
	},

    comments: function (mongoCollection, callback) {
		mongoCollection
			.find({"competition": 2017, "comments": { $ne: "" }})
			.sort({"_id": -1})
			.toArray(function (err, matches) {
				callback([
					{
                        name: "Team Comments",
                        cols: [],
                        headers: [
                            {
                                text: "Team",
                                value: "team"
                            },
                            {
                                text: "Event",
                                value: "event"
                            },
                            {
                                text: "Comments",
                                value: "comments"
                            }
                        ],
                        data: matches
					}
				]);

				db.close();
			});
	},

    stratAverages: function (mongoCollection, callback) {
        mongoCollection.aggregate(this.query).toArray(function(err, matches) {
            callback([
                {
                    name: "Match Strategy Averages",
                    cols: [2,3,4,5,6,7],
                    headers: [
                        {
                            text: "Team",
                            value: "team"
                        },
                        {
                            text: "Event",
                            value: "event"
                        },
                        {
                            text: "Avg. Score",
                            value: "total-score"
                        },
                        {
                            text: "Avg. Gears Placed",
                            value: "total-gears"
                        },
                        {
                            text: "Max Gears Placed",
                            value: "total-max-gears"
                        },
                        {
                            text: "Climb Avg. / Match",
                            value: "touchpad"
                        },
                        {
                            text: "Climb Avg. / Attempt",
                            value: "touchpad-success"
                        },
                        {
                            text: "Avg. kPa",
                            value: "total-kPa"
                        }
                    ],
                    data: matches
                }
            ]);

            db.close();
        });
	}
};<commit_msg>Add Auto Gears<commit_after>module.exports = {
	views: [{
		"name": "Match Strategy Profile",
		"views": [
            {
                "name": "stratAverages",
                "disableInfo": true,
                "disablePaging": true,
                "colorcode": true
            },
            {
                "name": "matches",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            },
            {
                "name": "comments",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            }
        ]
	},{
		"name": "Alliance Selection Profile",
		"views": [
            {
                "name": "selecAverages",
                "disableInfo": true,
                "disablePaging": true,
                "colorcode": true
            },
            {
                "name": "matches",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            },
            {
                "name": "comments",
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ]
            }
        ]
	},{
		"name": "Raw Match Data",
		"views": [
            {
                "name": "matches",
                "disableInfo": true,
                "disablePaging": true
            }
        ]
	}],

    query: [
      {
          $match: {"competition": 2017}
      },
      {
          $group: {
              _id: {
                  "team": '$team',
                  "event": '$event'
              },

              "baseline": { $avg: '$baseline' },

              "auto-low-kPa": { $avg: '$auto-low-kPa' },
              "teleop-low-kPa": { $avg: '$teleop-low-kPa' },

              "auto-high-kPa": { $avg: '$auto-high-kPa' },
              "teleop-high-kPa": { $avg: '$teleop-high-kPa' },

              "auto-gears": { $avg: '$auto-gears' },
              "teleop-gears": { $avg: '$teleop-gears' },

              "auto-max-gears": { $max: '$auto-gears' },
              "teleop-max-gears": { $max: '$teleop-gears' },

              "auto-drop-gears": { $avg: '$auto-drop-gears' },
              "teleop-drop-gears": { $avg: '$teleop-drop-gears' },

              "touchpad": { $avg: '$touchpad' },
              "touchpad-attempted": { $avg: '$touchpad-attempted' }
          }
      },
      {
         $addFields: {
           "touchpad-success": {
               $cond: [
                   { "$eq": ["$touchpad", 0] },
                   0,
                   { "$divide": ['$touchpad', '$touchpad-attempted']}
               ]
           },
           "auto-success-gears": {
               $cond: [
                   { "$eq": ["$auto-gears", 0] },
                   0,
                   { "$divide": ['$auto-gears', { "$sum": ["$auto-gears", "$auto-drop-gears"]}]}
               ]
           },
           "teleop-success-gears": {
               $cond: [
                   { "$eq": [{ "$sum": ["$teleop-gears", "$teleop-gears-dropped"]}, 0] },
                   0,
                   { "$divide": ['$teleop-gears', { "$sum": ["$teleop-gears", "$teleop-drop-gears"]}]}
               ]
           }
         }
      },
      {
         $addFields: {
           "total-gears-score": {
                "$multiply": [
                    { "$sum": ["$auto-gears", "$teleop-gears"] },
                    12.3
                ]
           },

           "total-kPa": { "$sum": [
                "$auto-low-kPa", "$teleop-low-kPa","$auto-high-kPa","teleop-high-kPa"
           ]},

           "total-gears": { "$sum": [
                "$auto-gears", "$teleop-gears"
           ]},
           "total-max-gears": { "$sum": [
                "$auto-max-gears", "$teleop-max-gears"
           ]},
           "total-drop-gears": { "$sum": [
                "$auto-drop-gears", "$teleop-drop-gears"
           ]},
         }
      },
      {
         $addFields: {
            "total-score": { "$sum": [
                    {"$multiply": [5, "$baseline"]},
                    "$total-gears-score",
                    "$total-kPa",
                    {"$multiply": [50, "$touchpad"]},
            ]}
         }
      },
      {
         $addFields: {
           "team": {"$substr":["$_id.team", 0, -1 ]},
           "event": "$_id.event",
           "baseline": { "$divide": [ { "$trunc": { "$multiply": ["$baseline", 20] } }, 20] },
           "auto-low-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$auto-low-kPa", 20] } }, 20] },
           "teleop-low-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-low-kPa", 20] } }, 20] },
           "auto-high-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$auto-high-kPa", 20] } }, 20] },
           "teleop-high-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-high-kPa", 20] } }, 20] },
           "total-kPa": { "$divide": [ { "$trunc": { "$multiply": ["$total-kPa", 20] } }, 20] },
           "auto-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-gears", 20] } }, 20] },
           "teleop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-gears", 20] } }, 20] },
           "auto-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-drop-gears", 20] } }, 20] },
           "teleop-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-drop-gears", 20] } }, 20] },
           "total-drop-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-drop-gears", 20] } }, 20] },
           "auto-success-gears": { "$divide": [ { "$trunc": { "$multiply": ["$auto-drop-gears", 20] } }, 20] },
           "teleop-success-gears": { "$divide": [ { "$trunc": { "$multiply": ["$teleop-drop-gears", 20] } }, 20] },
           "total-gears-score": { "$divide": [ { "$trunc": { "$multiply": ["$total-gears-score", 20] } }, 20] },
           "total-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-gears", 20] } }, 20] },
           "total-max-gears": { "$divide": [ { "$trunc": { "$multiply": ["$total-max-gears", 20] } }, 20] },
           "total-score": { "$divide": [ { "$trunc": { "$multiply": ["$total-score", 20] } }, 20] },
           "touchpad": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad", 20] } }, 20] },
           "touchpad-attempted": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad-attempted", 20] } }, 20] },
           "touchpad-success": { "$divide": [ { "$trunc": { "$multiply": ["$touchpad-success", 20] } }, 20] }
         }
      },
      {
          $project: {
              "_id": 0,
              "team": 1,
              "event": 1,
              "auto-gears": 1, // Avg. Auto Gears / Match
              "total-gears": 1, // Avg. Gears / Match
              "total-max-gears": 1, // Max. Gears / Match
              "total-drop-gears": 1, // Dropped Gears / Match
              "total-kPa": 1, // Avg. kPa / Match
              "touchpad": 1, // Avg. Climb / Match
              "touchpad-success": 1, // Avg. Climb / Attempt
              "total-score": 1 // Calculated Score
          }
      }
    ],

	matches: function (mongoCollection, callback) {
		mongoCollection
			.find({"competition": 2017})
			.sort({"_id": -1})
			.toArray(function (err, matches) {
				callback([
					{
                        name: "Team Matches",
                        cols: [2,3,4,5,6,7,8,9,10,11],
                        headers: [
                            {
                                text: "Team",
                                value: "team"
                            },
                            {
                                text: "Event",
                                value: "event"
                            },
                            {
                                text: "Baseline",
                                value: "baseline"
                            },
                            {
                                text: "Auto. Low Goal kPa",
                                value: "auto-low-kPa"
                            },
                            {
                                text: "Auto. High Goal kPa",
                                value: "auto-high-kPa"
                            },
                            {
                                text: "Auto. Gears Placed",
                                value: "auto-gears"
                            },
                            {
                                text: "Auto. Gears Dropped",
                                value: "auto-drop-gears"
                            },
                            {
                                text: "Teleop. Low Goal kPa",
                                value: "teleop-low-kPa"
                            },
                            {
                                text: "Teleop. High Goal kPa",
                                value: "teleop-high-kPa"
                            },
                            {
                                text: "Teleop. Gears Placed",
                                value: "teleop-gears"
                            },
                            {
                                text: "Teleop. Gears Dropped",
                                value: "teleop-drop-gears"
                            },
                            {
                                text: "Attempted Touchpad",
                                value: "touchpad-attempted"
                            },
                            {
                                text: "Pressed Touchpad",
                                value: "touchpad"
                            },
                            {
                                text: "Comments",
                                value: "comments"
                            }
                        ],
                        data: matches
					}
				]);

				db.close();
			});
	},

    comments: function (mongoCollection, callback) {
		mongoCollection
			.find({"competition": 2017, "comments": { $ne: "" }})
			.sort({"_id": -1})
			.toArray(function (err, matches) {
				callback([
					{
                        name: "Team Comments",
                        cols: [],
                        headers: [
                            {
                                text: "Team",
                                value: "team"
                            },
                            {
                                text: "Event",
                                value: "event"
                            },
                            {
                                text: "Comments",
                                value: "comments"
                            }
                        ],
                        data: matches
					}
				]);

				db.close();
			});
	},

    stratAverages: function (mongoCollection, callback) {
        mongoCollection.aggregate(this.query).toArray(function(err, matches) {
            callback([
                {
                    name: "Match Strategy Averages",
                    cols: [2,3,4,5,6,7],
                    headers: [
                        {
                            text: "Team",
                            value: "team"
                        },
                        {
                            text: "Event",
                            value: "event"
                        },
                        {
                            text: "Avg. Score",
                            value: "total-score"
                        },
                        {
                            text: "Avg. Gears Placed",
                            value: "total-gears"
                        },
                        {
                            text: "Avg. Auto Gears Placed",
                            value: "auto-gears"
                        },
                        {
                            text: "Max. Gears Placed",
                            value: "total-max-gears"
                        },
                        {
                            text: "Climb Avg. / Match",
                            value: "touchpad"
                        },
                        {
                            text: "Climb Avg. / Attempt",
                            value: "touchpad-success"
                        },
                        {
                            text: "Avg. kPa",
                            value: "total-kPa"
                        }
                    ],
                    data: matches
                }
            ]);

            db.close();
        });
	}
};<|endoftext|>


<commit_before>/* eslint-disable no-template-curly-in-string */
// Do not edit this file - edit config.json instead.

const path = require("path");

const util = require("./util");

const loadJSON = util.loadJSON;
const saveJSON = util.saveJSON;

const defaultConfig = {
    eris: {
        token: "TOKEN GOES HERE",
        id: "CHANNEL ID GOES HERE",
        topicTimeout: 10000,
        playing: "Just Cause 3 Multiplayer"
    },
    formatting: {
        discordToGame: {
            chat: "${nick}: ${message}",
            colour: "7289DA"
        },
        gameToDiscord: {
            topic: "Join the server at xxx.xxx.xxx.xxx:port | ${players}/${maxPlayers} players currently online | Current tick rate: ${jcmp.server.currentTickRate}",
            chat: "${username}: ${message}",
            death: "${username} ${(killer && killer.name ? \"was killed by \" + killer.name : \"died\")}",
            connect: "${username} connected to the server.",
            disconnect: "${username} disconnected from the server."
        }
    }
};

function getFullConfig() {
    const configPath = path.join(__dirname, "./config.json");
    const loadedConfig = loadJSON(configPath);
    const fullConfig = Object.assign(defaultConfig, loadedConfig);

    if (fullConfig.length > loadedConfig.length) {
        fullConfig.lastUpdated = (new Date()).toUTCString();
        saveJSON(configPath, fullConfig);
    }

    return fullConfig;
}

module.exports = getFullConfig;
module.exports.defaultConfig = defaultConfig;
<commit_msg>Always save config for formatting<commit_after>/* eslint-disable no-template-curly-in-string */
// Do not edit this file - edit config.json instead.

const path = require("path");

const util = require("./util");

const loadJSON = util.loadJSON;
const saveJSON = util.saveJSON;

const defaultConfig = {
    eris: {
        token: "TOKEN GOES HERE",
        id: "CHANNEL ID GOES HERE",
        topicTimeout: 10000,
        playing: "Just Cause 3 Multiplayer"
    },
    formatting: {
        discordToGame: {
            chat: "${nick}: ${message}",
            colour: "7289DA"
        },
        gameToDiscord: {
            topic: "Join the server at xxx.xxx.xxx.xxx:port | ${players}/${maxPlayers} players currently online | Current tick rate: ${jcmp.server.currentTickRate}",
            chat: "${username}: ${message}",
            death: "${username} ${(killer && killer.name ? \"was killed by \" + killer.name : \"died\")}",
            connect: "${username} connected to the server.",
            disconnect: "${username} disconnected from the server."
        }
    }
};

function getFullConfig() {
    const configPath = path.join(__dirname, "./config.json");
    const loadedConfig = loadJSON(configPath);
    const fullConfig = Object.assign(defaultConfig, loadedConfig);

    if (fullConfig.length > loadedConfig.length) {
        fullConfig.lastUpdated = (new Date()).toUTCString();
    }
    saveJSON(configPath, fullConfig);

    return fullConfig;
}

module.exports = getFullConfig;
module.exports.defaultConfig = defaultConfig;
<|endoftext|>


<commit_before><commit_msg>Activates cocoon:after-insert only if there are existing menu items<commit_after><|endoftext|>


<commit_before>// Javascript specific to guide admin
$(function() {
  var sortable_opts = {
    axis: "y",
    handle: "a.accordion-toggle",
    stop: function(event, ui) {
      $('.part').each(function (i, elem) {
        $(elem).find('input.order').val(i + 1);
        ui.item.find("a.accordion-toggle").addClass("highlight");
        setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 )
      });
    }
  }
  $('#parts').sortable(sortable_opts)
      .find("a.accordion-toggle").css({cursor: 'move'});

  // simulate a click on the first part to open it
  $('#parts .part .accordion-body').first().collapse('show');

  $('input.title').
    on('change', function () {
      var elem = $(this);
      var value = elem.val();

      // Set slug on change.
      var slug_field = elem.closest('.part').find('.slug');
      if (slug_field.text() === '') {
        slug_field.val(GovUKGuideUtils.convertToSlug(value));
      }

      // Set header on change.
      var header = elem.closest('fieldset').prev('h3').find('a');
      header.text(value);
    });
});
<commit_msg>Don't collapse any parts on page load<commit_after>// Javascript specific to guide admin
$(function() {
  var sortable_opts = {
    axis: "y",
    handle: "a.accordion-toggle",
    stop: function(event, ui) {
      $('.part').each(function (i, elem) {
        $(elem).find('input.order').val(i + 1);
        ui.item.find("a.accordion-toggle").addClass("highlight");
        setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 )
      });
    }
  }
  $('#parts').sortable(sortable_opts)
      .find("a.accordion-toggle").css({cursor: 'move'});

  $('input.title').
    on('change', function () {
      var elem = $(this);
      var value = elem.val();

      // Set slug on change.
      var slug_field = elem.closest('.part').find('.slug');
      if (slug_field.text() === '') {
        slug_field.val(GovUKGuideUtils.convertToSlug(value));
      }

      // Set header on change.
      var header = elem.closest('fieldset').prev('h3').find('a');
      header.text(value);
    });
});
<|endoftext|>


<commit_before>Scoof.View = Backbone.View.extend({
  addListeners: {},
  presenterClass: function () { return Scoof.Presenter; },

  initialize: function (opts) {
    opts = opts || {};
    this.parent = opts.parent;
    this.attachmentMethod = opts.attachMethod || 'append';
    this.init();
  },

  init: function () {
    // override in classes
  },

  render: function() {
    this.renderTemplate();
    this.attachToParent();
    this.afterRender();
  },

  attachToParent: function () {
    var $parent = new Scoof.View.ParentFinder(
      this.parent, this.parentSelector, this.attachmentMethod
    ).perform();
    $parent && $parent[this.attachmentMethod](this.el);
  },

  afterRender: function() { /* template method hook ! */ },

  events: function() {
    if (!Scoof.Events.isTouch()) return this.addListeners;

    var eventSet = {};

    _.each(_.keys(this.addListeners), function(eventKey) {
      var key = eventKey.replace('click', Scoof.Events.startEvent);
      eventSet[key] = this.addListeners[eventKey];
    }.bind(this));

    return eventSet;
  },

  renderTemplate: function(){
    var template = HoganTemplates[this.templateName];
    if (!template) {return;}
    var rendered = template.render(this.presenter(), this.partials());
    this.$el.html(rendered);
  },

  presenter: function() {
    var presented = this.model || this.collection || {};
    var presenter = new (this.presenterClass())(presented);
    return presenter.toJSON();
  },

  partials: function() {
    // override with own partials if necessary
    return {};
  }
});
<commit_msg>Fixes attachmentMethod acquisition<commit_after>Scoof.View = Backbone.View.extend({
  addListeners: {},
  presenterClass: function () { return Scoof.Presenter; },

  initialize: function (opts) {
    opts = opts || {};
    this.parent = opts.parent;
    this.attachmentMethod = opts.attachmentMethod || 'append';
    this.init();
  },

  init: function () {
    // override in classes
  },

  render: function() {
    this.renderTemplate();
    this.attachToParent();
    this.afterRender();
  },

  attachToParent: function () {
    var $parent = new Scoof.View.ParentFinder(
      this.parent, this.parentSelector, this.attachmentMethod
    ).perform();
    $parent && $parent[this.attachmentMethod](this.el);
  },

  afterRender: function() { /* template method hook ! */ },

  events: function() {
    if (!Scoof.Events.isTouch()) return this.addListeners;

    var eventSet = {};

    _.each(_.keys(this.addListeners), function(eventKey) {
      var key = eventKey.replace('click', Scoof.Events.startEvent);
      eventSet[key] = this.addListeners[eventKey];
    }.bind(this));

    return eventSet;
  },

  renderTemplate: function(){
    var template = HoganTemplates[this.templateName];
    if (!template) {return;}
    var rendered = template.render(this.presenter(), this.partials());
    this.$el.html(rendered);
  },

  presenter: function() {
    var presented = this.model || this.collection || {};
    var presenter = new (this.presenterClass())(presented);
    return presenter.toJSON();
  },

  partials: function() {
    // override with own partials if necessary
    return {};
  }
});
<|endoftext|>


<commit_before>/**@ngInject*/
function DashboardController($scope, serviceAllCount,
                             serviceProjectCount, projectList) {
  "use strict";

  this.projectList = projectList;
  $scope.budgetCharts = [];

  angular.forEach(projectList, function (value) {

      if (_.inRange(value.budget, 0, 9999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD)",
          ranges: [0, 0, value.budget],
          measures: [value.spent],
          markers: [0]
        };
      } else if (_.inRange(value.budget, 10000, 999999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD, thousands)",
          ranges: [0, 0, (value.budget / 1000)],
          measures: [(value.spent / 1000)],
          markers: [0]
        };
      } else if (_.inRange(value.budget, 1000000, 999999999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD, millions)",
          ranges: [0, 0, (value.budget / 1000000)],
          measures: [(value.spent / 1000000)],
          markers: [0]
        };
      } else {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD)",
          ranges: [0, 0, value.budget],
          measures: [value.spent],
          markers: [0]
        };
      }
      $scope.budgetCharts.push($scope.temp);
    }
  );

  $scope.chartCollection = [{
    options: {
      chart: {
        type: "multiBarChart",
        height: 350,
        margin: {
          top: 20,
          right: 20,
          bottom: 60,
          left: 45
        },
        clipEdge: true,
        staggerLabels: true,
        transitionDuration: 500,
        stacked: true,
        xAxis: {
          axisLabel: "",
          showMaxMin: false,
          tickFormat: function (d) {
            return d;
          }
        },
        yAxis: {
          axisLabel: "Number of Instances",
          axisLabelDistance: 50,
          tickFormat: function (d) {
            return d;
          }
        }
      },
      title: {
        enable: true,
        text: "Service Allocation by Project",
        class: "h4",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: []
  }, {
    options: {
      chart: {
        type: "pieChart",
        height: 350,
        pie: {
          growOnHover: true
        },
        noData: "Data Incoming, Thanks for your patience.",
        x: function (d) {
          return d.key;
        },
        y: function (d) {
          return d.value;
        },
        showLabels: false,
        transitionDuration: 500,
        labelThreshold: 0.01,
        legend: {
          margin: {
            top: 5,
            right: 35,
            bottom: 5,
            left: 0
          }
        }
      },
      title: {
        enable: true,
        text: "Cumulative Service Allocation",
        class: "h3",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: []
  }, {
    options: {
      chart: {
        type: "bulletChart",
        transitionDuration: 500,
        bullet: {
          dispatch: {},
          forceX: [
            0
          ],
          tickFormat: null,
          margin: {
            top: 0,
            right: 10,
            bottom: 0,
            left: 10
          },
          orient: "left"
        },
        dispatch: {},
        forceX: [
          0
        ],
        width: null,
        height: 50,
        tickFormat: null,
        margin: {
          top: 5,
          right: 40,
          bottom: 20,
          left: 180
        },
        orient: "left",
        tooltips: true,
        noData: "Data Incoming, Thanks for your patience."
      }
    },
    data: {}
  }, {
    options: {
      chart: {
        type: "discreteBarChart",
        height: 350,
        margin: {
          top: 20,
          right: 20,
          bottom: 60,
          left: 55
        },
        x: function (d) {
          return d.key;
        },
        y: function (d) {
          return d.value;
        },
        showValues: true,
        valueFormat: function (d) {
          return d;
        },
        transitionDuration: 500,
        xAxis: {
          axisLabel: "Week"
        },
        yAxis: {
          axisLabel: "Volume",
          axisLabelDistance: 30
        }
      },
      title: {
        enable: true,
        text: "*NOTIONAL* Order Frequency Insight",
        class: "h3",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: [{
      key: "Cumulative Return",
      values: [{
        key: 1,
        value: -29.765957771107
      }, {
        key: 2,
        value: 0
      }, {
        key: 3,
        value: 32.807804682612
      }, {
        key: 4,
        value: 196.45946739256
      }, {
        key: 5,
        value: 0.19434030906893
      }, {
        key: 6,
        value: -98.079782601442
      }, {
        key: 7,
        value: -13.925743130903
      }, {
        key: 8,
        value: -5.1387322875705
      }]
    }]
  }
  ];

  angular.forEach($scope.chartCollection, function (value) {
    switch (value.options.chart.type) {
      case "pieChart":
        value.data = serviceAllCount;
        break;
      case "multiBarChart":
        value.data = serviceProjectCount;
        break;
    }
  });

  $scope.onDropComplete = function (index, obj) {
    var secondObj = $scope.chartCollection[index];
    var secondIndex = $scope.chartCollection.indexOf(obj);
    $scope.chartCollection[index] = obj;
    $scope.chartCollection[secondIndex] = secondObj;
  };
}

DashboardController.resolve = {
  /**@ngInject*/
  serviceAllCount: function (ServiceAllCountResource) {

    return ServiceAllCountResource.query().$promise;
  },
  /**@ngInject*/
  serviceProjectCount: function (ServiceProjectCountResource) {
    return ServiceProjectCountResource.query().$promise;
  },
  /**@ngInject*/
  projectList: function (ProjectsResource) {
    return ProjectsResource.query().$promise;
  }
};

window.DashboardController = DashboardController;
window.lodash = _;<commit_msg>houndci<commit_after>/* global _:false */
/**@ngInject*/
function DashboardController($scope, serviceAllCount,
                             serviceProjectCount, projectList) {
  "use strict";

  this.projectList = projectList;
  $scope.budgetCharts = [];

  angular.forEach(projectList, function (value) {

      if (_.inRange(value.budget, 0, 9999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD)",
          ranges: [0, 0, value.budget],
          measures: [value.spent],
          markers: [0]
        };
      } else if (_.inRange(value.budget, 10000, 999999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD, thousands)",
          ranges: [0, 0, (value.budget / 1000)],
          measures: [(value.spent / 1000)],
          markers: [0]
        };
      } else if (_.inRange(value.budget, 1000000, 999999999)) {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD, millions)",
          ranges: [0, 0, (value.budget / 1000000)],
          measures: [(value.spent / 1000000)],
          markers: [0]
        };
      } else {
        $scope.temp = {
          title: value.name,
          subtitle: "($ USD)",
          ranges: [0, 0, value.budget],
          measures: [value.spent],
          markers: [0]
        };
      }
      $scope.budgetCharts.push($scope.temp);
    }
  );

  $scope.chartCollection = [{
    options: {
      chart: {
        type: "multiBarChart",
        height: 350,
        margin: {
          top: 20,
          right: 20,
          bottom: 60,
          left: 45
        },
        clipEdge: true,
        staggerLabels: true,
        transitionDuration: 500,
        stacked: true,
        xAxis: {
          axisLabel: "",
          showMaxMin: false,
          tickFormat: function (d) {
            return d;
          }
        },
        yAxis: {
          axisLabel: "Number of Instances",
          axisLabelDistance: 50,
          tickFormat: function (d) {
            return d;
          }
        }
      },
      title: {
        enable: true,
        text: "Service Allocation by Project",
        class: "h4",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: []
  }, {
    options: {
      chart: {
        type: "pieChart",
        height: 350,
        pie: {
          growOnHover: true
        },
        noData: "Data Incoming, Thanks for your patience.",
        x: function (d) {
          return d.key;
        },
        y: function (d) {
          return d.value;
        },
        showLabels: false,
        transitionDuration: 500,
        labelThreshold: 0.01,
        legend: {
          margin: {
            top: 5,
            right: 35,
            bottom: 5,
            left: 0
          }
        }
      },
      title: {
        enable: true,
        text: "Cumulative Service Allocation",
        class: "h3",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: []
  }, {
    options: {
      chart: {
        type: "bulletChart",
        transitionDuration: 500,
        bullet: {
          dispatch: {},
          forceX: [
            0
          ],
          tickFormat: null,
          margin: {
            top: 0,
            right: 10,
            bottom: 0,
            left: 10
          },
          orient: "left"
        },
        dispatch: {},
        forceX: [
          0
        ],
        width: null,
        height: 50,
        tickFormat: null,
        margin: {
          top: 5,
          right: 40,
          bottom: 20,
          left: 180
        },
        orient: "left",
        tooltips: true,
        noData: "Data Incoming, Thanks for your patience."
      }
    },
    data: {}
  }, {
    options: {
      chart: {
        type: "discreteBarChart",
        height: 350,
        margin: {
          top: 20,
          right: 20,
          bottom: 60,
          left: 55
        },
        x: function (d) {
          return d.key;
        },
        y: function (d) {
          return d.value;
        },
        showValues: true,
        valueFormat: function (d) {
          return d;
        },
        transitionDuration: 500,
        xAxis: {
          axisLabel: "Week"
        },
        yAxis: {
          axisLabel: "Volume",
          axisLabelDistance: 30
        }
      },
      title: {
        enable: true,
        text: "*NOTIONAL* Order Frequency Insight",
        class: "h3",
        css: {width: "nullpx", textAlign: "center"}
      }
    },
    data: [{
      key: "Cumulative Return",
      values: [{
        key: 1,
        value: -29.765957771107
      }, {
        key: 2,
        value: 0
      }, {
        key: 3,
        value: 32.807804682612
      }, {
        key: 4,
        value: 196.45946739256
      }, {
        key: 5,
        value: 0.19434030906893
      }, {
        key: 6,
        value: -98.079782601442
      }, {
        key: 7,
        value: -13.925743130903
      }, {
        key: 8,
        value: -5.1387322875705
      }]
    }]
  }
  ];

  angular.forEach($scope.chartCollection, function (value) {
    switch (value.options.chart.type) {
      case "pieChart":
        value.data = serviceAllCount;
        break;
      case "multiBarChart":
        value.data = serviceProjectCount;
        break;
    }
  });

  $scope.onDropComplete = function (index, obj) {
    var secondObj = $scope.chartCollection[index];
    var secondIndex = $scope.chartCollection.indexOf(obj);
    $scope.chartCollection[index] = obj;
    $scope.chartCollection[secondIndex] = secondObj;
  };
}

DashboardController.resolve = {
  /**@ngInject*/
  serviceAllCount: function (ServiceAllCountResource) {

    return ServiceAllCountResource.query().$promise;
  },
  /**@ngInject*/
  serviceProjectCount: function (ServiceProjectCountResource) {
    return ServiceProjectCountResource.query().$promise;
  },
  /**@ngInject*/
  projectList: function (ProjectsResource) {
    return ProjectsResource.query().$promise;
  }
};

window.DashboardController = DashboardController;<|endoftext|>


<commit_before>import CoughDrop from '../app';

export default {
  name: 'defer_readiness',
  initialize: function(container, app) {
    if(window.Hammer && window.Hammer.time && window.Hammer.time.getTouchAction) {
      var pre = window.Hammer.time.getTouchAction;
      window.Hammer.time.getTouchAction = function(element) {
        if(element.classList && element.classList.contains('touchy')) {
          return 'none';
        } else {
          return pre(element);
        }
      };
    }
  }
};
<commit_msg>initializers must have unique names<commit_after>import CoughDrop from '../app';

export default {
  name: 'hammer-time-class-check',
  initialize: function(container, app) {
    if(window.Hammer && window.Hammer.time && window.Hammer.time.getTouchAction) {
      var pre = window.Hammer.time.getTouchAction;
      window.Hammer.time.getTouchAction = function(element) {
        if(element.classList && element.classList.contains('touchy')) {
          return 'none';
        } else {
          return pre(element);
        }
      };
    }
  }
};
<|endoftext|>


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

  Chart.defaults.global.responsive = true;
  Chart.defaults.global.multiTooltipTemplate = "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>";

  Chart.defaults.global.colours = [
    { // blue
      fillColor: "rgba(151,187,205,0.2)",
      strokeColor: "rgba(151,187,205,1)",
      pointColor: "rgba(151,187,205,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(151,187,205,0.8)"
    },
    { // light grey
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,0.8)"
    },
    { // red
      fillColor: "rgba(247,70,74,0.2)",
      strokeColor: "rgba(247,70,74,1)",
      pointColor: "rgba(247,70,74,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(247,70,74,0.8)"
    },
    { // green
      fillColor: "rgba(70,191,189,0.2)",
      strokeColor: "rgba(70,191,189,1)",
      pointColor: "rgba(70,191,189,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(70,191,189,0.8)"
    },
    { // yellow
      fillColor: "rgba(253,180,92,0.2)",
      strokeColor: "rgba(253,180,92,1)",
      pointColor: "rgba(253,180,92,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(253,180,92,0.8)"
    },
    { // grey
      fillColor: "rgba(148,159,177,0.2)",
      strokeColor: "rgba(148,159,177,1)",
      pointColor: "rgba(148,159,177,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(148,159,177,0.8)"
    },
    { // dark grey
      fillColor: "rgba(77,83,96,0.2)",
      strokeColor: "rgba(77,83,96,1)",
      pointColor: "rgba(77,83,96,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(77,83,96,1)"
    }
  ];

  angular.module("chart.js", [])
    .directive("chartBase", function () { return chart(); })
    .directive("chartLine", function () { return chart('Line'); })
    .directive("chartBar", function () { return chart('Bar'); })
    .directive("chartRadar", function () { return chart('Radar'); })
    .directive("chartDoughnut", function () { return chart('Doughnut'); })
    .directive("chartPie", function () { return chart('Pie'); })
    .directive("chartPolarArea", function () { return chart('PolarArea'); });

  function chart (type) {
    return {
      restrict: 'CA',
      scope: {
        data: '=',
        labels: '=',
        options: '=',
        series: '=',
        colours: '=',
        chartType: '=',
        legend: '@',
        click: '='
      },
      link: function (scope, elem, attrs) {
        var chart;

        scope.$watch('data', function (newVal, oldVal) {
          if (! newVal || ! newVal.length || (hasDataSets(type) && ! newVal[0].length)) return;
          var chartType = type || scope.chartType;
          if (! chartType) return;
          if (chart) updateChart(chart, chartType, newVal);
          else chart = createChart(chartType, scope, elem);
        }, true);

        scope.$watch('chartType', function (newVal, oldVal) {
          if (! newVal) return;
          if (chart) chart.destroy();
          chart = createChart(newVal, scope, elem);
        });
      }
    };
  }

  function createChart (type, scope, elem) {
    var cvs = elem[0], ctx = cvs.getContext("2d");
    var data = hasDataSets(type) ?
      getDataSets(scope.labels, scope.data, scope.series || [], scope.colours) :
      getData(scope.labels, scope.data, scope.colours);
    var chart = new Chart(ctx)[type](data, scope.options || {});
    if (scope.click) {
      cvs.onclick = function (evt) {
        if (chart.getPointsAtEvent || chart.getSegmentsAtEvent) {
          var activePoints = hasDataSets(type) ? chart.getPointsAtEvent(evt) : chart.getSegmentsAtEvent(evt);
          scope.click(activePoints, evt);
        }
      };
    }
    if (scope.legend) setLegend(elem, chart);
    return chart;
  }

  function setLegend (elem, chart) {
    var $parent = elem.parent(),
        $oldLegend = $parent.find('chart-legend'),
        legend = '<chart-legend>' + chart.generateLegend() + '</chart-legend>';
    if ($oldLegend.length) $oldLegend.replaceWith(legend);
    else $parent.append(legend);
  }

  function updateChart (chart, type, values) {
    if (hasDataSets(type)){
        chart.datasets.forEach(function (dataset, i) {
          (dataset.points || dataset.bars).forEach(function (dataItem, j) {
            dataItem.value = values[i][j];
          });
      });
    } else {
      chart.segments.forEach(function (segment, i) {
        segment.value = values[i];
      });
    }
    chart.update();
  }

  function hasDataSets (type) {
    return ['Line', 'Bar', 'Radar'].indexOf(type) > -1;
  }

  function getDataSets (labels, data, series, colours) {
    colours = colours || Chart.defaults.global.colours;
    return {
      labels: labels,
      datasets: data.map(function (item, i) {
        var dataSet = clone(colours[i]);
        dataSet.label = series[i];
        dataSet.data = item;
        return dataSet;
      })
    };
  }

  function clone (obj) {
    var newObj = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) newObj[key] = obj[key];
    }
    return newObj;
  }

  function getData (labels, data, colours) {
    colours = colours || Chart.defaults.global.colours;
    return labels.map(function (label, i) {
      return {
        label: label,
        value: data[i],
        color: colours[i].strokeColor,
        highlight: colours[i].pointHighlightStroke
      };
    });
  }

})();<commit_msg>Ability to create a complete new chart when the data updates (instead of only providing new values for existing data)<commit_after>(function () {
  "use strict";

  Chart.defaults.global.responsive = true;
  Chart.defaults.global.multiTooltipTemplate = "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>";

  Chart.defaults.global.colours = [
    { // blue
      fillColor: "rgba(151,187,205,0.2)",
      strokeColor: "rgba(151,187,205,1)",
      pointColor: "rgba(151,187,205,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(151,187,205,0.8)"
    },
    { // light grey
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,0.8)"
    },
    { // red
      fillColor: "rgba(247,70,74,0.2)",
      strokeColor: "rgba(247,70,74,1)",
      pointColor: "rgba(247,70,74,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(247,70,74,0.8)"
    },
    { // green
      fillColor: "rgba(70,191,189,0.2)",
      strokeColor: "rgba(70,191,189,1)",
      pointColor: "rgba(70,191,189,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(70,191,189,0.8)"
    },
    { // yellow
      fillColor: "rgba(253,180,92,0.2)",
      strokeColor: "rgba(253,180,92,1)",
      pointColor: "rgba(253,180,92,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(253,180,92,0.8)"
    },
    { // grey
      fillColor: "rgba(148,159,177,0.2)",
      strokeColor: "rgba(148,159,177,1)",
      pointColor: "rgba(148,159,177,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(148,159,177,0.8)"
    },
    { // dark grey
      fillColor: "rgba(77,83,96,0.2)",
      strokeColor: "rgba(77,83,96,1)",
      pointColor: "rgba(77,83,96,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(77,83,96,1)"
    }
  ];

  angular.module("chart.js", [])
    .directive("chartBase", function () { return chart(); })
    .directive("chartLine", function () { return chart('Line'); })
    .directive("chartBar", function () { return chart('Bar'); })
    .directive("chartRadar", function () { return chart('Radar'); })
    .directive("chartDoughnut", function () { return chart('Doughnut'); })
    .directive("chartPie", function () { return chart('Pie'); })
    .directive("chartPolarArea", function () { return chart('PolarArea'); });

  function chart (type) {
    return {
      restrict: 'CA',
      scope: {
        data: '=',
        labels: '=',
        options: '=',
        series: '=',
        colours: '=',
        chartType: '=',
        legend: '@',
        click: '=',
        destroyOnUpdate: '='
      },
      link: function (scope, elem, attrs) {
        var chart;

        scope.$watch('data', function (newVal, oldVal) {
          if (! newVal || ! newVal.length || (hasDataSets(type) && ! newVal[0].length)) return;
          var chartType = type || scope.chartType;
          if (! chartType) return;
          if (chart && !destroyOnUpdate) updateChart(chart, chartType, newVal);
          else {
          	if (chart) {
          		chart.destroy();
          	}

          	chart = createChart(chartType, scope, elem);
          }
        }, true);

        scope.$watch('chartType', function (newVal, oldVal) {
          if (! newVal) return;
          if (chart) chart.destroy();
          chart = createChart(newVal, scope, elem);
        });
      }
    };
  }

  function createChart (type, scope, elem) {
    var cvs = elem[0], ctx = cvs.getContext("2d");
    var data = hasDataSets(type) ?
      getDataSets(scope.labels, scope.data, scope.series || [], scope.colours) :
      getData(scope.labels, scope.data, scope.colours);
    var chart = new Chart(ctx)[type](data, scope.options || {});
    if (scope.click) {
      cvs.onclick = function (evt) {
        if (chart.getPointsAtEvent || chart.getSegmentsAtEvent) {
          var activePoints = hasDataSets(type) ? chart.getPointsAtEvent(evt) : chart.getSegmentsAtEvent(evt);
          scope.click(activePoints, evt);
        }
      };
    }
    if (scope.legend) setLegend(elem, chart);
    return chart;
  }

  function setLegend (elem, chart) {
    var $parent = elem.parent(),
        $oldLegend = $parent.find('chart-legend'),
        legend = '<chart-legend>' + chart.generateLegend() + '</chart-legend>';
    if ($oldLegend.length) $oldLegend.replaceWith(legend);
    else $parent.append(legend);
  }

  function updateChart (chart, type, values) {
    if (hasDataSets(type)){
        chart.datasets.forEach(function (dataset, i) {
          (dataset.points || dataset.bars).forEach(function (dataItem, j) {
            dataItem.value = values[i][j];
          });
      });
    } else {
      chart.segments.forEach(function (segment, i) {
        segment.value = values[i];
      });
    }
    chart.update();
  }

  function hasDataSets (type) {
    return ['Line', 'Bar', 'Radar'].indexOf(type) > -1;
  }

  function getDataSets (labels, data, series, colours) {
    colours = colours || Chart.defaults.global.colours;
    return {
      labels: labels,
      datasets: data.map(function (item, i) {
        var dataSet = clone(colours[i]);
        dataSet.label = series[i];
        dataSet.data = item;
        return dataSet;
      })
    };
  }

  function clone (obj) {
    var newObj = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) newObj[key] = obj[key];
    }
    return newObj;
  }

  function getData (labels, data, colours) {
    colours = colours || Chart.defaults.global.colours;
    return labels.map(function (label, i) {
      return {
        label: label,
        value: data[i],
        color: colours[i].strokeColor,
        highlight: colours[i].pointHighlightStroke
      };
    });
  }

})();<|endoftext|>


<commit_before>(function () {
    "use strict";
    var ngRaven = angular.module("angular-raven", []);

    ngRaven.config(["$provide", function ($provide) {
        $provide.decorator("$exceptionHandler", ["RavenConfig", "$delegate", function (cfg, del) {
            if (!cfg) { throw new Error("Raven config must be set before using this"); }
            Raven.config(cfg.ravenUrl).install();
            return function (ex, cause) {
                del(ex, cause);
                Raven.captureException(ex, cause);
            };
        }]);
    }]);
    ngRaven.value("Raven", Raven);

})();
<commit_msg>add license header<commit_after>/*!
 * Copyright (c) 2013, Umur Kontacı
 * https://github.com/fastreload/angular-raven
 * All rights reserved.
 *
 * See github link for example usage
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

(function () {
    "use strict";
    var ngRaven = angular.module("angular-raven", []);

    ngRaven.config(["$provide", function ($provide) {
        $provide.decorator("$exceptionHandler", ["RavenConfig", "$delegate", function (cfg, del) {
            if (!cfg) { throw new Error("Raven config must be set before using this"); }
            Raven.config(cfg.ravenUrl).install();
            return function (ex, cause) {
                del(ex, cause);
                Raven.captureException(ex, cause);
            };
        }]);
    }]);
    ngRaven.value("Raven", Raven);

})();
<|endoftext|>


<commit_before>const WeatherReport = require('../../models/WeatherReport');
const getLocation = require('./getLocation');
const getTimeZone = require('./getTimeZone');
const moment = require('moment-timezone');

module.exports = function(token, location, message, units) {
  getLocation(location)
    .then((coords) => {
      return getTimeZone(coords.lat, coords.lng)
    })
    .then((timeZone) => {
      const hour = moment('8', 'H').tz(timeZone).utc().format("H");
      const channel = message.channel;
      WeatherReport.create({
        token: token,
        channel: message.channel,
        location: location.trim(),
        cron: {
          enabled: true,
          startAt: new Date(),
          // interval: `0 0 ${hour} * * *`
          interval: `* * * * * *`
        }
      });
    });
}
<commit_msg>At 8 am<commit_after>const WeatherReport = require('../../models/WeatherReport');
const getLocation = require('./getLocation');
const getTimeZone = require('./getTimeZone');
const moment = require('moment-timezone');

module.exports = function(token, location, message, units) {
  getLocation(location)
    .then((coords) => {
      return getTimeZone(coords.lat, coords.lng)
    })
    .then((timeZone) => {
      const hour = moment('8', 'H').tz(timeZone).utc().format("H");
      const channel = message.channel;
      WeatherReport.create({
        token: token,
        channel: message.channel,
        location: location.trim(),
        cron: {
          enabled: true,
          startAt: new Date(),
          interval: `0 0 ${hour} * * *`
        }
      });
    });
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Flex } from 'rebass/styled-components';
import { Label, Input, InputProps } from '@rebass/forms';
import { Caption } from './FontStyles';
import { Icon } from './Icon';
import { fonts, fontSizes, colors, borders, radii, space } from '../../themes/baseTheme';

const StyledWrapper = styled(Flex)`
  position: relative;
  flex-wrap: wrap;

  > input {
    flex-grow: 1;
  }

.MuiSvgIcon-root {
    position: absolute;
    right: ${space[2]}px;
    top: 12px;
    color: inherit;
    /* Disable pointer events so click actually applies to the dropdown menu underneath */
    pointer-events: none;
  }
`;

const StyledInput = styled(Input)`
  border: ${borders.input};
  box-shadow: none;
  border-radius: ${radii.input}px;
  padding: ${styleprops => (styleprops.space ? space[styleprops.space] : 12)}px;
  caret-color: ${colors.mediumPurple};
  font-size: ${fontSizes[1]}px;
  font-family: ${fonts.default};
  color: ${colors.mediumPurple};

  &::placeholder {
    color: ${colors.text.primaryTextSubdued};
  }

  &.active {
    color: ${colors.text.primaryTextSubdued};
    box-shadow: none;
  }

  &:focus {
    box-shadow: none;
  }

  &:disabled {
    background: ${colors.grays[0]};
    color: ${colors.text.primaryDisabled};
  }
`;

export const TextInput = props => {
  const { label, name, width, icon, ...inputProps } = props;
  return (
    <React.Fragment>
      {label &&

{label}

      }

    </React.Fragment>
  );
};

TextInput.propTypes = {
  ...InputProps,
  name: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  label: PropTypes.string,
  space: PropTypes.number,
  disabled: PropTypes.bool,
  icon: PropTypes.elementType,
};

TextInput.defaultProps = {
  placeholder: '',
  width: ['100%', '75%', '50%'],
};

export default TextInput;
<commit_msg>[WEB-587] fix indent<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Flex } from 'rebass/styled-components';
import { Label, Input, InputProps } from '@rebass/forms';
import { Caption } from './FontStyles';
import { Icon } from './Icon';
import { fonts, fontSizes, colors, borders, radii, space } from '../../themes/baseTheme';

const StyledWrapper = styled(Flex)`
  position: relative;
  flex-wrap: wrap;

  > input {
    flex-grow: 1;
  }

  .MuiSvgIcon-root {
    position: absolute;
    right: ${space[2]}px;
    top: 12px;
    color: inherit;
    /* Disable pointer events so click actually applies to the dropdown menu underneath */
    pointer-events: none;
  }
`;

const StyledInput = styled(Input)`
  border: ${borders.input};
  box-shadow: none;
  border-radius: ${radii.input}px;
  padding: ${styleprops => (styleprops.space ? space[styleprops.space] : 12)}px;
  caret-color: ${colors.mediumPurple};
  font-size: ${fontSizes[1]}px;
  font-family: ${fonts.default};
  color: ${colors.mediumPurple};

  &::placeholder {
    color: ${colors.text.primaryTextSubdued};
  }

  &.active {
    color: ${colors.text.primaryTextSubdued};
    box-shadow: none;
  }

  &:focus {
    box-shadow: none;
  }

  &:disabled {
    background: ${colors.grays[0]};
    color: ${colors.text.primaryDisabled};
  }
`;

export const TextInput = props => {
  const { label, name, width, icon, ...inputProps } = props;
  return (
    <React.Fragment>
      {label &&

{label}

      }

    </React.Fragment>
  );
};

TextInput.propTypes = {
  ...InputProps,
  name: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  label: PropTypes.string,
  space: PropTypes.number,
  disabled: PropTypes.bool,
  icon: PropTypes.elementType,
};

TextInput.defaultProps = {
  placeholder: '',
  width: ['100%', '75%', '50%'],
};

export default TextInput;
<|endoftext|>