<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

app.ui.comp.panel = cs.clazz({
    mixin: [ cs.marker.controller ],
    dynamics: {
        peepholeConstraintSet: [],
        temporalConstraints: [],
        temporalMonitors: []
    },
    protos: {
        create: function () {
            var self = this
            cs(self).property('ComponentJS:state-auto-increase', true)
            cs(self).create(
                'panel/panel/' +
                '{tracing,checking,peepholeConstraints,temporalConstraints,componentTree,statistics,statusbar,headline}',
                app.ui.widget.panel.model,
                app.ui.widget.panel.view,
                app.ui.comp.tracing,
                app.ui.comp.checking,
                app.ui.comp.constraints.peephole,
                app.ui.comp.constraints.temporal,
                app.ui.comp.componentTree,
                app.ui.comp.statistics,
                app.ui.widget.statusbar,
                app.ui.widget.headline.view
            )

            /*  this may cause constraints to be overwritten, since no
            **  disjunct naming among different constraint sets is enforced
            */
            var computeHierarchy = function (constraintSets) {
                var flat = _.flatten(constraintSets)
                var actual = {}
                var result = []
                _.each(flat, function (constraint) { actual[constraint.id] = constraint })
                _.forIn(actual, function (value) {
                    result.push(value)
                })
                return result
            }

            cs(self).subscribe({
                name: 'peepholeConstraintSetChanged', spool: 'created',
                func: function (ev, nVal) {
                    nVal = computeHierarchy(nVal)
                    self.peepholeConstraintSet = app.lib.sorter(nVal)
                }
            })

            cs(self).subscribe({
                name: 'temporalConstraintSetChanged', spool: 'created',
                func: function (ev, constraints) {
                    self.temporalConstraints = constraints
                    self.temporalMonitors = []
                    _.each(self.temporalConstraints, function (temporal) {
                        self.temporalMonitors.push(new app.lib.happens_before_monitor(temporal))
                    })
                }
            })

            cs(self).subscribe({
                name: 'checkJournal', spool: 'created',
                func: function (ev, traces) {
                    _.each(traces, function (trace) {
                        cs(self).publish('checkTrace', trace)
                    })
                }
            })

            cs(self).subscribe({
                name: 'checkTrace', spool: 'created',
                func: function (ev, trace) {
                    var resTraces = cs('/sv').call('checkTraces', [ trace ], self.peepholeConstraintSet)
                    _.each(self.temporalMonitors, function (monitor) {
                        var res = monitor.processTrace(trace)
                        if (res)
                            resTraces.push(res)
                    })
                    if (resTraces.length === 0)
                        return
                    cs(self, 'panel/panel/checking').call('unshift', resTraces[0])
                }
            })

            cs(self).subscribe({
                name: 'event:status-message', spool: 'created',
                func: function (ev, status) {
                    cs(self, 'panel/panel/statusbar').publish('status', status)
                }
            })

            /*  handle the websocket state and push it to the statusbar  */
            cs(self, 'panel/panel/statusbar').publish('message', 'Connecting ...')
            cs(self, 'panel/panel/statusbar').publish('color', 'yellow')

            /* global io: true */
            var socket = io.connect()
            socket.on('connect', function () {
                socket.emit('join')
                cs(self, 'panel/panel/statusbar').publish('message', 'Connected')
                cs(self, 'panel/panel/statusbar').publish('color', 'black')
            })
            socket.on('reconnect', function () {
                cs(self, 'panel/panel/statusbar').publish('message', 'Reconnected')
                cs(self, 'panel/panel/statusbar').publish('color', 'black')
            })
            socket.on('disconnect', function () {
                cs(self, 'panel/panel/statusbar').publish('message', 'Trying to reconnect ...')
                cs(self, 'panel/panel/statusbar').publish('color', 'red')
            })

            cs(self).subscribe({
                name: 'sendCommand', spool: 'created',
                func: function (ev, cmd) {
                    socket.emit('cmd', cmd)
                }
            })

            socket.on('newTrace', function (trace) {
                trace = app.lib.richTrace.enrich(trace)
                cs(self, 'panel/panel').publish({ name : 'event:new-trace', args : [ trace ], capturing : false, bubbling : false, spreading : true })
            })

            cs(self).subscribe({
                name: 'sendTerminate', spool: 'created',
                func: function () {
                    var result = []
                    var terminate = {id: -1, operation: 'terminate', origin: '/', originType: 'na', parameters: {}, source: '/', sourceType: 'na', time: -1}
                    terminate = app.lib.richTrace.enrich(terminate)
                    _.each(self.temporalMonitors, function (monitor) {
                        result = result.concat(monitor.processTerminate(terminate))
                    })
                    if (result.length === 0)
                        return
                    _.each(result, function (item) {
                        cs(self, 'panel/panel/checking').call('unshift', item)
                    })
                }
            })
        },
        prepare: function () {
            cs(this, 'panel').value('data:tabs', [
                { id: 'tracing',             name: 'Tracing',              icon: 'gears'                                  },
                { id: 'checking',            name: 'Checking',             icon: 'thumbs-down'                            },
                { id: 'peepholeConstraints', name: 'Peephole Constraints', icon: 'screenshot'                             },
                { id: 'temporalConstraints', name: 'Temporal Constraints', icon: 'time'                                   },
                { id: 'componentTree',       name: 'Component Tree',       icon: 'sitemap',    classes: 'icon-rotate-180' },
                { id: 'statistics',          name: 'Statistics',           icon: 'bar-chart'                              }
            ])
        },
        render: function () {
            var ui = $('body').markup('comp-panel')
            cs(this).socket({ spool: 'materialized', ctx: ui, type: 'jquery' })
            cs(this).spool('materialized', this, function () { $(ui).remove() })

            var headline = $('.headline', ui)
            cs(this).socket({ scope: 'headline', spool: 'materialized', ctx: headline, type: 'jquery' })
            cs(this).spool('materialized', this, function () { $(headline).remove() })
        }
    }
})<commit_msg>Artificial trace is no longer needed<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

app.ui.comp.panel = cs.clazz({
    mixin: [ cs.marker.controller ],
    dynamics: {
        peepholeConstraintSet: [],
        temporalConstraints: [],
        temporalMonitors: []
    },
    protos: {
        create: function () {
            var self = this
            cs(self).property('ComponentJS:state-auto-increase', true)
            cs(self).create(
                'panel/panel/' +
                '{tracing,checking,peepholeConstraints,temporalConstraints,componentTree,statistics,statusbar,headline}',
                app.ui.widget.panel.model,
                app.ui.widget.panel.view,
                app.ui.comp.tracing,
                app.ui.comp.checking,
                app.ui.comp.constraints.peephole,
                app.ui.comp.constraints.temporal,
                app.ui.comp.componentTree,
                app.ui.comp.statistics,
                app.ui.widget.statusbar,
                app.ui.widget.headline.view
            )

            /*  this may cause constraints to be overwritten, since no
            **  disjunct naming among different constraint sets is enforced
            */
            var computeHierarchy = function (constraintSets) {
                var flat = _.flatten(constraintSets)
                var actual = {}
                var result = []
                _.each(flat, function (constraint) { actual[constraint.id] = constraint })
                _.forIn(actual, function (value) {
                    result.push(value)
                })
                return result
            }

            cs(self).subscribe({
                name: 'peepholeConstraintSetChanged', spool: 'created',
                func: function (ev, nVal) {
                    nVal = computeHierarchy(nVal)
                    self.peepholeConstraintSet = app.lib.sorter(nVal)
                }
            })

            cs(self).subscribe({
                name: 'temporalConstraintSetChanged', spool: 'created',
                func: function (ev, constraints) {
                    self.temporalConstraints = constraints
                    self.temporalMonitors = []
                    _.each(self.temporalConstraints, function (temporal) {
                        self.temporalMonitors.push(new app.lib.happens_before_monitor(temporal))
                    })
                }
            })

            cs(self).subscribe({
                name: 'checkJournal', spool: 'created',
                func: function (ev, traces) {
                    _.each(traces, function (trace) {
                        cs(self).publish('checkTrace', trace)
                    })
                }
            })

            cs(self).subscribe({
                name: 'checkTrace', spool: 'created',
                func: function (ev, trace) {
                    var resTraces = cs('/sv').call('checkTraces', [ trace ], self.peepholeConstraintSet)
                    _.each(self.temporalMonitors, function (monitor) {
                        var res = monitor.processTrace(trace)
                        if (res)
                            resTraces.push(res)
                    })
                    if (resTraces.length === 0)
                        return
                    cs(self, 'panel/panel/checking').call('unshift', resTraces[0])
                }
            })

            cs(self).subscribe({
                name: 'event:status-message', spool: 'created',
                func: function (ev, status) {
                    cs(self, 'panel/panel/statusbar').publish('status', status)
                }
            })

            /*  handle the websocket state and push it to the statusbar  */
            cs(self, 'panel/panel/statusbar').publish('message', 'Connecting ...')
            cs(self, 'panel/panel/statusbar').publish('color', 'yellow')

            /* global io: true */
            var socket = io.connect()
            socket.on('connect', function () {
                socket.emit('join')
                cs(self, 'panel/panel/statusbar').publish('message', 'Connected')
                cs(self, 'panel/panel/statusbar').publish('color', 'black')
            })
            socket.on('reconnect', function () {
                cs(self, 'panel/panel/statusbar').publish('message', 'Reconnected')
                cs(self, 'panel/panel/statusbar').publish('color', 'black')
            })
            socket.on('disconnect', function () {
                cs(self, 'panel/panel/statusbar').publish('message', 'Trying to reconnect ...')
                cs(self, 'panel/panel/statusbar').publish('color', 'red')
            })

            cs(self).subscribe({
                name: 'sendCommand', spool: 'created',
                func: function (ev, cmd) {
                    socket.emit('cmd', cmd)
                }
            })

            socket.on('newTrace', function (trace) {
                trace = app.lib.richTrace.enrich(trace)
                cs(self, 'panel/panel').publish({ name : 'event:new-trace', args : [ trace ], capturing : false, bubbling : false, spreading : true })
            })

            cs(self).subscribe({
                name: 'sendTerminate', spool: 'created',
                func: function () {
                    var result = []
                    _.each(self.temporalMonitors, function (monitor) {
                        result = result.concat(monitor.processTerminate())
                    })
                    if (result.length === 0)
                        return
                    _.each(result, function (item) {
                        cs(self, 'panel/panel/checking').call('unshift', item)
                    })
                }
            })
        },
        prepare: function () {
            cs(this, 'panel').value('data:tabs', [
                { id: 'tracing',             name: 'Tracing',              icon: 'gears'                                  },
                { id: 'checking',            name: 'Checking',             icon: 'thumbs-down'                            },
                { id: 'peepholeConstraints', name: 'Peephole Constraints', icon: 'screenshot'                             },
                { id: 'temporalConstraints', name: 'Temporal Constraints', icon: 'time'                                   },
                { id: 'componentTree',       name: 'Component Tree',       icon: 'sitemap',    classes: 'icon-rotate-180' },
                { id: 'statistics',          name: 'Statistics',           icon: 'bar-chart'                              }
            ])
        },
        render: function () {
            var ui = $('body').markup('comp-panel')
            cs(this).socket({ spool: 'materialized', ctx: ui, type: 'jquery' })
            cs(this).spool('materialized', this, function () { $(ui).remove() })

            var headline = $('.headline', ui)
            cs(this).socket({ scope: 'headline', spool: 'materialized', ctx: headline, type: 'jquery' })
            cs(this).spool('materialized', this, function () { $(headline).remove() })
        }
    }
})<|endoftext|>


