<commit_before>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        require: '^form',
        template:
            '
' +
                '
' +
                    '{{error}}' +
                '
' +
            '
',
        replace: true,
        transclude: true,
        restrict: 'AE',
        scope: { isValid: '=' },
        link: function postLink(scope, elem, attrs, ctrl) {
            // list of some default error reasons
            var defaultErrorReasons = {
                    required: 'is required.',
                    minlength: 'is too short.',
                    maxlength: 'is too long.',
                    email: 'is not a valid email address.',
                    pattern: 'does not match the expected pattern.',
                    number: 'is not a number.',

                    fallback: 'is invalid.'
                },
                // humanize words, turning:
                //     camelCase  --> Camel Case
                //     dash-case  --> Dash Case
                //     snake_case --> Snake Case
                humanize = function (str) {
                    return str.replace(/[-_+]/g, ' ') // turn _ and - into spaces
                              .replace(/([A-Z])/g, ' $1') // put a splace before every capital letter
                              .replace(/^([a-z])|\s+([a-z])/g, // capitalize the first letter of each word
                                    function ($1) { return $1.toUpperCase(); }
                    );
                },
                // this is where we form our message
                errorMessage = function (name, error, props) {
                    // get the nice name if they used the niceName
                    // directive or humanize the name and call it good
                    var niceName = props.$niceName || humanize(name);

                    // get a reason from our default set
                    var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;

                    // if they used the errorMessages directive, grab that message
                    if(typeof props.$errorMessages === 'object')
                        reason = props.$errorMessages[error];
                    else if(typeof props.$errorMessages === 'string')
                        reason = props.$errorMessages;

                    // return our nicely formatted message
                    return niceName + ' ' + reason;
                };

            // only update the list of errors if there was actually a change
            scope.$watch(function() { return ctrl.$error; }, function() {
                // we can pass in a variable to keep track of form validity in page's ctrl
                scope.isValid = ctrl.$valid;
                scope.errors = [];
                angular.forEach(ctrl, function(props, name) {
                    // name has some internal properties we don't want to iterate over
                    if(name[0] === '$') return;
                    angular.forEach(props.$error, function(isInvalid, error) {
                        // don't need to even try and get a a message unless it's invalid
                        if(isInvalid) {
                            scope.errors.push(errorMessage(name, error, props));
                        }
                    });
                });
            }, true);
        }
    };
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            ctrl.$niceName = attrs.niceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch(e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }
        }
    };
}]);<commit_msg>isValid wasn't really necessary I guess...<commit_after>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        require: '^form',
        template:
            '
' +
                '
' +
                    '{{error}}' +
                '
' +
            '
',
        replace: true,
        transclude: true,
        restrict: 'AE',
        link: function postLink(scope, elem, attrs, ctrl) {
            // list of some default error reasons
            var defaultErrorReasons = {
                    required: 'is required.',
                    minlength: 'is too short.',
                    maxlength: 'is too long.',
                    email: 'is not a valid email address.',
                    pattern: 'does not match the expected pattern.',
                    number: 'is not a number.',

                    fallback: 'is invalid.'
                },
                // humanize words, turning:
                //     camelCase  --> Camel Case
                //     dash-case  --> Dash Case
                //     snake_case --> Snake Case
                humanize = function (str) {
                    return str.replace(/[-_+]/g, ' ') // turn _ and - into spaces
                              .replace(/([A-Z])/g, ' $1') // put a splace before every capital letter
                              .replace(/^([a-z])|\s+([a-z])/g, // capitalize the first letter of each word
                                    function ($1) { return $1.toUpperCase(); }
                    );
                },
                // this is where we form our message
                errorMessage = function (name, error, props) {
                    // get the nice name if they used the niceName
                    // directive or humanize the name and call it good
                    var niceName = props.$niceName || humanize(name);

                    // get a reason from our default set
                    var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;

                    // if they used the errorMessages directive, grab that message
                    if(typeof props.$errorMessages === 'object')
                        reason = props.$errorMessages[error];
                    else if(typeof props.$errorMessages === 'string')
                        reason = props.$errorMessages;

                    // return our nicely formatted message
                    return niceName + ' ' + reason;
                };

            // only update the list of errors if there was actually a change in $error
            scope.$watch(function() { return ctrl.$error; }, function() {
                // reset error array
                scope.errors = [];
                angular.forEach(ctrl, function(props, name) {
                    // name has some internal properties we don't want to iterate over
                    if(name[0] === '$') return;
                    angular.forEach(props.$error, function(isInvalid, error) {
                        // don't need to even try and get a a message unless it's invalid
                        if(isInvalid) {
                            scope.errors.push(errorMessage(name, error, props));
                        }
                    });
                });
            }, true);
        }
    };
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            ctrl.$niceName = attrs.niceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch(e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }
        }
    };
}]);<|endoftext|>


<commit_before>// ***********************************************//
//                 controllers
// ***********************************************//

// Define the main application controller. This is automatically picked up by
// the application and initialized.
require('akvo-flow/core');
FLOW.ApplicationController = Ember.Controller.extend({
	init:function(){
		Ember.STRINGS=Ember.STRINGS_EN;
		//this.set("dashboardLanguage","en");
	}
});

// Navigation controllers
FLOW.NavigationController = Em.Controller.extend({
	selected: null
});

FLOW.NavHomeController = Ember.Controller.extend();

FLOW.NavSurveysController = Ember.Controller.extend();

FLOW.NavDevicesController = Ember.Controller.extend();
FLOW.DevicesSubnavController = Em.Controller.extend();
FLOW.DevicesTableHeaderController = Em.Controller.extend({
	selected:null
});

FLOW.NavDataController = Ember.Controller.extend();
FLOW.DatasubnavController = Em.Controller.extend();
FLOW.InspectDataController = Ember.ArrayController.extend();
FLOW.ImportSurveyController = Ember.Controller.extend();
FLOW.ExcelImportController = Ember.Controller.extend();
FLOW.ExcelExportController = Ember.Controller.extend();

FLOW.NavReportsController = Ember.Controller.extend();

FLOW.NavMapsController = Ember.Controller.extend();

FLOW.NavUsersController = Ember.Controller.extend();

FLOW.NavAdminController = Ember.Controller.extend();

// Data controllers

FLOW.languageControl = Ember.Object.create({
	dashboardLanguage:null,

	content:[
      Ember.Object.create({label: "English", value: "en"}),
      Ember.Object.create({label: "Dutch", value: "nl"}),
      Ember.Object.create({label: "Spanish", value: "sp"}),
      Ember.Object.create({label: "French", value: "fr"})],

	changeLanguage:function(){
		locale=this.get("dashboardLanguage.value");
		console.log('changing language to ',locale);

		if (locale == "nl") {Ember.STRINGS=Ember.STRINGS_NL;}
		else if (locale == "fr") {Ember.STRINGS=Ember.STRINGS_FR;}
		else if (locale == "sp") {Ember.STRINGS=Ember.STRINGS_SP;}
		else {Ember.STRINGS=Ember.STRINGS_EN;}
	}.observes('dashboardLanguage')
});

FLOW.questionTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Free text", value: "freeText"}),
   Ember.Object.create({label: "Option", value: "option"}),
   Ember.Object.create({label: "Number", value: "number"}),
   Ember.Object.create({label: "Geolocation", value: "geoLoc"}),
   Ember.Object.create({label: "Photo", value: "photo"}),
   Ember.Object.create({label: "Video", value: "video"}),
   Ember.Object.create({label: "Date", value: "date"}),
   Ember.Object.create({label: "Barcode", value: "barcode"})
]});

