<commit_before>App.controller('EmployeesController', function($scope, $timeout, yammer,
                                               Utils, GroupEmployee, AssignmentStats, AdminsResource, EMPTY_GROUP) {

        function getGroupEmployeesData(group) {
            if (group == EMPTY_GROUP) {
                group.employees = [];
                return;
            }
            group.employees = GroupEmployee.query({group_id: group.id}, function(response) {
                group.employeeMap = _.indexBy(response.employees, 'id');
            });
        }

        function addEmployee(yEmployee) {
            var group = $scope.selectedGroup;
            var yid = yEmployee.id;
            if (yid == undefined || yid == "") {
                return false;
            }
            if (_.find(group.employees, function(e){ return e.yammerId == yid; })) {
                $scope.newEmployeeName = "";
                return false;
            }

            var employee = new GroupEmployee({groupId: group.id});
            employee.yammerId = yid;
            employee.name = yEmployee.full_name;
            employee.imageUrlTemplate = yEmployee.photo;
            employee.$save({}, function(response) {
                group.addEmployee(employee);
                $scope.newEmployeeName = "";
            });
            return true;

        }

        $scope.deleteEmployee = function (employee) {
            var group = $scope.selectedGroup;
            employee.groupId = group.id;
            employee.$delete().then(function() {
                group.employees = _.without(group.employees, _.findWhere(group.employees, employee));
            });;
        }

        $scope.autocompleteList = [];

        var timeout;
        var AUTOCOMPLETE_QUERY_WAIT_TIME = 300; // as suggested by yammers api
        $scope.$watch('newEmployeeName', function(prefix) {
            if (prefix == undefined || prefix == "" || $scope.newEmployee != undefined) {
                return;
            }
            if (timeout != undefined) {
                $timeout.cancel(timeout);
            }
            timeout = $timeout(function() {
                yammer.autocomplete(prefix, function(response) {
                    if (response == undefined) {
                        return;
                    }
                    var users = response.user;
                    $timeout(function(){
                        $scope.autocompleteList =
                            (users.map(function(user) {
                                var names = user.full_name.split(" ");
                                user.label = names[0] + " " + names[names.length - 1];
                                return {
                                    label: user.label,
                                    value: user
                                }
                            }));
                        $scope.autocompleteList = _.unique($scope.autocompleteList, function(e) { return e.label; } );
                    });
                });

            }, AUTOCOMPLETE_QUERY_WAIT_TIME);
        });

        $scope.getAutocompleteItem = function(user) {
            return "" +
                "

" +
                "
" + user.label + "
";
        }

        $scope.stat = {
            selected: {counter: 3, unit: 'months'},
            units: {
                days:   {label: 'days',   multiplier: 1  },
                weeks:  {label: 'weeks',  multiplier: 7  },
                months: {label: 'months', multiplier: 30 },
                years:  {label: 'years',  multiplier: 365}
            }
        }

        $scope.getDaysOffset = function() {
            var counter = $scope.stat.selected.counter;
            var unit = $scope.stat.units[$scope.stat.selected.unit];
            return counter * unit.multiplier;
        }

        $scope.incrementStatCounter = function(delta) {
            $scope.stat.selected.counter = Math.max(0, $scope.stat.selected.counter + delta);
        }

        $scope.getAssignmentStats = function() {
            var group = $scope.selectedGroup;
            if (group == EMPTY_GROUP) {
                return;
            }

            var endDate = Date.TODAY;
            var startDate = endDate.plusDays(- $scope.getDaysOffset());

            AssignmentStats.query({
                group_id: group.id,
                start_date: startDate.toISOLocalDateString(),
                end_date: endDate.toISOLocalDateString()
            }, function(assignmentStats) {
                _.each(group.employees, function(e) {
                    e.statistics = {};
                    if (!assignmentStats[e.id]) return;
                    e.statistics = _.chain(assignmentStats[e.id])
                        .each(function(s) {s.assignmentType = group.assignmentTypeFor(s.assignmentTypeId);})
                        .indexBy('assignmentTypeId')
                        .value();
                });
                // complete with "count: 0" for other assignment types
                _.each(group.employees, function(e) {
                    _.each(group.assignmentTypes, function(a) {
                        if (e.statisticsFor(a.id)) return;
                        e.statistics[a.id] = {
                            assignmentTypeId: a.id,
                            assignmentType: a,
                            count: 0
                        };
                    });
                });
            });
        }

        $scope.$watch('assignmentsChange', $scope.getAssignmentStats);
        $scope.$watch('getDaysOffset()', $scope.getAssignmentStats);

        $scope.getAssignmentTypeHeaderStyle = function(assignmentType) {
            var ids = _.map($scope.employeeOrder, Math.abs);
            var i = _.indexOf(ids, assignmentType.id);
            var n = _.size(ids);
            var current = n - i - 1;
            var srcScale = [0, n - 1];

            return {
                position: 'relative',
                opacity: Utils.interpolate(current, srcScale, [0.25, 0.9]),
                paddingTop: Utils.interpolate(current, srcScale, [2, 8]) + 'px',
                bottom: Utils.interpolate(current, srcScale, [-3, 3]) + 'px'
            };
        }

        $scope.employeeOrder = []
        $scope.employeeOrderKey = []

        function computeEmployeeOrderKey(employeeOrder) {
            return _.map(employeeOrder, function(id) {
                var prefix = (id < 0) ? '-' : '+';
                return prefix + 'statistics[' + Math.abs(id) + '].count';
            })
        }

        function getOrderedId(assignmentType) {
            return (assignmentType.desc) ? -assignmentType.id : +assignmentType.id;
        }

        function tryUpdateOrder(newOrder) {
            if (_.isEqual(newOrder, $scope.employeeOrder)) return;
            $scope.employeeOrder = newOrder;
            $scope.employeeOrderKey = computeEmployeeOrderKey(newOrder);
        }

        function tryComputeEmployeeOrder() {
            var assignmentTypes = $scope.selectedGroup.assignmentTypes;
            if (assignmentTypes == null || assignmentTypes.length <= 0) return;
            var map = _.indexBy(assignmentTypes, 'id');
            var newIds = _.map(assignmentTypes, 'id');
            var currentIds = _.map($scope.employeeOrder, Math.abs);
            var newOrder = _.chain(currentIds)       // [unorderedId]
                .union(newIds)                       // [unorderedId]
                .intersection(newIds)                // intersect() after union() to keep original order
                .map(function(id) {return map[id];}) // [assignmentType]
                .map(getOrderedId)                   // [orderedId]
                .value();

            tryUpdateOrder(newOrder);
        }

        $scope.$watch('assignmentsChange', tryComputeEmployeeOrder);

        $scope.updateEmployeesOrder = function(assignmentType) {
            var oldId = getOrderedId(assignmentType);
            assignmentType.desc = !assignmentType.desc;
            var newId = getOrderedId(assignmentType);

            var newOrder = _.chain($scope.employeeOrder)
                .without(oldId)
                .unshift(newId)
                .value();

            tryUpdateOrder(newOrder);
        }

        $scope.employeeInput = null; // <input/>

        $scope.triggerAddEmployee = function() {
            if ($scope.newEmployee) {
                addEmployee($scope.newEmployee);
                $scope.newEmployee = undefined;
            } else {
                Utils.shakeOnError($scope.employeeInput);
            }
        }

        $scope.userInputKeyDown = function(e) {
            $scope.newEmployee = undefined;
        }

        $scope.userInputEnter = function(e) {
            $scope.triggerAddEmployee();
        }

        $scope.onSelectAutocomplete = function(user) {
            $scope.newEmployee = user;
            $scope.newEmployeeName = user.label;
        }

        $scope.toggleAdmin = function(employee) {
            if (employee.groupAdmin) {
                $scope.deleteAdmin(employee);
            } else {
                $scope.addAdmin(employee);
            }
        }

        $scope.addAdmin = function(employee) {
            AdminsResource.save({groupId: $scope.selectedGroup.id, employeeId: employee.id}, function() {
                employee.groupAdmin = true;
            });
        }

        $scope.deleteAdmin = function(employee) {
            AdminsResource.delete({group_id: $scope.selectedGroup.id, employee_id: employee.id}, function() {
                employee.groupAdmin = false;
            });
        }

        $scope.$watch('selectedGroup', function() {
            if ($scope.selectedGroup == null || $scope.selectedGroup == EMPTY_GROUP) return;
            getGroupEmployeesData($scope.selectedGroup);
            $scope.getAssignmentStats();
        });

        // Create new property to centralize assignments change events
        $scope.assignmentsChange = 0;

        function touchAssignments() {
            $scope.assignmentsChange++;
        }

        $scope.$watch('selectedGroup.employees.length', Utils.lastOfBurst(touchAssignments));
        $scope.$watch('selectedGroup.assignmentTypes.length', Utils.lastOfBurst(touchAssignments));
        $scope.$watch('assignmentTypeBuckets', Utils.lastOfBurst(touchAssignments), true);

});
<commit_msg>[bugfix] Fix inconsistency between employeeMap and employees<commit_after>App.controller('EmployeesController', function($scope, $timeout, yammer,
                                               Utils, GroupEmployee, AssignmentStats, AdminsResource, EMPTY_GROUP) {

        function getGroupEmployeesData(group) {
            if (group == EMPTY_GROUP) {
                group.employees = [];
                return;
            }
            group.employees = GroupEmployee.query({group_id: group.id}, function(response) {
                group.employeeMap = _.indexBy(group.employees, 'id');
            });
        }

        function addEmployee(yEmployee) {
            var group = $scope.selectedGroup;
            var yid = yEmployee.id;
            if (yid == undefined || yid == "") {
                return false;
            }
            if (_.find(group.employees, function(e){ return e.yammerId == yid; })) {
                $scope.newEmployeeName = "";
                return false;
            }

            var employee = new GroupEmployee({groupId: group.id});
            employee.yammerId = yid;
            employee.name = yEmployee.full_name;
            employee.imageUrlTemplate = yEmployee.photo;
            employee.$save({}, function(response) {
                group.addEmployee(employee);
                $scope.newEmployeeName = "";
            });
            return true;

        }

        $scope.deleteEmployee = function (employee) {
            var group = $scope.selectedGroup;
            employee.groupId = group.id;
            employee.$delete().then(function() {
                group.employees = _.without(group.employees, _.findWhere(group.employees, employee));
            });;
        }

        $scope.autocompleteList = [];

        var timeout;
        var AUTOCOMPLETE_QUERY_WAIT_TIME = 300; // as suggested by yammers api
        $scope.$watch('newEmployeeName', function(prefix) {
            if (prefix == undefined || prefix == "" || $scope.newEmployee != undefined) {
                return;
            }
            if (timeout != undefined) {
                $timeout.cancel(timeout);
            }
            timeout = $timeout(function() {
                yammer.autocomplete(prefix, function(response) {
                    if (response == undefined) {
                        return;
                    }
                    var users = response.user;
                    $timeout(function(){
                        $scope.autocompleteList =
                            (users.map(function(user) {
                                var names = user.full_name.split(" ");
                                user.label = names[0] + " " + names[names.length - 1];
                                return {
                                    label: user.label,
                                    value: user
                                }
                            }));
                        $scope.autocompleteList = _.unique($scope.autocompleteList, function(e) { return e.label; } );
                    });
                });

            }, AUTOCOMPLETE_QUERY_WAIT_TIME);
        });

        $scope.getAutocompleteItem = function(user) {
            return "" +
                "

" +
                "
" + user.label + "
";
        }

        $scope.stat = {
            selected: {counter: 3, unit: 'months'},
            units: {
                days:   {label: 'days',   multiplier: 1  },
                weeks:  {label: 'weeks',  multiplier: 7  },
                months: {label: 'months', multiplier: 30 },
                years:  {label: 'years',  multiplier: 365}
            }
        }

        $scope.getDaysOffset = function() {
            var counter = $scope.stat.selected.counter;
            var unit = $scope.stat.units[$scope.stat.selected.unit];
            return counter * unit.multiplier;
        }

        $scope.incrementStatCounter = function(delta) {
            $scope.stat.selected.counter = Math.max(0, $scope.stat.selected.counter + delta);
        }

        $scope.getAssignmentStats = function() {
            var group = $scope.selectedGroup;
            if (group == EMPTY_GROUP) {
                return;
            }

            var endDate = Date.TODAY;
            var startDate = endDate.plusDays(- $scope.getDaysOffset());

            AssignmentStats.query({
                group_id: group.id,
                start_date: startDate.toISOLocalDateString(),
                end_date: endDate.toISOLocalDateString()
            }, function(assignmentStats) {
                _.each(group.employees, function(e) {
                    e.statistics = {};
                    if (!assignmentStats[e.id]) return;
                    e.statistics = _.chain(assignmentStats[e.id])
                        .each(function(s) {s.assignmentType = group.assignmentTypeFor(s.assignmentTypeId);})
                        .indexBy('assignmentTypeId')
                        .value();
                });
                // complete with "count: 0" for other assignment types
                _.each(group.employees, function(e) {
                    _.each(group.assignmentTypes, function(a) {
                        if (e.statisticsFor(a.id)) return;
                        e.statistics[a.id] = {
                            assignmentTypeId: a.id,
                            assignmentType: a,
                            count: 0
                        };
                    });
                });
            });
        }

        $scope.$watch('assignmentsChange', $scope.getAssignmentStats);
        $scope.$watch('getDaysOffset()', $scope.getAssignmentStats);

        $scope.getAssignmentTypeHeaderStyle = function(assignmentType) {
            var ids = _.map($scope.employeeOrder, Math.abs);
            var i = _.indexOf(ids, assignmentType.id);
            var n = _.size(ids);
            var current = n - i - 1;
            var srcScale = [0, n - 1];

            return {
                position: 'relative',
                opacity: Utils.interpolate(current, srcScale, [0.25, 0.9]),
                paddingTop: Utils.interpolate(current, srcScale, [2, 8]) + 'px',
                bottom: Utils.interpolate(current, srcScale, [-3, 3]) + 'px'
            };
        }

        $scope.employeeOrder = []
        $scope.employeeOrderKey = []

        function computeEmployeeOrderKey(employeeOrder) {
            return _.map(employeeOrder, function(id) {
                var prefix = (id < 0) ? '-' : '+';
                return prefix + 'statistics[' + Math.abs(id) + '].count';
            })
        }

        function getOrderedId(assignmentType) {
            return (assignmentType.desc) ? -assignmentType.id : +assignmentType.id;
        }

        function tryUpdateOrder(newOrder) {
            if (_.isEqual(newOrder, $scope.employeeOrder)) return;
            $scope.employeeOrder = newOrder;
            $scope.employeeOrderKey = computeEmployeeOrderKey(newOrder);
        }

        function tryComputeEmployeeOrder() {
            var assignmentTypes = $scope.selectedGroup.assignmentTypes;
            if (assignmentTypes == null || assignmentTypes.length <= 0) return;
            var map = _.indexBy(assignmentTypes, 'id');
            var newIds = _.map(assignmentTypes, 'id');
            var currentIds = _.map($scope.employeeOrder, Math.abs);
            var newOrder = _.chain(currentIds)       // [unorderedId]
                .union(newIds)                       // [unorderedId]
                .intersection(newIds)                // intersect() after union() to keep original order
                .map(function(id) {return map[id];}) // [assignmentType]
                .map(getOrderedId)                   // [orderedId]
                .value();

            tryUpdateOrder(newOrder);
        }

        $scope.$watch('assignmentsChange', tryComputeEmployeeOrder);

        $scope.updateEmployeesOrder = function(assignmentType) {
            var oldId = getOrderedId(assignmentType);
            assignmentType.desc = !assignmentType.desc;
            var newId = getOrderedId(assignmentType);

            var newOrder = _.chain($scope.employeeOrder)
                .without(oldId)
                .unshift(newId)
                .value();

            tryUpdateOrder(newOrder);
        }

        $scope.employeeInput = null; // <input/>

        $scope.triggerAddEmployee = function() {
            if ($scope.newEmployee) {
                addEmployee($scope.newEmployee);
                $scope.newEmployee = undefined;
            } else {
                Utils.shakeOnError($scope.employeeInput);
            }
        }

        $scope.userInputKeyDown = function(e) {
            $scope.newEmployee = undefined;
        }

        $scope.userInputEnter = function(e) {
            $scope.triggerAddEmployee();
        }

        $scope.onSelectAutocomplete = function(user) {
            $scope.newEmployee = user;
            $scope.newEmployeeName = user.label;
        }

        $scope.toggleAdmin = function(employee) {
            if (employee.groupAdmin) {
                $scope.deleteAdmin(employee);
            } else {
                $scope.addAdmin(employee);
            }
        }

        $scope.addAdmin = function(employee) {
            AdminsResource.save({groupId: $scope.selectedGroup.id, employeeId: employee.id}, function() {
                employee.groupAdmin = true;
            });
        }

        $scope.deleteAdmin = function(employee) {
            AdminsResource.delete({group_id: $scope.selectedGroup.id, employee_id: employee.id}, function() {
                employee.groupAdmin = false;
            });
        }

        $scope.$watch('selectedGroup', function() {
            if ($scope.selectedGroup == null || $scope.selectedGroup == EMPTY_GROUP) return;
            getGroupEmployeesData($scope.selectedGroup);
            $scope.getAssignmentStats();
        });

        // Create new property to centralize assignments change events
        $scope.assignmentsChange = 0;

        function touchAssignments() {
            $scope.assignmentsChange++;
        }

        $scope.$watch('selectedGroup.employees.length', Utils.lastOfBurst(touchAssignments));
        $scope.$watch('selectedGroup.assignmentTypes.length', Utils.lastOfBurst(touchAssignments));
        $scope.$watch('assignmentTypeBuckets', Utils.lastOfBurst(touchAssignments), true);

});
<|endoftext|>