<commit_before>'use strict';

angular.module('UpdateModule', [])
    .controller('UpdateController',
                ['$rootScope',
                 '$http',
                 'LocationHierarchyService',
                 'FieldWorkerService',
                 'LocationService',
                 'IndividualService',
                 'MembershipService',
                 'RelationshipService',
                 'ResidencyService',
                 'VisitService',
                 'DeathService',
                 'InMigrationService',
                 'OutMigrationService',
                 'PregnancyObservationService',
                 'PregnancyOutcomeService',
                 'PregnancyResultService',
                 UpdateController ]);

function UpdateController($rootScope,
                          $http,
                          LocationHierarchyService,
                          FieldWorkerService,
                          LocationService,
                          IndividualService,
                          MembershipService,
                          RelationshipService,
                          ResidencyService,
                          VisitService,
                          DeathService,
                          InMigrationService,
                          OutMigrationService,
                          PregnancyObservationService,
                          PregnancyOutcomeService,
                          PregnancyResultService) {

    var vm = this;
    var headers = { authorization: "Basic " + $rootScope.credentials };

    vm.selectedHierarchy = [];

    vm.selectedLocation = null;
    vm.selectedIndividual = null;
    vm.submittedEvents = [];

    vm.submittedVisits = [];

    vm.currentResidency = null;
    vm.currentInMigration = null;
    vm.currentOutMigration = null;
    vm.currentDeath = null;
    vm.currentPregnancyObservation = null;
    vm.currentPregnancyOutcome = null;

    vm.setFather = function(row) {
        if (vm.currentPregnancyOutcome === null) {
            vm.currentPregnancyOutcome = {father: row};
        } else {
            vm.currentPregnancyOutcome.father = row;
        }
        console.log(vm.currentPregnancyOutcome);
    };

    vm.submitVisit = function() {
        VisitService.submit(vm.currentFieldWorker, vm.visitDate, vm.selectedLocation, vm.visit)
            .then(function(response) {
                vm.currentVisit = response.data;
            });
        $('#eventTab').tab('show');
    };

    vm.submitInMigration = function(event){
        InMigrationService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate,
            vm.currentVisit, vm.currentIndividual, vm.currentResidency, event)
            .then(function(response) {
                vm.submittedEvents.push(response.data);
            });
        vm.currentInMigration = null;
    };

    vm.submitOutMigration = function(event){
        console.log(vm.currentResidency);
        OutMigrationService.submit(vm.currentFieldWorker, vm.collectionDateTime,
            vm.currentVisit, vm.currentIndividual, vm.currentResidency, event)
            .then(function(response) {
                vm.submittedEvents.push(response.data);
            });
        vm.currentOutMigration = null;
    };

    vm.submitDeath = function(event) {
        DeathService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit, vm.currentIndividual, event)
            .then(function(response) {
                var event = {
                    uuid: response.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "death"
                };
                vm.submittedEvents.push(event);
            });
        vm.currentDeath = null;
    };

    vm.submitPregnancyObservation = function(event) {
        PregnancyObservationService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit, vm.currentIndividual, event)
            .then(function(response) {
                var event = {
                    uuid: response.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "pregnancy observation"
                };
                vm.submittedEvents.push(event);
                vm.currentPregnancyObservation = null;
            });
    };

    vm.submitPregnancyOutcome = function(outcome, result){
        PregnancyOutcomeService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit,
                                       vm.currentIndividual, vm.currentPregnancyOutcome.father, vm.currentPregnancyOutcome)
            .then(function(outcomeResponse) {
                var event = {
                    uuid: outcomeResponse.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "pregnancy outcome"
                };
                vm.submittedEvents.push(event);

                if (vm.currentPregnancyResult.type === 'LIVE_BIRTH') {
                    IndividualService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate, result.child)
                        .then(function(childResponse) {
                            PregnancyResultService.submit(vm.currentFieldWorker,
                                                          vm.currentVisit.visitDate,
                                                          vm.currentVisit,
                                                          outcomeResponse.data,
                                                          childResponse.data,
                                                          result)
                                .then(function(response) {
                                    var event = {
                                        uuid: response.data.uuid,
                                        individual: childResponse.uuid,
                                        eventType: "pregnancy result"
                                    };
                                    vm.submittedEvents.push(event);
                                });
                        });
                    vm.currentPregnancyOutcome = null;
                    vm.currentPregnancyResult = null;
                }
                else {
                    PregnancyResultService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate,
                                                  vm.currentVisit, outcomeResponse, {}, vm.currentPregnancyResult)
                        .then(function(response) {
                            var event = {
                                uuid: response.uuid,
                                individual: null,
                                eventType: "pregnancy result"
                            };
                            vm.submittedEvents.push(event);
                            vm.currentPregnancyOutcome = null;
                            vm.currentPregnancyResult = null;
                        });
                }
            });
    };

    // For External In-Migration
    vm.submitIndividual = function(indiv){
        IndividualService.submit(vm.currentFieldWorker,
                                 vm.currentVisit.visitDate,
                                 indiv)
            .then(function(response) {
                console.log(response.data);
                vm.currentIndividual = response.data;
            });
    };

    vm.pregnancyDisableCheck = function(){
        if(vm.currentIndividual == null){
            return false;
        }
        else if( vm.currentIndividual.gender == "MALE"){
            return false;
        }
        else{
            return true;
        }
    };

    vm.finishVisit = function(){

        vm.submittedVisits.push(vm.currentVisit);
        vm.currentVisit = null;
        vm.visit = null;

        vm.submittedEvents = [];
        vm.selectedLocation = null;
        vm.selectedIndividual = null;
        $('#updateTab').tab('show');

    };

    vm.migrationTypes = [
        {
            display: "Internal",
            codeValue : "INTERNAL_MIGRATION",
            description : "migrated between locations in the study area"
        },
        {
            display: "External",
            codeValue : "EXTERNAL_MIGRATION",
            description : "migrated from a location outside the study area"
        }
    ];

    vm.saveLocationHierarchy = function() {
        var parentIndex = vm.selectedHierarchy.length - 2;
        var lastIndex = vm.selectedHierarchy.length - 1;

        var parent = vm.selectedHierarchy[parentIndex];
        var last = vm.selectedHierarchy[lastIndex];
        var children = vm.locationHierarchies[parent];
        vm.currentHierarchy = children.filter(function(child) {
            return child.uuid === last;
        })[0];

        LocationService.getByHierarchy(vm.currentHierarchy.uuid)
            .then(function(response) {
                vm.allLocations = response;
                vm.locationDisplayCollection = [].concat(response);
            });

    };
    vm.setCurrentIndividual = function(row) {
        vm.currentIndividual = row;
        if (vm.residencies === null) {
            vm.currentResidency = {uuid: "UNKNOWN"};
        } else {
            vm.currentResidency = vm.residencies.filter(function(res) {
                return res.individual.uuid === vm.currentIndividual.uuid;
            })[0];
        }
    };
    vm.setLocation = function(row) {
        vm.selectedLocation = row;

        IndividualService.getByLocation(row.uuid).then(function(response){
            vm.allIndividuals = response;
            vm.individualDisplayCollection = [].concat(response);

        });

        vm.residencies = vm.allResidencies.filter(function(residency){
            return residency.location.uuid === row.uuid;
        });
    };

    vm.availableHierarchies = function() {
        var result = [];

        vm.selectedHierarchy.forEach(function(h) {
            result.push(vm.locationHierarchies[h]);
        });
        return result;
    };

    vm.init = function() {

        var codesUrl = $rootScope.restApiUrl + "/projectCodes/bulk.json";

        $http.get(codesUrl, {headers: headers})
            .then(function(response) {
                vm.codes = response.data;
            });

        FieldWorkerService.getAllFieldWorkers().then(function(fieldworkers) {
            vm.allFieldWorkers = fieldworkers;
        });

        LocationHierarchyService.locationHierarchies().then(function(hierarchyTree) {
            vm.locationHierarchies = hierarchyTree;
        });
        LocationHierarchyService.getLevels().then(function(response) {
            vm.allHierarchyLevels = response.data;
        });

    };

    return vm;

}
<commit_msg>remove old residency filter<commit_after>'use strict';

angular.module('UpdateModule', [])
    .controller('UpdateController',
                ['$rootScope',
                 '$http',
                 'LocationHierarchyService',
                 'FieldWorkerService',
                 'LocationService',
                 'IndividualService',
                 'MembershipService',
                 'RelationshipService',
                 'ResidencyService',
                 'VisitService',
                 'DeathService',
                 'InMigrationService',
                 'OutMigrationService',
                 'PregnancyObservationService',
                 'PregnancyOutcomeService',
                 'PregnancyResultService',
                 UpdateController ]);