FLOW.surveyTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Point", value: "point"}),
   Ember.Object.create({label: "Household", value: "household"}),
   Ember.Object.create({label: "Public institution", value: "publicInstitution"}),
   Ember.Object.create({label: "Community", value: "community"})

]});

FLOW.surveySectorTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Water and Sanitation", value: "waterAndSanitation"}),
   Ember.Object.create({label: "Education", value: "education"}),
   Ember.Object.create({label: "Economic development", value: "economicDevelopment"}),
   Ember.Object.create({label: "Health care", value: "healthCare"}),
   Ember.Object.create({label: "IT and Communication", value: "ItAndCommunication"}),
   Ember.Object.create({label: "Food security", value: "foodSecurity"}),
   Ember.Object.create({label: "Other", value: "other"})
]});

FLOW.selectedControl = Ember.Controller.create({
	selectedSurveyGroup: null,
	selectedSurvey: null,
	selectedQuestionGroup: null,
	selectedForMoveQuestionGroup:null,
	selectedForCopyQuestionGroup:null,
	selectedQuestion: null,
	selectedOption: null,
	selectedCreateNewGroup:false
});

FLOW.selectedControl.addObserver('selectedSurveyGroup', function() {
	FLOW.selectedControl.set('selectedSurvey', null);
	FLOW.selectedControl.set('selectedQuestionGroup', null);

});

FLOW.deviceControl = Ember.ArrayController.create({
	sortProperties:['phoneNumber'],
	pleaseShow:true,
	sortAscending:true,
	sortSelected:null,

	//active: function() {
	//		//TODO find out how items are being loaded, difference find and findAll
	//		return FLOW.store.findAll(FLOW.Device);
	//}.property('').cacheable()

	allAreSelected: function(key, value) {
    if (arguments.length === 2) {
      this.setEach('isSelected', value);
      return value;
    }
    else {
      return !this.get('isEmpty') && this.everyProperty('isSelected', true);
    }
  }.property('@each.isSelected'),

  atLeastOneSelected: function() {
    return this.filterProperty('isSelected', true).get('length');
  }.property('@each.isSelected')

});

FLOW.SurveyGroupController = Ember.ArrayController.extend({});

FLOW.surveyGroupControl = Ember.ArrayController.create({
	content:FLOW.store.findAll(FLOW.SurveyGroup)

	//init: function(){
//		this.set("content",FLOW.store.find(FLOW.SurveyGroup,{}));
//	}

//	active: function() {
			//TODO find out how items are being loaded, difference find and findAll
			//console.log(FLOW.store.find(FLOW.SurveyGroup,{}));
		//	return FLOW.store.find(FLOW.SurveyGroup,{});
//	}.property('').cacheable()
});

FLOW.surveyControl = Ember.ArrayController.create({

	active: function() {
		if (FLOW.selectedControl.get('selectedSurveyGroup')) {
			var id = FLOW.selectedControl.selectedSurveyGroup.get('keyId');
			return FLOW.store.findQuery(FLOW.Survey, {surveyGroupId: id});
		} else {
			FLOW.selectedControl.set('selectedSurvey', null);
			FLOW.selectedControl.set('selectedQuestionGroup', null);
			return null;
		}
	}.property('FLOW.selectedControl.selectedSurveyGroup').cacheable()
});

FLOW.questionGroupControl = Ember.ArrayController.create({
	sortProperties:['order'],
	sortAscending:true,

	// not used at the moment in survey tab
	active: function() {
		if (FLOW.selectedControl.get('selectedSurvey')) {
			var id = FLOW.selectedControl.selectedSurvey.get('keyId');
			return FLOW.store.findQuery(FLOW.QuestionGroup, {surveyId: id});
		} else {
			FLOW.selectedControl.set('selectedQuestionGroup', null);
			return null;
		}
	}.property('FLOW.selectedControl.selectedSurvey').cacheable()

});

FLOW.questionControl = Ember.ArrayController.create({
	active: function() {
		if (FLOW.selectedControl.get('selectedQuestionGroup')) {
			var id = FLOW.selectedControl.selectedQuestionGroup.get('keyId');

			return FLOW.store.findQuery(FLOW.Question, {questionGroupId: id});
		} else {
			return null;
		}
	}.property('FLOW.selectedControl.selectedQuestionGroup', 'FLOW.selectedControl.selectedSurvey').cacheable()
});

FLOW.optionControl = Ember.ArrayController.create({

	//editCopy:null,

	//questionOptions: function() {
	//	if (FLOW.selectedControl.get('selectedQuestion')) {
	//		var id = FLOW.selectedControl.selectedQuestion.get('keyId');
	//		return FLOW.store.find(FLOW.QuestionOption, {questionId: id});
	//	} else {
	//		return null;
	//}
	//}.property('FLOW.selectedControl.selectedQuestion').cacheable(),

	//questionOptionsList: function(){
	//	var opList = this.get('questionOptions').mapProperty('text').join("\n");
	//	return opList;
	//	}.property('this.questionOptions','this.questionOptions.isLoaded').cacheable(),

	//makeEditCopy: function(){
	//	this.set('editCopy',this.get('questionOptionsList'));
	//}.observes('questionOptionsList')
});

<commit_msg>add reloadSurveys to trigger reloading surveys<commit_after>// ***********************************************//
//                 controllers
// ***********************************************//

// Define the main application controller. This is automatically picked up by
// the application and initialized.
require('akvo-flow/core');
FLOW.ApplicationController = Ember.Controller.extend({
	init:function(){
		Ember.STRINGS=Ember.STRINGS_EN;
		//this.set("dashboardLanguage","en");
	}
});

// Navigation controllers
FLOW.NavigationController = Em.Controller.extend({
	selected: null
});

FLOW.NavHomeController = Ember.Controller.extend();

FLOW.NavSurveysController = Ember.Controller.extend();

FLOW.NavDevicesController = Ember.Controller.extend();
FLOW.DevicesSubnavController = Em.Controller.extend();
FLOW.DevicesTableHeaderController = Em.Controller.extend({
	selected:null
});

FLOW.NavDataController = Ember.Controller.extend();
FLOW.DatasubnavController = Em.Controller.extend();
FLOW.InspectDataController = Ember.ArrayController.extend();
FLOW.ImportSurveyController = Ember.Controller.extend();
FLOW.ExcelImportController = Ember.Controller.extend();
FLOW.ExcelExportController = Ember.Controller.extend();

FLOW.NavReportsController = Ember.Controller.extend();

FLOW.NavMapsController = Ember.Controller.extend();

FLOW.NavUsersController = Ember.Controller.extend();

FLOW.NavAdminController = Ember.Controller.extend();

// Data controllers

FLOW.languageControl = Ember.Object.create({
	dashboardLanguage:null,

	content:[
      Ember.Object.create({label: "English", value: "en"}),
      Ember.Object.create({label: "Dutch", value: "nl"}),
      Ember.Object.create({label: "Spanish", value: "sp"}),
      Ember.Object.create({label: "French", value: "fr"})],

	changeLanguage:function(){
		locale=this.get("dashboardLanguage.value");
		console.log('changing language to ',locale);

		if (locale == "nl") {Ember.STRINGS=Ember.STRINGS_NL;}
		else if (locale == "fr") {Ember.STRINGS=Ember.STRINGS_FR;}
		else if (locale == "sp") {Ember.STRINGS=Ember.STRINGS_SP;}
		else {Ember.STRINGS=Ember.STRINGS_EN;}
	}.observes('dashboardLanguage')
});