<commit_before>import {getDivider} from '../../../utilities/menu';
import {displayModes} from '../modes';

const colorsConfigAvailable = (state, tracks, track) => state.featureCountsDisplayMode === displayModes.barChart &&
    track.fcSourcesManager &&
    track.fcSourcesManager.sources.length;
const colorsConfigAvailableForSources = (state, tracks, track) => colorsConfigAvailable(state, tracks, track) &&
    track.fcSourcesManager.sources.length > 1;

export default {
    displayAdditionalName: state => {
        if (state.featureCountsDisplayMode === displayModes.barChart) {
            const parts = [];
            if (state.singleBarChartColors) {
                parts.push('Single color');
            }
            if (state.grayScaleColors) {
                parts.push('Grayscale');
            }
            if (parts.length > 0) {
                return parts.join('/');
            }
        }
        return undefined;
    },
    displayName: state => {
        switch (state.featureCountsDisplayMode) {
            case displayModes.features:
                return 'Features';
            case displayModes.barChart: {
                return 'Bar Graph';
            }
        }
    },
    fields: [
        {
            disable: state => state.featureCountsDisplayMode = displayModes.features,
            enable: state => state.featureCountsDisplayMode = displayModes.features,
            isEnabled: state => state.featureCountsDisplayMode === displayModes.features,
            label: 'Features',
            name: 'featurecounts>display>default',
            type: 'checkbox'
        },
        {
            disable: state => state.featureCountsDisplayMode = displayModes.features,
            enable: state => state.featureCountsDisplayMode = displayModes.barChart,
            isEnabled: state => state.featureCountsDisplayMode === displayModes.barChart,
            label: 'Bar Graph',
            name: 'featurecounts>display>barchart',
            type: 'checkbox'
        },
        getDivider({isVisible: colorsConfigAvailable}),
        {
            disable: state => state.singleBarChartColors = false,
            enable: state => state.singleBarChartColors = true,
            isEnabled: state => !!state.singleBarChartColors,
            isVisible: colorsConfigAvailableForSources,
            label: 'Use single color for sources',
            name: 'featurecounts>display>singleColor',
            type: 'checkbox'
        },
        {
            disable: state => state.grayScaleColors = false,
            enable: state => state.grayScaleColors = true,
            isEnabled: state => !!state.grayScaleColors,
            isVisible: colorsConfigAvailable,
            label: 'Use grayscale',
            name: 'featurecounts>display>grayscale',
            type: 'checkbox'
        }
    ],
    label: 'Display',
    name: 'featurecounts>display',
    type: 'submenu',
    isVisible: () => true
};
<commit_msg>Feature count tracks shall support histogram view (#521) - "unable to uncheck features menu"<commit_after>import {getDivider} from '../../../utilities/menu';
import {displayModes} from '../modes';

const colorsConfigAvailable = (state, tracks, track) => state.featureCountsDisplayMode === displayModes.barChart &&
    track.fcSourcesManager &&
    track.fcSourcesManager.sources.length;
const colorsConfigAvailableForSources = (state, tracks, track) => colorsConfigAvailable(state, tracks, track) &&
    track.fcSourcesManager.sources.length > 1;

export default {
    displayAdditionalName: state => {
        if (state.featureCountsDisplayMode === displayModes.barChart) {
            const parts = [];
            if (state.singleBarChartColors) {
                parts.push('Single color');
            }
            if (state.grayScaleColors) {
                parts.push('Grayscale');
            }
            if (parts.length > 0) {
                return parts.join('/');
            }
        }
        return undefined;
    },
    displayName: state => {
        switch (state.featureCountsDisplayMode) {
            case displayModes.features:
                return 'Features';
            case displayModes.barChart: {
                return 'Bar Graph';
            }
        }
    },
    fields: [
        {
            disable: state => state.featureCountsDisplayMode = displayModes.barChart,
            enable: state => state.featureCountsDisplayMode = displayModes.features,
            isEnabled: state => state.featureCountsDisplayMode === displayModes.features,
            label: 'Features',
            name: 'featurecounts>display>default',
            type: 'checkbox'
        },
        {
            disable: state => state.featureCountsDisplayMode = displayModes.features,
            enable: state => state.featureCountsDisplayMode = displayModes.barChart,
            isEnabled: state => state.featureCountsDisplayMode === displayModes.barChart,
            label: 'Bar Graph',
            name: 'featurecounts>display>barchart',
            type: 'checkbox'
        },
        getDivider({isVisible: colorsConfigAvailable}),
        {
            disable: state => state.singleBarChartColors = false,
            enable: state => state.singleBarChartColors = true,
            isEnabled: state => !!state.singleBarChartColors,
            isVisible: colorsConfigAvailableForSources,
            label: 'Use single color for sources',
            name: 'featurecounts>display>singleColor',
            type: 'checkbox'
        },
        {
            disable: state => state.grayScaleColors = false,
            enable: state => state.grayScaleColors = true,
            isEnabled: state => !!state.grayScaleColors,
            isVisible: colorsConfigAvailable,
            label: 'Use grayscale',
            name: 'featurecounts>display>grayscale',
            type: 'checkbox'
        }
    ],
    label: 'Display',
    name: 'featurecounts>display',
    type: 'submenu',
    isVisible: () => true
};
<|endoftext|>


<commit_before>let Mixpanel;
const Sinon = require('sinon');
const proxyquire = require('proxyquire');
const https = require('https');
const events = require('events');
const httpProxyOrig  = process.env.HTTP_PROXY;
const httpsProxyOrig = process.env.HTTPS_PROXY;
let HttpsProxyAgent;

exports.send_request = {
    setUp: function(next) {
        HttpsProxyAgent = Sinon.stub();
        Mixpanel = proxyquire('../lib/mixpanel-node', {
            'https-proxy-agent': HttpsProxyAgent,
        });

        Sinon.stub(https, 'request');

        this.http_emitter = new events.EventEmitter;
        this.http_end_spy = Sinon.spy();
        this.http_write_spy = Sinon.spy();
        this.http_emitter.write = this.http_write_spy;
        this.http_emitter.end = this.http_end_spy;
        this.res = new events.EventEmitter;
        https.request.returns(this.http_emitter);
        https.request.callsArgWith(1, this.res);

        this.mixpanel = Mixpanel.init('token');

        next();
    },

    tearDown: function(next) {
        https.request.restore();

        // restore proxy variables
        process.env.HTTP_PROXY = httpProxyOrig;
        process.env.HTTPS_PROXY = httpsProxyOrig;

        next();
    },

    "sends correct data on GET": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'GET',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0&data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ%3D%3D'
            };

        this.mixpanel.send_request({ method: 'get', endpoint: endpoint, data: data });

        test.expect(3);
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct arguments");
        test.ok(this.http_end_spy.callCount === 1, "send_request didn't end https.request");
        test.ok(this.http_write_spy.callCount === 0, "send_request called write for a GET");

        test.done();
    },

    "defaults to GET": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'GET',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0&data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ%3D%3D'
            };

        this.mixpanel.send_request({ endpoint: endpoint, data: data }); // method option not defined

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct method argument");

        test.done();
    },

    "sends correct data on POST": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'POST',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0'
            },
            expected_http_request_body = "data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ==";

        this.mixpanel.send_request({ method: 'post', endpoint: endpoint, data: data });

        test.expect(3);
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct arguments");
        test.ok(this.http_end_spy.callCount === 1, "send_request didn't end https.request");
        test.ok(this.http_write_spy.calledWithExactly(expected_http_request_body), "send_request did not write data correctly for a POST");

        test.done();
    },

    "handles mixpanel errors": function(test) {
        test.expect(1);
        this.mixpanel.send_request({ endpoint: "/track", data: { event: "test" } }, function(e) {
            test.equal(e.message, 'Mixpanel Server Error: 0', "error did not get passed back to callback");
            test.done();
        });

        this.res.emit('data', '0');
        this.res.emit('end');
    },

    "handles https.request errors": function(test) {
        test.expect(1);
        this.mixpanel.send_request({ endpoint: "/track", data: { event: "test" } }, function(e) {
            test.equal(e, 'error', "error did not get passed back to callback");
            test.done();
        });

        this.http_emitter.emit('error', 'error');
    },

    "default use keepAlive agent": function(test) {
        test.expect(2);
        var httpsStub = {
          request: Sinon.stub().returns(this.http_emitter).callsArgWith(1, this.res),
          Agent: Sinon.stub().returns({})
        };
        Mixpanel = proxyquire('../lib/mixpanel-node', {
            'https': httpsStub
        });
        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        var agentOpts = httpsStub.Agent.firstCall.args[0];
        test.ok(agentOpts.keepAlive === true, "HTTP Agent is set to keepAlive by default");

        var getConfig = httpsStub.request.firstCall.args[0];
        test.ok(getConfig.agent !== undefined, "send_request didn't call https.request with agent");

        test.done();
    },

    "uses correct hostname": function(test) {
        var host = 'testhost.fakedomain';
        var customHostnameMixpanel = Mixpanel.init('token', { host: host });
        var expected_http_request = {
            host: host
        };

        customHostnameMixpanel.send_request({ endpoint: "", data: {} });

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname");

        test.done();
    },

    "uses correct port": function(test) {
        var host = 'testhost.fakedomain:1337';
        var customHostnameMixpanel = Mixpanel.init('token', { host: host });
        var expected_http_request = {
            host: 'testhost.fakedomain',
            port: 1337
        };

        customHostnameMixpanel.send_request({ endpoint: "", data: {} });

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "uses correct path": function(test) {
        var host = 'testhost.fakedomain';
        var customPath = '/mypath';
        var customHostnameMixpanel = Mixpanel.init('token', {
            host,
            path: customPath,
        });
        var expected_http_request = {
            host,
            path: '/mypath?ip=0&verbose=0&data=e30%3D',
        };

        customHostnameMixpanel.send_request({endpoint: "", data: {}});
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "combines custom path and endpoint": function(test) {
        var host = 'testhost.fakedomain';
        var customPath = '/mypath';
        var customHostnameMixpanel = Mixpanel.init('token', {
            host,
            path: customPath,
        });
        var expected_http_request = {
            host,
            path: '/mypath/track?ip=0&verbose=0&data=e30%3D',
        };

        customHostnameMixpanel.send_request({endpoint: '/track', data: {}});
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "uses HTTP_PROXY if set": function(test) {
        HttpsProxyAgent.reset(); // Mixpanel is instantiated in setup, need to reset callcount
        delete process.env.HTTPS_PROXY;
        process.env.HTTP_PROXY = 'this.aint.real.https';

        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        test.ok(HttpsProxyAgent.calledOnce, "HttpsProxyAgent was not called when process.env.HTTP_PROXY was set");

        var agentOpts = HttpsProxyAgent.firstCall.args[0];
        test.ok(agentOpts.pathname === "this.aint.real.https", "HttpsProxyAgent was not called with the correct proxy path");
        test.ok(agentOpts.keepAlive === true, "HttpsProxyAgent was not called with the correct proxy path");

        var getConfig = https.request.firstCall.args[0];
        test.ok(getConfig.agent !== undefined, "send_request didn't call https.request with agent");

        test.done();
    },

    "uses HTTPS_PROXY if set": function(test) {
        HttpsProxyAgent.reset(); // Mixpanel is instantiated in setup, need to reset callcount
        delete process.env.HTTP_PROXY;
        process.env.HTTPS_PROXY = 'this.aint.real.https';

        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        test.ok(HttpsProxyAgent.calledOnce, "HttpsProxyAgent was not called when process.env.HTTPS_PROXY was set");

        var proxyOpts = HttpsProxyAgent.firstCall.args[0];
        test.ok(proxyOpts.pathname === 'this.aint.real.https', "HttpsProxyAgent was not called with the correct proxy path");

        var getConfig = https.request.firstCall.args[0];
        test.ok(getConfig.agent !== undefined, "send_request didn't call https.request with agent");

        test.done();
    },

    "requires credentials for import requests": function(test) {
        test.throws(
            this.mixpanel.send_request.bind(this, {
                endpoint: `/import`,
                data: {event: `test event`},
            }),
            /The Mixpanel Client needs a Mixpanel API Secret when importing old events/,
            "import request didn't throw error when no credentials provided"
        );
        test.done();
    },

    "sets basic auth header if API secret is provided": function(test) {
        this.mixpanel.set_config({secret: `foobar`});
        this.mixpanel.send_request({
            endpoint: `/import`,
            data: {event: `test event`},
        });
        test.ok(https.request.calledOnce);
        test.deepEqual(https.request.args[0][0].headers, {
            'Authorization': `Basic Zm9vYmFyOg==`, // base64 of "foobar:"
        }, "send_request didn't pass correct auth header to https.request");
        test.done();
    },

    "still supports import with api_key (legacy)": function(test) {
        this.mixpanel.set_config({key: `barbaz`});
        this.mixpanel.send_request({
            endpoint: `/import`,
            data: {},
        });
        test.ok(https.request.calledOnce);
        test.equal(
            https.request.args[0][0].path,
            `/import?ip=0&verbose=0&data=e30%3D&api_key=barbaz`,
            "send_request didn't pass correct query params to https.request"
        );
        test.done();
    },
};
<commit_msg>Fixed the testcases<commit_after>let Mixpanel;
const Sinon = require('sinon');
const proxyquire = require('proxyquire');
const https = require('https');
const events = require('events');
const httpProxyOrig  = process.env.HTTP_PROXY;
const httpsProxyOrig = process.env.HTTPS_PROXY;
let HttpsProxyAgent;

exports.send_request = {
    setUp: function(next) {
        HttpsProxyAgent = Sinon.stub();
        Mixpanel = proxyquire('../lib/mixpanel-node', {
            'https-proxy-agent': HttpsProxyAgent,
        });

        Sinon.stub(https, 'request');

        this.http_emitter = new events.EventEmitter;
        this.http_end_spy = Sinon.spy();
        this.http_write_spy = Sinon.spy();
        this.http_emitter.write = this.http_write_spy;
        this.http_emitter.end = this.http_end_spy;
        this.res = new events.EventEmitter;
        https.request.returns(this.http_emitter);
        https.request.callsArgWith(1, this.res);

        this.mixpanel = Mixpanel.init('token');

        next();
    },

    tearDown: function(next) {
        https.request.restore();

        // restore proxy variables
        process.env.HTTP_PROXY = httpProxyOrig;
        process.env.HTTPS_PROXY = httpsProxyOrig;

        next();
    },

    "sends correct data on GET": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'GET',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0&data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ%3D%3D'
            };

        this.mixpanel.send_request({ method: 'get', endpoint: endpoint, data: data });

        test.expect(3);
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct arguments");
        test.ok(this.http_end_spy.callCount === 1, "send_request didn't end https.request");
        test.ok(this.http_write_spy.callCount === 0, "send_request called write for a GET");

        test.done();
    },

    "defaults to GET": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'GET',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0&data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ%3D%3D'
            };

        this.mixpanel.send_request({ endpoint: endpoint, data: data }); // method option not defined

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct method argument");

        test.done();
    },

    "sends correct data on POST": function(test) {
        var endpoint = "/track",
            data = {
                event: 'test',
                properties: {
                    key1: 'val1',
                    token: 'token',
                    time: 1346876621
                }
            },
            expected_http_request = {
                method: 'POST',
                host: 'api.mixpanel.com',
                headers: {},
                path: '/track?ip=0&verbose=0'
            },
            expected_http_request_body = "data=eyJldmVudCI6InRlc3QiLCJwcm9wZXJ0aWVzIjp7ImtleTEiOiJ2YWwxIiwidG9rZW4iOiJ0b2tlbiIsInRpbWUiOjEzNDY4NzY2MjF9fQ==";

        this.mixpanel.send_request({ method: 'post', endpoint: endpoint, data: data });

        test.expect(3);
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct arguments");
        test.ok(this.http_end_spy.callCount === 1, "send_request didn't end https.request");
        test.ok(this.http_write_spy.calledWithExactly(expected_http_request_body), "send_request did not write data correctly for a POST");

        test.done();
    },

    "handles mixpanel errors": function(test) {
        test.expect(1);
        this.mixpanel.send_request({ endpoint: "/track", data: { event: "test" } }, function(e) {
            test.equal(e.message, 'Mixpanel Server Error: 0', "error did not get passed back to callback");
            test.done();
        });

        this.res.emit('data', '0');
        this.res.emit('end');
    },

    "handles https.request errors": function(test) {
        test.expect(1);
        this.mixpanel.send_request({ endpoint: "/track", data: { event: "test" } }, function(e) {
            test.equal(e, 'error', "error did not get passed back to callback");
            test.done();
        });

        this.http_emitter.emit('error', 'error');
    },

    "default use keepAlive agent": function(test) {
        test.expect(2);
        var agent = new https.Agent({ keepAlive: true });
        var httpsStub = {
            request: Sinon.stub().returns(this.http_emitter).callsArgWith(1, this.res),
            Agent: Sinon.stub().returns(agent),
        };
        // force SDK not use `undefined` string to initialize proxy-agent
        delete process.env.HTTP_PROXY
        delete process.env.HTTPS_PROXY
        Mixpanel = proxyquire('../lib/mixpanel-node', {
            'https': httpsStub
        });
        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        var getConfig = httpsStub.request.firstCall.args[0];
        var agentOpts = httpsStub.Agent.firstCall.args[0];
        test.ok(agentOpts.keepAlive === true, "HTTP Agent is set to keepAlive by default");

        test.ok(getConfig.agent === agent, "send_request didn't call https.request with agent");

        test.done();
    },

    "uses correct hostname": function(test) {
        var host = 'testhost.fakedomain';
        var customHostnameMixpanel = Mixpanel.init('token', { host: host });
        var expected_http_request = {
            host: host
        };

        customHostnameMixpanel.send_request({ endpoint: "", data: {} });

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname");

        test.done();
    },

    "uses correct port": function(test) {
        var host = 'testhost.fakedomain:1337';
        var customHostnameMixpanel = Mixpanel.init('token', { host: host });
        var expected_http_request = {
            host: 'testhost.fakedomain',
            port: 1337
        };

        customHostnameMixpanel.send_request({ endpoint: "", data: {} });

        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "uses correct path": function(test) {
        var host = 'testhost.fakedomain';
        var customPath = '/mypath';
        var customHostnameMixpanel = Mixpanel.init('token', {
            host,
            path: customPath,
        });
        var expected_http_request = {
            host,
            path: '/mypath?ip=0&verbose=0&data=e30%3D',
        };

        customHostnameMixpanel.send_request({endpoint: "", data: {}});
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "combines custom path and endpoint": function(test) {
        var host = 'testhost.fakedomain';
        var customPath = '/mypath';
        var customHostnameMixpanel = Mixpanel.init('token', {
            host,
            path: customPath,
        });
        var expected_http_request = {
            host,
            path: '/mypath/track?ip=0&verbose=0&data=e30%3D',
        };

        customHostnameMixpanel.send_request({endpoint: '/track', data: {}});
        test.ok(https.request.calledWithMatch(expected_http_request), "send_request didn't call https.request with correct hostname and port");

        test.done();
    },

    "uses HTTP_PROXY if set": function(test) {
        HttpsProxyAgent.reset(); // Mixpanel is instantiated in setup, need to reset callcount
        delete process.env.HTTPS_PROXY;
        process.env.HTTP_PROXY = 'this.aint.real.https';

        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        test.ok(HttpsProxyAgent.calledOnce, "HttpsProxyAgent was not called when process.env.HTTP_PROXY was set");

        var agentOpts = HttpsProxyAgent.firstCall.args[0];
        test.ok(agentOpts.pathname === "this.aint.real.https", "HttpsProxyAgent was not called with the correct proxy path");
        test.ok(agentOpts.keepAlive === true, "HttpsProxyAgent was not called with the correct proxy path");

        var getConfig = https.request.firstCall.args[0];
        test.ok(getConfig.agent !== undefined, "send_request didn't call https.request with agent");

        test.done();
    },

    "uses HTTPS_PROXY if set": function(test) {
        HttpsProxyAgent.reset(); // Mixpanel is instantiated in setup, need to reset callcount
        delete process.env.HTTP_PROXY;
        process.env.HTTPS_PROXY = 'this.aint.real.https';

        var proxyMixpanel = Mixpanel.init('token');
        proxyMixpanel.send_request({ endpoint: '', data: {} });

        test.ok(HttpsProxyAgent.calledOnce, "HttpsProxyAgent was not called when process.env.HTTPS_PROXY was set");

        var proxyOpts = HttpsProxyAgent.firstCall.args[0];
        test.ok(proxyOpts.pathname === 'this.aint.real.https', "HttpsProxyAgent was not called with the correct proxy path");

        var getConfig = https.request.firstCall.args[0];
        test.ok(getConfig.agent !== undefined, "send_request didn't call https.request with agent");

        test.done();
    },

    "requires credentials for import requests": function(test) {
        test.throws(
            this.mixpanel.send_request.bind(this, {
                endpoint: `/import`,
                data: {event: `test event`},
            }),
            /The Mixpanel Client needs a Mixpanel API Secret when importing old events/,
            "import request didn't throw error when no credentials provided"
        );
        test.done();
    },

    "sets basic auth header if API secret is provided": function(test) {
        this.mixpanel.set_config({secret: `foobar`});
        this.mixpanel.send_request({
            endpoint: `/import`,
            data: {event: `test event`},
        });
        test.ok(https.request.calledOnce);
        test.deepEqual(https.request.args[0][0].headers, {
            'Authorization': `Basic Zm9vYmFyOg==`, // base64 of "foobar:"
        }, "send_request didn't pass correct auth header to https.request");
        test.done();
    },

    "still supports import with api_key (legacy)": function(test) {
        this.mixpanel.set_config({key: `barbaz`});
        this.mixpanel.send_request({
            endpoint: `/import`,
            data: {},
        });
        test.ok(https.request.calledOnce);
        test.equal(
            https.request.args[0][0].path,
            `/import?ip=0&verbose=0&data=e30%3D&api_key=barbaz`,
            "send_request didn't pass correct query params to https.request"
        );
        test.done();
    },
};
<|endoftext|>


<commit_before>'use strict';

describe('Storage Service test: ', function() {
	var storage, $timeout;
	beforeEach(module('IntergenStorage'))

	beforeEach(inject(function (_IntergenStorageService_, _$timeout_) {
		storage = _IntergenStorageService_;
		$timeout = _$timeout_
	}));

	afterEach(function() {
		sessionStorage.clear();
		localStorage.clear();
	});

	it('should be able to set in local and session storage', function() {
		var valueToBeSet = 'hello'
		storage.set('testKey', valueToBeSet).then(function() {
			var browserSessionStorage = sessionStorage.getItem('intergen.testKey');
			var browserLocalStorage = localStorage.getItem('intergen.testKey');
			expect(browserSessionStorage).toBe(valueToBeSet);
			expect(browserLocalStorage).toBe(valueToBeSet);
		});
		$timeout.flush();
	});

	it('should compress the target value and set in local and session storage', function() {
		storage.configure({
			useCompression: true
		});

		var valueToBeSet = {
			a: 'adsfklsdfkmlsklfsdlkdsfklfsdlkjfsdklsfdkljsfdkjlsfdjklsfdjkfsdj dsfjfdsjlkfdsjlkfsdjlkjksldf j sfjkfds jlk sfdjkl sfd',
			b: 'adskldsl kfdjkslfjdslk jkdfsjksfd jfksdjk dfsjk fdskjfsdkjl fdskfkjlfdkjlfdkfskjljk sldfjk l sdfk js kjsfdkjlfsdjksfdjksfdkj l kjfs dkjlsf djkljkl fsdkjls'
		}
		var stringLength = JSON.stringify(valueToBeSet).length;

		storage.set('compressionTest', valueToBeSet).then(function() {
			var browserSessionStorage = sessionStorage.getItem('intergen.compressionTest').length;
			expect(browserSessionStorage).toBeLessThan(stringLength)
			console.log('size before: ' + stringLength + ' size after:' +  browserSessionStorage);
		});
		$timeout.flush();
		storage.configure({
			useCompression: false
		});
	});

	it('should get value from session storage', function() {
		var value = {
			a: 'blah'
		};

		sessionStorage.setItem('intergen.ses', value);

		var fromSessionStorage = storage.get('ses');

		expect(fromSessionStorage).not.toBe(null);
		expect(fromSessionStorage).not.toBe(undefined);
	});

	it('should get value from storage - with session storage preference', function() {
	  	var valueSession = {
	  		a: 'blah'
	  	};
	  	var valueLocal = {
	  		a: 'notblah'
	  	};

		sessionStorage.setItem('intergen.ses', JSON.stringify(valueSession));
	  	localStorage.setItem('intergen.ses', JSON.stringify(valueLocal));

	  	var fromSessionStorage = storage.get('ses');

	  	expect(fromSessionStorage.a).toBe(valueSession.a);
	});

	it('should not set over the current value if the object going in to storage is exactly the same', function() {
		var value = 'test';
		spyOn(storage, 'store').and.callThrough();

		storage.set('test', value);
		$timeout.flush();

		storage.set('test', value).then(function() {
			expect(storage.store.calls.count()).toEqual(1);
		});

		$timeout.flush();
	});

	it('should set over the current value if the object going in to storage is exactly the same', function() {
		var value = 'test';
		spyOn(storage, 'store').and.callThrough();

		storage.set('test', value);
		$timeout.flush();

		value = 'changed';

		storage.set('test', value).then(function() {
			expect(storage.store.calls.count()).toEqual(2);
		});

		$timeout.flush();
	});

	it('should return js objects if they are set as such', function() {
		var obj = {
			prop: 'hello',
			truth: false,
			h: 5
		};

		storage.set('val', obj);
		$timeout.flush();

		var after = storage.get('val');

		expect(angular.isString(after.prop)).toBeTruthy();
		expect(angular.isNumber(after.h)).toBeTruthy();
		expect(after.truth).toBeFalsy();
	});

	it('should return ISO date strings', function() {
		var date = new Date();
		storage.set('ab', date);
		$timeout.flush();

		var val = storage.get('ab');

		expect(angular.isString(val)).toBeTruthy();
		expect(val).toEqual(date.toISOString())
	});

	it('should throw an error if the key passed in set is undefined', function() {
		expect(function() {
			storage.set(undefined, { test: 'a'});
		}).toThrowError();
	});

	it('should throw an error if the value passed in set is undefined', function() {
		expect(function() {
			storage.set('legitKey', undefined);
		}).toThrowError();
	});

	it('should throw an error if the key passed in get is undefined', function() {
		expect(function() {
			storage.set(undefined);
		}).toThrowError();
	});

	it('should have the correct config values when the configure method is called', function() {
		var oldOptions = storage.options;
		var prefix = 'someOtherPrefix';
		var useCompression = true;
		var storageType = 1;

		storage.configure({
			storagePrefix: prefix,
			useCompression: useCompression,
			storageType: storageType
		});

		expect(storage.options.storagePrefix).toBe(prefix);
		expect(storage.options.useCompression).toBe(useCompression);
		expect(storage.options.storageType).toBe(storageType);

		storage.configure(oldOptions);
	});

	it('should remove value from session storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 1);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(value);
		});
		$timeout.flush();
	});

	it('should remove value from local storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 0);
			expect(sessionStorage.getItem('intergen.item')).toBe(value);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should remove value from local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 2);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should clear local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.removeAll(2);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should clear local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(2);
			expect(sessionStorage.length).toBe(0);
			expect(localStorage.length).toBe(0);
		});
	});

	it('should clear session storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(1);
			expect(sessionStorage.length).toBe(0);
			expect(localStorage.length).toBe(2);
		});
	});

	it('should clear session storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(0);
			expect(sessionStorage.length).toBe(2);
			expect(localStorage.length).toBe(0);
		});
	});
});<commit_msg>editing test to have correct description<commit_after>'use strict';