function UpdateController($rootScope,
                          $http,
                          LocationHierarchyService,
                          FieldWorkerService,
                          LocationService,
                          IndividualService,
                          MembershipService,
                          RelationshipService,
                          ResidencyService,
                          VisitService,
                          DeathService,
                          InMigrationService,
                          OutMigrationService,
                          PregnancyObservationService,
                          PregnancyOutcomeService,
                          PregnancyResultService) {

    var vm = this;
    var headers = { authorization: "Basic " + $rootScope.credentials };

    vm.selectedHierarchy = [];

    vm.selectedLocation = null;
    vm.selectedIndividual = null;
    vm.submittedEvents = [];

    vm.submittedVisits = [];

    vm.currentResidency = null;
    vm.currentInMigration = null;
    vm.currentOutMigration = null;
    vm.currentDeath = null;
    vm.currentPregnancyObservation = null;
    vm.currentPregnancyOutcome = null;

    vm.setFather = function(row) {
        if (vm.currentPregnancyOutcome === null) {
            vm.currentPregnancyOutcome = {father: row};
        } else {
            vm.currentPregnancyOutcome.father = row;
        }
        console.log(vm.currentPregnancyOutcome);
    };

    vm.submitVisit = function() {
        VisitService.submit(vm.currentFieldWorker, vm.visitDate, vm.selectedLocation, vm.visit)
            .then(function(response) {
                vm.currentVisit = response.data;
            });
        $('#eventTab').tab('show');
    };

    vm.submitInMigration = function(event){
        InMigrationService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate,
            vm.currentVisit, vm.currentIndividual, vm.currentResidency, event)
            .then(function(response) {
                vm.submittedEvents.push(response.data);
            });
        vm.currentInMigration = null;
    };

    vm.submitOutMigration = function(event){
        console.log(vm.currentResidency);
        OutMigrationService.submit(vm.currentFieldWorker, vm.collectionDateTime,
            vm.currentVisit, vm.currentIndividual, vm.currentResidency, event)
            .then(function(response) {
                vm.submittedEvents.push(response.data);
            });
        vm.currentOutMigration = null;
    };

    vm.submitDeath = function(event) {
        DeathService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit, vm.currentIndividual, event)
            .then(function(response) {
                var event = {
                    uuid: response.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "death"
                };
                vm.submittedEvents.push(event);
            });
        vm.currentDeath = null;
    };

    vm.submitPregnancyObservation = function(event) {
        PregnancyObservationService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit, vm.currentIndividual, event)
            .then(function(response) {
                var event = {
                    uuid: response.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "pregnancy observation"
                };
                vm.submittedEvents.push(event);
                vm.currentPregnancyObservation = null;
            });
    };

    vm.submitPregnancyOutcome = function(outcome, result){
        PregnancyOutcomeService.submit(vm.currentFieldWorker, vm.collectionDateTime, vm.currentVisit,
                                       vm.currentIndividual, vm.currentPregnancyOutcome.father, vm.currentPregnancyOutcome)
            .then(function(outcomeResponse) {
                var event = {
                    uuid: outcomeResponse.data.uuid,
                    individual: vm.currentIndividual,
                    eventType: "pregnancy outcome"
                };
                vm.submittedEvents.push(event);

                if (vm.currentPregnancyResult.type === 'LIVE_BIRTH') {
                    IndividualService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate, result.child)
                        .then(function(childResponse) {
                            PregnancyResultService.submit(vm.currentFieldWorker,
                                                          vm.currentVisit.visitDate,
                                                          vm.currentVisit,
                                                          outcomeResponse.data,
                                                          childResponse.data,
                                                          result)
                                .then(function(response) {
                                    var event = {
                                        uuid: response.data.uuid,
                                        individual: childResponse.uuid,
                                        eventType: "pregnancy result"
                                    };
                                    vm.submittedEvents.push(event);
                                });
                        });
                    vm.currentPregnancyOutcome = null;
                    vm.currentPregnancyResult = null;
                }
                else {
                    PregnancyResultService.submit(vm.currentFieldWorker, vm.currentVisit.visitDate,
                                                  vm.currentVisit, outcomeResponse, {}, vm.currentPregnancyResult)
                        .then(function(response) {
                            var event = {
                                uuid: response.uuid,
                                individual: null,
                                eventType: "pregnancy result"
                            };
                            vm.submittedEvents.push(event);
                            vm.currentPregnancyOutcome = null;
                            vm.currentPregnancyResult = null;
                        });
                }
            });
    };

    // For External In-Migration
    vm.submitIndividual = function(indiv){
        IndividualService.submit(vm.currentFieldWorker,
                                 vm.currentVisit.visitDate,
                                 indiv)
            .then(function(response) {
                console.log(response.data);
                vm.currentIndividual = response.data;
            });
    };

    vm.pregnancyDisableCheck = function(){
        if(vm.currentIndividual == null){
            return false;
        }
        else if( vm.currentIndividual.gender == "MALE"){
            return false;
        }
        else{
            return true;
        }
    };

    vm.finishVisit = function(){

        vm.submittedVisits.push(vm.currentVisit);
        vm.currentVisit = null;
        vm.visit = null;

        vm.submittedEvents = [];
        vm.selectedLocation = null;
        vm.selectedIndividual = null;
        $('#updateTab').tab('show');

    };

    vm.migrationTypes = [
        {
            display: "Internal",
            codeValue : "INTERNAL_MIGRATION",
            description : "migrated between locations in the study area"
        },
        {
            display: "External",
            codeValue : "EXTERNAL_MIGRATION",
            description : "migrated from a location outside the study area"
        }
    ];

    vm.saveLocationHierarchy = function() {
        var parentIndex = vm.selectedHierarchy.length - 2;
        var lastIndex = vm.selectedHierarchy.length - 1;

        var parent = vm.selectedHierarchy[parentIndex];
        var last = vm.selectedHierarchy[lastIndex];
        var children = vm.locationHierarchies[parent];
        vm.currentHierarchy = children.filter(function(child) {
            return child.uuid === last;
        })[0];

        LocationService.getByHierarchy(vm.currentHierarchy.uuid)
            .then(function(response) {
                vm.allLocations = response;
                vm.locationDisplayCollection = [].concat(response);
            });

    };
    vm.setCurrentIndividual = function(row) {
        vm.currentIndividual = row;
        if (vm.residencies === null) {
            vm.currentResidency = {uuid: "UNKNOWN"};
        } else {
            vm.currentResidency = vm.residencies.filter(function(res) {
                return res.individual.uuid === vm.currentIndividual.uuid;
            })[0];
        }
    };
    vm.setLocation = function(row) {
        vm.selectedLocation = row;

        IndividualService.getByLocation(row.uuid).then(function(response){
            vm.allIndividuals = response;
            vm.individualDisplayCollection = [].concat(response);

        });

    };

    vm.availableHierarchies = function() {
        var result = [];

        vm.selectedHierarchy.forEach(function(h) {
            result.push(vm.locationHierarchies[h]);
        });
        return result;
    };

    vm.init = function() {

        var codesUrl = $rootScope.restApiUrl + "/projectCodes/bulk.json";

        $http.get(codesUrl, {headers: headers})
            .then(function(response) {
                vm.codes = response.data;
            });

        FieldWorkerService.getAllFieldWorkers().then(function(fieldworkers) {
            vm.allFieldWorkers = fieldworkers;
        });

        LocationHierarchyService.locationHierarchies().then(function(hierarchyTree) {
            vm.locationHierarchies = hierarchyTree;
        });
        LocationHierarchyService.getLevels().then(function(response) {
            vm.allHierarchyLevels = response.data;
        });

    };

    return vm;

}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var projectConfig = require(process.cwd() + '/project.config.js')();
var $ = require('gulp-load-plugins')({lazy: true});
var path = require('path');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var chalk = require('chalk');<% if(prompts.styleSourcemaps) {%>
var sourcemaps = require('gulp-sourcemaps');<% } %>

/**
 * LESS
 * Generates a new css file from our less files
 */
gulp.task('less', function () {

  var mainLessFile = path.join(projectConfig.path.srcDir, projectConfig.path.assets.lessMain);
  var mainCssDir = path.join(projectConfig.path.srcDir, projectConfig.path.assets.cssDir);

  var cssFile = projectConfig.pkg.name + '.css';

  return gulp
    .src(mainLessFile)<% if(prompts.styleSourcemaps) {%>
    .pipe(sourcemaps.init()) <% } %>
    .pipe($.less({
      paths: [path.join(__dirname, 'less', 'includes')]
    })
      .on('error', function (err) {
        console.log('');
        console.log(chalk.red('X ') + 'LESS - ' + err.message);
        console.log('');
        this.emit('end');
      }))<% if(prompts.autoPrefixr) {%>
    .pipe(autoprefixer({
            browsers: projectConfig.autoprefixer.browsers,
            cascade: false,
            remove: projectConfig.autoprefixer.remove
    }))<% } %><% if(prompts.styleSourcemaps) {%>
    .pipe(sourcemaps.write()) <% } %>
    .pipe($.rename(cssFile))
    .pipe(gulp.dest(mainCssDir))
    .pipe(reload({stream: true}));

});
<commit_msg>fix(app): fixes less task<commit_after>'use strict';

var gulp = require('gulp');
var projectConfig = require(process.cwd() + '/project.config.js')();
var $ = require('gulp-load-plugins')({lazy: true});
var path = require('path');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var chalk = require('chalk');<% if(prompts.styleSourcemaps) {%>
var sourcemaps = require('gulp-sourcemaps');<% } %><% if(prompts.autoPrefixr) {%>
var autoprefixer = require('gulp-autoprefixer');<% } %>

/**
 * LESS
 * Generates a new css file from our less files
 */
gulp.task('less', function () {

  var mainLessFile = path.join(projectConfig.path.srcDir, projectConfig.path.assets.lessMain);
  var mainCssDir = path.join(projectConfig.path.srcDir, projectConfig.path.assets.cssDir);

  var cssFile = projectConfig.pkg.name + '.css';

  return gulp
    .src(mainLessFile)<% if(prompts.styleSourcemaps) {%>
    .pipe(sourcemaps.init()) <% } %>
    .pipe($.less({
      paths: [path.join(__dirname, 'less', 'includes')]
    })
      .on('error', function (err) {
        console.log('');
        console.log(chalk.red('X ') + 'LESS - ' + err.message);
        console.log('');
        this.emit('end');
      }))<% if(prompts.autoPrefixr) {%>
    .pipe(autoprefixer({
            browsers: projectConfig.autoprefixer.browsers,
            cascade: false,
            remove: projectConfig.autoprefixer.remove
    }))<% } %><% if(prompts.styleSourcemaps) {%>
    .pipe(sourcemaps.write()) <% } %>
    .pipe($.rename(cssFile))
    .pipe(gulp.dest(mainCssDir))
    .pipe(reload({stream: true}));

});
<|endoftext|>


<commit_before>/*!
 * type-detect
 * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
 * MIT Licensed
 */

/*!
 * Primary Exports
 */

var exports = module.exports = getType;

/**
 * ### typeOf (obj)
 *
 * Use several different techniques to determine
 * the type of object being tested.
 *
 *
 * @param {Mixed} object
 * @return {String} object type
 * @api public
 */
var objectTypeRegexp = /^\[object (.*)\]$/;

function getType(obj) {
  var type = Object.prototype.toString.call(obj).match(objectTypeRegexp)[1].toLowerCase();
  // Let "new String('')" return 'object'
  if (typeof Promise === 'function' && obj instanceof Promise) return 'promise';
  // PhantomJS has type "DOMWindow" for null
  if (obj === null) return 'null';
  // PhantomJS has type "DOMWindow" for undefined
  if (obj === undefined) return 'undefined';
  return type;
}