FLOW.questionTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Free text", value: "freeText"}),
   Ember.Object.create({label: "Option", value: "option"}),
   Ember.Object.create({label: "Number", value: "number"}),
   Ember.Object.create({label: "Geolocation", value: "geoLoc"}),
   Ember.Object.create({label: "Photo", value: "photo"}),
   Ember.Object.create({label: "Video", value: "video"}),
   Ember.Object.create({label: "Date", value: "date"}),
   Ember.Object.create({label: "Barcode", value: "barcode"})
]});

FLOW.surveyTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Point", value: "point"}),
   Ember.Object.create({label: "Household", value: "household"}),
   Ember.Object.create({label: "Public institution", value: "publicInstitution"}),
   Ember.Object.create({label: "Community", value: "community"})

]});

FLOW.surveySectorTypeControl = Ember.Object.create({
content:[
	Ember.Object.create({label: "Water and Sanitation", value: "waterAndSanitation"}),
   Ember.Object.create({label: "Education", value: "education"}),
   Ember.Object.create({label: "Economic development", value: "economicDevelopment"}),
   Ember.Object.create({label: "Health care", value: "healthCare"}),
   Ember.Object.create({label: "IT and Communication", value: "ItAndCommunication"}),
   Ember.Object.create({label: "Food security", value: "foodSecurity"}),
   Ember.Object.create({label: "Other", value: "other"})
]});

FLOW.selectedControl = Ember.Controller.create({
	selectedSurveyGroup: null,
	selectedSurvey: null,
	selectedQuestionGroup: null,
	selectedForMoveQuestionGroup:null,
	selectedForCopyQuestionGroup:null,
	selectedQuestion: null,
	selectedOption: null,
	selectedCreateNewGroup:false,
	reloadSurveys:false
});

FLOW.selectedControl.addObserver('selectedSurveyGroup', function() {
	FLOW.selectedControl.set('selectedSurvey', null);
	FLOW.selectedControl.set('selectedQuestionGroup', null);

});

FLOW.deviceControl = Ember.ArrayController.create({
	sortProperties:['phoneNumber'],
	pleaseShow:true,
	sortAscending:true,
	sortSelected:null,

	//active: function() {
	//		//TODO find out how items are being loaded, difference find and findAll
	//		return FLOW.store.findAll(FLOW.Device);
	//}.property('').cacheable()

	allAreSelected: function(key, value) {
    if (arguments.length === 2) {
      this.setEach('isSelected', value);
      return value;
    }
    else {
      return !this.get('isEmpty') && this.everyProperty('isSelected', true);
    }
  }.property('@each.isSelected'),

  atLeastOneSelected: function() {
    return this.filterProperty('isSelected', true).get('length');
  }.property('@each.isSelected')

});

FLOW.SurveyGroupController = Ember.ArrayController.extend({});

FLOW.surveyGroupControl = Ember.ArrayController.create({
	content:FLOW.store.find(FLOW.SurveyGroup)
});

FLOW.surveyControl = Ember.ArrayController.create({

	active: function() {
		if (FLOW.selectedControl.get('selectedSurveyGroup')) {
			var id = FLOW.selectedControl.selectedSurveyGroup.get('keyId');
			return FLOW.store.findQuery(FLOW.Survey, {surveyGroupId: id});
		} else {
			FLOW.selectedControl.set('selectedSurvey', null);
			FLOW.selectedControl.set('selectedQuestionGroup', null);
			return null;
		}
	}.property('FLOW.selectedControl.selectedSurveyGroup','FLOW.selectedControl.reloadSurveys').cacheable()
});

FLOW.questionGroupControl = Ember.ArrayController.create({
	sortProperties:['order'],
	sortAscending:true,

	// not used at the moment in survey tab
	active: function() {
		if (FLOW.selectedControl.get('selectedSurvey')) {
			var id = FLOW.selectedControl.selectedSurvey.get('keyId');
			return FLOW.store.findQuery(FLOW.QuestionGroup, {surveyId: id});
		} else {
			FLOW.selectedControl.set('selectedQuestionGroup', null);
			return null;
		}
	}.property('FLOW.selectedControl.selectedSurvey').cacheable()

});

FLOW.questionControl = Ember.ArrayController.create({
	active: function() {
		if (FLOW.selectedControl.get('selectedQuestionGroup')) {
			var id = FLOW.selectedControl.selectedQuestionGroup.get('keyId');

			return FLOW.store.findQuery(FLOW.Question, {questionGroupId: id});
		} else {
			return null;
		}
	}.property('FLOW.selectedControl.selectedQuestionGroup', 'FLOW.selectedControl.selectedSurvey').cacheable()
});

FLOW.optionControl = Ember.ArrayController.create({

	//editCopy:null,

	//questionOptions: function() {
	//	if (FLOW.selectedControl.get('selectedQuestion')) {
	//		var id = FLOW.selectedControl.selectedQuestion.get('keyId');
	//		return FLOW.store.find(FLOW.QuestionOption, {questionId: id});
	//	} else {
	//		return null;
	//}
	//}.property('FLOW.selectedControl.selectedQuestion').cacheable(),

	//questionOptionsList: function(){
	//	var opList = this.get('questionOptions').mapProperty('text').join("\n");
	//	return opList;
	//	}.property('this.questionOptions','this.questionOptions.isLoaded').cacheable(),

	//makeEditCopy: function(){
	//	this.set('editCopy',this.get('questionOptionsList'));
	//}.observes('questionOptionsList')
});

<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'
process.title = 'ucompiler'

require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)

if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
  console.log('Usage: ucompiler go|watch [path]')
  process.exit(0)
}

if (parameters[0] === 'go') {
  UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}, function(e) {
    console.error(e)
  }).then(function(result) {
    if (!result.status) {
      process.exit(1)
    }
  })
} else if (parameters[0] === 'watch') {
  if (!parameters[1]) {
    console.error('You must specify a path to watch')
    process.exit(1)
  }
  UCompiler.watch(parameters[1], {}, function(e) {
    console.error(e)
  })
}
<commit_msg>:arrow_up: Upgrade cli to latest version<commit_after>#!/usr/bin/env node
'use strict'
process.title = 'ucompiler'

require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)

if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
  console.log('Usage: ucompiler go|watch [path]')
  process.exit(0)
}

if (parameters[0] === 'go') {
  UCompiler.compile(process.cwd(), parameters[1] || null, function(e) {
    console.error(e)
  }).then(function(result) {
    if (!result.status) {
      process.exit(1)
    }
  })
} else if (parameters[0] === 'watch') {
  UCompiler.watch(process.cwd(), parameters[1] || null, function(e) {
    console.error(e)
  })
}
<|endoftext|>


<commit_before>import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import classNames from 'classnames';

import Heading from './MediaHeading';
import Body from './MediaBody';
import Left from './MediaLeft';
import Right from './MediaRight';
import List from './MediaList';
import ListItem from './MediaListItem';

const Media = React.createClass({
  displayName: 'Media.Media',
  propTypes: {
    /**
     * You can use a custom element for the media container
     */
    componentClass: elementType
  },

  getDefaultProps() {
    return {
      componentClass: 'div'
    };
  },

  render() {
    const ComponentClass = this.props.componentClass;

    return (
      <ComponentClass {...this.props} className={classNames(this.props.className, 'media')}>
        {this.props.children}
      </ComponentClass>
    );
  }
});