describe('Storage Service test: ', function() {
	var storage, $timeout;
	beforeEach(module('IntergenStorage'))

	beforeEach(inject(function (_IntergenStorageService_, _$timeout_) {
		storage = _IntergenStorageService_;
		$timeout = _$timeout_
	}));

	afterEach(function() {
		sessionStorage.clear();
		localStorage.clear();
	});

	it('should be able to set in local and session storage', function() {
		var valueToBeSet = 'hello'
		storage.set('testKey', valueToBeSet).then(function() {
			var browserSessionStorage = sessionStorage.getItem('intergen.testKey');
			var browserLocalStorage = localStorage.getItem('intergen.testKey');
			expect(browserSessionStorage).toBe(valueToBeSet);
			expect(browserLocalStorage).toBe(valueToBeSet);
		});
		$timeout.flush();
	});

	it('should compress the target value and set in local and session storage', function() {
		storage.configure({
			useCompression: true
		});

		var valueToBeSet = {
			a: 'adsfklsdfkmlsklfsdlkdsfklfsdlkjfsdklsfdkljsfdkjlsfdjklsfdjkfsdj dsfjfdsjlkfdsjlkfsdjlkjksldf j sfjkfds jlk sfdjkl sfd',
			b: 'adskldsl kfdjkslfjdslk jkdfsjksfd jfksdjk dfsjk fdskjfsdkjl fdskfkjlfdkjlfdkfskjljk sldfjk l sdfk js kjsfdkjlfsdjksfdjksfdkj l kjfs dkjlsf djkljkl fsdkjls'
		}
		var stringLength = JSON.stringify(valueToBeSet).length;

		storage.set('compressionTest', valueToBeSet).then(function() {
			var browserSessionStorage = sessionStorage.getItem('intergen.compressionTest').length;
			expect(browserSessionStorage).toBeLessThan(stringLength)
			console.log('size before: ' + stringLength + ' size after:' +  browserSessionStorage);
		});
		$timeout.flush();
		storage.configure({
			useCompression: false
		});
	});

	it('should get value from session storage', function() {
		var value = {
			a: 'blah'
		};

		sessionStorage.setItem('intergen.ses', value);

		var fromSessionStorage = storage.get('ses');

		expect(fromSessionStorage).not.toBe(null);
		expect(fromSessionStorage).not.toBe(undefined);
	});

	it('should get value from storage - with session storage preference', function() {
	  	var valueSession = {
	  		a: 'blah'
	  	};
	  	var valueLocal = {
	  		a: 'notblah'
	  	};

		sessionStorage.setItem('intergen.ses', JSON.stringify(valueSession));
	  	localStorage.setItem('intergen.ses', JSON.stringify(valueLocal));

	  	var fromSessionStorage = storage.get('ses');

	  	expect(fromSessionStorage.a).toBe(valueSession.a);
	});

	it('should not set over the current value if the object going in to storage is exactly the same', function() {
		var value = 'test';
		spyOn(storage, 'store').and.callThrough();

		storage.set('test', value);
		$timeout.flush();

		storage.set('test', value).then(function() {
			expect(storage.store.calls.count()).toEqual(1);
		});

		$timeout.flush();
	});

	it('should set over the current value if the object going in to storage is exactly the same', function() {
		var value = 'test';
		spyOn(storage, 'store').and.callThrough();

		storage.set('test', value);
		$timeout.flush();

		value = 'changed';

		storage.set('test', value).then(function() {
			expect(storage.store.calls.count()).toEqual(2);
		});

		$timeout.flush();
	});

	it('should return js objects if they are set as such', function() {
		var obj = {
			prop: 'hello',
			truth: false,
			h: 5
		};

		storage.set('val', obj);
		$timeout.flush();

		var after = storage.get('val');

		expect(angular.isString(after.prop)).toBeTruthy();
		expect(angular.isNumber(after.h)).toBeTruthy();
		expect(after.truth).toBeFalsy();
	});

	it('should return ISO date strings', function() {
		var date = new Date();
		storage.set('ab', date);
		$timeout.flush();

		var val = storage.get('ab');

		expect(angular.isString(val)).toBeTruthy();
		expect(val).toEqual(date.toISOString())
	});

	it('should throw an error if the key passed in set is undefined', function() {
		expect(function() {
			storage.set(undefined, { test: 'a'});
		}).toThrowError();
	});

	it('should throw an error if the value passed in set is undefined', function() {
		expect(function() {
			storage.set('legitKey', undefined);
		}).toThrowError();
	});

	it('should throw an error if the key passed in get is undefined', function() {
		expect(function() {
			storage.set(undefined);
		}).toThrowError();
	});

	it('should have the correct config values when the configure method is called', function() {
		var oldOptions = storage.options;
		var prefix = 'someOtherPrefix';
		var useCompression = true;
		var storageType = 1;

		storage.configure({
			storagePrefix: prefix,
			useCompression: useCompression,
			storageType: storageType
		});

		expect(storage.options.storagePrefix).toBe(prefix);
		expect(storage.options.useCompression).toBe(useCompression);
		expect(storage.options.storageType).toBe(storageType);

		storage.configure(oldOptions);
	});

	it('should remove value from session storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 1);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(value);
		});
		$timeout.flush();
	});

	it('should remove value from local storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 0);
			expect(sessionStorage.getItem('intergen.item')).toBe(value);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should remove value from local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.remove('item', 2);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should clear local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
			storage.removeAll(2);
			expect(sessionStorage.getItem('intergen.item')).toBe(null);
			expect(localStorage.getItem('intergen.item')).toBe(null);
		});
		$timeout.flush();
	});

	it('should clear local and session storage', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(2);
			expect(sessionStorage.length).toBe(0);
			expect(localStorage.length).toBe(0);
		});
	});

	it('should clear session storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(1);
			expect(sessionStorage.length).toBe(0);
			expect(localStorage.length).toBe(2);
		});
	});

	it('should clear local storage only', function() {
		var value = 's';
		storage.set('item', value).then(function() {
			expect(storage.get('item')).toBe(value);
		});
		$timeout.flush();
		storage.set('anotherItem', value).then(function() {
			storage.removeAll(0);
			expect(sessionStorage.length).toBe(2);
			expect(localStorage.length).toBe(0);
		});
	});
});<|endoftext|>


