<commit_before>require("should");
var SpinningSalesContractDataUtil =  require("../../data-util/sales/spinning-sales-contract-data-util");
var helper = require("../../helper");
var validate =require("dl-models").validator.sales.spinningSalesContract;
var moment = require('moment');

var SpinningSalesContractManager = require("../../../src/managers/sales/spinning-sales-contract-manager");
var spinningSalesContractManager = null;

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            spinningSalesContractManager = new SpinningSalesContractManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

it('#01. should error when create with empty data ', function (done) {
    spinningSalesContractManager.create({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                e.errors.should.have.property('buyer');
                e.errors.should.have.property('quality');
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it('#02. should error when create new data with deliverySchedule less than today', function (done) {
    SpinningSalesContractDataUtil.getNewData()
        .then(me => {
            var dateYesterday = new Date().setDate(new Date().getDate() -1);

            me.deliverySchedule = moment(dateYesterday).format('YYYY-MM-DD');

            spinningSalesContractManager.create(me)
                .then(id => {
                    done("should error when create new data with deliverySchedule less than today");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('deliverySchedule');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#03. should error when create new data with shippingQuantityTolerance more than 100', function (done) {
    SpinningSalesContractDataUtil.getNewData()
        .then(sc => {

            sc.shippingQuantityTolerance = 120;

            spinningSalesContractManager.create(sc)
                .then(id => {
                    done("should error when create new data with shippingQuantityTolerance more than 100");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('shippingQuantityTolerance');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});

it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank', function (done) {
    SpinningSalesContractDataUtil.getNewData()
        .then(sc => {

            sc.quality._id = '';
            sc.comodity._id = '';
            sc.buyer._id = '';
            sc.accountBank._id = '';

            spinningSalesContractManager.create(sc)
                .then(id => {
                    done("should error when create new data with non existent quality, comodity, buyer, accountBank");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('quality');
                        e.errors.should.have.property('comodity');
                        e.errors.should.have.property('buyer');
                        e.errors.should.have.property('accountBank');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});<commit_msg>update spinning sales contract<commit_after>require("should");
var SpinningSalesContractDataUtil = require("../../data-util/sales/spinning-sales-contract-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator.sales.spinningSalesContract;
var moment = require('moment');

var SpinningSalesContractManager = require("../../../src/managers/sales/spinning-sales-contract-manager");
var spinningSalesContractManager = null;

var buyerDataUtil = require("../../data-util/master/buyer-data-util");
var BuyerManager = require("../../../src/managers/master/buyer-manager");
var buyerManager;

before('#00. connect db', function(done) {
    helper.getDb()
        .then((db) => {
            spinningSalesContractManager = new SpinningSalesContractManager(db, {
                username: 'dev'
            });

            buyerManager = new BuyerManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it('#01. should error when create with empty data ', function(done) {
    spinningSalesContractManager.create({})
        .then((id) => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                e.errors.should.have.property('buyer');
                e.errors.should.have.property('quality');
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it('#02. should error when create new data with deliverySchedule less than today', function(done) {
    SpinningSalesContractDataUtil.getNewData()
        .then((me) => {
            var dateYesterday = new Date().setDate(new Date().getDate() - 1);

            me.deliverySchedule = moment(dateYesterday).format('YYYY-MM-DD');

            spinningSalesContractManager.create(me)
                .then((id) => {
                    done("should error when create new data with deliverySchedule less than today");
                })
                .catch((e) => {
                    try {
                        e.errors.should.have.property('deliverySchedule');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch((e) => {
            done(e);
        });
});

it('#03. should error when create new data with shippingQuantityTolerance more than 100', function(done) {
    SpinningSalesContractDataUtil.getNewData()
        .then((sc) => {

            sc.shippingQuantityTolerance = 120;

            spinningSalesContractManager.create(sc)
                .then((id) => {
                    done("should error when create new data with shippingQuantityTolerance more than 100");
                })
                .catch((e) => {
                    try {
                        e.errors.should.have.property('shippingQuantityTolerance');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch((e) => {
            done(e);
        });
});

it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank', function(done) {
    SpinningSalesContractDataUtil.getNewData()
        .then((sc) => {

            sc.quality._id = '';
            sc.comodity._id = '';
            sc.buyer._id = '';
            sc.accountBank._id = '';

            spinningSalesContractManager.create(sc)
                .then((id) => {
                    done("should error when create new data with non existent quality, comodity, buyer, accountBank");
                })
                .catch((e) => {
                    try {
                        e.errors.should.have.property('quality');
                        e.errors.should.have.property('comodity');
                        e.errors.should.have.property('buyer');
                        e.errors.should.have.property('accountBank');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch((e) => {
            done(e);
        });
});

var createdDataBuyer;
var createdDataBuyerId;
it("#05. should success when create new data export buyer", function(done) {
    buyerDataUtil.getNewData()
        .then((data) => {
            data.type = "Ekspor";
            createdDataBuyer = data;
            buyerManager.create(data)
                .then((id) => {
                    id.should.be.Object();
                    createdDataBuyerId = id;
                    done();
                })
                .catch((e) => {
                    done(e);
                });
        });
});

it('#06. it should error when create new data with export buyer with agent without comission, amount, term of shipment', function(done) {
    SpinningSalesContractDataUtil.getNewData()
        .then((sc) => {

            sc.buyer = createdDataBuyer;
            sc.buyerId = createdDataBuyerId;
            sc.comission = '';
            sc.amount = 0;
            sc.termOfShipment = '';

            spinningSalesContractManager.create(sc)
                .then((id) => {
                    done("should error when create new data with non existent quality, comodity, buyer, accountBank, uom, materialConstruction, yarnMaterial, orderType");
                })
                .catch((e) => {
                    try {
                        e.errors.should.have.property('comission');
                        e.errors.should.have.property('amount');
                        e.errors.should.have.property('termOfShipment');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch((e) => {
            done(e);
        });
});
<|endoftext|>


<commit_before>Package.describe({
	summary: "Three.js - A JavaScript 3D library"
});

Package.on_use(function(api) {
	api.add_files(["lib/three.js"], "client");

	api.export("THREE", "client");

	api.add_files([
		// Loaders
		"extras/loaders/OBJMTLLoader.js",
		"extras/loaders/MTLLoader.js",
		"extras/loaders/OBJLoader.js",
		"extras/loaders/ctm/ctm.js",
		"extras/loaders/ctm/CTMLoader.js",
		"extras/loaders/ctm/CTMWorker.js",
		"extras/loaders/ctm/lzma.js",

		// Exporters
		"extras/exporters/STLBinaryExporter.js",

		// Controls
		"extras/controls/TrackballControls.js",
		"extras/controls/OrbitControls.js",
		"extras/controls/FlyControls.js",

		// PostProcessing
		"extras/postprocessing/BloomPass.js",
		"extras/postprocessing/BokehPass.js",
		"extras/postprocessing/DotScreenPass.js",
		"extras/postprocessing/EffectComposer.js",
		"extras/postprocessing/FilmPass.js",
		"extras/postprocessing/GlitchPass.js",
		"extras/postprocessing/MaskPass.js",
		"extras/postprocessing/RenderPass.js",
		"extras/postprocessing/SavePass.js",
		"extras/postprocessing/ShaderPass.js",
		"extras/postprocessing/TexturePass.js",

		// Shaders
		"extras/shaders/BasicShader.js",
		"extras/shaders/BleachBypassShader.js",
		"extras/shaders/BlendShader.js",
		"extras/shaders/BokehShader.js",
		"extras/shaders/BokehShader2.js",
		"extras/shaders/BrightnessContrastShader.js",
		"extras/shaders/ColorCorrectionShader.js",
		"extras/shaders/ColorifyShader.js",
		"extras/shaders/ConvolutionShader.js",
		"extras/shaders/CopyShader.js",
		"extras/shaders/DigitalGlitch.js",
		"extras/shaders/DOFMipMapShader.js",
		"extras/shaders/DotScreenShader.js",
		"extras/shaders/EdgeShader.js",
		"extras/shaders/EdgeShader2.js",
		"extras/shaders/FilmShader.js",
		"extras/shaders/FocusShader.js",
		"extras/shaders/FresnelShader.js",
		"extras/shaders/FXAAShader.js",
		"extras/shaders/HorizontalBlurShader.js",
		"extras/shaders/HorizontalTiltShiftShader.js",
		"extras/shaders/HueSaturationShader.js",
		"extras/shaders/KaleidoShader.js",
		"extras/shaders/LuminosityShader.js",
		"extras/shaders/MirrorShader.js",
		"extras/shaders/NormalMapShader.js",
		"extras/shaders/OceanShaders.js",
		"extras/shaders/RGBShiftShader.js",
		"extras/shaders/SepiaShader.js",
		"extras/shaders/SSAOShader.js",
		"extras/shaders/TechnicolorShader.js",
		"extras/shaders/TriangleBlurShader.js",
		"extras/shaders/UnpackDepthRGBAShader.js",
		"extras/shaders/VerticalBlurShader.js",
		"extras/shaders/VerticalTiltShiftShader.js",
		"extras/shaders/VignetteShader.js"
	], "client");
});
<commit_msg>Exorting THREE everywhere<commit_after>Package.describe({
	summary: "Three.js - A JavaScript 3D library"
});

Package.on_use(function(api) {
	api.add_files(["lib/three.js"], "client");

	api.export("THREE");

	api.add_files([
		// Loaders
		"extras/loaders/OBJMTLLoader.js",
		"extras/loaders/MTLLoader.js",
		"extras/loaders/OBJLoader.js",
		"extras/loaders/ctm/ctm.js",
		"extras/loaders/ctm/CTMLoader.js",
		"extras/loaders/ctm/CTMWorker.js",
		"extras/loaders/ctm/lzma.js",

		// Exporters
		"extras/exporters/STLBinaryExporter.js",

		// Controls
		"extras/controls/TrackballControls.js",
		"extras/controls/OrbitControls.js",
		"extras/controls/FlyControls.js",

		// PostProcessing
		"extras/postprocessing/BloomPass.js",
		"extras/postprocessing/BokehPass.js",
		"extras/postprocessing/DotScreenPass.js",
		"extras/postprocessing/EffectComposer.js",
		"extras/postprocessing/FilmPass.js",
		"extras/postprocessing/GlitchPass.js",
		"extras/postprocessing/MaskPass.js",
		"extras/postprocessing/RenderPass.js",
		"extras/postprocessing/SavePass.js",
		"extras/postprocessing/ShaderPass.js",
		"extras/postprocessing/TexturePass.js",

		// Shaders
		"extras/shaders/BasicShader.js",
		"extras/shaders/BleachBypassShader.js",
		"extras/shaders/BlendShader.js",
		"extras/shaders/BokehShader.js",
		"extras/shaders/BokehShader2.js",
		"extras/shaders/BrightnessContrastShader.js",
		"extras/shaders/ColorCorrectionShader.js",
		"extras/shaders/ColorifyShader.js",
		"extras/shaders/ConvolutionShader.js",
		"extras/shaders/CopyShader.js",
		"extras/shaders/DigitalGlitch.js",
		"extras/shaders/DOFMipMapShader.js",
		"extras/shaders/DotScreenShader.js",
		"extras/shaders/EdgeShader.js",
		"extras/shaders/EdgeShader2.js",
		"extras/shaders/FilmShader.js",
		"extras/shaders/FocusShader.js",
		"extras/shaders/FresnelShader.js",
		"extras/shaders/FXAAShader.js",
		"extras/shaders/HorizontalBlurShader.js",
		"extras/shaders/HorizontalTiltShiftShader.js",
		"extras/shaders/HueSaturationShader.js",
		"extras/shaders/KaleidoShader.js",
		"extras/shaders/LuminosityShader.js",
		"extras/shaders/MirrorShader.js",
		"extras/shaders/NormalMapShader.js",
		"extras/shaders/OceanShaders.js",
		"extras/shaders/RGBShiftShader.js",
		"extras/shaders/SepiaShader.js",
		"extras/shaders/SSAOShader.js",
		"extras/shaders/TechnicolorShader.js",
		"extras/shaders/TriangleBlurShader.js",
		"extras/shaders/UnpackDepthRGBAShader.js",
		"extras/shaders/VerticalBlurShader.js",
		"extras/shaders/VerticalTiltShiftShader.js",
		"extras/shaders/VignetteShader.js"
	], "client");
});
<|endoftext|>


<commit_before>Package.describe({
  name: "ground:util",
  version: "0.1.4",
  summary: "Adds utillity functions for ground db to use",
  git: "https://github.com/GroundMeteor/util.git"
});

Package.onUse(function (api) {

  api.export('_groundUtil');
  api.export('Ground');

  api.versionsFrom('1.0');

  api.use('meteor-platform', ['client', 'server']);

  api.use([
    'meteor',
    'underscore',
    'random',
    'minimongo',
    'ejson',
    'reactive-var',
    'ground:minimax@1.0.1'
    ], ['client', 'server']);

  api.imply('ground:minimax', ['client', 'server']);

  api.use(['tracker'], 'client');

  api.addFiles('util.client.js', 'client');

  api.addFiles('util.server.js', 'server');
});

Package.onTest(function (api) {
  api.use('ground:util', ['client', 'server']);
  api.use('test-helpers', 'client');
  api.use(['tinytest', 'underscore', 'ejson']);

  api.addFiles('util.tests.js', 'client');

});
<commit_msg>Bump to version 0.1.5<commit_after>Package.describe({
  name: "ground:util",
  version: "0.1.5",
  summary: "Adds utillity functions for ground db to use",
  git: "https://github.com/GroundMeteor/util.git"
});

Package.onUse(function (api) {

  api.export('_groundUtil');
  api.export('Ground');

  api.versionsFrom('1.0');

  api.use('meteor-platform', ['client', 'server']);

  api.use([
    'meteor',
    'underscore',
    'random',
    'minimongo',
    'ejson',
    'reactive-var',
    'ground:minimax@1.0.1'
    ], ['client', 'server']);

  api.imply('ground:minimax', ['client', 'server']);

  api.use(['tracker'], 'client');

  api.addFiles('util.client.js', 'client');

  api.addFiles('util.server.js', 'server');
});

Package.onTest(function (api) {
  api.use('ground:util', ['client', 'server']);
  api.use('test-helpers', 'client');
  api.use(['tinytest', 'underscore', 'ejson']);

  api.addFiles('util.tests.js', 'client');

});
<|endoftext|>


<commit_before>Package.describe({
  name: 'picsoung:accounts-uber',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Login service for Uber',
  // URL to the Git repository containing the source code for this package.
  git: 'http://github.com/picsoung/meteor-accounts-uber',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use('accounts-base', ['client', 'server']);
  api.use('accounts-oauth', ['client', 'server']);
  api.imply('accounts-base', ['client', 'server']);
  api.use('picsoung:uber@1.0.0', ['client', 'server']);

  api.add_files("uber.js");
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('picsoung:uber');
  api.addFiles('accounts-uber-tests.js');
});
<commit_msg>no test<commit_after>Package.describe({
  name: 'picsoung:accounts-uber',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Login service for Uber',
  // URL to the Git repository containing the source code for this package.
  git: 'http://github.com/picsoung/meteor-accounts-uber',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use('accounts-base', ['client', 'server']);
  api.use('accounts-oauth', ['client', 'server']);
  api.imply('accounts-base', ['client', 'server']);
  api.use('picsoung:uber@1.0.0', ['client', 'server']);

  api.add_files("uber.js");
});
<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';
import moment from 'moment';
import {BernieText, BernieColors} from '../styles/bernie-css';
import {Paper} from 'material-ui';
import GCBooleanField from '../forms/GCBooleanField';

class SingleEventRSVPSurvey extends React.Component {
  static propTypes = {
    onSubmitted: React.PropTypes.func,
    survey: React.PropTypes.object
  }

  checkForm() {
    if (this.state.signupQuestion === null) {
      this.setState({errors: {signupQuestion: 'This field is required'}})
      return false
    }
    return true;
  }

  submit() {
    if (this.checkForm())
      this.props.onSubmitted({
        event_id: this.state.signupQuestion ? this.props.callAssignment.relatedEvent.eventIdObfuscated : null
      })
  }

  // Some of this should get put into some sort of shared component
  styles = {
    question: {
      ...BernieText.secondaryTitle,
      fontWeight: 600,
      marginTop: 20,
      color: BernieColors.blue,
      fontSize: '1em',
      letterSpacing: '0em'
    }
  }

  eventInfo = {
    'phonebank event' : "At this phone bank party, you will get to meet other volunteers and make phone calls into the early primary states. Making these calls is the most effective way for volunteers to get Bernie elected."
  }

  state = {
    signupQuestion: null,
    errors: {}
  }

  render() {
    let relatedEvent = this.props.callAssignment.relatedEvent
    let relatedPerson = this.props.currentUser.relatedPerson
    let attendance = relatedEvent.attendeesCount
    if (relatedEvent.capacity)
      attendance = attendance + '/' + relatedEvent.capacity
    return (

          Hi {this.props.interviewee.firstName}, my name is {this.props.currentUser.firstName} and I'm a volunteer with the Bernie Sanders campaign. I'm calling you to invite you to a {relatedEvent.eventType.name} on {moment(relatedEvent.startDate).utcOffset(relatedEvent.localUTCOffset).format('dddd, MMMM Do')} at {relatedEvent.venueAddr1}{relatedPerson && relatedEvent.host.id === relatedPerson.id ? ' that I am hosting' : ''}.

          {this.eventInfo[relatedEvent.eventType.name.toLowerCase()] || '' }

        <GCBooleanField
          errorText={this.state.errors.signupQuestion}
          label="Can I sign you up for this event?"
          labelStyle={this.styles.question}
          value={this.state.signupQuestion}
          onChange={(value) => {
            this.setState({
              signupQuestion: value
            })
          }}
          />
          <Paper zDepth={0} style={{
            marginTop: 40,
            border: '1px solid ' + BernieColors.green,
            padding: '10px 10px 10px 10px'
          }}>

              Event Info

              {relatedEvent.name}

{relatedEvent.venueName}

{relatedEvent.venueAddr1}

{relatedEvent.venueAddr2}

{relatedEvent.venueCity}, {relatedEvent.venueState} {relatedEvent.venueZip}

Attendance: {attendance}

          </Paper>

    )
  }
}

export default Relay.createContainer(SingleEventRSVPSurvey, {
  fragments: {
    callAssignment: () => Relay.QL`
      fragment on CallAssignment {
        relatedEvent {
          venueAddr1
          venueAddr2
          venueCity
          venueState
          venueZip
          attendeesCount
          description
          eventIdObfuscated
          host {
            id
          }
          eventType {
            name
          }
          startDate
          localUTCOffset
          venueAddr1
          name
          link
        }
      }
    `,
    currentUser: () => Relay.QL`
      fragment on User {
        firstName
        relatedPerson {
          id
        }
      }
    `,
    interviewee: () => Relay.QL`
      fragment on Person {
        firstName
      }
    `,
  }
})<commit_msg>catch nil `relatedEvent` on SingleEventRSVPSurvey<commit_after>import React from 'react'
import Relay from 'react-relay'
import moment from 'moment'
import {BernieText, BernieColors} from '../styles/bernie-css'
import {Paper} from 'material-ui'
import GCBooleanField from '../forms/GCBooleanField'

class SingleEventRSVPSurvey extends React.Component {
  static propTypes = {
    onSubmitted: React.PropTypes.func,
    survey: React.PropTypes.object
  }

  checkForm() {
    if (this.state.signupQuestion === null) {
      this.setState({errors: {signupQuestion: 'This field is required'}})
      return false
    } else {
      return true
    }
  }

  submit() {
    if (this.checkForm())
      this.props.onSubmitted({
        event_id: this.state.signupQuestion ? this.props.callAssignment.relatedEvent.eventIdObfuscated : null
      })
  }

  // Some of this should get put into some sort of shared component
  styles = {
    question: {
      ...BernieText.secondaryTitle,
      fontWeight: 600,
      marginTop: 20,
      color: BernieColors.blue,
      fontSize: '1em',
      letterSpacing: '0em'
    }
  }

  eventInfo = {
    'phonebank event' : "At this phone bank party, you will get to meet other volunteers and make phone calls into the early primary states. Making these calls is the most effective way for volunteers to get Bernie elected."
  }

  state = {
    signupQuestion: null,
    errors: {}
  }

  render() {
    let relatedEvent = this.props.callAssignment.relatedEvent
    let attendance = relatedEvent ? relatedEvent.attendeesCount : 0
    let relatedPerson = this.props.currentUser.relatedPerson

    if (relatedEvent.capacity)
      attendance = attendance + '/' + relatedEvent.capacity

    return (

          Hi {this.props.interviewee.firstName}, my name is {this.props.currentUser.firstName} and I'm a volunteer with the Bernie Sanders campaign. I'm calling you to invite you to a {relatedEvent.eventType.name} on {moment(relatedEvent.startDate).utcOffset(relatedEvent.localUTCOffset).format('dddd, MMMM Do')} at {relatedEvent.venueAddr1}{relatedPerson && relatedEvent.host.id === relatedPerson.id ? ' that I am hosting' : ''}.

          {this.eventInfo[relatedEvent.eventType.name.toLowerCase()] || '' }

        <GCBooleanField
          errorText={this.state.errors.signupQuestion}
          label="Can I sign you up for this event?"
          labelStyle={this.styles.question}
          value={this.state.signupQuestion}
          onChange={(value) => {
            this.setState({
              signupQuestion: value
            })
          }}
          />
          <Paper zDepth={0} style={{
            marginTop: 40,
            border: '1px solid ' + BernieColors.green,
            padding: '10px 10px 10px 10px'
          }}>

              Event Info

              {relatedEvent.name}

{relatedEvent.venueName}

{relatedEvent.venueAddr1}

{relatedEvent.venueAddr2}

{relatedEvent.venueCity}, {relatedEvent.venueState} {relatedEvent.venueZip}

Attendance: {attendance}

          </Paper>

    )
  }
}

export default Relay.createContainer(SingleEventRSVPSurvey, {
  fragments: {
    callAssignment: () => Relay.QL`
      fragment on CallAssignment {
        relatedEvent {
          venueAddr1
          venueAddr2
          venueCity
          venueState
          venueZip
          attendeesCount
          description
          eventIdObfuscated
          host {
            id
          }
          eventType {
            name
          }
          startDate
          localUTCOffset
          venueAddr1
          name
          link
        }
      }
    `,
    currentUser: () => Relay.QL`
      fragment on User {
        firstName
        relatedPerson {
          id
        }
      }
    `,
    interviewee: () => Relay.QL`
      fragment on Person {
        firstName
      }
    `
  }
})
<|endoftext|>


<commit_before>Package.describe({
  name: 'babrahams:editable-text-wysiwyg-bootstrap-3',
  summary: 'Extends the babrahams:editable-text package to include a wysiwyg editor that uses bootstrap-3',
  version: '0.3.10',
  git: 'https://github.com/jackadams/meteor-editable-text-wysiwyg-bootstrap-3.git'
});

Package.onUse(function(api) {

  api.versionsFrom('1.0');

  api.use('babrahams:editable-text@0.7.8', ['client','server']);
  api.imply('babrahams:editable-text');
  api.use('babrahams:editable-text-wysiwyg@0.4.8', 'client');
  api.use('templating', 'client');
  api.use('blaze', 'client');
  api.use('spacebars', 'client');
  api.use('jquery', 'client');
  api.use(['twbs:bootstrap-noglyph@3.3.1','twbs:bootstrap@3.3.1', 'nemo64:bootstrap@3.3.1_1'], 'client', {weak: true});
  api.use('fortawesome:fontawesome@4.2.0', 'client', {weak: true});

  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.css', 'client');
  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.html', 'client');
  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.js', 'client');

});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('babrahams:editable-text-wysiwyg');
  api.addFiles('editable-text-wysiwyg-tests.js');
});<commit_msg>Version bump<commit_after>Package.describe({
  name: 'babrahams:editable-text-wysiwyg-bootstrap-3',
  summary: 'Extends the babrahams:editable-text package to include a wysiwyg editor that uses bootstrap-3',
  version: '0.3.11',
  git: 'https://github.com/jackadams/meteor-editable-text-wysiwyg-bootstrap-3.git'
});

Package.onUse(function(api) {

  api.versionsFrom('1.0');

  api.use('babrahams:editable-text@0.7.8', ['client','server']);
  api.imply('babrahams:editable-text');
  api.use('babrahams:editable-text-wysiwyg@0.4.8', 'client');
  api.use('templating', 'client');
  api.use('blaze', 'client');
  api.use('spacebars', 'client');
  api.use('jquery', 'client');
  api.use(['twbs:bootstrap-noglyph@3.3.1','twbs:bootstrap@3.3.1', 'nemo64:bootstrap@3.3.1_1'], 'client', {weak: true});
  api.use('fortawesome:fontawesome@4.2.0', 'client', {weak: true});

  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.css', 'client');
  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.html', 'client');
  api.add_files('lib/editable_text_wysiwyg_bootstrap_3.js', 'client');

});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('babrahams:editable-text-wysiwyg');
  api.addFiles('editable-text-wysiwyg-tests.js');
});<|endoftext|>


<commit_before>Package.describe({
  name: "iron-url",
  summary: "Url utilities and support for compiling a url into a regular expression.",
  version: "0.1.0",
  githubUrl: "https://github.com/eventedmind/iron-url"
});

Package.on_use(function (api) {
  api.add_files('lib/compiler.js');
  api.add_files('lib/url.js');
  api.export('Iron');
});

Package.on_test(function (api) {
  api.use('iron-url');
  api.use('tinytest');
  api.use('test-helpers');
  api.add_files('test/url_test.js', ['client', 'server']);
});
<commit_msg>use and imply iron-core<commit_after>Package.describe({
  name: "iron-url",
  summary: "Url utilities and support for compiling a url into a regular expression.",
  version: "0.1.0",
  githubUrl: "https://github.com/eventedmind/iron-url"
});

Package.on_use(function (api) {
  api.use('iron-core');
  api.imply('iron-core');
  api.add_files('lib/compiler.js');
  api.add_files('lib/url.js');
});

Package.on_test(function (api) {
  api.use('iron-url');
  api.use('tinytest');
  api.use('test-helpers');
  api.add_files('test/url_test.js', ['client', 'server']);
});
<|endoftext|>


<commit_before>Package.describe({
	version : '0.9.0',
	summary : 'Progressbar for iron:router',
	git     : 'https://github.com/Multiply/iron-router-progress.git'
});

Package.onUse(function (api) {
	api.use([
		'coffeescript@1.0.0',
		'less@1.0.0',
		'jquery@1.0.0',
		'underscore@1.0.0',
		'iron:router@0.9.1'
	], 'client');

	api.addFiles([
		'progress.coffee',
		'progress.less'
	], 'client');

	api.export('IronRouterProgress', 'client');
});
<commit_msg>Imply iron:router<commit_after>Package.describe({
	version : '0.9.1',
	summary : 'Progressbar for iron:router',
	git     : 'https://github.com/Multiply/iron-router-progress.git'
});

Package.onUse(function (api) {
	api.use([
		'coffeescript@1.0.0',
		'less@1.0.0',
		'jquery@1.0.0',
		'underscore@1.0.0',
		'iron:router@0.9.1'
	], 'client');

	api.imply('iron:router');

	api.addFiles([
		'progress.coffee',
		'progress.less'
	], 'client');

	api.export('IronRouterProgress', 'client');
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'cultofcoders:grapher',
  version: '1.3.4',
  // Brief, one-line summary of the package.
  summary: 'Grapher is a data fetching layer on top of Meteor',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/cult-of-coders/grapher',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md',
});

Npm.depends({
  sift: '3.2.6',
  'dot-object': '1.5.4',
  'lodash.clonedeep': '4.5.0',
  'deep-extend': '0.5.0',
});

Package.onUse(function(api) {
  api.versionsFrom('1.3');

  var packages = [
    'ecmascript',
    'underscore',
    'promise',
    'check',
    'reactive-var',
    'mongo',
    'matb33:collection-hooks@0.8.4',
    'reywood:publish-composite@1.5.2',
    'dburles:mongo-collection-instances@0.3.5',
    'herteby:denormalize@0.6.5',
  ];

  api.use(packages);

  api.mainModule('main.client.js', 'client');
  api.mainModule('main.server.js', 'server');
});

Package.onTest(function(api) {
  api.use('cultofcoders:grapher');

  var packages = [
    'ecmascript',
    'underscore',
    'matb33:collection-hooks@0.8.4',
    'reywood:publish-composite@1.5.2',
    'dburles:mongo-collection-instances@0.3.5',
    'herteby:denormalize@0.6.5',
    'mongo',
  ];

  api.use(packages);
  api.use('tracker');

  api.use(['cultofcoders:mocha', 'practicalmeteor:chai']);

  // LINKS
  api.addFiles('lib/links/tests/main.js', 'server');

  // EXPOSURE
  api.addFiles('lib/exposure/testing/server.js', 'server');
  api.addFiles('lib/exposure/testing/client.js', 'client');

  // QUERY
  api.addFiles('lib/query/testing/bootstrap/index.js');

  // When you play with tests you should comment this to make tests go faster.
  // api.addFiles('lib/query/testing/bootstrap/fixtures.js', 'server');

  api.addFiles('lib/query/testing/server.test.js', 'server');
  api.addFiles('lib/query/testing/client.test.js', 'client');

  // NAMED QUERY
  api.addFiles('lib/namedQuery/testing/bootstrap/both.js');
  api.addFiles('lib/namedQuery/testing/bootstrap/client.js', 'client');
  api.addFiles('lib/namedQuery/testing/bootstrap/server.js', 'server');

  // REACTIVE COUNTS
  api.addFiles('lib/query/counts/testing/server.test.js', 'server');
  api.addFiles('lib/query/counts/testing/client.test.js', 'client');

  // NAMED QUERIES
  api.addFiles('lib/namedQuery/testing/server.test.js', 'server');
  api.addFiles('lib/namedQuery/testing/client.test.js', 'client');

  // GRAPHQL
  api.addFiles('lib/graphql/testing/index.js', 'server');
});
<commit_msg>Removed the bloody comment of fixtures<commit_after>Package.describe({
  name: 'cultofcoders:grapher',
  version: '1.3.4',
  // Brief, one-line summary of the package.
  summary: 'Grapher is a data fetching layer on top of Meteor',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/cult-of-coders/grapher',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md',
});

Npm.depends({
  sift: '3.2.6',
  'dot-object': '1.5.4',
  'lodash.clonedeep': '4.5.0',
  'deep-extend': '0.5.0',
});

Package.onUse(function(api) {
  api.versionsFrom('1.3');

  var packages = [
    'ecmascript',
    'underscore',
    'promise',
    'check',
    'reactive-var',
    'mongo',
    'matb33:collection-hooks@0.8.4',
    'reywood:publish-composite@1.5.2',
    'dburles:mongo-collection-instances@0.3.5',
    'herteby:denormalize@0.6.5',
  ];

  api.use(packages);

  api.mainModule('main.client.js', 'client');
  api.mainModule('main.server.js', 'server');
});

Package.onTest(function(api) {
  api.use('cultofcoders:grapher');

  var packages = [
    'ecmascript',
    'underscore',
    'matb33:collection-hooks@0.8.4',
    'reywood:publish-composite@1.5.2',
    'dburles:mongo-collection-instances@0.3.5',
    'herteby:denormalize@0.6.5',
    'mongo',
  ];

  api.use(packages);
  api.use('tracker');

  api.use(['cultofcoders:mocha', 'practicalmeteor:chai']);

  // LINKS
  api.addFiles('lib/links/tests/main.js', 'server');

  // EXPOSURE
  api.addFiles('lib/exposure/testing/server.js', 'server');
  api.addFiles('lib/exposure/testing/client.js', 'client');

  // QUERY
  api.addFiles('lib/query/testing/bootstrap/index.js');

  // When you play with tests you should comment this to make tests go faster.
  api.addFiles('lib/query/testing/bootstrap/fixtures.js', 'server');

  api.addFiles('lib/query/testing/server.test.js', 'server');
  api.addFiles('lib/query/testing/client.test.js', 'client');

  // NAMED QUERY
  api.addFiles('lib/namedQuery/testing/bootstrap/both.js');
  api.addFiles('lib/namedQuery/testing/bootstrap/client.js', 'client');
  api.addFiles('lib/namedQuery/testing/bootstrap/server.js', 'server');

  // REACTIVE COUNTS
  api.addFiles('lib/query/counts/testing/server.test.js', 'server');
  api.addFiles('lib/query/counts/testing/client.test.js', 'client');

  // NAMED QUERIES
  api.addFiles('lib/namedQuery/testing/server.test.js', 'server');
  api.addFiles('lib/namedQuery/testing/client.test.js', 'client');

  // GRAPHQL
  api.addFiles('lib/graphql/testing/index.js', 'server');
});
<|endoftext|>


<commit_before>Package.describe({
    name: 'rnorth:yammer',
    summary: 'Yammer OAuth flow',
    version: '0.1.0',
    git: ' /* Fill me in! */ '
});

Package.onUse(function (api) {
    api.use('oauth2', ['client', 'server']);
    api.use('oauth', ['client', 'server']);
    api.use('http', ['server']);
    api.use('underscore', 'client');
    api.use('templating', 'client');
    api.use('random', 'client');
    api.use('service-configuration', ['client', 'server']);

    api.export('Yammer');

    api.versionsFrom('1.0');
    api.addFiles('yammer_server.js', 'server');
    api.addFiles('yammer_client.js', 'client');
});<commit_msg>Update git attribute in package.js<commit_after>Package.describe({
    name: 'rnorth:yammer',
    summary: 'Yammer OAuth flow',
    version: '0.1.0',
    git: 'https://github.com/rnorth/yammer.git'
});

Package.onUse(function (api) {
    api.use('oauth2', ['client', 'server']);
    api.use('oauth', ['client', 'server']);
    api.use('http', ['server']);
    api.use('underscore', 'client');
    api.use('templating', 'client');
    api.use('random', 'client');
    api.use('service-configuration', ['client', 'server']);

    api.export('Yammer');

    api.versionsFrom('1.0');
    api.addFiles('yammer_server.js', 'server');
    api.addFiles('yammer_client.js', 'client');
});<|endoftext|>


<commit_before>Package.describe({
  name: "brylie:api-umbrella",
  summary: "Wrapper for API Umbrella Admin API.",
  version: "1.3.0",
  git: "https://github.com/apinf/meteor-api-umbrella.git"
});

Package.onUse(function(api) {
  api.versionsFrom("METEOR@1.0");
  api.use(["http", "underscore"]);
  api.imply(["http", "underscore"]);

  api.addFiles("server/apiUmbrellaWeb.js", ["server"]);
  api.addFiles("server/apiUmbrellaError.js", ["server"]);

  api.export("ApiUmbrellaWeb", ["server"]);
});

Package.onTest(function (api) {
  api.use(["tinytest", "underscore"]);
  api.use("brylie:api-umbrella");

  api.addFiles("tests/server/configuration-tests.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/adminUsers.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/apiUsers.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/apiBackends.js", ["server"]);
  api.export("apiUmbrellaWeb", ["server"]);
});
<commit_msg>Bump version to 1.3.1<commit_after>Package.describe({
  name: "brylie:api-umbrella",
  summary: "Wrapper for API Umbrella Admin API.",
  version: "1.3.1",
  git: "https://github.com/apinf/meteor-api-umbrella.git"
});

Package.onUse(function(api) {
  api.versionsFrom("METEOR@1.0");
  api.use(["http", "underscore"]);
  api.imply(["http", "underscore"]);

  api.addFiles("server/apiUmbrellaWeb.js", ["server"]);
  api.addFiles("server/apiUmbrellaError.js", ["server"]);

  api.export("ApiUmbrellaWeb", ["server"]);
});

Package.onTest(function (api) {
  api.use(["tinytest", "underscore"]);
  api.use("brylie:api-umbrella");

  api.addFiles("tests/server/configuration-tests.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/adminUsers.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/apiUsers.js", ["server"]);
  api.addFiles("tests/server/admin-api/v1/apiBackends.js", ["server"]);
  api.export("apiUmbrellaWeb", ["server"]);
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'dispatch:configuration',
  summary: 'App configuration manager with inheritance',
  version: '0.1.6'
});

Package.onUse(function(api) {
  api.use([
    'underscore@1.0.3',
    'templating@1.1.1',
    'check@1.0.5',
    'aldeed:simple-schema@1.3.3',
    'aldeed:collection2@2.5.0',
    'dispatch:bound-document@0.0.2',
    'gfk:underscore-deep@1.0.0'
  ]);

  api.imply('aldeed:simple-schema');

  api.addFiles([
    'lib/configuration.js',
    'lib/user.js'
  ], ['client', 'server']);

  api.addFiles([
    'lib/server/server.js',
    'lib/server/publish.js',
    'lib/server/write.js',
    'lib/server/methods.js',
  ], 'server');

  api.addFiles([
    'lib/client/client.js'
  ], 'client');

  api.export('Configuration');
});

Package.onTest(function(api) {
  api.use('sanjo:jasmine@0.19.0');

  api.use([
    'mongo',
    'tracker',
    'dispatch:configuration',
    'aldeed:simple-schema'
  ]);

  api.addFiles([
    'tests/inheritance.js'
  ]);
  api.addFiles([
    'tests/server-only/bulk.js',
    'tests/server-only/setSchema.js'
  ], 'server');
});
<commit_msg>Bump package<commit_after>Package.describe({
  name: 'dispatch:configuration',
  summary: 'App configuration manager with inheritance',
  version: '0.1.7'
});

Package.onUse(function(api) {
  api.use([
    'underscore@1.0.3',
    'templating@1.1.1',
    'check@1.0.5',
    'aldeed:simple-schema@1.3.3',
    'aldeed:collection2@2.5.0',
    'dispatch:bound-document@0.0.2',
    'gfk:underscore-deep@1.0.0'
  ]);

  api.imply('aldeed:simple-schema');

  api.addFiles([
    'lib/configuration.js',
    'lib/user.js'
  ], ['client', 'server']);

  api.addFiles([
    'lib/server/server.js',
    'lib/server/publish.js',
    'lib/server/write.js',
    'lib/server/methods.js',
  ], 'server');

  api.addFiles([
    'lib/client/client.js'
  ], 'client');

  api.export('Configuration');
});

Package.onTest(function(api) {
  api.use('sanjo:jasmine@0.19.0');

  api.use([
    'mongo',
    'tracker',
    'dispatch:configuration',
    'aldeed:simple-schema'
  ]);

  api.addFiles([
    'tests/inheritance.js'
  ]);
  api.addFiles([
    'tests/server-only/bulk.js',
    'tests/server-only/setSchema.js'
  ], 'server');
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

/**
 * A simple pagelet.
 *
 * @constructor
 * @api public
 */
function Pagelet() {
  this.page = null;
  this.pipe = null;
  this.id = null;
}

Pagelet.prototype.__proto__ = require('stream').prototype;

/**
 * The name of this pagelet so it can checked to see if's enabled. In addition
 * to that, it can be injected in to placeholders using this name.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.name = '';

/**
 * An authorization handler to see if the request is authorized to interact with
 * this pagelet. This is set to `null` by default as there isn't any
 * authorization in place. The authorization function will receive 2 arguments:
 *
 * - req, the http request that initialized the pagelet
 * - done, a callback function that needs to be called with only a boolean.
 *
 * ```js
 * Pagelet.extend({
 *   authorize: function authorize(req, done) {
 *     done(true); // True indicates that the request is authorized for access.
 *   }
 * });
 * ```
 *
 * @type {Function}
 * @public
 */
Pagelet.prototype.authorize = null;

/**
 * Optional template engine preference. Useful when we detect the wrong template
 * engine based on the view's file name.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.engine = '';

/**
 * The location of your view template. But just because you've got a view
 * template it doesn't mean we will render it. It depends on how the pagelet is
 * called. If it's called from the client side we will only forward the data to
 * server.
 *
 * As a user you need to make sure that your template runs on the client as well
 * as on the server side.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.view = '';

/**
 * The location of the StyleSheet for this pagelet. It should contain all the
 * CSS that's needed to render this pagelet.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.css = '';

/**
 * The location of the JavaScript file that you need for this page. This file
 * needs to be included in order for this pagelet to function.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.js = '';

/**
 * An array with dependencies that your pagelet depends on. This can be CSS or
 * JavaScript files/frameworks what evers. It should be an array of strings
 * which represent the location of these files.
 *
 * @type {Array}
 * @public
 */
Pagelet.prototype.dependencies = [];

/**
 * Save the location where we got our resources from, this will help us with
 * fetching assets from the correct location.
 *
 * @type {String}
 * @public
 */
Pagelet.prototype.directory = '';

/**
 * Initialization function that is called when the pagelet is activated. This is
 * done AFTER any of the authorization hooks are handled. So your sure that this
 * pagelet is allowed for usage.
 *
 * @type {Function}
 * @public
 */
Pagelet.prototype.initialize = function initialize() {};

/**
 * Check if the given pagelet has been enabled for the page.
 *
 * @api public
 */
Pagelet.prototype.enabled = function enabled(name) {
  return name in this.page.enabled;
};

/**
 * Check if the given pagelet has been enabled for the page.
 *
 * @api public
 */
Pagelet.prototype.disabled = function disabled(name) {
  return name in this.page.disabled;
};

/**
 * Simple emit wrapper that returns a function that emits an event once it's
 * called.
 *
 * ```js
 * page.on('close', pagelet.emits('close'));
 * ```
 *
 * @param {String} event Name of the event that we should emit.
 * @param {Function} parser Argument parser.
 * @api public
 */
Pagelet.prototype.emits = function emits(event, parser) {
  var self = this;

  return function emit(arg) {
    self.emit(event, parser ? parser.apply(self, arguments) : arg);
  };
};

/**
 * Reset the instance to it's orignal state.
 *
 * @param {Page} page The page instance which created this pagelet.
 * @api private
 */
Pagelet.prototype.configure = function configure(page) {
  this.pipe = page.pipe;
  this.page = page;

  //
  // Set a new id.
  //
  this.id = [1, 1, 1, 1].map(function generator() {
    return Math.random().toString(36).substring(2).toUpperCase();
  }).join('-');

  return this.removeAllListeners();
};

//
// Make the Pagelet extendable. This allows us to use:
//
// ```js
// Pagelet.extend({
//   prop: value
// });
// ```
//
// For extending the prototypes, just like you're used to in Backbone.
//
Pagelet.extend = require('extendable');

//
// Expose the Pagelet on the exports and parse our the directory. This ensures
// that we can properly resolve all relative assets:
//
// ```js
// Pagelet.extend({
//   ..
// }).on(module);
// ```
//
Pagelet.on = function on(module) {
  this.prototype.directory = this.prototype.directory || path.dirname(module.filename);
  module.exports = this;

  return this;
};

//
// Expose the pagelet.
//
module.exports = Pagelet;
<commit_msg>[ocd] Use Object.create();<commit_after>'use strict';

var path = require('path');

/**
 * A simple pagelet.
 *
 * @constructor
 * @api public
 */
function Pagelet() {
  this.page = null;
  this.pipe = null;
  this.id = null;
}

Pagelet.prototype = Object.create(require('stream').prototype, {
  constructor: {
    value: Pagelet,
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * The name of this pagelet so it can checked to see if's enabled. In addition
   * to that, it can be injected in to placeholders using this name.
   *
   * @type {String}
   * @public
   */
  name: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * An authorization handler to see if the request is authorized to interact with
   * this pagelet. This is set to `null` by default as there isn't any
   * authorization in place. The authorization function will receive 2 arguments:
   *
   * - req, the http request that initialized the pagelet
   * - done, a callback function that needs to be called with only a boolean.
   *
   * ```js
   * Pagelet.extend({
   *   authorize: function authorize(req, done) {
   *     done(true); // True indicates that the request is authorized for access.
   *   }
   * });
   * ```
   *
   * @type {Function}
   * @public
   */
  authorize: {
    value: null,
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * Optional template engine preference. Useful when we detect the wrong template
   * engine based on the view's file name.
   *
   * @type {String}
   * @public
   */
  engine: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * The location of your view template. But just because you've got a view
   * template it doesn't mean we will render it. It depends on how the pagelet is
   * called. If it's called from the client side we will only forward the data to
   * server.
   *
   * As a user you need to make sure that your template runs on the client as well
   * as on the server side.
   *
   * @type {String}
   * @public
   */
  view: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * The location of the StyleSheet for this pagelet. It should contain all the
   * CSS that's needed to render this pagelet.
   *
   * @type {String}
   * @public
   */
  css: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * The location of the JavaScript file that you need for this page. This file
   * needs to be included in order for this pagelet to function.
   *
   * @type {String}
   * @public
   */
  js: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * An array with dependencies that your pagelet depends on. This can be CSS or
   * JavaScript files/frameworks what evers. It should be an array of strings
   * which represent the location of these files.
   *
   * @type {Array}
   * @public
   */
  dependencies: {
    value: [],
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * Save the location where we got our resources from, this will help us with
   * fetching assets from the correct location.
   *
   * @type {String}
   * @public
   */
  directory: {
    value: '',
    writable: true,
    enumerable: false,
    configurable: true
  },

  /**
   * Initialization function that is called when the pagelet is activated. This is
   * done AFTER any of the authorization hooks are handled. So your sure that this
   * pagelet is allowed for usage.
   *
   * @type {Function}
   * @public
   */
  initialize: {
    value: function initialize() {},
    writable: true,
    enumerable: false,
    configurable: true
  },

  //
  // !IMPORTANT
  //
  // Function's should never overriden as we might depend on them internally,
  // that's why they are configured with writable: false and configurable: false
  // by default.
  //
  // !IMPORTANT
  //

  /**
   * Check if the given pagelet has been enabled for the page.
   *
   * @param {String} name The name of the pagelet.
   * @api public
   */
  enabled: {
    enumerable: false,
    value: function enabled(name) {
      return name in this.page.enabled;
    }
  },

  /**
   * Check if the given pagelet has been disabled for the page.
   *
   * @param {String} name The name of the pagelet.
   * @api public
   */
  disabled: {
    enumerable: false,
    value: function disabled(name) {
      return name in this.page.disabled;
    }
  },

  /**
   * Simple emit wrapper that returns a function that emits an event once it's
   * called.
   *
   * ```js
   * page.on('close', pagelet.emits('close'));
   * ```
   *
   * @param {String} event Name of the event that we should emit.
   * @param {Function} parser Argument parser.
   * @api public
   */
  emits: {
    enumerable: false,
    value: function emits(event, parser) {
      var self = this;

      return function emit(arg) {
        self.emit(event, parser ? parser.apply(self, arguments) : arg);
      };
    }
  },

  /**
   * Reset the instance to it's orignal state.
   *
   * @param {Page} page The page instance which created this pagelet.
   * @api private
   */
  configure: {
    enumerable: false,
    value: function configure(page) {
      this.pipe = page.pipe;
      this.page = page;

      //
      // Set a new id.
      //
      this.id = [1, 1, 1, 1].map(function generator() {
        return Math.random().toString(36).substring(2).toUpperCase();
      }).join('-');

      return this.removeAllListeners();
    }
  }
});

//
// Make the Pagelet extendable. This allows us to use:
//
// ```js
// Pagelet.extend({
//   prop: value
// });
// ```
//
// For extending the prototypes, just like you're used to in Backbone.
//
Pagelet.extend = require('extendable');

//
// Expose the Pagelet on the exports and parse our the directory. This ensures
// that we can properly resolve all relative assets:
//
// ```js
// Pagelet.extend({
//   ..
// }).on(module);
// ```
//
Pagelet.on = function on(module) {
  this.prototype.directory = this.prototype.directory || path.dirname(module.filename);
  module.exports = this;

  return this;
};

//
// Expose the pagelet.
//
module.exports = Pagelet;
<|endoftext|>


<commit_before>/// <reference path="../Services/IdentityService.js" />
/// <reference path="../Services/PollService.js" />
/// <reference path="../Services/VoteService.js" />
(function () {
    angular
        .module('GVA.Voting')
        .controller('ResultsPageController', ResultsPageController);

    ResultsPageController.$inject = ['$scope', '$routeParams', 'IdentityService', 'VoteService', 'RoutingService'];

    function ResultsPageController($scope, $routeParams, IdentityService, VoteService, RoutingService) {

        var pollId = $routeParams.pollId;
        var tokenId = $routeParams['tokenId'] || '';
        var chart;

        // Turn "/#/results/abc/123" into "/#/voting/abc/123"
        $scope.votingLink = RoutingService.getVotePageUrl(pollId, tokenId);

        $scope.winner = 'Lorem';
        //Whether or not we have an "s" on the end of "Winner"
        $scope.plural = '';

        $scope.voteCount = 0;

        var canvas = document.createElement('canvas');

        var textWidth = function (text) {
            var context = canvas.getContext('2d');
            context.font = '16px Open Sans';
            var metrics = context.measureText(text);
            return metrics.width;
        };

        var tickFrequencyForRange = function (range) {
            var tickFrequency = 1;
            var step = 0;

            while (range / tickFrequency >= 10) {
                // Multiply by: 2x, 5x, 10x, 20x, 50x, 100x, etc.
                var multiplier = (step % 3 === 1) ? 2.5 : 2;
                tickFrequency = tickFrequency * multiplier;

                step++;
            }

            return tickFrequency;
        };

        var drawD3Chart = function (data) {
            // Hack to fix lack of data reloading
            document.getElementById('results-chart').innerHTML = '';

            data = data.sort(function (a, b) { return b.Sum - a.Sum; });

            var chartHeight = Math.min(data.length * 60, 600);
            var chartWidth = Math.min(600, document.getElementById('results-chart').offsetWidth);

            var longestTextWidth = d3.max(data, function (d) { return textWidth(d.Name); });

            var margin = { top: 30, right: 10, bottom: 10, left: longestTextWidth + 10 };
            var width = chartWidth - margin.left - margin.right;
            var height = chartHeight - margin.top - margin.bottom;

            var minX = d3.min(data, function (d) { return d.Sum; });
            var maxX = d3.max(data, function (d) { return d.Sum; });

            var x = d3.scale.linear()
                .range([0, width])
                .domain([Math.min(0, minX), Math.max(0, maxX)]).nice();

            var dataRange = x.domain()[1] - x.domain()[0];
            var tickFrequency = tickFrequencyForRange(dataRange);

            var y = d3.scale.ordinal()
                .rangeRoundBands([0, height], 0.1)
                .domain(data.map(function (d) { return d.Name; }));

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .ticks(dataRange / tickFrequency); // Ticks is *how many* ticks we display, not the frequency...

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

            var chart = d3.select('#results-chart')
                .append('svg')
                    .attr('width', chartWidth)
                    .attr('height', chartHeight)
                .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

            var tooltip = d3.tip()
                .attr('class', 'd3-tip')
                .offset([-10, 0])
                .html(function (d) {
                    var voterNames = d.Voters.slice(0, 5).map(function(d) { return d.Name + ' (' + d.Value + ')';});
                    var tooltipText = '' + d.Name + ': ' + d.Sum + ' votes

' + voterNames.join('
');
                    // Clip for more than 5 voters
                    if (d.Voters.length > 5) {
                        tooltipText += '
+ ' + (d.Voters.length - 5) + ' others';
                    }

                    return tooltipText;
                });

            chart.call(tooltip);

            chart.append('g')
                .attr('class', 'x axis')
                .call(xAxis);

            chart.append('g')
                .attr('class', 'y axis')
                .call(yAxis)
                .append('line')
                .attr('x1', x(0))
                .attr('x2', x(0))
                .attr('y2', height);

            chart.selectAll('.bar')
                .data(data)
                .enter().append('rect')
                .attr('class', function (d) { return d.Sum < 0 ? 'bar negative' : 'bar positive'; })
                .attr('x', function (d) {
                    return x(Math.min(0, d.Sum));
                })
                .attr('y', function (d) {
                    return y(d.Name);
                })
                .attr('width', function (d) {
                    return Math.abs(x(-d.Sum) - x(0));
                })
                .attr('height', y.rangeBand())
                .on('mouseover', tooltip.show)
                .on('mouseout', tooltip.hide);
        };

        var reloadData = function () {
            VoteService.getResults(pollId, getResultsSuccessCallback);
        };

        function getResultsSuccessCallback(data, status) {

            if (data) {
                $scope.voteCount = data.length;
            }

            var groupedData = {};

            // Group together votes for the same options
            data.forEach(function (d) {
                if (!(d.OptionName in groupedData)) {
                    groupedData[d.OptionName] = { Value: 0, Voters: [] };
                }

                groupedData[d.OptionName].Value += d.VoteValue;
                var optionVote = { Name: d.VoterName, Value: d.VoteValue };
                groupedData[d.OptionName].Voters.push(optionVote);

            });

            var winningScore = 0;

            var datapoints = [];

            // Separate into datapoints
            for (var key in groupedData) {
                if (groupedData.hasOwnProperty(key)) {
                    datapoints.push({ Name: key, Sum: groupedData[key].Value, Voters: groupedData[key].Voters });
                    winningScore = Math.max(winningScore, groupedData[key].Value);
                }
            }

            var winners = datapoints.filter(function (d) {
                return d.Sum === winningScore;
            });

            $scope.winner = winners.map(function (d) {
                return d.Name;
            }).join(', ');

            $scope.plural = (winners.length > 1) ? 's (Draw)' : '';

            drawD3Chart(datapoints);
        }

        VoteService.refreshLastChecked(pollId);
        reloadData();
        setInterval(reloadData, 3000);
    }
})();
<commit_msg>Tweaks to code style<commit_after>/// <reference path="../Services/IdentityService.js" />
/// <reference path="../Services/PollService.js" />
/// <reference path="../Services/VoteService.js" />
(function () {
    angular
        .module('GVA.Voting')
        .controller('ResultsPageController', ResultsPageController);

    ResultsPageController.$inject = ['$scope', '$routeParams', 'IdentityService', 'VoteService', 'RoutingService'];

    function ResultsPageController($scope, $routeParams, IdentityService, VoteService, RoutingService) {

        var pollId = $routeParams.pollId;
        var tokenId = $routeParams['tokenId'] || '';
        var chart;

        // Turn "/#/results/abc/123" into "/#/voting/abc/123"
        $scope.votingLink = RoutingService.getVotePageUrl(pollId, tokenId);

        $scope.winner = 'Lorem';
        //Whether or not we have an "s" on the end of "Winner"
        $scope.plural = '';

        $scope.voteCount = 0;

        var canvas = document.createElement('canvas');

        var textWidth = function (text) {
            var context = canvas.getContext('2d');
            context.font = '16px Open Sans';
            var metrics = context.measureText(text);
            return metrics.width;
        };

        var tickFrequencyForRange = function (range) {
            var tickFrequency = 1;
            var step = 0;

            while (range / tickFrequency >= 10) {
                // Multiply by: 2x, 5x, 10x, 20x, 50x, 100x, etc.
                var multiplier = (step % 3 === 1) ? 2.5 : 2;
                tickFrequency = tickFrequency * multiplier;

                step++;
            }

            return tickFrequency;
        };

        var drawD3Chart = function (data) {
            // Hack to fix lack of data reloading
            document.getElementById('results-chart').innerHTML = '';

            data = data.sort(function (a, b) { return b.Sum - a.Sum; });

            var chartHeight = Math.min(data.length * 60, 600);
            var chartWidth = Math.min(600, document.getElementById('results-chart').offsetWidth);

            var longestTextWidth = d3.max(data, function (d) { return textWidth(d.Name); });

            var margin = { top: 30, right: 10, bottom: 10, left: longestTextWidth + 10 };
            var width = chartWidth - margin.left - margin.right;
            var height = chartHeight - margin.top - margin.bottom;

            var minX = d3.min(data, function (d) { return d.Sum; });
            var maxX = d3.max(data, function (d) { return d.Sum; });

            var x = d3.scale.linear()
                .range([0, width])
                .domain([Math.min(0, minX), Math.max(0, maxX)])
                .nice();

            var dataRange = x.domain()[1] - x.domain()[0];
            var tickFrequency = tickFrequencyForRange(dataRange);

            var y = d3.scale.ordinal()
                .rangeRoundBands([0, height], 0.1)
                .domain(data.map(function (d) { return d.Name; }));

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .ticks(dataRange / tickFrequency); // Ticks is *how many* ticks we display, not the frequency...

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

            var tooltip = d3.tip()
                .attr('class', 'd3-tip')
                .offset([-10, 0])
                .html(function (d) {
                    var voterNames = d.Voters.slice(0, 5).map(function (d) { return d.Name + ' (' + d.Value + ')'; });
                    var tooltipText = '' + d.Name + ': ' + d.Sum + ' votes

' + voterNames.join('
');
                    // Clip for more than 5 voters
                    if (d.Voters.length > 5) {
                        tooltipText += '
+ ' + (d.Voters.length - 5) + ' others';
                    }

                    return tooltipText;
                });

            var chart = d3.select('#results-chart')
                .append('svg')
                    .attr('width', chartWidth)
                    .attr('height', chartHeight)
                .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

            chart.append('g')
                .attr('class', 'x axis')
                .call(xAxis);

            chart.append('g')
                .attr('class', 'y axis')
                .call(yAxis)
                .append('line')
                    .attr('x1', x(0))
                    .attr('x2', x(0))
                    .attr('y2', height);

            chart.selectAll('.bar')
                .data(data)
                .enter()
                .append('rect')
                    .attr('class', function (d) { return d.Sum < 0 ? 'bar negative' : 'bar positive'; })
                    .attr('x', function (d) {
                        return x(Math.min(0, d.Sum));
                    })
                    .attr('y', function (d) {
                        return y(d.Name);
                    })
                    .attr('width', function (d) {
                        return Math.abs(x(-d.Sum) - x(0));
                    })
                    .attr('height', y.rangeBand())
                    .on('mouseover', tooltip.show)
                    .on('mouseout', tooltip.hide);

            chart.call(tooltip);
        };

        var reloadData = function () {
            VoteService.getResults(pollId, getResultsSuccessCallback);
        };

        function getResultsSuccessCallback(data, status) {

            if (data) {
                $scope.voteCount = data.length;
            }

            var groupedData = {};

            // Group together votes for the same options
            data.forEach(function (d) {
                if (!(d.OptionName in groupedData)) {
                    groupedData[d.OptionName] = { Value: 0, Voters: [] };
                }

                groupedData[d.OptionName].Value += d.VoteValue;
                var optionVote = { Name: d.VoterName, Value: d.VoteValue };
                groupedData[d.OptionName].Voters.push(optionVote);

            });

            var winningScore = 0;

            var datapoints = [];

            // Separate into datapoints
            for (var key in groupedData) {
                if (groupedData.hasOwnProperty(key)) {
                    datapoints.push({ Name: key, Sum: groupedData[key].Value, Voters: groupedData[key].Voters });
                    winningScore = Math.max(winningScore, groupedData[key].Value);
                }
            }

            var winners = datapoints.filter(function (d) {
                return d.Sum === winningScore;
            });

            $scope.winner = winners.map(function (d) {
                return d.Name;
            }).join(', ');

            $scope.plural = (winners.length > 1) ? 's (Draw)' : '';

            drawD3Chart(datapoints);
        }

        VoteService.refreshLastChecked(pollId);
        reloadData();
        setInterval(reloadData, 3000);
    }
})();
<|endoftext|>


<commit_before>const getSteps = require('./new_account_form_config/wizard-step-config');
const Client = require('../../../base/client');
const BinarySocket = require('../../../base/socket');
const AccountOpening = require('../../../common/account_opening');
const FormManager = require('../../../common/form_manager');
const FormProgress = require('../../../common/form_progress');
const getElementById = require('../../../../_common/common_functions').getElementById;
const param = require('../../../../_common/url').param;
const { localize } = require('../../../../_common/localize');

const RealAccountOpening = (() => {
    let real_account_signup_target,
        steps,
        current_step,
        account_details,
        action_previous_buttons;

    const onLoad = async () => {
        real_account_signup_target = param('account_type');
        const currency_to_set = sessionStorage.getItem('new_financial_account_set_currency');
        if (currency_to_set) AccountOpening.setCurrencyForFinancialAccount(currency_to_set);
        else {
            const residence_list_promise = BinarySocket.send({ residence_list: 1 });
            const account_settings_promise = BinarySocket.send({ get_settings: 1 });
            const financial_assessment_promise = BinarySocket.send({ get_financial_assessment: 1 });
            const [residence_list_response, account_settings_response, financial_assessment_response] =
                await Promise.all([residence_list_promise, account_settings_promise, financial_assessment_promise]);
            const account_settings = account_settings_response.get_settings;
            const residence_list = residence_list_response.residence_list;
            const financial_assessment = financial_assessment_response.get_financial_assessment || {};
            if (AccountOpening.redirectAccount()) return;
            const upgrade_info = Client.getUpgradeInfo();

            account_details = { residence: account_settings.country_code };
            Object.assign(account_details,
                real_account_signup_target === 'maltainvest'
                    ? { new_account_maltainvest: 1, accept_risk: 0 }
                    : { new_account_real: 1 }
            );

            action_previous_buttons = document.getElementsByClassName('action_previous');
            Array.from(action_previous_buttons).forEach(item => { item.addEventListener('click', onClickPrevious); });
            getElementById('financial_risk_warning').addEventListener('submit', onRiskAccept);

            steps = getSteps({
                real_account_signup_target,
                residence_list,
                account_settings,
                upgrade_info,
                financial_assessment,
            });
            current_step = 0;
            steps.forEach(step => { step.body_module.init(step.fields, real_account_signup_target); });

            setPageTitle();
            getElementById('loading').setVisibility(0);
            getElementById('real_account_wrapper').setVisibility(1);
            getElementById('account_opening_steps').setVisibility(1);
            renderStep();
        }
    };

    const renderStep = (previous_step = 0) => {
        FormProgress.render('form_progress', steps, current_step);

        if (previous_step >= 0) getElementById(steps[previous_step].body_module_step).setVisibility(0);
        getElementById(steps[current_step].body_module_step).setVisibility(1);

        FormManager.init(`#${steps[current_step].body_module_step}_form`, getValidationRules(steps[current_step]));
        FormManager.handleSubmit({
            form_selector     : `#${steps[current_step].body_module_step}_form`,
            get_submitted_data: onStepSubmitted,
        });
        $.scrollTo(0, 500);
    };

    const onRiskAccept = (e) => {
        e.preventDefault();
        Object.assign(account_details, { accept_risk: 1 });
        AccountOpening.createNewAccount(account_details, $('#financial_risk_accept'));
    };

    const onStepSubmitted = async (req) => {
        Object.assign(account_details, req);
        if (current_step === steps.length - 1) {
            const should_show_financial_risk_warning = await AccountOpening.createNewAccount(account_details, $('#new_account_submit'));
            if (should_show_financial_risk_warning) showFinancialRiskWarning();
        } else renderStep(current_step++);
    };

    const showFinancialRiskWarning = () => {
        getElementById('account_opening_steps').setVisibility(0);
        getElementById('financial_risk_warning').setVisibility(1);
        $.scrollTo(0, 500);
    };

    const onClickPrevious = () => renderStep(current_step--);

    const getValidationRules = (step) => step.fields.map(field => ({
        selector   : `#${field.id}`,
        validations: field.rules,
    }));

    const setPageTitle = () => {
        getElementById('page_title').innerHTML =
            real_account_signup_target === 'maltainvest'
                ? localize('Financial Account Opening')
                : localize('Real money account opening');
    };

    const onUnload = () => { AccountOpening.showHidePulser(1); };

    return {
        onLoad,
        onUnload,
    };
})();

module.exports = RealAccountOpening;
<commit_msg>Pavel-Latyshou/Account creation form for MF still using Financial Account term (#6871)<commit_after>const getSteps = require('./new_account_form_config/wizard-step-config');
const Client = require('../../../base/client');
const BinarySocket = require('../../../base/socket');
const AccountOpening = require('../../../common/account_opening');
const FormManager = require('../../../common/form_manager');
const FormProgress = require('../../../common/form_progress');
const getElementById = require('../../../../_common/common_functions').getElementById;
const param = require('../../../../_common/url').param;
const { localize } = require('../../../../_common/localize');

const RealAccountOpening = (() => {
    let real_account_signup_target,
        steps,
        current_step,
        account_details,
        action_previous_buttons;

    const onLoad = async () => {
        real_account_signup_target = param('account_type');
        const currency_to_set = sessionStorage.getItem('new_financial_account_set_currency');
        if (currency_to_set) AccountOpening.setCurrencyForFinancialAccount(currency_to_set);
        else {
            const residence_list_promise = BinarySocket.send({ residence_list: 1 });
            const account_settings_promise = BinarySocket.send({ get_settings: 1 });
            const financial_assessment_promise = BinarySocket.send({ get_financial_assessment: 1 });
            const [residence_list_response, account_settings_response, financial_assessment_response] =
                await Promise.all([residence_list_promise, account_settings_promise, financial_assessment_promise]);
            const account_settings = account_settings_response.get_settings;
            const residence_list = residence_list_response.residence_list;
            const financial_assessment = financial_assessment_response.get_financial_assessment || {};
            if (AccountOpening.redirectAccount()) return;
            const upgrade_info = Client.getUpgradeInfo();

            account_details = { residence: account_settings.country_code };
            Object.assign(account_details,
                real_account_signup_target === 'maltainvest'
                    ? { new_account_maltainvest: 1, accept_risk: 0 }
                    : { new_account_real: 1 }
            );

            action_previous_buttons = document.getElementsByClassName('action_previous');
            Array.from(action_previous_buttons).forEach(item => { item.addEventListener('click', onClickPrevious); });
            getElementById('financial_risk_warning').addEventListener('submit', onRiskAccept);

            steps = getSteps({
                real_account_signup_target,
                residence_list,
                account_settings,
                upgrade_info,
                financial_assessment,
            });
            current_step = 0;
            steps.forEach(step => { step.body_module.init(step.fields, real_account_signup_target); });

            setPageTitle();
            getElementById('loading').setVisibility(0);
            getElementById('real_account_wrapper').setVisibility(1);
            getElementById('account_opening_steps').setVisibility(1);
            renderStep();
        }
    };

    const renderStep = (previous_step = 0) => {
        FormProgress.render('form_progress', steps, current_step);

        if (previous_step >= 0) getElementById(steps[previous_step].body_module_step).setVisibility(0);
        getElementById(steps[current_step].body_module_step).setVisibility(1);

        FormManager.init(`#${steps[current_step].body_module_step}_form`, getValidationRules(steps[current_step]));
        FormManager.handleSubmit({
            form_selector     : `#${steps[current_step].body_module_step}_form`,
            get_submitted_data: onStepSubmitted,
        });
        $.scrollTo(0, 500);
    };

    const onRiskAccept = (e) => {
        e.preventDefault();
        Object.assign(account_details, { accept_risk: 1 });
        AccountOpening.createNewAccount(account_details, $('#financial_risk_accept'));
    };

    const onStepSubmitted = async (req) => {
        Object.assign(account_details, req);
        if (current_step === steps.length - 1) {
            const should_show_financial_risk_warning = await AccountOpening.createNewAccount(account_details, $('#new_account_submit'));
            if (should_show_financial_risk_warning) showFinancialRiskWarning();
        } else renderStep(current_step++);
    };

    const showFinancialRiskWarning = () => {
        getElementById('account_opening_steps').setVisibility(0);
        getElementById('financial_risk_warning').setVisibility(1);
        $.scrollTo(0, 500);
    };

    const onClickPrevious = () => renderStep(current_step--);

    const getValidationRules = (step) => step.fields.map(field => ({
        selector   : `#${field.id}`,
        validations: field.rules,
    }));

    const setPageTitle = () => {
        getElementById('page_title').innerHTML = localize('Real money account opening');
    };

    const onUnload = () => { AccountOpening.showHidePulser(1); };

    return {
        onLoad,
        onUnload,
    };
})();

module.exports = RealAccountOpening;
<|endoftext|>


<commit_before>'use strict'

const generators = require('yeoman-generator')
const replace = require('replace')
const path = require('path')
const got = require('got')
const semver = require('semver')
const zlib = require('zlib')
const tar = require('tar')

const cwd = process.cwd()
let THEME_PATH = cwd
let THEME_NAME

module.exports = generators.Base.extend({

  constructor: function () {
    generators.Base.apply(this, arguments)
    this.argument('name', {type: String, required: false})
  },

  prompting: function () {
    let done = this.async()

    if (this.name) {
      THEME_PATH = path.join(cwd, this.name)
      THEME_NAME = this.name
      return done()
    }

    this.prompt({
      type: 'input',
      name: 'name',
      message: 'Your theme name',
      default: 'oddbaby'
    }, function (answers) {
      THEME_PATH = path.join(cwd, answers.name)
      THEME_NAME = answers.name
      done()
    })
  },

  // Download oddbaby
  download: function () {
    let done = this.async()
    let self = this

    self.log('Downloading Oddbaby...')

    // Get latest oddbaby-8 release from the api: /repos/:owner/:repo/releases/latest
    got('https://api.github.com/repos/oddhill/oddbaby-8/tags', { json: true, headers: { 'accept': 'application/vnd.github.v3+json' } })
      .then(function (res) {
        let versions = res.body.sort(function (a, b) {
          return semver.compare(b.name, a.name)
        })

        return versions[0].tarball_url
      })
      .then(function (tarURL) {
        // Download and extract the zip to public/themes
        got.stream(tarURL)
          .pipe(zlib.Unzip())
          .pipe(tar.Extract({ path: THEME_PATH, strip: 1 }))
          .on('end', function () {
            self.log('Done')
            done()
          })
      })
  },

  renameFiles: function () {
    // @TODO:
    // - Rename oddbaby.* files.
    // - oddbaby.breakpoints.yml
    // - oddbaby.info.yml
    // - oddbaby.libraries.yml
    // - oddbaby.theme
  },

  renameFilesContent: function () {
    // @TODO:
    // - Rename `oddbaby` in oddbaby.info.yml
    // - Rename `oddbaby` in oddbaby.breakpoints.yml
    // - Rename `oddbaby` in oddbaby.theme
  },

  install: function () {
    // Run npm-install
    this.destinationRoot(theme_path)
    this.installDependencies({bower: false})
  },

  end: function () {
    this.log('All done!')
  }

})
<commit_msg>Rename files [ci skip]<commit_after>'use strict'

const generators = require('yeoman-generator')
const replace = require('replace')
const path = require('path')
const got = require('got')
const semver = require('semver')
const zlib = require('zlib')
const tar = require('tar')
const fs = require('fs')

const cwd = process.cwd()
let THEME_PATH = cwd
let THEME_NAME

module.exports = generators.Base.extend({

  constructor: function () {
    generators.Base.apply(this, arguments)
    this.argument('name', {type: String, required: false})
  },

  prompting: function () {
    let done = this.async()

    if (this.name) {
      THEME_PATH = path.join(cwd, this.name)
      THEME_NAME = this.name
      return done()
    }

    this.prompt({
      type: 'input',
      name: 'name',
      message: 'Your theme name',
      default: 'oddbaby'
    }, function (answers) {
      THEME_PATH = path.join(cwd, answers.name)
      THEME_NAME = answers.name
      done()
    })
  },

  // Download oddbaby
  download: function () {
    let done = this.async()
    let self = this

    self.log('Downloading Oddbaby...')

    // Get latest oddbaby-8 release from the api: /repos/:owner/:repo/releases/latest
    got('https://api.github.com/repos/oddhill/oddbaby-8/tags', { json: true, headers: { 'accept': 'application/vnd.github.v3+json' } })
      .then(function (res) {
        let versions = res.body.sort(function (a, b) {
          return semver.compare(b.name, a.name)
        })

        return versions[0].tarball_url
      })
      .then(function (tarURL) {
        // Download and extract the zip to public/themes
        got.stream(tarURL)
          .pipe(zlib.Unzip())
          .pipe(tar.Extract({ path: THEME_PATH, strip: 1 }))
          .on('end', function () {
            self.log('Done')
            done()
          })
      })
  },

  renameFiles: function () {
    // Rename oddbaby.* files.
    let files = ['oddbaby.breakpoints.yml', 'oddbaby.info.yml', 'oddbaby.libraries.yml', 'oddbaby.theme']
    for (let file in files) {
      fs.renameSync(path.join(THEME_PATH, files[file]), path.join(THEME_PATH, files[file].replace(/[^.]*/, THEME_NAME)))
    }
  },

  renameFilesContent: function () {
    // @TODO:
    // - Rename `oddbaby` in oddbaby.info.yml
    // - Rename `oddbaby` in oddbaby.breakpoints.yml
    // - Rename `oddbaby` in oddbaby.theme
  },

  install: function () {
    // Run npm-install
    this.destinationRoot(THEME_PATH)
    this.installDependencies({bower: false})
  },

  end: function () {
    this.log('All done!')
  }

})
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.3.3
(function() {
  var App;

  App = Em.Application.create({
    rootElement: '#application',
    autoinit: true,
    applicationTitle: 'Dynamic Extensions for Alfresco',
    title: '',
    titleDidChange: (function() {
      var title;
      title = this.get('title');
      if (title) {
        title = "" + title + " - " + (this.get('applicationTitle'));
      } else {
        title = this.get('applicationTitle');
      }
      return document.title = title;
    }).observes('title', 'applicationTitle')
  });

  App.Api = Em.Object.extend({
    baseUri: 'http://localhost:8080/alfresco/service',
    managementInfoUri: (function() {
      return this._uri('/dynamic-extensions/management/info');
    }).property('baseUri'),
    dictionaryUri: (function() {
      return this._uri('/json-api/dictionary');
    }).property('baseUri'),
    dataTypesUri: (function() {
      return this._uri('/json-api/dictionary/data-types');
    }).property('baseUri'),
    namespacesUri: (function() {
      return this._uri('/json-api/dictionary/namespaces');
    }).property('baseUri'),
    _uri: function(relativePath) {
      return this.get('baseUri') + relativePath;
    },
    init: function() {
      return $.ajaxSetup({
        dataFilter: function(data, type) {
          return data.replace(/"\/Date\((\d+)\)\/"/, '$1');
        }
      });
    },
    getManagementInfo: function() {
      var location;
      location = this.get('managementInfoUri');
      return $.getJSON(location).promise();
    },
    getModelDefinitions: function() {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/models";
      return $.getJSON(location).promise();
    },
    getModelMetadata: function(name) {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/models/" + (encodeURI(name)) + "/metadata";
      return $.getJSON(location).promise();
    },
    getClassDefinition: function(name) {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/classes/" + (encodeURI(name));
      return $.getJSON(location).promise();
    },
    getDataTypes: function() {
      var location;
      location = this.get('dataTypesUri');
      return $.getJSON(location).promise();
    },
    getNamespaces: function() {
      var location;
      location = this.get('namespacesUri');
      return $.getJSON(location).promise();
    }
  });

  App.api = App.Api.create();

  (typeof exports !== "undefined" && exports !== null ? exports : this).App = App;

}).call(this);
<commit_msg>make baseUri relative, so Dashboard can be used remotely<commit_after>// Generated by CoffeeScript 1.3.3
(function() {
  var App;

  App = Em.Application.create({
    rootElement: '#application',
    autoinit: true,
    applicationTitle: 'Dynamic Extensions for Alfresco',
    title: '',
    titleDidChange: (function() {
      var title;
      title = this.get('title');
      if (title) {
        title = "" + title + " - " + (this.get('applicationTitle'));
      } else {
        title = this.get('applicationTitle');
      }
      return document.title = title;
    }).observes('title', 'applicationTitle')
  });

  App.Api = Em.Object.extend({
    baseUri: '/alfresco/service',
    managementInfoUri: (function() {
      return this._uri('/dynamic-extensions/management/info');
    }).property('baseUri'),
    dictionaryUri: (function() {
      return this._uri('/json-api/dictionary');
    }).property('baseUri'),
    dataTypesUri: (function() {
      return this._uri('/json-api/dictionary/data-types');
    }).property('baseUri'),
    namespacesUri: (function() {
      return this._uri('/json-api/dictionary/namespaces');
    }).property('baseUri'),
    _uri: function(relativePath) {
      return this.get('baseUri') + relativePath;
    },
    init: function() {
      return $.ajaxSetup({
        dataFilter: function(data, type) {
          return data.replace(/"\/Date\((\d+)\)\/"/, '$1');
        }
      });
    },
    getManagementInfo: function() {
      var location;
      location = this.get('managementInfoUri');
      return $.getJSON(location).promise();
    },
    getModelDefinitions: function() {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/models";
      return $.getJSON(location).promise();
    },
    getModelMetadata: function(name) {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/models/" + (encodeURI(name)) + "/metadata";
      return $.getJSON(location).promise();
    },
    getClassDefinition: function(name) {
      var location;
      location = "" + (this.get('dictionaryUri')) + "/classes/" + (encodeURI(name));
      return $.getJSON(location).promise();
    },
    getDataTypes: function() {
      var location;
      location = this.get('dataTypesUri');
      return $.getJSON(location).promise();
    },
    getNamespaces: function() {
      var location;
      location = this.get('namespacesUri');
      return $.getJSON(location).promise();
    }
  });

  App.api = App.Api.create();

  (typeof exports !== "undefined" && exports !== null ? exports : this).App = App;

}).call(this);
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import uniqBy from 'lodash/uniqBy';
import sumBy from 'lodash/sumBy';
import findIndex from 'lodash/findIndex';
import { sortByKey } from 'utils/data';
import { format } from 'd3-format';

// get list data
const getData = state => state.data || null;
const getSettings = state => state.settings || null;
const getLocation = state => state.payload || null;
const getLocationsMeta = state => state[state.adminKey] || null;
const getColors = state => state.colors || null;
const getIndicator = state => state.indicator || null;
const getCurrentLocation = state => state.currentLocation || null;
const getCurrentLabel = state => state.currentLabel || null;
const getSentences = state => state.config.sentences || null;

export const getSortedData = createSelector(
  [getData, getSettings],
  (data, settings) => {
    if (!data || !data.length) return null;
    return sortByKey(
      uniqBy(data, 'id'),
      settings.unit === 'ha' ? 'gain' : 'percentage',
      true
    ).map((d, i) => ({
      ...d,
      rank: i + 1
    }));
  }
);

export const parseData = createSelector(
  [
    getSortedData,
    getSettings,
    getLocation,
    getCurrentLocation,
    getLocationsMeta,
    getColors
  ],
  (data, settings, location, currentLocation, meta, colors) => {
    if (!data || !data.length) return null;
    const locationIndex = findIndex(data, d => d.id === currentLocation.value);
    let trimStart = locationIndex - 2;
    let trimEnd = locationIndex + 3;
    if (locationIndex < 2) {
      trimStart = 0;
      trimEnd = 5;
    }
    if (locationIndex > data.length - 3) {
      trimStart = data.length - 5;
      trimEnd = data.length;
    }
    const dataTrimmed = data.slice(trimStart, trimEnd);
    return dataTrimmed.map(d => {
      const locationData = meta && meta.find(l => d.id === l.value);
      let path = '/dashboards/country/';
      if (location.subRegion) {
        path += `${location.country}/${location.region}/${d.id}`;
      } else if (location.region) {
        path += `${location.country}/${d.id}`;
      } else {
        path += d.id;
      }

      return {
        ...d,
        label: (locationData && locationData.label) || '',
        color: colors.main,
        path,
        value: settings.unit === 'ha' ? d.gain : d.percentage
      };
    });
  }
);

export const getSentence = createSelector(
  [
    getSortedData,
    getSettings,
    getIndicator,
    getCurrentLocation,
    getCurrentLabel,
    getSentences
  ],
  (data, settings, indicator, currentLocation, currentLabel, sentences) => {
    if (!data || !data.length) return null;
    const {
      initial,
      withIndicator,
      globalWithIndicator,
      globalInitial
    } = sentences;
    const locationData = currentLabel && data.find(l => l.id === currentLabel);
    const gain = locationData ? locationData.gain : sumBy(data, 'gain');
    const globalPercent = gain ? 100 * gain / sumBy(data, 'gain') : 0;
    const areaPercent = locationData
      ? locationData.percentage
      : 100 * gain / sumBy(data, 'extent');
    const indicatorName = indicator ? indicator.label : 'region-wide';

    const params = {
      location: currentLabel === 'global' ? 'globally' : currentLabel,
      gain: `${format('.3s')(gain)}ha`,
      indicator: indicatorName.toLowerCase(),
      indicator_alt: indicatorName.toLowerCase(),
      percent: areaPercent >= 0.1 ? `${format('.1f')(areaPercent)}%` : '<0.1%',
      globalPercent:
        globalPercent >= 0.1 ? `${format('.1f')(globalPercent)}%` : '<0.1%',
      extentYear: settings.extentYear
    };

    let sentence = indicator ? withIndicator : initial;
    if (currentLabel === 'global') {
      sentence = indicator ? globalWithIndicator : globalInitial;
    }

    return {
      sentence,
      params
    };
  }
);
<commit_msg>Fix fix<commit_after>import { createSelector } from 'reselect';
import uniqBy from 'lodash/uniqBy';
import sumBy from 'lodash/sumBy';
import findIndex from 'lodash/findIndex';
import { sortByKey } from 'utils/data';
import { format } from 'd3-format';

// get list data
const getData = state => state.data || null;
const getSettings = state => state.settings || null;
const getLocation = state => state.payload || null;
const getLocationsMeta = state => state[state.adminKey] || null;
const getColors = state => state.colors || null;
const getIndicator = state => state.indicator || null;
const getCurrentLocation = state => state.currentLocation || null;
const getCurrentLabel = state => state.currentLabel || null;
const getSentences = state => state.config.sentences || null;

export const getSortedData = createSelector(
  [getData, getSettings],
  (data, settings) => {
    if (!data || !data.length) return null;
    return sortByKey(
      uniqBy(data, 'id'),
      settings.unit === 'ha' ? 'gain' : 'percentage',
      true
    ).map((d, i) => ({
      ...d,
      rank: i + 1
    }));
  }
);

export const parseData = createSelector(
  [
    getSortedData,
    getSettings,
    getLocation,
    getCurrentLocation,
    getLocationsMeta,
    getColors
  ],
  (data, settings, location, currentLocation, meta, colors) => {
    if (!data || !data.length) return null;
    const locationIndex = findIndex(data, d => d.id === currentLocation.value);
    let trimStart = locationIndex - 2;
    let trimEnd = locationIndex + 3;
    if (locationIndex < 2) {
      trimStart = 0;
      trimEnd = 5;
    }
    if (locationIndex > data.length - 3) {
      trimStart = data.length - 5;
      trimEnd = data.length;
    }
    const dataTrimmed = data.slice(trimStart, trimEnd);
    return dataTrimmed.map(d => {
      const locationData = meta && meta.find(l => d.id === l.value);
      let path = '/dashboards/country/';
      if (location.subRegion) {
        path += `${location.country}/${location.region}/${d.id}`;
      } else if (location.region) {
        path += `${location.country}/${d.id}`;
      } else {
        path += d.id;
      }

      return {
        ...d,
        label: (locationData && locationData.label) || '',
        color: colors.main,
        path,
        value: settings.unit === 'ha' ? d.gain : d.percentage
      };
    });
  }
);

export const getSentence = createSelector(
  [
    getSortedData,
    getSettings,
    getIndicator,
    getCurrentLocation,
    getCurrentLabel,
    getSentences
  ],
  (data, settings, indicator, currentLocation, currentLabel, sentences) => {
    if (!data || !data.length) return null;
    const {
      initial,
      withIndicator,
      globalWithIndicator,
      globalInitial
    } = sentences;
    const locationData =
      currentLocation && data.find(l => l.id === currentLocation.value);
    const gain = locationData ? locationData.gain : sumBy(data, 'gain');
    const globalPercent = gain ? 100 * gain / sumBy(data, 'gain') : 0;
    const areaPercent = locationData
      ? locationData.percentage
      : 100 * gain / sumBy(data, 'extent');
    const indicatorName = indicator ? indicator.label : 'region-wide';

    const params = {
      location: currentLabel === 'global' ? 'globally' : currentLabel,
      gain: `${format('.3s')(gain)}ha`,
      indicator: indicatorName.toLowerCase(),
      indicator_alt: indicatorName.toLowerCase(),
      percent: areaPercent >= 0.1 ? `${format('.1f')(areaPercent)}%` : '<0.1%',
      globalPercent:
        globalPercent >= 0.1 ? `${format('.1f')(globalPercent)}%` : '<0.1%',
      extentYear: settings.extentYear
    };

    let sentence = indicator ? withIndicator : initial;
    if (currentLabel === 'global') {
      sentence = indicator ? globalWithIndicator : globalInitial;
    }

    return {
      sentence,
      params
    };
  }
);
<|endoftext|>