export default { Media, Heading, Body, Left, Right, List, ListItem };
<commit_msg>refactor exports<commit_after>import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import classNames from 'classnames';

import Heading from './MediaHeading';
import Body from './MediaBody';
import Left from './MediaLeft';
import Right from './MediaRight';
import List from './MediaList';
import ListItem from './MediaListItem';

const Media = React.createClass({
  displayName: 'Media',
  propTypes: {
    /**
     * You can use a custom element for the media container
     */
    componentClass: elementType
  },

  getDefaultProps() {
    return {
      componentClass: 'div'
    };
  },

  render() {
    const ComponentClass = this.props.componentClass;

    return (
      <ComponentClass {...this.props} className={classNames(this.props.className, 'media')}>
        {this.props.children}
      </ComponentClass>
    );
  }
});

Object.assign(Media, { Heading, Body, Left, Right, List, ListItem });

export default Media;

export { Heading, Body, Left, Right, List, ListItem };
<|endoftext|>


<commit_before>// Copyright 2013-2015, University of Colorado Boulder

require.config( {
  deps: [ 'main' ],

  paths: {
    AXON: '.',
    PHET_CORE: '../../phet-core/js'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );<commit_msg>Adding ifphetio to config<commit_after>// Copyright 2013-2015, University of Colorado Boulder

require.config( {
  deps: [ 'main' ],

  paths: {
    AXON: '.',
    PHET_CORE: '../../phet-core/js',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );<|endoftext|>


<commit_before>/**
 * Main App Controller for the Angular Material Starter App
 * @param HueAuthService
 * @param HueDataService
 * @param $mdSidenav
 * @param $mdDialog
 * @constructor
 */
function AppController(HueAuthService, HueDataService, $mdSidenav, $mdDialog) {
    var self = this;

  self.selected     = null;
  self.selectedUser = null;
  self.selectedLight = null;
  self.selectedGroup = null;
  self.selectItem   = selectItem;
  self.toggleList   = toggleUsersList;

  self.users        = [ ];
  self.lights       = [ ];
  self.scenes       = [ ];
  self.groups       = [ ];

    function startPairing(bridges, ev) {
        // Appending dialog to document.body to cover sidenav in docs app
        // Modal dialogs should fully cover application
        // to prevent interaction outside of dialog
        if (bridges.length == 1) {
            var hue = new HueApi();
            hue.registerUser(bridges[0].ipaddress, "MaterialHue")
                .then(function(token) {
                    storeCredentials(token, bridges[0].ipaddress)
                })
                .fail(showCouldNotConnect)
                .done();
        } else {
            $mdDialog.show(
                $mdDialog.alert()
                .parent(angular.element(document.querySelector('#popupContainer')))
                .title('No bridges found')
                .textContent('Please connect to your WiFi network and refresh the page')
                .ariaLabel('No bridge found')
                .ok('Oops')
            );
        }
    };

    function showCouldNotConnect(state) {
        $mdDialog.show(
            $mdDialog.alert()
            .parent(angular.element(document.querySelector('#popupContainer')))
            .title('Press to pair')
            .textContent('Please press the pairing button on your Hue to authenticate this app.')
            .ariaLabel('Alert press pairing button')
            .ok('Did it!')
        ).then(function() {
            nupnpSearch().then(function(bridges) {
                startPairing(bridges)
            }).done();
        });
    }

    function storeCredentials(token, ip) {
        localStorage.setItem('hue-host', ip);
        localStorage.setItem('hue-token', token);
        console.log(ip, token);
    }

    HueAuthService.checkCredentialsPresentInLocalStorage().then(function(greeting) {
        HueDataService
            .loadAllUsers()
            .then(function(users) {
                self.users = [].concat(users);
            });

        HueDataService
            .loadAllLights()
            .then(function(lights) {
                self.lights = [].concat(lights);
            });

        HueDataService
            .loadAllScenes()
            .then(function(scenes) {
                self.scenes = [].concat(scenes);
            });

        HueDataService
            .loadAllGroups()
            .then(function(groups) {
                self.groups = [].concat(groups);
            });

    }, function(reason) {
        alert('Failed: ' + reason);
        nupnpSearch().then(function(bridges) {
            startPairing(bridges)
        }).done();
    });

    // *********************************
    // Internal methods
    // *********************************

    /**
     * Hide or Show the 'left' sideNav area
     */
    function toggleUsersList() {
        $mdSidenav('left').toggle();
    }

  function selectLight(light) {
      self.selected = light;
      self.selectedLight = light;
      HueDataService.blinkLight(light.id);
      HueDataService.lightStatusWithRGB(light.id).then(function(response) {
          if(typeof(response.rgb) === 'undefined') {
              console.log("No color on this one!")
          } else {
              console.log("YAY COLOR");
              self.selectedLight.state = response;
          }
      });
  }

  function selectUser(user) {
      self.selected = user;
      self.selectedUser = user;
  }

  function selectGroup(group) {
      self.selected = group;
      self.selectedGroup = group;
  }

  function selectItem ( user, light, group ) {
    var _item = user || light || group;
    if(this.users.indexOf(_item) !== -1) {
        selectUser(_item);
    } else if (this.lights.indexOf(_item) !== -1) {
        selectLight(_item);
    } else if (this.groups.indexOf(_item) !== -1) {
        selectGroup(_item);
    } else {
      console.log('unknown item');
      console.log(_item);
    }
  }
};
export default ['HueAuthService', 'HueDataService', '$mdSidenav', '$mdDialog', AppController];<commit_msg>Remove annoying alert<commit_after>/**
 * Main App Controller for the Angular Material Starter App
 * @param HueAuthService
 * @param HueDataService
 * @param $mdSidenav
 * @param $mdDialog
 * @constructor
 */
function AppController(HueAuthService, HueDataService, $mdSidenav, $mdDialog) {
    var self = this;

  self.selected     = null;
  self.selectedUser = null;
  self.selectedLight = null;
  self.selectedGroup = null;
  self.selectItem   = selectItem;
  self.toggleList   = toggleUsersList;

  self.users        = [ ];
  self.lights       = [ ];
  self.scenes       = [ ];
  self.groups       = [ ];

    function startPairing(bridges, ev) {
        // Appending dialog to document.body to cover sidenav in docs app
        // Modal dialogs should fully cover application
        // to prevent interaction outside of dialog
        if (bridges.length == 1) {
            var hue = new HueApi();
            hue.registerUser(bridges[0].ipaddress, "MaterialHue")
                .then(function(token) {
                    storeCredentials(token, bridges[0].ipaddress)
                })
                .fail(showCouldNotConnect)
                .done();
        } else {
            $mdDialog.show(
                $mdDialog.alert()
                .parent(angular.element(document.querySelector('#popupContainer')))
                .title('No bridges found')
                .textContent('Please connect to your WiFi network and refresh the page')
                .ariaLabel('No bridge found')
                .ok('Oops')
            );
        }
    };

    function showCouldNotConnect(state) {
        $mdDialog.show(
            $mdDialog.alert()
            .parent(angular.element(document.querySelector('#popupContainer')))
            .title('Press to pair')
            .textContent('Please press the pairing button on your Hue to authenticate this app.')
            .ariaLabel('Alert press pairing button')
            .ok('Did it!')
        ).then(function() {
            nupnpSearch().then(function(bridges) {
                startPairing(bridges)
            }).done();
        });
    }

    function storeCredentials(token, ip) {
        localStorage.setItem('hue-host', ip);
        localStorage.setItem('hue-token', token);
        console.log(ip, token);
    }

    HueAuthService.checkCredentialsPresentInLocalStorage().then(function(greeting) {
        HueDataService
            .loadAllUsers()
            .then(function(users) {
                self.users = [].concat(users);
            });

        HueDataService
            .loadAllLights()
            .then(function(lights) {
                self.lights = [].concat(lights);
            });

        HueDataService
            .loadAllScenes()
            .then(function(scenes) {
                self.scenes = [].concat(scenes);
            });

        HueDataService
            .loadAllGroups()
            .then(function(groups) {
                self.groups = [].concat(groups);
            });

    }, function(reason) {
        nupnpSearch().then(function(bridges) {
            startPairing(bridges)
        }).done();
    });

    // *********************************
    // Internal methods
    // *********************************

    /**
     * Hide or Show the 'left' sideNav area
     */
    function toggleUsersList() {
        $mdSidenav('left').toggle();
    }

  function selectLight(light) {
      self.selected = light;
      self.selectedLight = light;
      HueDataService.blinkLight(light.id);
      HueDataService.lightStatusWithRGB(light.id).then(function(response) {
          if(typeof(response.rgb) === 'undefined') {
              console.log("No color on this one!")
          } else {
              console.log("YAY COLOR");
              self.selectedLight.state = response;
          }
      });
  }

  function selectUser(user) {
      self.selected = user;
      self.selectedUser = user;
  }

  function selectGroup(group) {
      self.selected = group;
      self.selectedGroup = group;
  }

  function selectItem ( user, light, group ) {
    var _item = user || light || group;
    if(this.users.indexOf(_item) !== -1) {
        selectUser(_item);
    } else if (this.lights.indexOf(_item) !== -1) {
        selectLight(_item);
    } else if (this.groups.indexOf(_item) !== -1) {
        selectGroup(_item);
    } else {
      console.log('unknown item');
      console.log(_item);
    }
  }
};
export default ['HueAuthService', 'HueDataService', '$mdSidenav', '$mdDialog', AppController];<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var karma = require('karma').server;

var paths = {
  sass: ['./scss/**/*.scss', './www/lib/ionic/scss/_variables.scss']
};

gulp.task('default', ['sass']);

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass())
    .on('error', sass.logError)
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['sass']);
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('test', function(done) {
  karma.start({
    configFile: __dirname + '/tests/unit-tests.conf.js',
    singleRun: true
  }, function() {
    done();
  });
});

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});
<commit_msg>(feat) Gulp test can now run tests<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var karma = require('karma').server;