<commit_before>/**
 * Copyright 2006 - 2013 TubePress LLC (http://tubepress.com)
 *
 * This file is part of TubePress (http://tubepress.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/.
 */
var TubePressBootstrapMultiselectInitializer = (function () {

    'use strict';

    var init = function () {

        jQuery('.tubepress-bootstrap-multiselect-field').multiselect({

            buttonClass : 'btn btn-default btn-sm',
            dropRight   : true,
            buttonText  : jQuery(this).data('selectText')
        });
    };

    return {

        init : init
    };

}());

jQuery(function () {

    'use strict';

    TubePressBootstrapMultiselectInitializer.init();
});<commit_msg>Fixing behavior of bootstrap-multiselect to show "select ..." at all times<commit_after>/**
 * Copyright 2006 - 2013 TubePress LLC (http://tubepress.com)
 *
 * This file is part of TubePress (http://tubepress.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/.
 */
var TubePressBootstrapMultiselectInitializer = (function () {

    'use strict';

    var multiSelectIt = function (index, val) {

            var field      = jQuery(val),
                selectText = field.data('selecttext');

            field.multiselect({

                buttonClass : 'btn btn-default btn-sm',
                dropRight   : true,
                buttonText  : function () { return selectText; }
            });
        },

        init = function () {

            jQuery('.tubepress-bootstrap-multiselect-field').each(multiSelectIt);
        };

    return {

        init : init
    };

}());