exports.Library = Library;

/**
 * ### Library
 *
 * Create a repository for custom type detection.
 *
 * ```js
 * var lib = new type.Library;
 * ```
 *
 */

function Library() {
  if (!(this instanceof Library)) return new Library();
  this.tests = {};
}

/**
 * #### .of (obj)
 *
 * Expose replacement `typeof` detection to the library.
 *
 * ```js
 * if ('string' === lib.of('hello world')) {
 *   // ...
 * }
 * ```
 *
 * @param {Mixed} object to test
 * @return {String} type
 */

Library.prototype.of = getType;

/**
 * #### .define (type, test)
 *
 * Add a test to for the `.test()` assertion.
 *
 * Can be defined as a regular expression:
 *
 * ```js
 * lib.define('int', /^[0-9]+$/);
 * ```
 *
 * ... or as a function:
 *
 * ```js
 * lib.define('bln', function (obj) {
 *   if ('boolean' === lib.of(obj)) return true;
 *   var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ];
 *   if ('string' === lib.of(obj)) obj = obj.toLowerCase();
 *   return !! ~blns.indexOf(obj);
 * });
 * ```
 *
 * @param {String} type
 * @param {RegExp|Function} test
 * @api public
 */

Library.prototype.define = function(type, test) {
  if (arguments.length === 1) return this.tests[type];
  this.tests[type] = test;
  return this;
};

/**
 * #### .test (obj, test)
 *
 * Assert that an object is of type. Will first
 * check natives, and if that does not pass it will
 * use the user defined custom tests.
 *
 * ```js
 * assert(lib.test('1', 'int'));
 * assert(lib.test('yes', 'bln'));
 * ```
 *
 * @param {Mixed} object
 * @param {String} type
 * @return {Boolean} result
 * @api public
 */