var paths = {
  sass: ['./scss/**/*.scss', './www/lib/ionic/scss/_variables.scss']
};

gulp.task('default', ['sass']);

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass())
    .on('error', sass.logError)
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['sass']);
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('test', function(done) {
  karma.start({
    configFile: __dirname + '../../karma.conf.js',
    singleRun: true
  }, function() {
    done();
  });
});

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});
<|endoftext|>


<commit_before>import "./createVectorEditor";

import "./style.css";

//export components
export {
  default as CircularView,
  CircularView as CircularViewUnconnected
} from "./CircularView";
export { default as RowView, RowView as RowViewUnconnected } from "./RowView";
export { default as RowItem, RowItem as RowItemUnconnected } from "./RowItem";
export { default as Editor, Editor as EditorUnconnected } from "./Editor";
export { default as ToolBar, ToolBar as ToolBarUnconnected } from "./ToolBar";
export {
  default as CutsiteFilter,
  CutsiteFilter as CutsiteFilterUnconnected
} from "./CutsiteFilter";
export {
  default as LinearView,
  LinearView as LinearViewUnconnected
} from "./LinearView";
export {
  default as StatusBar,
  StatusBar as StatusBarUnconnected
} from "./StatusBar";
export {
  default as DigestTool,
  DigestTool as DigestToolUnconnected
} from "./DigestTool/DigestTool";
export { default as withHover } from "./helperComponents/withHover";

export { default as vectorEditorReducer, actions } from "./redux";
export { default as updateEditor } from "./updateEditor";

export {
  default as getRangeAnglesSpecial
} from "./CircularView/getRangeAnglesSpecial";
export {
  default as PositionAnnotationOnCircle
} from "./CircularView/PositionAnnotationOnCircle";
export { default as EnzymeViewer } from "./EnzymeViewer";
<commit_msg>getting rid of funky blue outlines<commit_after>import { FocusStyleManager } from "@blueprintjs/core";
import "./createVectorEditor";
import "./style.css";

FocusStyleManager.onlyShowFocusOnTabs();

//export components
export {
  default as CircularView,
  CircularView as CircularViewUnconnected
} from "./CircularView";
export { default as RowView, RowView as RowViewUnconnected } from "./RowView";
export { default as RowItem, RowItem as RowItemUnconnected } from "./RowItem";
export { default as Editor, Editor as EditorUnconnected } from "./Editor";
export { default as ToolBar, ToolBar as ToolBarUnconnected } from "./ToolBar";
export {
  default as CutsiteFilter,
  CutsiteFilter as CutsiteFilterUnconnected
} from "./CutsiteFilter";
export {
  default as LinearView,
  LinearView as LinearViewUnconnected
} from "./LinearView";
export {
  default as StatusBar,
  StatusBar as StatusBarUnconnected
} from "./StatusBar";
export {
  default as DigestTool,
  DigestTool as DigestToolUnconnected
} from "./DigestTool/DigestTool";
export { default as withHover } from "./helperComponents/withHover";

export { default as vectorEditorReducer, actions } from "./redux";
export { default as updateEditor } from "./updateEditor";