jQuery(function () {

    'use strict';

    TubePressBootstrapMultiselectInitializer.init();
});<|endoftext|>


<commit_before>/**
 *
 */
$( document ).ready(function() {
	/**
	 * TODO LO CONCERNIENTE A ADMINISTARCION DE PATOLOGIAS
	 */
	$('#agregarPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombrePatologia:
			   {
			     	required: true,
			     	minlength: 5,
			     	remote:
					{
				        type: "POST",
				        url: "/sicmec/Utils/validarPatologia",
			            data :
			                {
			            	nombrePatologia: function()
			                  { return $("#nombrePatologia").val(); }
			             }
				     }
			   },
			   descripcionPatologia:
			   {
			        required: true,
			     	minlength: 10
			  }
		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$('#modificarPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombrePatologiaUp:
			   {
			     	required: true,
			     	minlength: 5
			   },
			   descripcionPatologiaUp:
			   {
			        required: true
			  }
		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$("#tablePatologias").DataTable({
		"scrollY":        "350px",
        "scrollCollapse": false,
        "aoColumns":
        	[
        	 { "sWidth": "5%", "sClass": "center", "bSortable": false },
        	 { "sWidth": "10%" },
        	 { "sWidth": "15%" },
            ],
            language: {
                "sProcessing":     "Procesando...",
                "sLengthMenu":     "Mostrar _MENU_ registros",
                "sZeroRecords":    "No se encontraron resultados",
                "sEmptyTable":     "Ningún dato disponible en esta tabla",
                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                "sInfoPostFix":    "",
                "sSearch":         "Buscar:",
                "sUrl":            "",
                "sInfoThousands":  ",",
                "sLoadingRecords": "Cargando...",
                "oPaginate": {
                    "sFirst":    "Primero",
                    "sLast":     "Último",
                    "sNext":     "Siguiente",
                    "sPrevious": "Anterior"
                },
                "oAria": {
                    "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                    "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                } ,
                "fnDrawCallback": function() {
                	$(".onUpdatePatologia").click(function(){
                		var id = $(this).data("id");

                		$.ajax
                		({
                			type: "GET",
                			url:"/sicmec/admin/patologias/getPatologia/"+id,
                			success:function(result)
                			{
                				$("#idPatologiaUp").val(result.idSicPatologia);
                				$("#nombrePatologiaUp").val(result.nombrePatologia);
                				$("#descripcionPatologiaUp").val(result.descripcionPatologia);
                				//$("#modalUpdatePatologia").modal("show");
                			},
                			error: function (xhr, ajaxOptions, thrownError)
                			{
                				alert("unable to find server..")
                		    }
                		});
                	});
                },
            }
	});

/**
 * TODO LO CONCERNIENTE A ADMINISTARCION DE TIPOS DE PATOLOGIAS
 */
	$('#agregarTipoPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombreTipoPatologia:
			   {
			     	required: true,
			     	minlength: 5,
			     	remote:
					{
				        type: "POST",
				        url: "/sicmec/Utils/validarTipoPatologia",
			            data :
			                {
			            	nombreTipoPatologia: function()
			                  { return $("#nombreTipoPatologia").val(); }
			             }
				     }
			   },
			   descripcionTipoPatologia:
			   {
			        required: true,
			     	minlength: 10
			  },
			  patologia:
			   {
			        required: true
			  }

		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$('#modificarTipoPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombreTipoPatologiaUp:
			   {
			     	required: true,
			     	minlength: 5
			   },
			   descripcionTipoPatologiaUp:
			   {
			        required: true,
			     	minlength: 10
			  },
			  patologiaUp:
			   {
			        required: true
			  }

		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});

	$("#tableTipoPatologias").DataTable({
		"scrollY":        "350px",
        "scrollCollapse": false,
        "aoColumns":
        	[
        	 { "sWidth": "5%", "sClass": "center", "bSortable": false },
        	 { "sWidth": "10%" },
        	 { "sWidth": "15%" },
        	 { "sWidth": "10%" },
            ],
            language: {
                "sProcessing":     "Procesando...",
                "sLengthMenu":     "Mostrar _MENU_ registros",
                "sZeroRecords":    "No se encontraron resultados",
                "sEmptyTable":     "Ningún dato disponible en esta tabla",
                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                "sInfoPostFix":    "",
                "sSearch":         "Buscar:",
                "sUrl":            "",
                "sInfoThousands":  ",",
                "sLoadingRecords": "Cargando...",
                "oPaginate": {
                    "sFirst":    "Primero",
                    "sLast":     "Último",
                    "sNext":     "Siguiente",
                    "sPrevious": "Anterior"
                },
                "oAria": {
                    "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                    "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                } ,
                "fnDrawCallback": function() {
                	$(".onUpdateTipoPatologia").click(function(){
                		var id = $(this).data("id");

                		$.ajax
                		({
                			type: "GET",
                			url:"/sicmec/admin/patologias/getTipoPatologia/"+id,
                			success:function(result)
                			{
                				$("#idTipoPatologiaUp").val(result.idSicTipoPatologia);
                				$("#nombreTipoPatologiaUp").val(result.nombreTipoPatologia);
                				$("#descripcionTipoPatologiaUp").val(result.descripcionTipoPatologia);
                				$("#patologiaUp").val(result.fkSicPatologia.idSicPatologia);
                				//$("#modalUpdateTipoPatologia").modal("show");
                			},
                			error: function (xhr, ajaxOptions, thrownError)
                			{
                				alert("unable to find server..")
                		    }
                		});
                	});
                },
            }
	});
});<commit_msg>Ultimo cambio visual en pantalla Patologias.<commit_after>/**
 *
 */
$( document ).ready(function() {
	/**
	 * TODO LO CONCERNIENTE A ADMINISTARCION DE PATOLOGIAS
	 */
	$('#agregarPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombrePatologia:
			   {
			     	required: true,
			     	minlength: 5,
			     	remote:
					{
				        type: "POST",
				        url: "/sicmec/Utils/validarPatologia",
			            data :
			                {
			            	nombrePatologia: function()
			                  { return $("#nombrePatologia").val(); }
			             }
				     }
			   },
			   descripcionPatologia:
			   {
			        required: true,
			     	minlength: 10
			  }
		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$('#modificarPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombrePatologiaUp:
			   {
			     	required: true,
			     	minlength: 5
			   },
			   descripcionPatologiaUp:
			   {
			        required: true
			  }
		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$("#tablePatologias").DataTable({
		"scrollY":        "350px",
        "scrollCollapse": false,
        "aoColumns":
        	[
        	 { "sWidth": "5%", "sClass": "center", "bSortable": false },
        	 { "sWidth": "10%" },
        	 { "sWidth": "15%" },
            ],
            language: {
                "sProcessing":     "Procesando...",
                "sLengthMenu":     "Mostrar _MENU_ registros",
                "sZeroRecords":    "No se encontraron resultados",
                "sEmptyTable":     "Ningún dato disponible en esta tabla",
                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                "sInfoPostFix":    "",
                "sSearch":         "Buscar:",
                "sUrl":            "",
                "sInfoThousands":  ",",
                "sLoadingRecords": "Cargando...",
                "oPaginate": {
                    "sFirst":    "Primero",
                    "sLast":     "Último",
                    "sNext":     "Siguiente",
                    "sPrevious": "Anterior"
                },
                "oAria": {
                    "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                    "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                }
              },
                "fnDrawCallback": function() {
                	$(".onUpdatePatologia").click(function(){
                		var id = $(this).data("id");

                		$.ajax
                		({
                			type: "GET",
                			url:"/sicmec/admin/patologias/getPatologia/"+id,
                			success:function(result)
                			{
                				$("#idPatologiaUp").val(result.idSicPatologia);
                				$("#nombrePatologiaUp").val(result.nombrePatologia);
                				$("#descripcionPatologiaUp").val(result.descripcionPatologia);
                				//$("#modalUpdatePatologia").modal("show");
                			},
                			error: function (xhr, ajaxOptions, thrownError)
                			{
                				alert("unable to find server..")
                		    }
                		});
                	});
                }
            });

/**
 * TODO LO CONCERNIENTE A ADMINISTARCION DE TIPOS DE PATOLOGIAS
 */
	$('#agregarTipoPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombreTipoPatologia:
			   {
			     	required: true,
			     	minlength: 5,
			     	remote:
					{
				        type: "POST",
				        url: "/sicmec/Utils/validarTipoPatologia",
			            data :
			                {
			            	nombreTipoPatologia: function()
			                  { return $("#nombreTipoPatologia").val(); }
			             }
				     }
			   },
			   descripcionTipoPatologia:
			   {
			        required: true,
			     	minlength: 10
			  },
			  patologia:
			   {
			        required: true
			  }

		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});
	$('#modificarTipoPatologiaForm').validate({
		errorElement: "span",
		rules: {
			 nombreTipoPatologiaUp:
			   {
			     	required: true,
			     	minlength: 5
			   },
			   descripcionTipoPatologiaUp:
			   {
			        required: true,
			     	minlength: 10
			  },
			  patologiaUp:
			   {
			        required: true
			  }

		   },
		highlight: function(element) {
			$(element).closest('.form-group')
			.removeClass('has-success').addClass('has-error');
		},
		success: function(element) {
			element.addClass('help-inline')
			.closest('.form-group')
			.removeClass('has-error').addClass('has-success');
		}

	});

	$("#tableTipoPatologias").DataTable({
		"scrollY":        "350px",
        "scrollCollapse": false,
        "aoColumns":
        	[
        	 { "sWidth": "5%", "sClass": "center", "bSortable": false },
        	 { "sWidth": "10%" },
        	 { "sWidth": "15%" },
        	 { "sWidth": "10%" },
            ],
            language: {
                "sProcessing":     "Procesando...",
                "sLengthMenu":     "Mostrar _MENU_ registros",
                "sZeroRecords":    "No se encontraron resultados",
                "sEmptyTable":     "Ningún dato disponible en esta tabla",
                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                "sInfoPostFix":    "",
                "sSearch":         "Buscar:",
                "sUrl":            "",
                "sInfoThousands":  ",",
                "sLoadingRecords": "Cargando...",
                "oPaginate": {
                    "sFirst":    "Primero",
                    "sLast":     "Último",
                    "sNext":     "Siguiente",
                    "sPrevious": "Anterior"
                },
                "oAria": {
                    "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                    "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                }
            },
                "fnDrawCallback": function() {
                	$(".onUpdateTipoPatologia").click(function(){
                		var id = $(this).data("id");

                		$.ajax
                		({
                			type: "GET",
                			url:"/sicmec/admin/patologias/getTipoPatologia/"+id,
                			success:function(result)
                			{
                				$("#idTipoPatologiaUp").val(result.idSicTipoPatologia);
                				$("#nombreTipoPatologiaUp").val(result.nombreTipoPatologia);
                				$("#descripcionTipoPatologiaUp").val(result.descripcionTipoPatologia);
                				$("#patologiaUp").val(result.fkSicPatologia.idSicPatologia);
                				//$("#modalUpdateTipoPatologia").modal("show");
                			},
                			error: function (xhr, ajaxOptions, thrownError)
                			{
                				alert("unable to find server..")
                		    }
                		});
                	});
                }
            });
});<|endoftext|>


<commit_before>
var test = require('tap').test;
var async = require('async');
var setup = require('../setup.js')();
var dailyProtocol = require('../../daily-protocol.js');

setup.open();

test('close on client', function (t) {
  setup.pair(function (err, server, client) {
    t.equal(err, null);
    server = dailyProtocol.Server(server);
    client = dailyProtocol.Client(client);

    async.parallel({
      clientEnd: client.once.bind(client, 'end'),
      clientClose: client.once.bind(client, 'close'),
      serverEnd: server.once.bind(server, 'end'),
      serverClose: server.once.bind(server, 'close')
    }, function (err) {
      t.equal(err, null);
      t.end();
    });

    client.read(0); // required in node <= 0.10
    server.read(0);
    client.end();
  });
});

test('close on server', function (t) {
  setup.pair(function (err, server, client) {
    t.equal(err, null);
    server = dailyProtocol.Server(server);
    client = dailyProtocol.Client(client);

    async.parallel({
      clientEnd: client.once.bind(client, 'end'),
      clientClose: client.once.bind(client, 'close'),
      serverEnd: server.once.bind(server, 'end'),
      serverClose: server.once.bind(server, 'close')
    }, function (err) {
      t.equal(err, null);
      t.end();
    });

    client.read(0); // required in node <= 0.10
    server.read(0);
    server.end();
  });
});

setup.close();
<commit_msg>[test] fix close test for node v0.11<commit_after>
var test = require('tap').test;
var async = require('async');
var setup = require('../setup.js')();
var dailyProtocol = require('../../daily-protocol.js');

setup.open();

test('close on client', function (t) {
  setup.pair(function (err, server, client) {
    t.equal(err, null);
    server = dailyProtocol.Server(server);
    client = dailyProtocol.Client(client);

    async.parallel({
      clientEnd: client.once.bind(client, 'end'),
      clientClose: client.once.bind(client, 'close'),
      serverEnd: server.once.bind(server, 'end'),
      serverClose: server.once.bind(server, 'close')
    }, function (err) {
      t.equal(err, null);
      t.end();
    });

    client.resume();
    server.resume();
    client.end();
  });
});

test('close on server', function (t) {
  setup.pair(function (err, server, client) {
    t.equal(err, null);
    server = dailyProtocol.Server(server);
    client = dailyProtocol.Client(client);

    async.parallel({
      clientEnd: client.once.bind(client, 'end'),
      clientClose: client.once.bind(client, 'close'),
      serverEnd: server.once.bind(server, 'end'),
      serverClose: server.once.bind(server, 'close')
    }, function (err) {
      t.equal(err, null);
      t.end();
    });

    client.resume();
    server.resume();
    server.end();
  });
});

setup.close();
<|endoftext|>