Library.prototype.test = function(obj, type) {
  if (type === getType(obj)) return true;
  var test = this.tests[type];

  if (test && 'regexp' === getType(test)) {
    return test.test(obj);
  } else if (test && 'function' === getType(test)) {
    return test(obj);
  } else {
    throw new ReferenceError('Type test "' + type + '" not defined or invalid.');
  }
};
<commit_msg>Delete type.js<commit_after><|endoftext|>


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

    var gpii = fluid.registerNamespace("gpii");
    var d3 = fluid.registerNamespace("d3");

    fluid.defaults("gpii.nexusSensorVisualizer.pHScale", {
        gradeNames: ["gpii.nexusSensorVisualizerBase"],
        components: {
            visualizer: {
                type: "gpii.nexusSensorVisualizer.pHScale.visualizer",
                options: {
                    modelListeners: {
                        "{pHScale}.sensor.model.sensorValue": {
                            funcName: "gpii.nexusSensorVisualizer.pHScale.visualizer.updateVisualization",
                            args: ["{that}", "{change}"]
                        }
                    }
                }
            }
        }
    });

    fluid.defaults("gpii.nexusSensorVisualizer.pHScale.visualizer", {
        gradeNames: ["floe.svgDrawingArea"],
        model: {
            svgTitle: "An animated pH scale.",
            svgDescription: "An animated ph scale."
        },
        selectors: {
            pHIndicator: ".nexusc-pHIndicator"
        },
        scaleOptions: {
            // This set generated using the tool at https://gka.github.io/palettes/
            colors: ["#ff0000","#ff7100","#f49b00","#d9b100","#b3b500","#81ab00","#409200","#3a7539","#576071","#604b95","#6636a8","#6e20ab","#78079d","#800080"],
            textOptions: {
                // Creates labels for each point of the scale
                labels: {
                    template: "pH Value %index - %nextIndex"
                },
                // Creates precisely positioned text relative to the scale
                positionedText: {
                    0: "Battery Acid",
                    3: "Orange Juice",
                    6.5: "Milk",
                    7: "Pure Water",
                    8.1: "Sea Water",
                    12: "Soapy Water",
                    14: "Drain Cleaner",
                }
            },
            // All-around padding when creating the scale
            padding: 20,
            leftPadding: 75
        },
        indicatorOptions: {
            startingValue: 7
        },
        listeners: {
            "onCreate.prependSensorTitle": {
                "this": "{that}.container",
                method: "prepend",
                args: {
                    expander: {
                        funcName: "fluid.stringTemplate",
                        args: ["
%description
", "{sensor}.model"]
                    }
                }
            },
            "onCreate.createBaseSVGDrawingArea": {
                func: "{that}.createBaseSVGDrawingArea"
            },
            "onCreate.createPHVisualizer": {
                funcName: "gpii.nexusSensorVisualizer.pHScale.visualizer.createPHVisualizer",
                args: ["{that}"],
                priority: "after:createBaseSVGDrawingArea"
            }
        }
    });

    gpii.nexusSensorVisualizer.pHScale.visualizer.createYScale = function (that) {

        var h = that.options.svgOptions.height,
            padding = that.options.scaleOptions.padding,
            colors = that.options.scaleOptions.colors;

        var colorScaleLength = colors.length;

        that.yScale = d3.scale
               .linear()
               .domain([0,colorScaleLength])
               .range([h - padding, 0 + padding]);
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScale = function (that) {
        var h = that.options.svgOptions.height,
            w = that.options.svgOptions.width,
            padding = that.options.scaleOptions.padding,
            leftPadding = that.options.scaleOptions.leftPadding,
            colors = that.options.scaleOptions.colors,
            svg = that.svg;

        var colorScaleLength = colors.length;

        that.barHeight = (h - padding) / colorScaleLength;

        var barHeight = that.barHeight;

        fluid.each(colors, function(color, index) {
            svg.append("rect")
               .attr({
                  "x": leftPadding,
                  "y": function() {
                    return that.yScale(index) - barHeight;
                  },
                  "width": w - leftPadding,
                  "height": barHeight,
                  "fill": color,
                  "stroke": "#FCC"
              });
        });

    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScaleLabels = function (that) {

        var colors = that.options.scaleOptions.colors,
            textOptions = that.options.scaleOptions.textOptions,
            leftPadding = that.options.scaleOptions.leftPadding,
            w = that.options.svgOptions.width,
            svg = that.svg;

        fluid.each(colors, function(color, index) {
            svg.append("text")
              .text(gpii.nexusSensorVisualizer.pHScale.visualizer.getColorScaleLabelText(index, textOptions))
              .attr({
                "text-anchor": "middle",
                "transform": "translate(" + leftPadding + ")",
                "fill": "white",
                "x": (w - leftPadding) / 2,
                "y": function() {
                  return that.yScale(index) - that.barHeight / 3;
                },
                "font-size": that.barHeight / 2
            });
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.getColorScaleLabelText = function (index, textOptions) {
        var template = textOptions.labels.template;
        var templateValues = {
            index: index,
            nextIndex: index+1
        };

        return fluid.stringTemplate(template, templateValues);
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPositionedText = function (that) {
        var positionedTextValues = that.options.scaleOptions.textOptions.positionedText,
            leftPadding = that.options.scaleOptions.leftPadding,
            w = that.options.svgOptions.width,
            svg = that.svg;

            // Background filter for text
            var filter =
            svg.append("defs")
            .append("filter")
            .attr({
                "x": 0,
                "y": 0,
                "width": 1,
                "height": 1,
                "id": "solid"
            });

            filter.append("feFlood")
            .attr("flood-color", "black");

            filter.append("feComposite")
            .attr("in", "SourceGraphic");

        fluid.each(positionedTextValues, function (text, key) {
            svg.append("text")
            .text(text)
            .attr({
                "text-anchor": "end",
                "transform": "translate(" + leftPadding + ")",
                "fill": "white",
                "filter": "url(#solid)",
                "x": w - (leftPadding+5),
                "y": function() {
                  return that.yScale(key);
                },
                "font-size": that.barHeight / 3,
                "dominant-baseline": "central"
            });
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHIndicator = function (that) {
        // Draw the PH indicator

        var colors = that.options.scaleOptions.colors,
            svg = that.svg;

        var startingValue = that.options.indicatorOptions.startingValue;
        // Where the point of the arrow should be aligned
        var pointLocation = that.yScale(startingValue) - 15;

        that.pHIndicator =
        svg.append("path")
        .attr({
            "class" : "nexusc-pHIndicator",
            "transform": "translate(40, "+ pointLocation +")",
            "fill": function() {
                var colorIdx = Math.ceil(startingValue-1) > 0 ? Math.ceil(startingValue-1) : 0;
                return colors[colorIdx];
            },
            "d": "M20 20 h-40 v-10 h40 v-10 l15 15 l-15 15 v-10",
            "stroke": "black"
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHVisualizer = function (that) {

        var h = that.options.svgOptions.height,
            padding = that.options.scaleOptions.padding,
            colors = that.options.scaleOptions.colors;

        var colorScaleLength = colors.length;

    that.barHeight = (h - padding) / colorScaleLength;

    gpii.nexusSensorVisualizer.pHScale.visualizer.createYScale(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScale(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScaleLabels(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPositionedText(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHIndicator(that);
 };

    gpii.nexusSensorVisualizer.pHScale.visualizer.updateVisualization = function (visualizer, change) {
        var colors = visualizer.options.scaleOptions.colors;

            var pointLocation = visualizer.yScale(change.value)  - 15;

            visualizer.pHIndicator
            .transition()
            .duration(1000)
            .attr({
                "transform": "translate(40, "+ pointLocation +")",
                "fill": function() {
                    var colorIdx = Math.ceil(change.value-1) > 0 ? Math.ceil(change.value-1) : 0;
                    return colors[colorIdx];
                }
            });

    };

}());
<commit_msg>GPII-2189: refactoring towards a more generalized color scale (not there yet).<commit_after>(function () {
    "use strict";

    var gpii = fluid.registerNamespace("gpii");
    var d3 = fluid.registerNamespace("d3");

    fluid.defaults("gpii.nexusSensorVisualizer.pHScale", {
        gradeNames: ["gpii.nexusSensorVisualizerBase"],
        components: {
            visualizer: {
                type: "gpii.nexusSensorVisualizer.pHScale.visualizer",
                options: {
                    modelListeners: {
                        "{pHScale}.sensor.model.sensorValue": {
                            funcName: "gpii.nexusSensorVisualizer.pHScale.visualizer.updateVisualization",
                            args: ["{that}", "{change}"]
                        }
                    }
                }
            }
        }
    });

    fluid.defaults("gpii.nexusSensorVisualizer.pHScale.visualizer", {
        gradeNames: ["floe.svgDrawingArea"],
        model: {
            svgTitle: "An animated pH scale.",
            svgDescription: "An animated ph scale."
        },
        selectors: {
            pHIndicator: ".nexusc-pHIndicator"
        },
        scaleOptions: {
            min: 0,
            max: 14,
            // This set generated using the tool at https://gka.github.io/palettes/
            colors: ["#ff0000","#ff7100","#f49b00","#d9b100","#b3b500","#81ab00","#409200","#3a7539","#576071","#604b95","#6636a8","#6e20ab","#78079d","#800080"],
            textOptions: {
                // Creates labels for each point of the scale
                labels: {
                    template: "pH Value %index - %nextIndex"
                },
                // Creates precisely positioned text relative to the scale
                positionedText: {
                    0: "Battery Acid",
                    3: "Orange Juice",
                    6.5: "Milk",
                    7: "Pure Water",
                    8.1: "Sea Water",
                    12: "Soapy Water",
                    14: "Drain Cleaner"
                }
            },
            // All-around padding when creating the scale
            padding: 20,
            leftPadding: 75
        },
        indicatorOptions: {
            startingValue: 7
        },
        listeners: {
            "onCreate.prependSensorTitle": {
                "this": "{that}.container",
                method: "prepend",
                args: {
                    expander: {
                        funcName: "fluid.stringTemplate",
                        args: ["
%description
", "{sensor}.model"]
                    }
                }
            },
            "onCreate.createBaseSVGDrawingArea": {
                func: "{that}.createBaseSVGDrawingArea"
            },
            "onCreate.createPHVisualizer": {
                funcName: "gpii.nexusSensorVisualizer.pHScale.visualizer.createPHVisualizer",
                args: ["{that}"],
                priority: "after:createBaseSVGDrawingArea"
            }
        }
    });

    gpii.nexusSensorVisualizer.pHScale.visualizer.createYScale = function (that) {

        var h = that.options.svgOptions.height,
            padding = that.options.scaleOptions.padding,
            scaleMin = that.options.scaleOptions.min,
            scaleMax = that.options.scaleOptions.max;

        that.yScale = d3.scale
               .linear()
               .domain([scaleMin,scaleMax])
               .range([h - padding, 0 + padding]);
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScale = function (that) {
        var h = that.options.svgOptions.height,
            w = that.options.svgOptions.width,
            padding = that.options.scaleOptions.padding,
            leftPadding = that.options.scaleOptions.leftPadding,
            colors = that.options.scaleOptions.colors,
            scaleMax = that.options.scaleOptions.max,
            svg = that.svg;

        var colorScaleLength = colors.length;

        that.barHeightMultiplier = scaleMax / colorScaleLength;

        var barHeightMultiplier = that.barHeightMultiplier;

        console.log(barHeightMultiplier);

        that.barHeight = ((h - padding) / colorScaleLength) * barHeightMultiplier;

        var barHeight = that.barHeight;

        fluid.each(colors, function(color, index) {
            svg.append("rect")
               .attr({
                  "x": leftPadding,
                  "y": function() {
                    return that.yScale(index * barHeightMultiplier) - barHeight;
                  },
                  "width": w - leftPadding,
                  "height": barHeight,
                  "fill": color,
                  "stroke": "#FCC"
              });
        });

    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScaleLabels = function (that) {

        var colors = that.options.scaleOptions.colors,
            textOptions = that.options.scaleOptions.textOptions,
            leftPadding = that.options.scaleOptions.leftPadding,
            w = that.options.svgOptions.width,
            svg = that.svg,
            barHeight = that.barHeight,
            barHeightMultiplier = that.barHeightMultiplier;

        fluid.each(colors, function(color, index) {
            svg.append("text")
              .text(gpii.nexusSensorVisualizer.pHScale.visualizer.getColorScaleLabelText(index, textOptions))
              .attr({
                "text-anchor": "middle",
                "transform": "translate(" + leftPadding + ")",
                "fill": "white",
                "x": (w - leftPadding) / 2,
                "y": function() {
                  return that.yScale(index * barHeightMultiplier) - barHeight / 3;
                },
                "font-size": barHeight / 2
            });
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.getColorScaleLabelText = function (index, textOptions) {
        var template = textOptions.labels.template;
        var templateValues = {
            index: index,
            nextIndex: index+1
        };

        return fluid.stringTemplate(template, templateValues);
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPositionedText = function (that) {
        var positionedTextValues = that.options.scaleOptions.textOptions.positionedText,
            leftPadding = that.options.scaleOptions.leftPadding,
            w = that.options.svgOptions.width,
            svg = that.svg;

            // Background filter for text
            var filter =
            svg.append("defs")
            .append("filter")
            .attr({
                "x": 0,
                "y": 0,
                "width": 1,
                "height": 1,
                "id": "solid"
            });

            filter.append("feFlood")
            .attr("flood-color", "black");

            filter.append("feComposite")
            .attr("in", "SourceGraphic");

        fluid.each(positionedTextValues, function (text, key) {
            svg.append("text")
            .text(text)
            .attr({
                "text-anchor": "end",
                "transform": "translate(" + leftPadding + ")",
                "fill": "white",
                "filter": "url(#solid)",
                "x": w - (leftPadding+5),
                "y": function() {
                  return that.yScale(key);
                },
                "font-size": that.barHeight / 3,
                "dominant-baseline": "central"
            });
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHIndicator = function (that) {
        // Draw the PH indicator

        var colors = that.options.scaleOptions.colors,
            svg = that.svg;

        var startingValue = that.options.indicatorOptions.startingValue;
        // Where the point of the arrow should be aligned
        var pointLocation = that.yScale(startingValue) - 15;

        that.pHIndicator =
        svg.append("path")
        .attr({
            "class" : "nexusc-pHIndicator",
            "transform": "translate(40, "+ pointLocation +")",
            "fill": function() {
                var colorIdx = Math.ceil(startingValue-1) > 0 ? Math.ceil(startingValue-1) : 0;
                return colors[colorIdx];
            },
            "d": "M20 20 h-40 v-10 h40 v-10 l15 15 l-15 15 v-10",
            "stroke": "black"
        });
    };

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHVisualizer = function (that) {

        var h = that.options.svgOptions.height,
            padding = that.options.scaleOptions.padding,
            colors = that.options.scaleOptions.colors;

        var colorScaleLength = colors.length;

    that.barHeight = (h - padding) / colorScaleLength;

    gpii.nexusSensorVisualizer.pHScale.visualizer.createYScale(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScale(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createColorScaleLabels(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPositionedText(that);

    gpii.nexusSensorVisualizer.pHScale.visualizer.createPHIndicator(that);
 };

    gpii.nexusSensorVisualizer.pHScale.visualizer.updateVisualization = function (visualizer, change) {
        var colors = visualizer.options.scaleOptions.colors;

            var pointLocation = visualizer.yScale(change.value)  - 15;

            visualizer.pHIndicator
            .transition()
            .duration(1000)
            .attr({
                "transform": "translate(40, "+ pointLocation +")",
                "fill": function() {
                    var colorIdx = Math.ceil(change.value-1) > 0 ? Math.ceil(change.value-1) : 0;
                    return colors[colorIdx];
                }
            });

    };

}());
<|endoftext|>


<commit_before>Tools = function(self){
  this.bobParse = function(raw){
    var clients = [], data = {type: 'Clients'};
    // exit on null entry
    if ( raw === null ) return;
    for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
      client = {}, cols = ['Account ID',  'Account Start Date',  'Account Bucket',  'Account Spend',
      'Date of Next Ticket',  'Engaged Status',  'Timezone',  'Welcome Call',  'Keyword Research',
      'Local Profile Tab',  'Obtain or Create Google Logins',  'Create and Verify Google Profile',
      'Obtain Site Access',  'Implement Onsite Edits',  'Create Yahoo Account',  'Create and Verify Yahoo Profile',
      'Create and Verify Bing Profile',  'Install Analytics',  'Company Name',  'Contact Name',  'Website URL',
      'Email Address',  'Phone Number',  'Partner ID',];
      cells.length>0;){
      var keys = Object.keys(client).length;
      if (keys<cols.length-1){
        var param = cols[keys];
        client[param] = cells[0];
        cells.shift();
      } else {
        client.count = keys;
        clients.push(client);
        client = {};
      }
    }
    for (var i=0;i<clients.length;i++){
      var date = clients[i]['Date of Next Ticket'];
      if (data[date] === undefined) data[date] = [];
      data[date].push(clients[i]);
    }
    return data;
  };
  this.todoistExport = function (){
    var view, data,
    taskDate = function(day){
      var days = [new Date(),new Date(),new Date()];
      if (days[0].getDay() == 5) {
        days[1].setDate(days[0].getDate()+3);
        days[2].setDate(days[0].getDate()+4);
      } else if (days[0].getDay() == 4) {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+4);
      } else {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+2);
      }
      return 'date '+days[day].toDateString().substring(4);
    },
    textarea = document.createElement('textarea'), text = '',
    modal = bootbox.alert({
        size: 'large',
        message: 'placeholder',
        callback: function(){},
    })[0].children[0].children[0].children[0].children[1];
    if (ko.dataFor(window.app) !== undefined){
      view = ko.dataFor(window.app).contentViewModel();
    } else if (ko.dataFor(app) !== undefined){
      view = ko.dataFor(app).contentViewModel();
    }
    if (! view.hasOwnProperty('customersDataTable')){
      modal.remove();
      bootbox.alert('No client data available in active view.
Try running this tool after searching for a client.');
      return 1;
    } else {
      if (typeof(view.customersDataTable) === undefined) {
        console.log('No customersDataTable');
        return;
      } else {
        data = view.customersDataTable.dataSource()[0];
      }
      text += data.CustomerId+' - '+data.Name;
      text += '\n[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
      text += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
      text += '\n...'+data.CustomerId+' Keyword Research';
      text += '\n...'+data.CustomerId+' Local Profile';
      textarea.value = text;
      modal.parentNode.parentNode.parentNode.style.width = "50em";
      modal.innerHTML = '
'+text+'
';
    }
  };
  this.openClient = function(client) {
    var lp = ko.dataFor(app);
    lp.showManageCustomer(client);
  };
  this.closeClient = function() {
    var buttons = document.getElementsByClassName('close'),
    i = buttons.length - 1;
    if (i >= 1) buttons[i - 1].click();
  };
  this.createElement = function(parent, tag, attributes) {
    var element = parent.appendChild(document.createElement(tag));
    for (var attribute in attributes) {
      if (attributes.hasOwnProperty(attribute)) {
        element[attribute] = attributes[attribute];
      }
    }
    return element;
  };
  this.nextTicket = function(tickets){
    self.Tools.closeClient();
    self.Tools.openClient(tickets[0].CustomerId);
  };
  this.today = function(){
    var date = new Date();
    return (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
  }
};
<commit_msg>Update tools.js<commit_after>Tools = function(self){
  this.bobParse = function(raw){
    var clients = [], data = {type: 'Clients'};
    // exit on null entry
    if ( raw === null ) return;
    for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
      client = {}, cols = ['Account ID',  'Account Start Date',  'Account Bucket',  'Account Spend',
      'Date of Next Ticket',  'Engaged Status',  'Timezone',  'Welcome Call',  'Keyword Research',
      'Local Profile Tab',  'Obtain or Create Google Logins',  'Create and Verify Google Profile',
      'Obtain Site Access',  'Implement Onsite Edits',  'Create Yahoo Account',  'Create and Verify Yahoo Profile',
      'Create and Verify Bing Profile',  'Install Analytics',  'Company Name',  'Contact Name',  'Website URL',
      'Email Address',  'Phone Number',  'Partner ID',];
      cells.length>0;){
      var keys = Object.keys(client).length;
      if (keys<cols.length-1){
        var param = cols[keys];
        client[param] = cells[0];
        cells.shift();
      } else {
        client.count = keys;
        clients.push(client);
        client = {};
      }
    }
    for (var i=0;i<clients.length;i++){
      var date = clients[i]['Date of Next Ticket'];
      if (data[date] === undefined) data[date] = [];
      data[date].push(clients[i]);
    }
    return data;
  };
  this.todoistExport = function (){
    var view, data,
    taskDate = function(day){
      var days = [new Date(),new Date(),new Date()];
      if (days[0].getDay() == 5) {
        days[1].setDate(days[0].getDate()+3);
        days[2].setDate(days[0].getDate()+4);
      } else if (days[0].getDay() == 4) {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+4);
      } else {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+2);
      }
      return 'date '+days[day].toDateString().substring(4);
    },
    textarea = document.createElement('textarea'), text = '',
    modal = bootbox.alert({
        size: 'large',
        message: 'placeholder',
        callback: function(){},
    })[0].children[0].children[0].children[0].children[1];
    if (ko.dataFor(window.app) !== undefined){
      view = ko.dataFor(window.app).contentViewModel();
    } else if (ko.dataFor(app) !== undefined){
      view = ko.dataFor(app).contentViewModel();
    }
    if (! view.hasOwnProperty('customersDataTable')){
      modal.remove();
      bootbox.alert('No client data available in active view.
Try running this tool after searching for a client.');
      return 1;
    } else {
      if (typeof(view.customersDataTable) === undefined) {
        console.log('No customersDataTable');
        return;
      } else {
        data = view.customersDataTable.dataSource()[0];
      }
      text += data.CustomerId+' - '+data.Name;
      text += '\n[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
      text += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
      text += '\n...'+data.CustomerId+' Keyword Research';
      text += '\n...'+data.CustomerId+' Local Profile';
      textarea.value = text;
      modal.parentNode.parentNode.parentNode.style.width = "50em";
      modal.innerHTML = '
'+text+'
';
    }
  };
  this.openClient = function(client) {
    var lp = ko.dataFor(app);
    lp.showManageCustomer(client);
  };
  this.closeClient = function() {
    var buttons = document.getElementsByClassName('close'),
    i = buttons.length - 1;
    if (i >= 1) buttons[i - 1].click();
  };
  this.createElement = function(parent, tag, attributes) {
    var element = parent.appendChild(document.createElement(tag));
    for (var attribute in attributes) {
      if (attributes.hasOwnProperty(attribute)) {
        element[attribute] = attributes[attribute];
      }
    }
    return element;
  };
  this.nextTicket = function(tickets){
    self.Tools.closeClient();
    self.Tools.openClient(tickets[0].CustomerId);
  };
  this.today = function(){
    var date = new Date();
    return (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
  }
  this.httpRequest = function(data){
    var URL = data.url,
    headers = data.headers,
    request = new XMLHttpRequest();
    request.open( "GET", URL, false );
    for (var header in headers) {
      if (headers.hasOwnProperty(header)) {
          request.setRequestHeader(header, headers[header]);
      }
    }
    request.send( null );
    return request.responseText;
  };
  this.getKeywords = function(client){
   var activeResponse = httpRequest({
      url:'https://launchpad.boostability.com/WebsiteUrlApi/WebsiteUrl_SelectActiveUrls?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/'},
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    }),
   trackingResponse = httpRequest({
      url:'https://launchpad.boostability.com/WebsiteKeywordTrackingApi/WebsiteKeywordTracking_Select?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/'},
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    });
   //todo parse the recived data, and build return object
  };
};
<|endoftext|>


<commit_before>describe('filetree.service', function(){
  var $filetreeService;
  var httpBackend;
  var selectionDesc = {
      noSelections: true,
      multipleSelections: false,
      dirSelected: false
    };
  var dirs = [{
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }, {
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "root",
        "is_accessible": false,
        "perm": "-rw-r--r--",
        "perm_string": "644",
        "size": "4.0 KiB",
        "type": "dir"
      },
      {
        "filepath": "/home/saurabh/dir3",
        "filename": "dir3",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }];

    var files = [{
          "filepath": "/home/saurabh/file1",
          "filename": "file1",
          "group": "saurabh",
          "is_accessible": true,
          "perm": "-rw-rw-r--",
          "perm_string": "664",
          "size": "4.0 KiB",
          "type": "file"
        }, {
          "filepath": "/home/saurabh/file2",
          "filename": "file2",
          "group": "root",
          "is_accessible": false,
          "perm": "-rw-r--r--",
          "perm_string": "644",
          "size": "4.0 KiB",
          "type": "file"
        }];

    beforeEach(module('oide'));
    beforeEach(module('oide.editor'));
    beforeEach(module('oide.filesystemservice'));

    beforeEach(inject(function(FiletreeService, $httpBackend){
      $filetreeService = FiletreeService;

      httpBackend = $httpBackend;
      httpBackend.whenGET('/filebrowser/filetree/a/dir').respond(function(){
        return [200, dirs];
      });
    }));

    describe('Functionality of FiletreeService', function(){
      it('should initialize the FiletreeService', function(){
        httpBackend.flush();
        expect($filetreeService).toBeDefined();
        expect($filetreeService.treeData).toBeDefined();
        expect($filetreeService.treeData.filetreeContents).toBeDefined();
        expect($filetreeService.treeData.filetreeContents.length).toBe(3);
        expect($filetreeService.selectionDesc).toEqual(selectionDesc);
      });
      it('should list the directory contents', function(){
        httpBackend.flush();
        httpBackend.whenGET(/\/filebrowser\/filetree\/a\/dir\?dirpath=.*/).respond(function(){
          return [200, files];
        });
        $filetreeService.getDirContents($filetreeService.treeData.filetreeContents[0]);
        httpBackend.flush();
        // Retrieved files should be set as the childrens object of the 0th node
        expect($filetreeService.treeData.filetreeContents[0].children).toBeDefined();
        // Length of the children for the node should be 2
        expect($filetreeService.treeData.filetreeContents[0].children.length).toBe(2);
      });
      it('should be able to copy a file to the clipboard', function(){
        httpBackend.flush();
        //$filetreeService.describeSelection($filetreeService.treeData.filetreeContents[0], true);
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0]];
        $filetreeService.copyFiles();
        expect($filetreeService.clipboardEmpty()).not.toBeTruthy();
      });
      it('should be able to describe the selection for single selection', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).toBeTruthy();
      });
      it('should be able to describe the selection for single selected file', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [files[0]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).not.toBeTruthy();
      });
      it('should be able to describe the selection for multiple selection', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0], $filetreeService.treeData.filetreeContents[1]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).toBeTruthy();
      });
    });
});
<commit_msg>add spec for updating filetree<commit_after>describe('filetree.service', function(){
  var $filetreeService;
  var httpBackend;
  var selectionDesc = {
      noSelections: true,
      multipleSelections: false,
      dirSelected: false
    };
  var dirs = [{
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }, {
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "root",
        "is_accessible": false,
        "perm": "-rw-r--r--",
        "perm_string": "644",
        "size": "4.0 KiB",
        "type": "dir"
      },
      {
        "filepath": "/home/saurabh/dir3",
        "filename": "dir3",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }];

    var files = [{
          "filepath": "/home/saurabh/file1",
          "filename": "file1",
          "group": "saurabh",
          "is_accessible": true,
          "perm": "-rw-rw-r--",
          "perm_string": "664",
          "size": "4.0 KiB",
          "type": "file"
        }, {
          "filepath": "/home/saurabh/file2",
          "filename": "file2",
          "group": "root",
          "is_accessible": false,
          "perm": "-rw-r--r--",
          "perm_string": "644",
          "size": "4.0 KiB",
          "type": "file"
        }];

    beforeEach(module('oide'));
    beforeEach(module('oide.editor'));
    beforeEach(module('oide.filesystemservice'));

    beforeEach(inject(function(FiletreeService, $httpBackend){
      $filetreeService = FiletreeService;

      httpBackend = $httpBackend;
      httpBackend.whenGET('/filebrowser/filetree/a/dir').respond(function(){
        return [200, dirs];
      });
    }));

    describe('Functionality of FiletreeService', function(){
      it('should initialize the FiletreeService', function(){
        httpBackend.flush();
        expect($filetreeService).toBeDefined();
        expect($filetreeService.treeData).toBeDefined();
        expect($filetreeService.treeData.filetreeContents).toBeDefined();
        expect($filetreeService.treeData.filetreeContents.length).toBe(3);
        expect($filetreeService.selectionDesc).toEqual(selectionDesc);
      });
      it('should list the directory contents', function(){
        httpBackend.flush();
        httpBackend.whenGET(/\/filebrowser\/filetree\/a\/dir\?dirpath=.*/).respond(function(){
          return [200, files];
        });
        $filetreeService.getDirContents($filetreeService.treeData.filetreeContents[0]);
        httpBackend.flush();
        // Retrieved files should be set as the childrens object of the 0th node
        expect($filetreeService.treeData.filetreeContents[0].children).toBeDefined();
        // Length of the children for the node should be 2
        expect($filetreeService.treeData.filetreeContents[0].children.length).toBe(2);
      });
      it('should be able to copy a file to the clipboard', function(){
        httpBackend.flush();
        //$filetreeService.describeSelection($filetreeService.treeData.filetreeContents[0], true);
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0]];
        $filetreeService.copyFiles();
        expect($filetreeService.clipboardEmpty()).not.toBeTruthy();
      });
      it('should be able to describe the selection for single selection', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).toBeTruthy();
      });
      it('should be able to describe the selection for single selected file', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [files[0]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).not.toBeTruthy();
      });
      it('should be able to describe the selection for multiple selection', function(){
        httpBackend.flush();
        $filetreeService.treeData.selectedNodes = [$filetreeService.treeData.filetreeContents[0], $filetreeService.treeData.filetreeContents[1]];
        $filetreeService.describeSelection();
        expect($filetreeService.selectionDesc.multipleSelections).toBeTruthy();
        expect($filetreeService.selectionDesc.noSelections).not.toBeTruthy();
        expect($filetreeService.selectionDesc.dirSelected).toBeTruthy();
      });
      it('should be able to update the filetree', function(){
        httpBackend.flush();
        $filetreeService.treeData.expandedNodes = [$filetreeService.treeData.filetreeContents[0]];
        httpBackend.whenGET(/\/filebrowser\/filetree\/a\/dir\?dirpath=.*/).respond(function(){
          return [200, files];
        });
        $filetreeService.updateFiletree();
        httpBackend.flush();
        expect($filetreeService.treeData.filetreeContents[0].children.length).toBe(2);
      });
    });
});
<|endoftext|>


<commit_before>define(['Ti/_/lang', 'Ti/Tizen/Calendar/Calendar', 'Ti/Tizen/Calendar/CalendarTask', 'Ti/Tizen/Calendar/CalendarEvent', 'Ti/Tizen/Calendar/CalendarAttendee',
		'Ti/Tizen/Calendar/CalendarRecurrenceRule', 'Ti/Tizen/Calendar/CalendarEventId', 'Ti/Tizen/Calendar/CalendarAlarm', 'Ti/Tizen/Calendar/CalendarItem'],
		function(lang, Calendar, CalendarTask, CalendarEvent, CalendarAttendee, CalendarRecurrenceRule, CalendarEventId, CalendarAlarm, CalendarItem) {

	return lang.setObject('Ti.Tizen.Calendar', {

		constants: {
			CALENDAR_TYPE_EVENT: 'EVENT',
			CALENDAR_TYPE_TASK: 'TASK',
			CALENDAR_TEXT_FORMAT_ICALENDAR_20: 'ICALENDAR_20',
			CALENDAR_TEXT_FORMAT_VCALENDAR_10: 'VCALENDAR_10',
			ALARM_METHOD_SOUND: 'SOUND',
			ALARM_METHOD_DISPLAY: 'DISPLAY',
			RECURRENCE_RULE_FREQUENCY_DAILY: 'DAILY',
			RECURRENCE_RULE_FREQUENCY_WEEKLY: 'WEEKLY',
			RECURRENCE_RULE_FREQUENCY_MONTHLY: 'MONTHLY',
			RECURRENCE_RULE_FREQUENCY_YEARLY: 'YEARLY',
			BY_DAY_VALUE_MO: 'MO',
			BY_DAY_VALUE_TU: 'TU',
			BY_DAY_VALUE_WE: 'WE',
			BY_DAY_VALUE_TH: 'TH',
			BY_DAY_VALUE_FR: 'FR',
			BY_DAY_VALUE_SA: 'SA',
			BY_DAY_VALUE_SU: 'SU',
			EVENT_AVAILABILITY_BUSY: 'BUSY',
			EVENT_AVAILABILITY_FREE: 'FREE',
			ATTENDEE_TYPE_INDIVIDUAL: 'INDIVIDUAL',
			ATTENDEE_TYPE_GROUP: 'GROUP',
			ATTENDEE_TYPE_RESOURCE: 'RESOURCE',
			ATTENDEE_TYPE_ROOM: 'ROOM',
			ATTENDEE_TYPE_UNKNOWN: 'UNKNOWN',
			ATTENDEE_STATUS_PENDING: 'PENDING',
			ATTENDEE_STATUS_ACCEPTED: 'ACCEPTED',
			ATTENDEE_STATUS_DECLINED: 'DECLINED',
			ATTENDEE_STATUS_TENTATIVE: 'TENTATIVE',
			ATTENDEE_STATUS_DELEGATED: 'DELEGATED',
			ATTENDEE_STATUS_COMPLETED: 'COMPLETED',
			ATTENDEE_STATUS_IN_PROCESS: 'IN_PROCESS',
			ATTENDEE_ROLE_REQ_PARTICIPANT: 'REQ_PARTICIPANT',
			ATTENDEE_ROLE_OPT_PARTICIPANT: 'OPT_PARTICIPANT',
			ATTENDEE_ROLE_NON_PARTICIPANT: 'NON_PARTICIPANT',
			ATTENDEE_ROLE_CHAIR: 'CHAIR',
			CALENDAR_ITEM_PRIORITY_HIGH: 'HIGH',
			CALENDAR_ITEM_PRIORITY_MEDIUM: 'MEDIUM',
			CALENDAR_ITEM_PRIORITY_LOW: 'LOW',
			CALENDAR_ITEM_VISIBILITY_PUBLIC: 'PUBLIC',
			CALENDAR_ITEM_VISIBILITY_PRIVATE: 'PRIVATE',
			CALENDAR_ITEM_VISIBILITY_CONFIDENTIAL: 'CONFIDENTIAL',
			CALENDAR_ITEM_STATUS_TENTATIVE: 'TENTATIVE',
			CALENDAR_ITEM_STATUS_CONFIRMED: 'CONFIRMED',
			CALENDAR_ITEM_STATUS_CANCELLED: 'CANCELLED',
			CALENDAR_ITEM_STATUS_NEEDS_ACTION: 'NEEDS_ACTION',
			CALENDAR_ITEM_STATUS_IN_PROCESS: 'IN_PROCESS',
			CALENDAR_ITEM_STATUS_COMPLETED: 'COMPLETED',
		},

		getCalendars: function(type /*CalendarType*/, successCallback /*CalendarArraySuccessCallback*/, errorCallback /*ErrorCallback*/) {
			function calendarsListSuccessCallBack(calendars) {
				Ti.API.info("calendars.length: " + calendars.length);

				var i = 0,
					len = calendars.length,
					calendarsArr = [];

				for (; i < len; i++) {
					calendarsArr.push(new Calendar(calendars[i]));
				}

				successCallback.call(this, calendarsArr);
			}

			tizen.calendar.getCalendars(type, calendarsListSuccessCallBack, errorCallback);
		},

		getDefaultCalendar: function(type /*CalendarType*/) {
			return new Calendar(tizen.calendar.getDefaultCalendar(type));
		},

		getCalendar: function(type /*CalendarType*/, id /*CalendarId*/) {
			return new Calendar(tizen.calendar.getCalendar(type, id));
		},

		createCalendarTask: function(args) {
			return new CalendarTask(args);
		},

		createCalendarEvent: function(args) {
			return new CalendarEvent(args);
		},

		createCalendarAttendee: function(args) {
			return new CalendarAttendee(args);
		},

		createCalendarRecurrenceRule: function(args) {
			return new CalendarRecurrenceRule(args);
		},

		createCalendarEventId: function(args) {
			return new CalendarEventId(args);
		},

		createCalendarAlarm: function(args) {
			return new CalendarAlarm(args);
		},
	});

	function onCalendarEventArraySuccessCallback(object, onsuccess) {
		Ti.API.info('succ');
		onsuccess.call(null, new CalendarEvent(object));
	};

	function onCalendarItemArraySuccessCallback(object, onsuccess) {
		onsuccess.call(null, new CalendarItem(object));
	};

	function onCalendarArraySuccessCallback(object, onsuccess) {
		onsuccess.call(null, new Calendar(object));
	};
});<commit_msg>Removed logs from wrapper<commit_after>define(['Ti/_/lang', 'Ti/Tizen/Calendar/Calendar', 'Ti/Tizen/Calendar/CalendarTask', 'Ti/Tizen/Calendar/CalendarEvent', 'Ti/Tizen/Calendar/CalendarAttendee',
		'Ti/Tizen/Calendar/CalendarRecurrenceRule', 'Ti/Tizen/Calendar/CalendarEventId', 'Ti/Tizen/Calendar/CalendarAlarm', 'Ti/Tizen/Calendar/CalendarItem'],
		function(lang, Calendar, CalendarTask, CalendarEvent, CalendarAttendee, CalendarRecurrenceRule, CalendarEventId, CalendarAlarm, CalendarItem) {

	return lang.setObject('Ti.Tizen.Calendar', {

		constants: {
			CALENDAR_TYPE_EVENT: 'EVENT',
			CALENDAR_TYPE_TASK: 'TASK',
			CALENDAR_TEXT_FORMAT_ICALENDAR_20: 'ICALENDAR_20',
			CALENDAR_TEXT_FORMAT_VCALENDAR_10: 'VCALENDAR_10',
			ALARM_METHOD_SOUND: 'SOUND',
			ALARM_METHOD_DISPLAY: 'DISPLAY',
			RECURRENCE_RULE_FREQUENCY_DAILY: 'DAILY',
			RECURRENCE_RULE_FREQUENCY_WEEKLY: 'WEEKLY',
			RECURRENCE_RULE_FREQUENCY_MONTHLY: 'MONTHLY',
			RECURRENCE_RULE_FREQUENCY_YEARLY: 'YEARLY',
			BY_DAY_VALUE_MO: 'MO',
			BY_DAY_VALUE_TU: 'TU',
			BY_DAY_VALUE_WE: 'WE',
			BY_DAY_VALUE_TH: 'TH',
			BY_DAY_VALUE_FR: 'FR',
			BY_DAY_VALUE_SA: 'SA',
			BY_DAY_VALUE_SU: 'SU',
			EVENT_AVAILABILITY_BUSY: 'BUSY',
			EVENT_AVAILABILITY_FREE: 'FREE',
			ATTENDEE_TYPE_INDIVIDUAL: 'INDIVIDUAL',
			ATTENDEE_TYPE_GROUP: 'GROUP',
			ATTENDEE_TYPE_RESOURCE: 'RESOURCE',
			ATTENDEE_TYPE_ROOM: 'ROOM',
			ATTENDEE_TYPE_UNKNOWN: 'UNKNOWN',
			ATTENDEE_STATUS_PENDING: 'PENDING',
			ATTENDEE_STATUS_ACCEPTED: 'ACCEPTED',
			ATTENDEE_STATUS_DECLINED: 'DECLINED',
			ATTENDEE_STATUS_TENTATIVE: 'TENTATIVE',
			ATTENDEE_STATUS_DELEGATED: 'DELEGATED',
			ATTENDEE_STATUS_COMPLETED: 'COMPLETED',
			ATTENDEE_STATUS_IN_PROCESS: 'IN_PROCESS',
			ATTENDEE_ROLE_REQ_PARTICIPANT: 'REQ_PARTICIPANT',
			ATTENDEE_ROLE_OPT_PARTICIPANT: 'OPT_PARTICIPANT',
			ATTENDEE_ROLE_NON_PARTICIPANT: 'NON_PARTICIPANT',
			ATTENDEE_ROLE_CHAIR: 'CHAIR',
			CALENDAR_ITEM_PRIORITY_HIGH: 'HIGH',
			CALENDAR_ITEM_PRIORITY_MEDIUM: 'MEDIUM',
			CALENDAR_ITEM_PRIORITY_LOW: 'LOW',
			CALENDAR_ITEM_VISIBILITY_PUBLIC: 'PUBLIC',
			CALENDAR_ITEM_VISIBILITY_PRIVATE: 'PRIVATE',
			CALENDAR_ITEM_VISIBILITY_CONFIDENTIAL: 'CONFIDENTIAL',
			CALENDAR_ITEM_STATUS_TENTATIVE: 'TENTATIVE',
			CALENDAR_ITEM_STATUS_CONFIRMED: 'CONFIRMED',
			CALENDAR_ITEM_STATUS_CANCELLED: 'CANCELLED',
			CALENDAR_ITEM_STATUS_NEEDS_ACTION: 'NEEDS_ACTION',
			CALENDAR_ITEM_STATUS_IN_PROCESS: 'IN_PROCESS',
			CALENDAR_ITEM_STATUS_COMPLETED: 'COMPLETED',
		},

		getCalendars: function(type /*CalendarType*/, successCallback /*CalendarArraySuccessCallback*/, errorCallback /*ErrorCallback*/) {
			function calendarsListSuccessCallBack(calendars) {
				var i = 0,
					len = calendars.length,
					calendarsArr = [];

				for (; i < len; i++) {
					calendarsArr.push(new Calendar(calendars[i]));
				}

				successCallback.call(this, calendarsArr);
			}

			tizen.calendar.getCalendars(type, calendarsListSuccessCallBack, errorCallback);
		},

		getDefaultCalendar: function(type /*CalendarType*/) {
			return new Calendar(tizen.calendar.getDefaultCalendar(type));
		},

		getCalendar: function(type /*CalendarType*/, id /*CalendarId*/) {
			return new Calendar(tizen.calendar.getCalendar(type, id));
		},

		createCalendarTask: function(args) {
			return new CalendarTask(args);
		},

		createCalendarEvent: function(args) {
			return new CalendarEvent(args);
		},

		createCalendarAttendee: function(args) {
			return new CalendarAttendee(args);
		},

		createCalendarRecurrenceRule: function(args) {
			return new CalendarRecurrenceRule(args);
		},

		createCalendarEventId: function(args) {
			return new CalendarEventId(args);
		},

		createCalendarAlarm: function(args) {
			return new CalendarAlarm(args);
		},
	});

	function onCalendarEventArraySuccessCallback(object, onsuccess) {
		onsuccess.call(null, new CalendarEvent(object));
	};

	function onCalendarItemArraySuccessCallback(object, onsuccess) {
		onsuccess.call(null, new CalendarItem(object));
	};

	function onCalendarArraySuccessCallback(object, onsuccess) {
		onsuccess.call(null, new Calendar(object));
	};
});<|endoftext|>


<commit_before>export const typeOf = x => {
  let t = x == null ? 'Null' : (x.__typeName || x.constructor.name);

  if (t == 'Number') {
    t = Number.isSafeInteger(x)
      ? 'Integer' : 'Float';
  }
  else if (t == 'Array') {
    t = (x.length > 0 && x[0].constructor.name == 'Array')
      ? 'Matrix' : 'Vector';
  }

  return t;
};

const call = (dispatch, op, ops) => (...args) => {
  let next = dispatch;
  for (let i = 0; i < args.length && next; ++i)
    next = next[typeOf(args[i])];

  const method = next || dispatch['__default__'];

  if (method)
    return method(...args, ops);
  else {
    const msg = `Operator '${op}' not defined on [${args.map(typeOf)}]`;
    throw new Error(msg);
  }
};

const _isObject = o => o != null && o.constructor == Object;

const mergeDeep = (obj, mods) => {
  const out = Object.assign({}, obj);

  for (const k in mods) {
    if (_isObject(out[k]) && _isObject(mods[k]))
      out[k] = mergeDeep(out[k], mods[k]);
    else
      out[k] = mods[k];
  }

  return out;
};

const gcd = (a, b, ops) => {
  a = ops.abs(a);
  b = ops.abs(b);

  while (ops.sgn(b) > 0)
    [a, b] = [b, ops.mod(a, b)];

  return a;
};

const mod = (x, y, ops) => ops.minus(x, ops.times(ops.idiv(x, y), y));

const fromRepr = (obj, ops) => {
  const keys = Object.keys(obj);
  if (keys.length != 1)
    throw new Error('must have exactly one key');

  return ops[`__${keys[0]}__`](obj);
};

const defaults = {
  isInteger    : { __default__: x => false },
  isRational   : { __default__: x => false },
  isReal       : { __default__: x => false },

  eq: { __default__: (a, b, ops) => ops.cmp(a, b) == 0 },
  ne: { __default__: (a, b, ops) => ops.cmp(a, b) != 0 },
  lt: { __default__: (a, b, ops) => ops.cmp(a, b) <  0 },
  gt: { __default__: (a, b, ops) => ops.cmp(a, b) >  0 },
  le: { __default__: (a, b, ops) => ops.cmp(a, b) <= 0 },
  ge: { __default__: (a, b, ops) => ops.cmp(a, b) >= 0 },

  mod: { __default__: mod },
  gcd: { __default__: gcd },

  typeOf     : { __default__: x => typeOf(x) },
  repr       : { __default__: (x, ops) => ({ [typeOf(x)]: ops.__repr__(x) }) },
  fromRepr   : { Object: fromRepr },
  serialize  : { __default__: (x, ops) => JSON.stringify(ops.repr(x)) },
  deserialize: { String: (x, ops) => fromRepr(JSON.parse(x), ops) },

  __repr__: { __default__: x => x }
};

export function arithmetic(registry = mergeDeep({}, defaults)) {
  const result = {
    register(specs) {
      return arithmetic(mergeDeep(registry, specs));
    }
  };
  for (const op in registry)
    result[op] = call(registry[op], op, result);

  return result;
};

if (require.main == module) {
  const ops = arithmetic()
    .register({
      add: {
        Integer: {
          Integer: (a, b) => a + b,
          String : (n, s) => `${n}+"${s}"`
        },
        __default__: (x, y) => `${x} plus ${y}`
      },
      test: {
        __default__: (x, y, ops) => `<${ops.add(x, y)}>`
      }
    });

  console.log(`add(3, 4) = ${ops.add(3, 4)}`);
  console.log(`add(5, "Olaf") = ${ops.add(5, "Olaf")}`);
  console.log(`add("Olaf", "Delgado") = ${ops.add("Olaf", "Delgado")}`);
  console.log(`test(5, "Olaf") = ${ops.test(5, "Olaf")}`);
}
<commit_msg>cosmetic changes<commit_after>export const typeOf = x => {
  const t = x == null ? 'Null' : (x.__typeName || x.constructor.name);

  if (t == 'Number') {
    return Number.isSafeInteger(x) ? 'Integer' : 'Float';
  }
  else if (t == 'Array') {
    const isMatrix = x.length > 0 && x[0].constructor.name == 'Array';
    return isMatrix ? 'Matrix' : 'Vector';
  }
  else
    return t;
};

const call = (dispatch, op, ops) => (...args) => {
  let next = dispatch;
  for (let i = 0; next && i < args.length; ++i)
    next = next[typeOf(args[i])];

  const method = next || dispatch['__default__'];

  if (method)
    return method(...args, ops);
  else
    throw new Error(`Operator '${op}' not defined on [${args.map(typeOf)}]`);
};

const _isObject = o => o != null && o.constructor == Object;

const mergeDeep = (obj, mods) => {
  const out = Object.assign({}, obj);

  for (const k in mods) {
    if (_isObject(out[k]) && _isObject(mods[k]))
      out[k] = mergeDeep(out[k], mods[k]);
    else
      out[k] = mods[k];
  }

  return out;
};

const gcd = (a, b, ops) => {
  a = ops.abs(a);
  b = ops.abs(b);

  while (ops.sgn(b) > 0)
    [a, b] = [b, ops.mod(a, b)];

  return a;
};

const mod = (x, y, ops) => ops.minus(x, ops.times(ops.idiv(x, y), y));

const fromRepr = (obj, ops) => {
  const keys = Object.keys(obj);
  if (keys.length != 1)
    throw new Error('must have exactly one key');

  return ops[`__${keys[0]}__`](obj);
};

const defaults = {
  isInteger    : { __default__: x => false },
  isRational   : { __default__: x => false },
  isReal       : { __default__: x => false },

  eq: { __default__: (a, b, ops) => ops.cmp(a, b) == 0 },
  ne: { __default__: (a, b, ops) => ops.cmp(a, b) != 0 },
  lt: { __default__: (a, b, ops) => ops.cmp(a, b) <  0 },
  gt: { __default__: (a, b, ops) => ops.cmp(a, b) >  0 },
  le: { __default__: (a, b, ops) => ops.cmp(a, b) <= 0 },
  ge: { __default__: (a, b, ops) => ops.cmp(a, b) >= 0 },

  mod: { __default__: mod },
  gcd: { __default__: gcd },

  typeOf     : { __default__: x => typeOf(x) },
  repr       : { __default__: (x, ops) => ({ [typeOf(x)]: ops.__repr__(x) }) },
  fromRepr   : { Object: fromRepr },
  serialize  : { __default__: (x, ops) => JSON.stringify(ops.repr(x)) },
  deserialize: { String: (x, ops) => fromRepr(JSON.parse(x), ops) },

  __repr__: { __default__: x => x }
};

export function arithmetic(registry = mergeDeep({}, defaults)) {
  const result = {
    register(specs) {
      return arithmetic(mergeDeep(registry, specs));
    }
  };
  for (const op in registry)
    result[op] = call(registry[op], op, result);

  return result;
};

if (require.main == module) {
  const ops = arithmetic()
    .register({
      add: {
        Integer: {
          Integer: (a, b) => a + b,
          String : (n, s) => `${n}+"${s}"`
        },
        __default__: (x, y) => `${x} plus ${y}`
      },
      test: {
        __default__: (x, y, ops) => `<${ops.add(x, y)}>`
      }
    });

  console.log(`add(3, 4) = ${ops.add(3, 4)}`);
  console.log(`add(5, "Olaf") = ${ops.add(5, "Olaf")}`);
  console.log(`add("Olaf", "Delgado") = ${ops.add("Olaf", "Delgado")}`);
  console.log(`test(5, "Olaf") = ${ops.test(5, "Olaf")}`);
}
<|endoftext|>