export {
  default as getRangeAnglesSpecial
} from "./CircularView/getRangeAnglesSpecial";
export {
  default as PositionAnnotationOnCircle
} from "./CircularView/PositionAnnotationOnCircle";
export { default as EnzymeViewer } from "./EnzymeViewer";
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  "use strict";
  var Foxx = require("org/arangodb/foxx"),
    _ = require("underscore"),
    generateRepositoryState,
    generateEntityState,
    RepositoryWithOperations,
    ReplaceOperation,
    Generator,
    createCollection,
    createRepository,
    ArangoError = require('internal').ArangoError;

  RepositoryWithOperations = Foxx.Repository.extend({
    updateByIdWithOperations: function (id, operations) {
      var model = this.byId(id);
      _.each(operations, function (operation) {
        operation.execute(model);
      });
      return this.replace(model);
    }
  });

  ReplaceOperation = Foxx.Model.extend({
    isValid: function () {
      return (this.get('op') === 'replace');
    },

    execute: function (model) {
      model.set(this.getAttributeName(), this.get('value'));
    },

    // Fake implementation
    getAttributeName: function () {
      return this.get('path').split('/').pop();
    }
  }, {
    op: { type: 'string', required: true },
    path: { type: 'string', required: true },
    value: { type: 'string', required: true }
  });

  createCollection = function (appContext, collectionName) {
    var console = require("console"),
      db = require("org/arangodb").db,
      prefixedCollectionName = appContext.collectionName(collectionName);

    if (db._collection(prefixedCollectionName) === null) {
      db._create(prefixedCollectionName);
    } else if (appContext.isProduction) {
      console.warn("collection '%s' already exists. Leaving it untouched.", prefixedCollectionName);
    }

    return db._collection(prefixedCollectionName);
  };

  createRepository = function (appContext, collectionName, state) {
    var repository,
      collection = createCollection(appContext, collectionName);

    repository = new RepositoryWithOperations(collection, {
      model: state
    });

    return repository;
  };

  generateRepositoryState = function (controller, appContext, options) {
    var state = options.state,
      path = options.path,
      targetPath = options.targetPath,
      nameOfRootElement = options.nameOfRootElement,
      repository = createRepository(appContext, options.collectionName, options.state),
      perPage = options.perPage || 10,
      attributes = state.attributes,
      BodyParam = Foxx.Model.extend({}, { attributes: attributes });

    controller.get(path, function (req, res) {
      var data = {},
        page = req.params('page') || 0,
        skip = page * perPage;

      data[nameOfRootElement] = _.map(repository.all({skip: skip, limit: perPage}), function (datum) {
        return datum.forClient();
      });
      res.json(data);
    }).queryParam('page', {
      description: 'Page of the results',
      type: 'int'
    }).summary('Get all entries')
      .notes('Some fancy documentation');

    controller.get(targetPath, function (req, res) {
      var id = req.params('id'),
        entry = repository.byId(id),
        data = {};

      data[nameOfRootElement] = [entry.forClient()];

      res.json(data);
    }).pathParam('id', {
      description: 'ID of the document',
      type: 'string'
    }).summary('Get a specific entry')
      .notes('Some fancy documentation');

    // This works a little different from the standard:
    // It expects a root element, the standard does not
    controller.patch(targetPath, function (req, res) {
      var operations = req.params('operations'),
        id = req.params('id'),
        data = {};

      if (_.all(operations, function (x) { return x.isValid(); })) {
        data[nameOfRootElement] = repository.updateByIdWithOperations(id, operations).forClient();
        res.json(data);
      } else {
        res.json({ error: 'Only replace is supported right now' });
        res.status(405);
      }
    }).pathParam(path, {
      description: 'ID of the document',
      type: 'string'
    }).bodyParam('operations', 'The operations to be executed on the document', [ReplaceOperation])
      .summary('Update an entry')
      .notes('Some fancy documentation');

    controller.del(targetPath, function (req, res) {
      var id = req.params('id');
      repository.removeById(id);
      res.status(204);
    }).pathParam('id', {
      description: 'ID of the document',
      type: 'string'
    }).errorResponse(ArangoError, 404, 'An entry with this ID could not be found')
      .summary('Remove an entry')
      .notes('Some fancy documentation');

    controller.post(path, function (req, res) {
      var data = {};
      data[nameOfRootElement] = _.map(req.params(nameOfRootElement), function (model) {
        return repository.save(model).forClient();
      });
      res.status(201);
      res.json(data);
    }).bodyParam(nameOfRootElement, 'TODO', [BodyParam])
      .summary('Post new entries')
      .notes('Some fancy documentation');
  };

  generateEntityState = function (options) {
    var attributes = options.attributes;
    return Foxx.Model.extend({
      forClient: function () {
        return _.extend({ id: this.get('_key') }, this.whitelistedAttributes);
      }
    }, { attributes: attributes });
  };

  Generator = function (options) {
    this.appContext = options.applicationContext;
    this.controller = new Foxx.Controller(this.appContext, options);
    this.states = {};
    this.transitions = {};
  };

  _.extend(Generator.prototype, {
    addState: function (name, options) {
      if (options.type === 'entity') {
        // Check if it has attributes and transitions
        this.states[name] = generateEntityState(options);
      } else if (options.type === 'repository') {
        // Check if it has collectionName, perPage, transitions and a `contains` transition
        var containsRelation = _.find(options.transitions, function (transition) {
          return transition.via === 'contains';
        });
        options.state = this.states[containsRelation.to];
        options.path = '/' + name;
        options.targetPath = '/' + containsRelation.to;
        options.nameOfRootElement = name;
        this.states[name] = generateRepositoryState(this.controller, this.appContext, options);
      }
    },

    defineTransition: function (name, options) {
      this.transitions[name] = {
        relation: name,
        method: options.method
      };
    }
  });

  exports.Generator = Generator;
}());
<commit_msg>First implementation of the contains transition<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  "use strict";
  var Foxx = require("org/arangodb/foxx"),
    _ = require("underscore"),
    generateRepositoryState,
    generateEntityState,
    RepositoryWithOperations,
    ReplaceOperation,
    Generator,
    createCollection,
    createRepository,
    ContainsTransition,
    ArangoError = require('internal').ArangoError;

  RepositoryWithOperations = Foxx.Repository.extend({
    updateByIdWithOperations: function (id, operations) {
      var model = this.byId(id);
      _.each(operations, function (operation) {
        operation.execute(model);
      });
      return this.replace(model);
    }
  });

  ReplaceOperation = Foxx.Model.extend({
    isValid: function () {
      return (this.get('op') === 'replace');
    },

    execute: function (model) {
      model.set(this.getAttributeName(), this.get('value'));
    },

    // Fake implementation
    getAttributeName: function () {
      return this.get('path').split('/').pop();
    }
  }, {
    op: { type: 'string', required: true },
    path: { type: 'string', required: true },
    value: { type: 'string', required: true }
  });

  createCollection = function (appContext, collectionName) {
    var console = require("console"),
      db = require("org/arangodb").db,
      prefixedCollectionName = appContext.collectionName(collectionName);

    if (db._collection(prefixedCollectionName) === null) {
      db._create(prefixedCollectionName);
    } else if (appContext.isProduction) {
      console.warn("collection '%s' already exists. Leaving it untouched.", prefixedCollectionName);
    }

    return db._collection(prefixedCollectionName);
  };

  createRepository = function (appContext, collectionName, state) {
    var repository,
      collection = createCollection(appContext, collectionName);

    repository = new RepositoryWithOperations(collection, {
      model: state
    });

    return repository;
  };

  generateRepositoryState = function (controller, appContext, options) {
    var state = options.state,
      path = options.path,
      nameOfRootElement = options.nameOfRootElement,
      repository = createRepository(appContext, options.collectionName, options.state),
      perPage = options.perPage || 10,
      attributes = state.attributes,
      BodyParam = Foxx.Model.extend({}, { attributes: attributes });

    controller.get(path, function (req, res) {
      var data = {},
        page = req.params('page') || 0,
        skip = page * perPage;

      data[nameOfRootElement] = _.map(repository.all({skip: skip, limit: perPage}), function (datum) {
        return datum.forClient();
      });
      res.json(data);
    }).queryParam('page', {
      description: 'Page of the results',
      type: 'int'
    }).summary('Get all entries')
      .notes('Some fancy documentation');

    controller.post(path, function (req, res) {
      var data = {};
      data[nameOfRootElement] = _.map(req.params(nameOfRootElement), function (model) {
        return repository.save(model).forClient();
      });
      res.status(201);
      res.json(data);
    }).bodyParam(nameOfRootElement, 'TODO', [BodyParam])
      .summary('Post new entries')
      .notes('Some fancy documentation');

    return {
      repository: repository
    };
  };

  generateEntityState = function (name, options) {
    var attributes = options.attributes;
    return Foxx.Model.extend({
      forClient: function () {
        return _.extend({ id: this.get('_key') }, this.whitelistedAttributes);
      }
    }, {
      attributes: attributes,
      path: '/' + name
    });
  };

  // This should later inherit from Transition
  ContainsTransition = function (controller) {
    this.controller = controller;
  };

  _.extend(ContainsTransition.prototype, {
    apply: function (from, to) {
      var targetPath = to.path,
        repository = from.repository,
        nameOfRootElement = 'todos';

      this.controller.get(targetPath, function (req, res) {
        var id = req.params('id'),
          entry = repository.byId(id),
          data = {};

        data[nameOfRootElement] = [entry.forClient()];

        res.json(data);
      }).pathParam('id', {
        description: 'ID of the document',
        type: 'string'
      }).summary('Get a specific entry')
        .notes('Some fancy documentation');

      // This works a little different from the standard:
      // It expects a root element, the standard does not
      this.controller.patch(targetPath, function (req, res) {
        var operations = req.params('operations'),
          id = req.params('id'),
          data = {};

        if (_.all(operations, function (x) { return x.isValid(); })) {
          data[nameOfRootElement] = repository.updateByIdWithOperations(id, operations).forClient();
          res.json(data);
        } else {
          res.json({ error: 'Only replace is supported right now' });
          res.status(405);
        }
      }).pathParam('id', {
        description: 'ID of the document',
        type: 'string'
      }).bodyParam('operations', 'The operations to be executed on the document', [ReplaceOperation])
        .summary('Update an entry')
        .notes('Some fancy documentation');

      this.controller.del(targetPath, function (req, res) {
        var id = req.params('id');
        repository.removeById(id);
        res.status(204);
      }).pathParam('id', {
        description: 'ID of the document',
        type: 'string'
      }).errorResponse(ArangoError, 404, 'An entry with this ID could not be found')
        .summary('Remove an entry')
        .notes('Some fancy documentation');
    }
  });

  Generator = function (options) {
    this.appContext = options.applicationContext;
    this.controller = new Foxx.Controller(this.appContext, options);
    this.states = {};
    this.transitions = {
      contains: new ContainsTransition(this.controller)
    };
  };

  _.extend(Generator.prototype, {
    addState: function (name, options) {
      var newState, containsRelation;

      if (options.type === 'entity') {
        // Check if it has attributes and transitions
        newState = generateEntityState(name, options);
      } else if (options.type === 'repository') {
        // Check if it has collectionName, perPage, transitions and a `contains` transition
        containsRelation = _.find(options.transitions, function (transition) {
          return transition.via === 'contains';
        });
        options.state = this.states[containsRelation.to];
        options.path = '/' + name;
        options.nameOfRootElement = name;
        newState = generateRepositoryState(this.controller, this.appContext, options);
      }

      this.states[name] = newState;

      _.each(options.transitions, function (transitionDescription) {
        var transition = this.transitions[transitionDescription.via],
          from = newState,
          to = this.states[transitionDescription.to];

        transition.apply(from, to);
      }, this);
    },

    // This has to be adapted
    defineTransition: function (name, options) {
      var transition = {
        apply: function () {
          require('console').log('"%s" (with "%s") has to be adapted', name, options);
        }
      };
      this.transitions[name] = transition;
    }
  });

  exports.Generator = Generator;
}());
<|endoftext|>


<commit_before><commit_msg>Salary Component - account mandatory for separate payment entry<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

const program = require('commander');

program
	.version(require('../package.json').version)
	.usage('[options]')
	.option('-l, --live', 'Shows the live weather')
	.option('-h, --host [host]', 'The HOST, default to "localhost"')
	.option('-p, --port [port]', 'The PORT, default to "4223"', parseInt)
	.option('-w, --wait [time]', 'The Callback time in milliseconds, default to "1000" ms', parseInt)
	.parse(process.argv);

if (!program.host) {
	program.host = 'localhost';
}

if (!program.port) {
	program.port = 4223;
}

if (!program.wait) {
	program.wait = 1000;
}

if (program.live) {
	require('../src/weather.js').tfget(program.host, program.port, program.wait, program.live);
} else {
	require('../src/weather.js').tfget(program.host, program.port);
}
<commit_msg>define wait only in live mode<commit_after>#!/usr/bin/env node

const program = require('commander');

program
	.version(require('../package.json').version)
	.usage('[options]')
	.option('-l, --live', 'Shows the live weather')
	.option('-h, --host [host]', 'The HOST, default to "localhost"')
	.option('-p, --port [port]', 'The PORT, default to "4223"', parseInt)
	.option('-w, --wait [time]', 'The Callback time in milliseconds, default to "1000" ms', parseInt)
	.parse(process.argv);

if (!program.host) {
	program.host = 'localhost';
}

if (!program.port) {
	program.port = 4223;
}

if (program.live && !program.wait) {
	program.wait = 1000;
}

if (program.live) {
	require('../src/weather.js').tfget(program.host, program.port, program.wait, program.live);
} else {
	require('../src/weather.js').tfget(program.host, program.port);
}
<|endoftext|>


<commit_before>/*
*/

var express = require('express');

var require_loader = require('require_loader');

var settings = {};
var normalizedDomainList = [];
module.exports.normalizedDomainList = normalizedDomainList;

/*
* Add subodmain function
*/
var addFullDomain = function(fullDomainName, fullName, app)  {
    var canAdd = true;
    for (var i=0; i<normalizedDomainList.length;i++) {
            if (normalizedDomainList[i].name == fullDomainName) {
                    canAdd = false;
                    break;
            }
    }
    if (canAdd) {
            this.use(express.vhost(fullDomainName, app));   // this refer to the Server object
            normalizedDomainList.push({name:fullDomainName, fullName:fullName});
    }
}

/*
* a function to take the express server.. and append apps to it later
*/
var server = false;
module.exports.load = function(options) {
    settings = {
        appsPath    :   options.appsPath || false,  /* the folder path where it is beign watch */
        server      :   options.server  || false,   /* the express server / app object */
    }

    if (settings.appsPath !== false && settings.server !== false) {
        // bind util function to the server object first
        settings.server.addFullDomain = addFullDomain;
        //settings.server.removeFullDomain = removeFullDomain;

        // now load and watch the require folder.
    } else {
        // error.
    }
}<commit_msg>more code<commit_after>/*
*/

var express = require('express');

var REQUIRE_LOADER = require('require_loader');

var settings = {};
var normalizedDomainList = [];
module.exports.normalizedDomainList = normalizedDomainList;

/*
* Add subodmain function
*/
var addFullDomain = function(fullDomainName, fullName, app)  {
    var canAdd = true;
    for (var i=0; i<normalizedDomainList.length;i++) {
            if (normalizedDomainList[i].name == fullDomainName) {
                    canAdd = false;
                    break;
            }
    }
    if (canAdd) {
            this.use(express.vhost(fullDomainName, app));   // this refer to the Server object
            normalizedDomainList.push({name:fullDomainName, fullName:fullName});
    }
}

/*
*
*/
var onAppsFolderChange = function(err, data) {
    if (data.action == "add") {
        // Look into the file name and if it match the configSuffix

        // It matches and look into the content of the config file, build the apps from it.

        // It doesn't match and  consider it is already a file with module.exports.app

    } else if (data.action == "remove") {

    }
}
/*
* a function to take the express server.. and append apps to it later
*/
var require_loader = false;
module.exports.load = function(options) {
    settings = {
        appsPath    :   options.appsPath        || false,  /* the folder path where it is beign watch */
        server      :   options.server          || false,   /* the express server / app object */
        configSuffix:   options.configSuffix    || '.cfg.js',
        error       :   options.error           || function () {}
    }

    if (settings.appsPath !== false && settings.server !== false) {
        // bind util function to the server object first
        settings.server.addFullDomain = addFullDomain;
        //settings.server.removeFullDomain = removeFullDomain;

        // now load and watch the require folder.
        require_loader = REQUIRE_LOADER.create({path:settings.appsPath, init:true, isWatch:true, onChange:onAppsFolderChange});

    } else {
        // error.
        settings.error("Apps Path or the Server is undefined.");
    }
}<|endoftext|>


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

    angular.module('data-prep.services.utils')
        /**
         * @ngdoc object
         * @name data-prep.services.utils.service:apiUrl
         * @description The REST api base url
         */
        .constant('apiUrl', 'http://10.42.10.99:8888')  /* VM1 */
        /**
         * @ngdoc object
         * @name data-prep.services.utils.service:disableDebug
         * @description Application option. Disable debug mode (ex: in production) for performance
         */
        .constant('disableDebug', false);
})();
<commit_msg>server url<commit_after>(function() {
    'use strict';

    angular.module('data-prep.services.utils')
        /**
         * @ngdoc object
         * @name data-prep.services.utils.service:apiUrl
         * @description The REST api base url
         */
        .constant('apiUrl', 'http://10.42.10.99:8888')  /* VM1 */
        // .constant('apiUrl', 'http://10.42.40.91:8888')  /* VINCENT */
        //.constant('apiUrl', 'http://192.168.40.134:8888')  /* MARC VM DOCKER  */
        /**
         * @ngdoc object
         * @name data-prep.services.utils.service:disableDebug
         * @description Application option. Disable debug mode (ex: in production) for performance
         */
        .constant('disableDebug', false);
})();
<|endoftext|>


<commit_before>'use strict';

import { axios as http } from 'axios';

function instapago({keyId, publicKeyId, strict = true}) {
  if (!keyId || !publicKeyId) {
    throw new Error('Los parámetos keyId y publicKeyId son requerido');
  } else if (typeof keyId !== 'string' || typeof publicKeyId !== 'string') {
    throw new Error('Los parámetos keyId y publicKeyId deben ser String.');
  }

  const config = {
    keyId,
    publicKeyId,
    strict
  };

  return {
    pay: data => processPayment('pay', config, data),
    resume: data => processPayment('resume', config, data),
    cancel: data => processPayment('cancel', config, data),
    view: data => processPayment('view', config, data)
  }
}

function processPayment({type, config, data}) {
  const params = Object.assign({}, config, data);
  let endpoint;
  let method;

  switch (type) {
    case 'pay':
      endpoint = 'payment';
      method = 'POST';
      break;

    case 'resume':
      endpoint = 'complete';
      method = 'POST';
      break;

    case 'cancel':
      endpoint = 'payment';
      method = 'DELETE';
      break;

    case 'view':
      endpoint = 'payment';
      method = 'GET';
      break;
  }

  return http({
    method,
    url: `https://api.instapago.com/${endpoint}`,
    params: params
  });
}

export default instapago;
<commit_msg>Agrega funcionalidad para validación de datos<commit_after>'use strict';

import { axios as http } from 'axios';

function instapago({keyId, publicKeyId, strict = true}) {
  if (!keyId || !publicKeyId) {
    throw new Error('Los parámetos keyId y publicKeyId son requerido');
  } else if (typeof keyId !== 'string' || typeof publicKeyId !== 'string') {
    throw new Error('Los parámetos keyId y publicKeyId deben ser String.');
  }

  const config = {
    keyId,
    publicKeyId,
    strict
  };

  return {
    pay: data => processPayment('pay', config, data),
    resume: data => processPayment('resume', config, data),
    cancel: data => processPayment('cancel', config, data),
    view: data => processPayment('view', config, data)
  }
}

function processPayment({type, config, data}) {
  const validation = validatePaymentData(type, data);
  const params = Object.assign({}, config, data);
  let endpoint;
  let method;

  switch (type) {
    case 'pay':
      endpoint = 'payment';
      method = 'POST';
      break;

    case 'resume':
      endpoint = 'complete';
      method = 'POST';
      break;

    case 'cancel':
      endpoint = 'payment';
      method = 'DELETE';
      break;

    case 'view':
      endpoint = 'payment';
      method = 'GET';
      break;
  }

  if (config.strict && validation.error) {
    return new Promise((resolve, reject) => reject(validation.error));
  } else {
    return http({
      method,
      url: `https://api.instapago.com/${endpoint}`,
      params: params
    });
  }
}

function validatePaymentData(type, data) {
  const rules = [
    {
      param: 'amount',
      rule: 'Sólo caracteres numéricos y punto (.) como separador decimal.',
      valid: /[0-9]/.test(data.amount)
    },
    {
      param: 'description',
      rule: 'Cadena de caracteres con los detalles de la operación.',
      valid: typeof data.description === 'string'
    },
    {
      param: 'cardholder',
      rule: 'Sólo caracteres alfabéticos, incluyendo la letra ñ y espacio.',
      valid: /^[ñA-Za-z\s]*$/.test(data.cardholder)
    },
    {
      param: 'cardholderid',
      rule: 'Sólo caracteres numéricos; mínimo 6 dígitos y máximo 8.',
      valid: /^[0-9]{6,8}$/.test(data.cardholderid)
    },
    {
      param: 'cardnumber',
      rule: 'Sólo caracteres numéricos; mínimo 15 dígitos y máximo 16.',
      valid: /^[0-9]{15,16}$/.test(data.cardnumber)
    },
    {
      param: 'cvc',
      rule: 'Sólo caracteres numéricos; deben ser 3 dígitos.',
      valid: /^[0-9]{3}$/.test(data.cvc)
    },
    {
      param: 'expirationdate',
      rule: 'Sólo fechas mayores a la fecha en curso, en formato MM/YYYY.',
      valid: isCardExpired(data.expirationdate)
    },
    {
      param: 'statusid',
      rule: 'Sólo caracteres numéricos; debe ser 1 dígito.',
      valid: /^[1-2]{1}$/.test(data.statusid)
    },
    {
      param: 'ip',
      rule: 'Dirección IP del cliente que genera la solicitud del pago.',
      valid: typeof data.description === 'string'
    }
  ];
  let requiredParams = ['id'];
  let result = {};

  if (type === 'pay') {
    requiredParams = [
      'amount',
      'description',
      'cardholder',
      'cardholderId',
      'cardnumber',
      'cvc',
      'expirationdate',
      'statusid',
      'ip'
    ];
  } else if (type === 'resume') {
    requiredParams = ['id', 'amount'];
  }

  requiredParams.every(param => {
    const _param = rules.find(rule => rule.param === param);

    if (data[param] && _param.valid) {
      return true;
    }

    result = {param: param, error: _param.rule};

    return false;
  });

  return result;
}

function isCardExpired(date) {
  const _date = date ? date.split('/') : null;

  if (_date) {
    const yearOnCard = parseInt(_date[1]);
    const monthOnCard = parseInt(_date[0]);
    const year = new Date.getFullYear();
    const month = new Date.getUTCMonth() + 1;

    return ((yearOnCard === year && monthOnCard >= month) || yearOnCard > year);
  }

  return false;
}

export default instapago;
<|endoftext|>