<commit_before>var async = require('async'),
    events = require('events'),
    log = function (text, debug) {
        if(debug) {
            console.log(new Date().toLocaleTimeString(), '|', text);
        }
    },
    generateAndApplyETags = function (newBuilds) {
        for (var i = 0; i < newBuilds.length; i++) {
            var build = newBuilds[i];

            build.etag = require('crypto')
                .createHash('md5')
                .update(JSON.stringify(build))
                .digest('hex');
        }
    },
    sortBuilds = function (newBuilds, sortOrder) {
        if(sortOrder == "project") {
            newBuilds.sort(function (a, b) {
                if(a.project > b.project) return 1;
                if(a.project < b.project) return -1;

                return 0;
            });
        }
        else {
            var takeDate = function (build) {
                return build.isRunning ? build.startedAt : build.finishedAt;
            };

            newBuilds.sort(function (a, b) {
                var dateA = takeDate(a);
                var dateB = takeDate(b);

                if(dateA < dateB) return 1;
                if(dateA > dateB) return -1;

                return 0;
            });
        }
    },
    distinctBuildsByETag = function (newBuilds) {
        var unique = {};

        for (var i = newBuilds.length - 1; i >= 0; i--) {
            var build = newBuilds[i];

            if (unique[build.etag]) {
                newBuilds.splice(i, 1);
            }

            unique[build.etag] = true;
        }
    },
    onlyTake = function (numberOfBuilds, newBuilds) {
        newBuilds.splice(numberOfBuilds);
    },
    changed = function (currentBuilds, newBuilds) {
        var newBuildsHash = newBuilds
            .map(function (value) {
                return value.etag;
            })
            .join('|');

        var currentBuildsHash = currentBuilds
            .map(function (value) {
                return value.etag;
            })
            .join('|');

        return newBuildsHash !== currentBuildsHash;
    },
    detectChanges = function (currentBuilds, newBuilds) {
        var changes = {
                added: [],
                removed: [],
                updated: []
            },
            getById = function (builds, id) {
                return builds.filter(function (build) {
                    return build.id === id;
                })[0];
            };

        var currentBuildIds = currentBuilds.map(function (build) { return build.id; });
        var newBuildIds = newBuilds.map(function (build) { return build.id; });

        newBuildIds.forEach(function (newBuildId) {
            if (currentBuildIds.indexOf(newBuildId) === -1) {
                changes.added.push(getById(newBuilds, newBuildId));
            }

            if (currentBuildIds.indexOf(newBuildId) >= 0) {
                var currentBuild = getById(currentBuilds, newBuildId);
                var newBuild = getById(newBuilds, newBuildId);

                if (currentBuild.etag !== newBuild.etag) {
                    changes.updated.push(getById(newBuilds, newBuildId));
                }
            }
        });

        currentBuildIds.forEach(function (currentBuildId) {
            if (newBuildIds.indexOf(currentBuildId) === -1) {
                changes.removed.push(getById(currentBuilds, currentBuildId));
            }
        });

        changes.order = newBuildIds;

        return changes;
    };

module.exports = function () {
    var self = this;

    self.configuration = {
        interval: 5000,
        numberOfBuilds: 12,
        debug: false
    };
    self.plugins = [];
    self.currentBuilds = [];

    self.configure = function (config) {
        self.configuration = config;
    };

    self.watchOn = function (plugin) {
        self.plugins.push(plugin);
    };

    self.run = function () {
        var allBuilds = [];

        async.each(self.plugins, function (plugin, callback) {
            log('Check for builds...', self.configuration.debug);

            plugin.check(function (error, pluginBuilds) {
                if (error) {
                  console.log('**********************************************************************');
                  console.log('An error occured when fetching builds for the following configuration:');
                  console.log('----------------------------------------------------------------------');
                  console.log(plugin.configuration);
                  console.log('----------------------------------------------------------------------');
                  console.log();
                  console.error(error);
                  console.log('**********************************************************************');
                  console.log();
                  console.log();
                  callback();
                  return;
                }
                if(pluginBuilds.length > 0) {
                    if(self.configuration.latestBuildOnly) {
                        Array.prototype.push.apply(allBuilds, [pluginBuilds.shift()]);
                    } else {
                        Array.prototype.push.apply(allBuilds, pluginBuilds);
                    }
                }
                callback();
            });
        },
        function (error) {
            log(allBuilds.length + ' builds found....', self.configuration.debug);

            generateAndApplyETags(allBuilds);
            distinctBuildsByETag(allBuilds);
            sortBuilds(allBuilds, self.configuration.sortOrder);

            if(!self.configuration.latestBuildOnly) {
              onlyTake(self.configuration.numberOfBuilds, allBuilds);
            }

            if(changed(self.currentBuilds, allBuilds)) {
                log('builds changed', self.configuration.debug);

                self.emit('buildsChanged', detectChanges(self.currentBuilds, allBuilds));

                self.currentBuilds = allBuilds;
            }

            setTimeout(self.run, self.configuration.interval);
        });
    };
};

module.exports.prototype = new events.EventEmitter();
<commit_msg>Fix : Now sorting builds by date before plucking the top one. Previously you couldn't ensure it was the "latest" build.<commit_after>var async = require('async'),
    events = require('events'),
    log = function (text, debug) {
        if(debug) {
            console.log(new Date().toLocaleTimeString(), '|', text);
        }
    },
    generateAndApplyETags = function (newBuilds) {
        for (var i = 0; i < newBuilds.length; i++) {
            var build = newBuilds[i];

            build.etag = require('crypto')
                .createHash('md5')
                .update(JSON.stringify(build))
                .digest('hex');
        }
    },
    sortBuilds = function (newBuilds, sortOrder) {
        if(sortOrder == "project") {
            newBuilds.sort(function (a, b) {
                if(a.project > b.project) return 1;
                if(a.project < b.project) return -1;

                return 0;
            });
        }
        else {
            sortBuildsByDate(newBuilds);
        }
    },
    sortBuildsByDate = function(newBuilds){
        var takeDate = function (build) {
                return build.isRunning ? build.startedAt : build.finishedAt;
            };

        newBuilds.sort(function (a, b) {
            var dateA = takeDate(a);
            var dateB = takeDate(b);

            if(dateA < dateB) return 1;
            if(dateA > dateB) return -1;

            return 0;
        });
    }
    distinctBuildsByETag = function (newBuilds) {
        var unique = {};

        for (var i = newBuilds.length - 1; i >= 0; i--) {
            var build = newBuilds[i];

            if (unique[build.etag]) {
                newBuilds.splice(i, 1);
            }

            unique[build.etag] = true;
        }
    },
    onlyTake = function (numberOfBuilds, newBuilds) {
        newBuilds.splice(numberOfBuilds);
    },
    changed = function (currentBuilds, newBuilds) {
        var newBuildsHash = newBuilds
            .map(function (value) {
                return value.etag;
            })
            .join('|');

        var currentBuildsHash = currentBuilds
            .map(function (value) {
                return value.etag;
            })
            .join('|');

        return newBuildsHash !== currentBuildsHash;
    },
    detectChanges = function (currentBuilds, newBuilds) {
        var changes = {
                added: [],
                removed: [],
                updated: []
            },
            getById = function (builds, id) {
                return builds.filter(function (build) {
                    return build.id === id;
                })[0];
            };

        var currentBuildIds = currentBuilds.map(function (build) { return build.id; });
        var newBuildIds = newBuilds.map(function (build) { return build.id; });

        newBuildIds.forEach(function (newBuildId) {
            if (currentBuildIds.indexOf(newBuildId) === -1) {
                changes.added.push(getById(newBuilds, newBuildId));
            }

            if (currentBuildIds.indexOf(newBuildId) >= 0) {
                var currentBuild = getById(currentBuilds, newBuildId);
                var newBuild = getById(newBuilds, newBuildId);

                if (currentBuild.etag !== newBuild.etag) {
                    changes.updated.push(getById(newBuilds, newBuildId));
                }
            }
        });

        currentBuildIds.forEach(function (currentBuildId) {
            if (newBuildIds.indexOf(currentBuildId) === -1) {
                changes.removed.push(getById(currentBuilds, currentBuildId));
            }
        });

        changes.order = newBuildIds;

        return changes;
    };

module.exports = function () {
    var self = this;

    self.configuration = {
        interval: 5000,
        numberOfBuilds: 12,
        debug: false
    };
    self.plugins = [];
    self.currentBuilds = [];

    self.configure = function (config) {
        self.configuration = config;
    };

    self.watchOn = function (plugin) {
        self.plugins.push(plugin);
    };

    self.run = function () {
        var allBuilds = [];

        async.each(self.plugins, function (plugin, callback) {
            log('Check for builds...', self.configuration.debug);

            plugin.check(function (error, pluginBuilds) {
                if (error) {
                  console.log('**********************************************************************');
                  console.log('An error occured when fetching builds for the following configuration:');
                  console.log('----------------------------------------------------------------------');
                  console.log(plugin.configuration);
                  console.log('----------------------------------------------------------------------');
                  console.log();
                  console.error(error);
                  console.log('**********************************************************************');
                  console.log();
                  console.log();
                  callback();
                  return;
                }
                if(pluginBuilds.length > 0) {
                    if(self.configuration.latestBuildOnly) {
                        sortBuildsByDate(pluginBuilds);
                        Array.prototype.push.apply(allBuilds, [pluginBuilds.shift()]);
                    } else {
                        Array.prototype.push.apply(allBuilds, pluginBuilds);
                    }
                }
                callback();
            });
        },
        function (error) {
            log(allBuilds.length + ' builds found....', self.configuration.debug);

            generateAndApplyETags(allBuilds);
            distinctBuildsByETag(allBuilds);
            sortBuilds(allBuilds, self.configuration.sortOrder);

            if(!self.configuration.latestBuildOnly) {
              onlyTake(self.configuration.numberOfBuilds, allBuilds);
            }

            if(changed(self.currentBuilds, allBuilds)) {
                log('builds changed', self.configuration.debug);

                self.emit('buildsChanged', detectChanges(self.currentBuilds, allBuilds));

                self.currentBuilds = allBuilds;
            }

            setTimeout(self.run, self.configuration.interval);
        });
    };
};

module.exports.prototype = new events.EventEmitter();
<|endoftext|>


<commit_before>/*
   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This file is licensed under the Apache License, Version 2.0 (the "License").
   You may not use this file except in compliance with the License. A copy of
   the License is located at

    http://aws.amazon.com/apache2.0/

   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied. See the License for the
   specific language governing permissions and limitations under the License.

   ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
   https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html
*/

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create the promise and SES service object
var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).createReceiptRuleSet({RuleSetName: "NAME"}).promise();

// Handle promise's fulfilled/rejected states
newRulePromise.then(
  function(data) {
    console.log(data);
  }).catch
    function(err) {
    console.error(err, err.stack);
  });
<commit_msg>Update ses_createreceiptruleset.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create the promise and SES service object
var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).createReceiptRuleSet({RuleSetName: "NAME"}).promise();

// Handle promise's fulfilled/rejected states
newRulePromise.then(
  function(data) {
    console.log(data);
  }).catch
    function(err) {
    console.error(err, err.stack);
  });
<|endoftext|>


<commit_before>goog.provide('ol.test.events');

goog.require('ol.events');
goog.require('ol.events.EventTarget');
goog.require('ol');

describe('ol.events', function() {
  var add, remove, target;

  beforeEach(function() {
    add = sinon.spy();
    remove = sinon.spy();
    target = {
      addEventListener: add,
      removeEventListener: remove
    };
  });

  describe('bindListener_()', function() {
    it('binds a listener and returns a bound listener function', function() {
      var listenerObj = {
        listener: sinon.spy(),
        bindTo: {id: 1}
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.bindTo);
    });
    it('binds to the target when bindTo is not provided', function() {
      var listenerObj = {
        listener: sinon.spy(),
        target: {id: 1}
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.target);
    });
    it('binds a self-unregistering listener when callOnce is true', function() {
      var bindTo = {id: 1};
      var listenerObj = {
        type: 'foo',
        target: target,
        bindTo: bindTo,
        callOnce: true
      };
      var unlistenSpy = sinon.spy(ol.events, 'unlistenByKey');
      listenerObj.listener = function() {
        expect(this).to.equal(bindTo);
        expect(unlistenSpy.firstCall.args[0]).to.eql(listenerObj);
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      unlistenSpy.restore();
    });
  });

  describe('findListener_()', function() {
    var listener, listenerObj, listeners;

    beforeEach(function() {
      listener = function() {};
      listenerObj = {
        type: 'foo',
        target: target,
        listener: listener
      };
      listeners = [listenerObj];
    });

    it('searches a listener array for a specific listener', function() {
      var bindTo = {id: 1};
      var result = ol.events.findListener_(listeners, listener);
      expect(result).to.be(listenerObj);
      result = ol.events.findListener_(listeners, listener, bindTo);
      expect(result).to.be(undefined);
      listenerObj.bindTo = bindTo;
      result = ol.events.findListener_(listeners, listener);
      expect(result).to.be(undefined);
      result = ol.events.findListener_(listeners, listener, bindTo);
      expect(result).to.be(listenerObj);
    });
    it('marks the delete index on a listener object', function() {
      var result = ol.events.findListener_(listeners, listener, undefined, true);
      expect(result).to.be(listenerObj);
      expect(listenerObj.deleteIndex).to.be(0);
    });
  });

  describe('getListeners()', function() {
    it('returns listeners for a target and type', function() {
      var foo = ol.events.listen(target, 'foo', function() {});
      var bar = ol.events.listen(target, 'bar', function() {});
      expect (ol.events.getListeners(target, 'foo')).to.eql([foo]);
      expect (ol.events.getListeners(target, 'bar')).to.eql([bar]);
    });
    it('returns undefined when no listeners are registered', function() {
      expect (ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
  });

  describe('listen()', function() {
    it('calls addEventListener on the target', function() {
      ol.events.listen(target, 'foo', function() {});
      expect(add.callCount).to.be(1);
    });
    it('returns a key', function() {
      var key = ol.events.listen(target, 'foo', function() {});
      expect(key).to.be.a(Object);
    });
    it('does not add the same listener twice', function() {
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener);
      var key2 = ol.events.listen(target, 'foo', listener);
      expect(key1).to.equal(key2);
      expect(add.callCount).to.be(1);
    });
    it('only treats listeners as same when all args are equal', function() {
      var listener = function() {};
      ol.events.listen(target, 'foo', listener, {});
      ol.events.listen(target, 'foo', listener, {});
      ol.events.listen(target, 'foo', listener, undefined);
      expect(add.callCount).to.be(3);
    });
  });

  describe('listenOnce()', function() {
    it('creates a one-off listener', function() {
      var listener = sinon.spy();
      var key = ol.events.listenOnce(target, 'foo', listener);
      expect(add.callCount).to.be(1);
      expect(key.callOnce).to.be(true);
      key.boundListener();
      expect(listener.callCount).to.be(1);
      expect(remove.callCount).to.be(1);
    });
    it('does not add the same listener twice', function() {
      var listener = function() {};
      var key1 = ol.events.listenOnce(target, 'foo', listener);
      var key2 = ol.events.listenOnce(target, 'foo', listener);
      expect(key1).to.equal(key2);
      expect(add.callCount).to.be(1);
      expect(key1.callOnce).to.be(true);
    });
    it('listen() can turn a one-off listener into a permanent one', function() {
      var listener = sinon.spy();
      var key = ol.events.listenOnce(target, 'foo', listener);
      expect(key.callOnce).to.be(true);
      key = ol.events.listen(target, 'foo', listener);
      expect(add.callCount).to.be(1);
      expect(key.callOnce).to.be(false);
      key.boundListener();
      expect(remove.callCount).to.be(0);
    });
  });

  describe('unlisten()', function() {
    it('unregisters previously registered listeners', function() {
      var listener = function() {};
      ol.events.listen(target, 'foo', listener);
      ol.events.unlisten(target, 'foo', listener);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
    it('works with multiple types', function() {
      var listener = function() {};
      ol.events.listen(target, ['foo', 'bar'], listener);
      ol.events.unlisten(target, ['bar', 'foo'], listener);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
    });
  });

  describe('unlistenByKey()', function() {
    it('unregisters previously registered listeners', function() {
      var key = ol.events.listen(target, 'foo', function() {});
      ol.events.unlistenByKey(key);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
    it('works with multiple types', function() {
      var key = ol.events.listen(target, ['foo', 'bar'], function() {});
      ol.events.unlistenByKey(key);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
    });
  });

  describe('unlistenAll()', function() {
    it('unregisters all listeners registered for a target', function() {
      var keys = [
        ol.events.listen(target, 'foo', function() {}),
        ol.events.listen(target, 'bar', function() {})
      ];
      ol.events.unlistenAll(target);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
      expect('ol_lm' in target).to.be(false);
      expect(keys).to.eql([{}, {}]);
    });
  });

  describe('Compatibility with ol.events.EventTarget', function() {
    it('does not register duplicated listeners', function() {
      var target = new ol.events.EventTarget();
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener);
      expect(target.getListeners('foo')).to.eql([key1.boundListener]);
      var key2 = ol.events.listen(target, 'foo', listener);
      expect(key2.boundListener).to.equal(key1.boundListener);
      expect(target.getListeners('foo')).to.eql([key1.boundListener]);
    });
    it('registers multiple listeners if this object is different', function() {
      var target = new ol.events.EventTarget();
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener, {});
      var key2 = ol.events.listen(target, 'foo', listener, {});
      expect(key1.boundListener).to.not.equal(key2.boundListener);
      expect(target.getListeners('foo')).to.eql(
          [key1.boundListener, key2.boundListener]);
    });
  });

});
<commit_msg>Remove unnecessary import in events.test.js<commit_after>goog.provide('ol.test.events');

goog.require('ol.events');
goog.require('ol.events.EventTarget');

describe('ol.events', function() {
  var add, remove, target;

  beforeEach(function() {
    add = sinon.spy();
    remove = sinon.spy();
    target = {
      addEventListener: add,
      removeEventListener: remove
    };
  });

  describe('bindListener_()', function() {
    it('binds a listener and returns a bound listener function', function() {
      var listenerObj = {
        listener: sinon.spy(),
        bindTo: {id: 1}
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.bindTo);
    });
    it('binds to the target when bindTo is not provided', function() {
      var listenerObj = {
        listener: sinon.spy(),
        target: {id: 1}
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.target);
    });
    it('binds a self-unregistering listener when callOnce is true', function() {
      var bindTo = {id: 1};
      var listenerObj = {
        type: 'foo',
        target: target,
        bindTo: bindTo,
        callOnce: true
      };
      var unlistenSpy = sinon.spy(ol.events, 'unlistenByKey'); // eslint-disable-line openlayers-internal/no-missing-requires
      listenerObj.listener = function() {
        expect(this).to.equal(bindTo);
        expect(unlistenSpy.firstCall.args[0]).to.eql(listenerObj);
      };
      var boundListener = ol.events.bindListener_(listenerObj);
      expect(listenerObj.boundListener).to.equal(boundListener);
      boundListener();
      unlistenSpy.restore();
    });
  });

  describe('findListener_()', function() {
    var listener, listenerObj, listeners;

    beforeEach(function() {
      listener = function() {};
      listenerObj = {
        type: 'foo',
        target: target,
        listener: listener
      };
      listeners = [listenerObj];
    });

    it('searches a listener array for a specific listener', function() {
      var bindTo = {id: 1};
      var result = ol.events.findListener_(listeners, listener);
      expect(result).to.be(listenerObj);
      result = ol.events.findListener_(listeners, listener, bindTo);
      expect(result).to.be(undefined);
      listenerObj.bindTo = bindTo;
      result = ol.events.findListener_(listeners, listener);
      expect(result).to.be(undefined);
      result = ol.events.findListener_(listeners, listener, bindTo);
      expect(result).to.be(listenerObj);
    });
    it('marks the delete index on a listener object', function() {
      var result = ol.events.findListener_(listeners, listener, undefined, true);
      expect(result).to.be(listenerObj);
      expect(listenerObj.deleteIndex).to.be(0);
    });
  });

  describe('getListeners()', function() {
    it('returns listeners for a target and type', function() {
      var foo = ol.events.listen(target, 'foo', function() {});
      var bar = ol.events.listen(target, 'bar', function() {});
      expect (ol.events.getListeners(target, 'foo')).to.eql([foo]);
      expect (ol.events.getListeners(target, 'bar')).to.eql([bar]);
    });
    it('returns undefined when no listeners are registered', function() {
      expect (ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
  });

  describe('listen()', function() {
    it('calls addEventListener on the target', function() {
      ol.events.listen(target, 'foo', function() {});
      expect(add.callCount).to.be(1);
    });
    it('returns a key', function() {
      var key = ol.events.listen(target, 'foo', function() {});
      expect(key).to.be.a(Object);
    });
    it('does not add the same listener twice', function() {
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener);
      var key2 = ol.events.listen(target, 'foo', listener);
      expect(key1).to.equal(key2);
      expect(add.callCount).to.be(1);
    });
    it('only treats listeners as same when all args are equal', function() {
      var listener = function() {};
      ol.events.listen(target, 'foo', listener, {});
      ol.events.listen(target, 'foo', listener, {});
      ol.events.listen(target, 'foo', listener, undefined);
      expect(add.callCount).to.be(3);
    });
  });

  describe('listenOnce()', function() {
    it('creates a one-off listener', function() {
      var listener = sinon.spy();
      var key = ol.events.listenOnce(target, 'foo', listener);
      expect(add.callCount).to.be(1);
      expect(key.callOnce).to.be(true);
      key.boundListener();
      expect(listener.callCount).to.be(1);
      expect(remove.callCount).to.be(1);
    });
    it('does not add the same listener twice', function() {
      var listener = function() {};
      var key1 = ol.events.listenOnce(target, 'foo', listener);
      var key2 = ol.events.listenOnce(target, 'foo', listener);
      expect(key1).to.equal(key2);
      expect(add.callCount).to.be(1);
      expect(key1.callOnce).to.be(true);
    });
    it('listen() can turn a one-off listener into a permanent one', function() {
      var listener = sinon.spy();
      var key = ol.events.listenOnce(target, 'foo', listener);
      expect(key.callOnce).to.be(true);
      key = ol.events.listen(target, 'foo', listener);
      expect(add.callCount).to.be(1);
      expect(key.callOnce).to.be(false);
      key.boundListener();
      expect(remove.callCount).to.be(0);
    });
  });

  describe('unlisten()', function() {
    it('unregisters previously registered listeners', function() {
      var listener = function() {};
      ol.events.listen(target, 'foo', listener);
      ol.events.unlisten(target, 'foo', listener);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
    it('works with multiple types', function() {
      var listener = function() {};
      ol.events.listen(target, ['foo', 'bar'], listener);
      ol.events.unlisten(target, ['bar', 'foo'], listener);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
    });
  });

  describe('unlistenByKey()', function() {
    it('unregisters previously registered listeners', function() {
      var key = ol.events.listen(target, 'foo', function() {});
      ol.events.unlistenByKey(key);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
    });
    it('works with multiple types', function() {
      var key = ol.events.listen(target, ['foo', 'bar'], function() {});
      ol.events.unlistenByKey(key);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
    });
  });

  describe('unlistenAll()', function() {
    it('unregisters all listeners registered for a target', function() {
      var keys = [
        ol.events.listen(target, 'foo', function() {}),
        ol.events.listen(target, 'bar', function() {})
      ];
      ol.events.unlistenAll(target);
      expect(ol.events.getListeners(target, 'foo')).to.be(undefined);
      expect(ol.events.getListeners(target, 'bar')).to.be(undefined);
      expect('ol_lm' in target).to.be(false);
      expect(keys).to.eql([{}, {}]);
    });
  });

  describe('Compatibility with ol.events.EventTarget', function() {
    it('does not register duplicated listeners', function() {
      var target = new ol.events.EventTarget();
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener);
      expect(target.getListeners('foo')).to.eql([key1.boundListener]);
      var key2 = ol.events.listen(target, 'foo', listener);
      expect(key2.boundListener).to.equal(key1.boundListener);
      expect(target.getListeners('foo')).to.eql([key1.boundListener]);
    });
    it('registers multiple listeners if this object is different', function() {
      var target = new ol.events.EventTarget();
      var listener = function() {};
      var key1 = ol.events.listen(target, 'foo', listener, {});
      var key2 = ol.events.listen(target, 'foo', listener, {});
      expect(key1.boundListener).to.not.equal(key2.boundListener);
      expect(target.getListeners('foo')).to.eql(
          [key1.boundListener, key2.boundListener]);
    });
  });

});
<|endoftext|>


<commit_before>const zlib = require('zlib');
const PSQL = require('cartodb-psql');
const copyTo = require('pg-copy-streams').to;
const copyFrom = require('pg-copy-streams').from;
const StreamCopyMetrics = require('./stream_copy_metrics');

module.exports = {
    to (res, sql, userDbParams, logger, cb) {
        let metrics = new StreamCopyMetrics(logger, 'copyto', sql);

        const pg = new PSQL(userDbParams);
        pg.connect(function (err, client) {
            if (err) {
                return cb(err);
            }

            const copyToStream = copyTo(sql);
            const pgstream = client.query(copyToStream);
            pgstream
                .on('error', err => {
                    pgstream.unpipe(res);
                    return cb(err);
                })
                .on('data', data => metrics.addSize(data.length))
                .on('end', () => {
                    metrics.end(copyToStream.rowCount);
                    return cb(null, metrics);
                })
                .pipe(res);
        });
    },

    from (req, sql, userDbParams, gzip, logger, cb) {
        let metrics = new StreamCopyMetrics(logger, 'copyfrom', sql, gzip);

        const pg = new PSQL(userDbParams);
        pg.connect(function (err, client) {
            if (err) {
                return cb(err);
            }

            let copyFromStream = copyFrom(sql);
            const pgstream = client.query(copyFromStream);
            pgstream
                .on('error', err => {
                    req.unpipe(pgstream);
                    return cb(err);
                })
                .on('end', function () {
                    metrics.end(copyFromStream.rowCount);
                    return cb(null, metrics);
                });

            let requestEnded = false;

            req
                .on('error', err => {
                    req.unpipe(pgstream);
                    pgstream.end();
                    return cb(err);
                })
                .on('close', () => {
                    if (!requestEnded) {
                        req.unpipe(pgstream);
                        pgstream.end();
                        return cb(new Error('Connection closed by client'));
                    }
                })
                .on('data', data => metrics.size += data.length)
                .on('end', () => requestEnded = true);

            if (gzip) {
                req.pipe(zlib.createGunzip()).pipe(pgstream);
            } else {
                req.pipe(pgstream);
            }
        });
    }
};
<commit_msg>send CopyFail when user close connection<commit_after>const zlib = require('zlib');
const PSQL = require('cartodb-psql');
const copyTo = require('pg-copy-streams').to;
const copyFrom = require('pg-copy-streams').from;
const StreamCopyMetrics = require('./stream_copy_metrics');

module.exports = {
    to (res, sql, userDbParams, logger, cb) {
        let metrics = new StreamCopyMetrics(logger, 'copyto', sql);

        const pg = new PSQL(userDbParams);
        pg.connect(function (err, client) {
            if (err) {
                return cb(err);
            }

            const copyToStream = copyTo(sql);
            const pgstream = client.query(copyToStream);
            pgstream
                .on('error', err => {
                    pgstream.unpipe(res);
                    return cb(err);
                })
                .on('data', data => metrics.addSize(data.length))
                .on('end', () => {
                    metrics.end(copyToStream.rowCount);
                    return cb(null, metrics);
                })
                .pipe(res);
        });
    },

    from (req, sql, userDbParams, gzip, logger, cb) {
        let metrics = new StreamCopyMetrics(logger, 'copyfrom', sql, gzip);

        const pg = new PSQL(userDbParams);
        pg.connect(function (err, client) {
            if (err) {
                return cb(err);
            }

            let copyFromStream = copyFrom(sql);
            const pgstream = client.query(copyFromStream);
            pgstream
                .on('error', err => {
                    req.unpipe(pgstream);
                    return cb(err);
                })
                .on('end', function () {
                    metrics.end(copyFromStream.rowCount);
                    return cb(null, metrics);
                });

            let requestEnded = false;

            req
                .on('error', err => {
                    req.unpipe(pgstream);
                    pgstream.end();
                    return cb(err);
                })
                .on('close', () => {
                    if (!requestEnded) {
                        const connection = client.connection;
                        connection.sendCopyFail();
                        req.unpipe(pgstream);
                        return cb(new Error('Connection closed by client'));
                    }
                })
                .on('data', data => metrics.size += data.length)
                .on('end', () => requestEnded = true);

            if (gzip) {
                req.pipe(zlib.createGunzip()).pipe(pgstream);
            } else {
                req.pipe(pgstream);
            }
        });
    }
};
<|endoftext|>


<commit_before>Ext.namespace('Ext.ux');

Ext.define('Ext.ux.Keypad', {
    extend: 'Ext.Panel',
    requires: [
        'Ext.Panel',
        'Ext.MessageBox',
        'Ext.field.Text',
        'Ext.Ajax',
        'Ext.util.JSON'
    ],
    alias: 'widget.keypad',

    config: {
        draggable: false,
        scroll: false,
        ui: 'normal',
        centered: false,
        clearText: 'Clear',
        submitText: 'Submit',
        submitUrl: '',
        submitParamName: 'value',
        submitHandler: null
    },

    constructor: function(config) {
        config = config || {};

        if (config.centered){
            config.layout = {type:'hbox', pack:'center'};
        }
        this.callParent([config]);

        var width = 500;
        var height = 650;
        var button_ui = 'action';
        var key_style = 'font-size:27pt;margin:5px;';
        if (this.getUi() == 'small'){
            width = 300;
            height = 350;
            button_ui = 'confirm-small';
            key_style = 'font-size:20pt;margin:5px;';
        }

        this.keypadDisplay = Ext.create('Ext.field.Text', {
            disabled: true,
            value: ''
        });

        this.clearButton = Ext.create('Ext.Button', {
            ui: button_ui,
            text: this.getClearText(),
            handler: function(){
                this.clear()
            },
            scope: this
        });

        this.submitButton = Ext.create('Ext.Button', {
            text: this.getSubmitText(),
            ui: button_ui,
            handler: function(b, e) {
                if (this.getSubmitUrl()) {
                    var params = {};
                    params[this.getSubmitParamName()] = this.getValue();

                    Ext.Ajax.request({
                        url: this.getSubmitUrl(),
                        params: params,
                        success: function(response, opts){
                            var data = Ext.util.JSON.decode(response.responseText);
                            if (data.success && data.redirect_url) {
                                window.location.href = data.redirect_url;
                            } else {
                                var message = data.msg || 'There was an error submitting the input.';

                                //Ext.Msg.alert('Error', message);
                                alert(message);
                            }
                        },
                        failure: function(response, opts){
                            var data = Ext.util.JSON.decode(response.responseText);
                            var message = data.msg || 'There was an error submitting the input.';

                            //Ext.Msg.alert('Error', message);
                            alert(message);
                        },
                        scope: this
                    });
                } else if (this.getSubmitHandler()) {
                    this.getSubmitHandler()(this.getValue(), this, b, e);
                } else {
                    //Ext.Msg.alert('No submission action specified', 'Value: ' + this.getValue());
                    alert('Value: ' + this.getValue());
                }
            },
            scope: this
        });

        this.createDigitKey = function(digit) {
            return {
                xtype: 'button',
                text: digit,
                handler: function(){
                    this.addDigit(digit);
                }, scope: this
            }
        };

        this.keypadPanel = Ext.create('Ext.Panel', {
            width: width,
            height: height,
            layout: {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
            },
            defaults: {
                layout: 'hbox',
                align: 'stretch',
                flex: 1,
                defaults: {
                    style: key_style,
                    flex: 1
                }
            },
            items: [{
                items: [this.keypadDisplay]
            },{
                items: [this.createDigitKey('1'), this.createDigitKey('2'), this.createDigitKey('3')]
            }, {
                items: [this.createDigitKey('4'), this.createDigitKey('5'), this.createDigitKey('6')]
            }, {
                items: [this.createDigitKey('7'), this.createDigitKey('8'), this.createDigitKey('9')]
            }, {
                items: [{},this.createDigitKey('0'),{}]
            }, {
                items: [
                    this.clearButton,
                    this.submitButton
                ]
            }]
        });

        this.add(this.keypadPanel);
    },

	addDigit: function(digit) {
		this.setValue(this.getValue() + digit);
	},

	clear: function() {
		this.keypadDisplay.setValue('');
	},

	setValue: function(value) {
		this.keypadDisplay.setValue(value);
	},

	getValue: function() {
		return this.keypadDisplay.getValue();
	}
});
<commit_msg>Fixed the width of the '0' key.<commit_after>Ext.namespace('Ext.ux');

Ext.define('Ext.ux.Keypad', {
    extend: 'Ext.Panel',
    requires: [
        'Ext.Panel',
        'Ext.MessageBox',
        'Ext.field.Text',
        'Ext.Ajax',
        'Ext.util.JSON'
    ],
    alias: 'widget.keypad',

    config: {
        draggable: false,
        scroll: false,
        ui: 'normal',
        centered: false,
        clearText: 'Clear',
        submitText: 'Submit',
        submitUrl: '',
        submitParamName: 'value',
        submitHandler: null
    },

    constructor: function(config) {
        config = config || {};

        if (config.centered){
            config.layout = {type:'hbox', pack:'center'};
        }
        this.callParent([config]);

        var width = 500;
        var height = 650;
        var button_ui = 'action';
        var key_style = 'font-size:27pt;margin:5px;';
        if (this.getUi() == 'small'){
            width = 300;
            height = 350;
            button_ui = 'confirm-small';
            key_style = 'font-size:20pt;margin:5px;';
        }

        this.keypadDisplay = Ext.create('Ext.field.Text', {
            disabled: true,
            value: ''
        });

        this.clearButton = Ext.create('Ext.Button', {
            ui: button_ui,
            text: this.getClearText(),
            handler: function(){
                this.clear()
            },
            scope: this
        });

        this.submitButton = Ext.create('Ext.Button', {
            text: this.getSubmitText(),
            ui: button_ui,
            handler: function(b, e) {
                if (this.getSubmitUrl()) {
                    var params = {};
                    params[this.getSubmitParamName()] = this.getValue();

                    Ext.Ajax.request({
                        url: this.getSubmitUrl(),
                        params: params,
                        success: function(response, opts){
                            var data = Ext.util.JSON.decode(response.responseText);
                            if (data.success && data.redirect_url) {
                                window.location.href = data.redirect_url;
                            } else {
                                var message = data.msg || 'There was an error submitting the input.';

                                //Ext.Msg.alert('Error', message);
                                alert(message);
                            }
                        },
                        failure: function(response, opts){
                            var data = Ext.util.JSON.decode(response.responseText);
                            var message = data.msg || 'There was an error submitting the input.';

                            //Ext.Msg.alert('Error', message);
                            alert(message);
                        },
                        scope: this
                    });
                } else if (this.getSubmitHandler()) {
                    this.getSubmitHandler()(this.getValue(), this, b, e);
                } else {
                    //Ext.Msg.alert('No submission action specified', 'Value: ' + this.getValue());
                    alert('Value: ' + this.getValue());
                }
            },
            scope: this
        });

        this.createDigitKey = function(digit, hidden) {
            var style = key_style;
            if (hidden) {
            	style = key_style + 'visibility:hidden;';
            }

            return {
                xtype: 'button',
                text: digit,
                style: style,
                handler: function(){
                    this.addDigit(digit);
                }, scope: this
            }
        };

        this.keypadPanel = Ext.create('Ext.Panel', {
            width: width,
            height: height,
            layout: {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
            },
            defaults: {
                layout: 'hbox',
                align: 'stretch',
                flex: 1,
                defaults: {
                    style: key_style,
                    flex: 1
                }
            },
            items: [{
                items: [this.keypadDisplay]
            },{
                items: [this.createDigitKey('1'), this.createDigitKey('2'), this.createDigitKey('3')]
            }, {
                items: [this.createDigitKey('4'), this.createDigitKey('5'), this.createDigitKey('6')]
            }, {
                items: [this.createDigitKey('7'), this.createDigitKey('8'), this.createDigitKey('9')]
            }, {
                items: [this.createDigitKey('0', true),this.createDigitKey('0'), this.createDigitKey('0', true)]
            }, {
                items: [
                    this.clearButton,
                    this.submitButton
                ]
            }]
        });

        this.add(this.keypadPanel);
    },

	addDigit: function(digit) {
		this.setValue(this.getValue() + digit);
	},

	clear: function() {
		this.keypadDisplay.setValue('');
	},

	setValue: function(value) {
		this.keypadDisplay.setValue(value);
	},

	getValue: function() {
		return this.keypadDisplay.getValue();
	}
});
<|endoftext|>


<commit_before>(function() {
/* Start angularLocalStorage */
'use strict';
var angularLocalStorage = angular.module('LocalStorageModule', []);

angularLocalStorage.provider('localStorageService', function(){
  // You should set a prefix to avoid overwriting any local storage variables from the rest of your app
  // e.g. angularLocalStorage.constant('prefix', 'youAppName');
  this.prefix = 'ls';
  // Cookie options (usually in case of fallback)
  // expiry = Number of days before cookies expire // 0 = Does not expire
  // path = The web path the cookie represents
  this.cookie = {
    expiry: 30,
    path: '/'
  };
  this.notify = {
    setItem: true,
    removeItem: false
  };
  this.setPrefix = function(prefix){
    this.prefix = prefix;
  };
  this.setStorageCookie = function(exp, path){
    this.cookie = {
      expiry: exp,
      path: path
    };
  };
  this.setNotify = function(itemSet, itemRemove){
    this.notify = {
      setItem: itemSet,
      removeItem: itemRemove
    };
  };

  this.$get = ['$rootScope', function($rootScope){

    var prefix = this.prefix;
    // If there is a prefix set in the config lets use that with an appended period for readability
    if (prefix.substr(-1) !== '.') {
      prefix = !!prefix ? prefix + '.' : '';
    }

    // Checks the browser to see if local storage is supported
    var browserSupportsLocalStorage = function () {
      try {
        var supported = ('localStorage' in window && window['localStorage'] !== null);

        // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
        // is available, but trying to call .setItem throws an exception.
        //
        // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
        // that exceeded the quota."
        var key = prefix + '__' + Math.round(Math.random() * 1e7);
        if (supported) {
          localStorage.setItem(key, '');
          localStorage.removeItem(key);
        }

        return true;
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return false;
      }
    };

    // Directly adds a value to local storage
    // If local storage is not available in the browser use cookies
    // Example use: localStorageService.add('library','angular');
    var addToLocalStorage = function (key, value) {

      // If this browser does not support local storage use cookies
      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
        }
        return addToCookies(key, value);
      }

      // Let's convert undefined values to null to get the value consistent
      if (typeof value === "undefined") {
        value = null;
      }

      try {
        if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
        }
        localStorage.setItem(prefix + key, value);
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return addToCookies(key, value);
      }
      return true;
    };

    // Directly get a value from local storage
    // Example use: localStorageService.get('library'); // returns 'angular'
    var getFromLocalStorage = function (key) {

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
        return getFromCookies(key);
      }

      var item = localStorage.getItem(prefix + key);
      // angular.toJson will convert null to 'null', so a proper conversion is needed
      // FIXME not a perfect solution, since a valid 'null' string can't be stored
      if (!item || item === 'null') {
        return null;
      }

      if (item.charAt(0) === "{" || item.charAt(0) === "[") {
        return angular.fromJson(item);
      }

      return item;
    };

    // Remove an item from local storage
    // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
    var removeFromLocalStorage = function (key) {
      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
        }
        return removeFromCookies(key);
      }

      try {
        localStorage.removeItem(prefix+key);
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return removeFromCookies(key);
      }
      return true;
    };

    // Return array of keys for local storage
    // Example use: var keys = localStorageService.keys()
    var getKeysForLocalStorage = function () {

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return false;
      }

      var prefixLength = prefix.length;
      var keys = [];
      for (var key in localStorage) {
        // Only return keys that are for this app
        if (key.substr(0,prefixLength) === prefix) {
          try {
            keys.push(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
            return [];
          }
        }
      }
      return keys;
    };

    // Remove all data for this app from local storage
    // Also optionally takes a regular expression string and removes the matching key-value pairs
    // Example use: localStorageService.clearAll();
    // Should be used mostly for development purposes
    var clearAllFromLocalStorage = function (regularExpression) {

      var regularExpression = regularExpression || "";
      //accounting for the '.' in the prefix when creating a regex
      var tempPrefix = prefix.slice(0, -1) + "\.";
      var testRegex = RegExp(tempPrefix + regularExpression);

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return clearAllFromCookies();
      }

      var prefixLength = prefix.length;

      for (var key in localStorage) {
        // Only remove items that are for this app and match the regular expression
        if (testRegex.test(key)) {
          try {
            removeFromLocalStorage(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
            return clearAllFromCookies();
          }
        }
      }
      return true;
    };

    // Checks the browser to see if cookies are supported
    var browserSupportsCookies = function() {
      try {
        return navigator.cookieEnabled ||
          ("cookie" in document && (document.cookie.length > 0 ||
          (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
      } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
          return false;
      }
    };

    // Directly adds a value to cookies
    // Typically used as a fallback is local storage is not available in the browser
    // Example use: localStorageService.cookie.add('library','angular');
    var addToCookies = function (key, value) {

      if (typeof value === "undefined") {
        return false;
      }

      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      try {
        var expiry = '',
            expiryDate = new Date();

        if (value === null) {
          // Mark that the cookie has expired one day ago
          expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
          value = '';
        } else if (cookie.expiry !== 0) {
          expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
        }
        if (!!key) {
          document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path;
          }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
        return false;
      }
      return true;
    };

    // Directly get a value from a cookie
    // Example use: localStorageService.cookie.get('library'); // returns 'angular'
    var getFromCookies = function (key) {
      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      var cookies = document.cookie.split(';');
      for(var i=0;i < cookies.length;i++) {
        var thisCookie = cookies[i];
        while (thisCookie.charAt(0)===' ') {
          thisCookie = thisCookie.substring(1,thisCookie.length);
        }
        if (thisCookie.indexOf(prefix + key + '=') === 0) {
          return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
        }
      }
      return null;
    };

    var removeFromCookies = function (key) {
      addToCookies(key,null);
    };

    var clearAllFromCookies = function () {
      var thisCookie = null, thisKey = null;
      var prefixLength = prefix.length;
      var cookies = document.cookie.split(';');
      for(var i = 0; i < cookies.length; i++) {
        thisCookie = cookies[i];

        while (thisCookie.charAt(0) === ' ') {
          thisCookie = thisCookie.substring(1, thisCookie.length);
        }

        key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
        removeFromCookies(key);
      }
    };

    return {
      isSupported: browserSupportsLocalStorage,
      set: addToLocalStorage,
      add: addToLocalStorage, //DEPRECATED
      get: getFromLocalStorage,
      keys: getKeysForLocalStorage,
      remove: removeFromLocalStorage,
      clearAll: clearAllFromLocalStorage,
      cookie: {
        set: addToCookies,
        add: addToCookies, //DEPRECATED
        get: getFromCookies,
        remove: removeFromCookies,
        clearAll: clearAllFromCookies
      }
    };
  }]
});
}).call(this);
<commit_msg>cookie and notify are not defined<commit_after>(function() {
/* Start angularLocalStorage */
'use strict';
var angularLocalStorage = angular.module('LocalStorageModule', []);

angularLocalStorage.provider('localStorageService', function(){
  // You should set a prefix to avoid overwriting any local storage variables from the rest of your app
  // e.g. angularLocalStorage.constant('prefix', 'youAppName');
  this.prefix = 'ls';
  // Cookie options (usually in case of fallback)
  // expiry = Number of days before cookies expire // 0 = Does not expire
  // path = The web path the cookie represents
  this.cookie = {
    expiry: 30,
    path: '/'
  };
  this.notify = {
    setItem: true,
    removeItem: false
  };
  this.setPrefix = function(prefix){
    this.prefix = prefix;
  };
  this.setStorageCookie = function(exp, path){
    this.cookie = {
      expiry: exp,
      path: path
    };
  };
  this.setNotify = function(itemSet, itemRemove){
    this.notify = {
      setItem: itemSet,
      removeItem: itemRemove
    };
  };

  this.$get = ['$rootScope', function($rootScope){

    var prefix = this.prefix;
    var cookie = this.cookie;
    var notify = this.notify;

    // If there is a prefix set in the config lets use that with an appended period for readability
    if (prefix.substr(-1) !== '.') {
      prefix = !!prefix ? prefix + '.' : '';
    }

    // Checks the browser to see if local storage is supported
    var browserSupportsLocalStorage = function () {
      try {
        var supported = ('localStorage' in window && window['localStorage'] !== null);

        // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
        // is available, but trying to call .setItem throws an exception.
        //
        // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
        // that exceeded the quota."
        var key = prefix + '__' + Math.round(Math.random() * 1e7);
        if (supported) {
          localStorage.setItem(key, '');
          localStorage.removeItem(key);
        }

        return true;
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return false;
      }
    };

    // Directly adds a value to local storage
    // If local storage is not available in the browser use cookies
    // Example use: localStorageService.add('library','angular');
    var addToLocalStorage = function (key, value) {

      // If this browser does not support local storage use cookies
      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
        }
        return addToCookies(key, value);
      }

      // Let's convert undefined values to null to get the value consistent
      if (typeof value === "undefined") {
        value = null;
      }

      try {
        if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
        }
        localStorage.setItem(prefix + key, value);
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return addToCookies(key, value);
      }
      return true;
    };

    // Directly get a value from local storage
    // Example use: localStorageService.get('library'); // returns 'angular'
    var getFromLocalStorage = function (key) {

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
        return getFromCookies(key);
      }

      var item = localStorage.getItem(prefix + key);
      // angular.toJson will convert null to 'null', so a proper conversion is needed
      // FIXME not a perfect solution, since a valid 'null' string can't be stored
      if (!item || item === 'null') {
        return null;
      }

      if (item.charAt(0) === "{" || item.charAt(0) === "[") {
        return angular.fromJson(item);
      }

      return item;
    };

    // Remove an item from local storage
    // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
    var removeFromLocalStorage = function (key) {
      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
        }
        return removeFromCookies(key);
      }

      try {
        localStorage.removeItem(prefix+key);
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return removeFromCookies(key);
      }
      return true;
    };

    // Return array of keys for local storage
    // Example use: var keys = localStorageService.keys()
    var getKeysForLocalStorage = function () {

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return false;
      }

      var prefixLength = prefix.length;
      var keys = [];
      for (var key in localStorage) {
        // Only return keys that are for this app
        if (key.substr(0,prefixLength) === prefix) {
          try {
            keys.push(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
            return [];
          }
        }
      }
      return keys;
    };

    // Remove all data for this app from local storage
    // Also optionally takes a regular expression string and removes the matching key-value pairs
    // Example use: localStorageService.clearAll();
    // Should be used mostly for development purposes
    var clearAllFromLocalStorage = function (regularExpression) {

      var regularExpression = regularExpression || "";
      //accounting for the '.' in the prefix when creating a regex
      var tempPrefix = prefix.slice(0, -1) + "\.";
      var testRegex = RegExp(tempPrefix + regularExpression);

      if (!browserSupportsLocalStorage()) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return clearAllFromCookies();
      }

      var prefixLength = prefix.length;

      for (var key in localStorage) {
        // Only remove items that are for this app and match the regular expression
        if (testRegex.test(key)) {
          try {
            removeFromLocalStorage(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
            return clearAllFromCookies();
          }
        }
      }
      return true;
    };

    // Checks the browser to see if cookies are supported
    var browserSupportsCookies = function() {
      try {
        return navigator.cookieEnabled ||
          ("cookie" in document && (document.cookie.length > 0 ||
          (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
      } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
          return false;
      }
    };

    // Directly adds a value to cookies
    // Typically used as a fallback is local storage is not available in the browser
    // Example use: localStorageService.cookie.add('library','angular');
    var addToCookies = function (key, value) {

      if (typeof value === "undefined") {
        return false;
      }

      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      try {
        var expiry = '',
            expiryDate = new Date();

        if (value === null) {
          // Mark that the cookie has expired one day ago
          expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
          value = '';
        } else if (cookie.expiry !== 0) {
          expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
        }
        if (!!key) {
          document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path;
          }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
        return false;
      }
      return true;
    };

    // Directly get a value from a cookie
    // Example use: localStorageService.cookie.get('library'); // returns 'angular'
    var getFromCookies = function (key) {
      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      var cookies = document.cookie.split(';');
      for(var i=0;i < cookies.length;i++) {
        var thisCookie = cookies[i];
        while (thisCookie.charAt(0)===' ') {
          thisCookie = thisCookie.substring(1,thisCookie.length);
        }
        if (thisCookie.indexOf(prefix + key + '=') === 0) {
          return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
        }
      }
      return null;
    };

    var removeFromCookies = function (key) {
      addToCookies(key,null);
    };

    var clearAllFromCookies = function () {
      var thisCookie = null, thisKey = null;
      var prefixLength = prefix.length;
      var cookies = document.cookie.split(';');
      for(var i = 0; i < cookies.length; i++) {
        thisCookie = cookies[i];

        while (thisCookie.charAt(0) === ' ') {
          thisCookie = thisCookie.substring(1, thisCookie.length);
        }

        key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
        removeFromCookies(key);
      }
    };

    return {
      isSupported: browserSupportsLocalStorage,
      set: addToLocalStorage,
      add: addToLocalStorage, //DEPRECATED
      get: getFromLocalStorage,
      keys: getKeysForLocalStorage,
      remove: removeFromLocalStorage,
      clearAll: clearAllFromLocalStorage,
      cookie: {
        set: addToCookies,
        add: addToCookies, //DEPRECATED
        get: getFromCookies,
        remove: removeFromCookies,
        clearAll: clearAllFromCookies
      }
    };
  }]
});
}).call(this);
<|endoftext|>


<commit_before>// some stuff<commit_msg>Some other test<commit_after>// some stuff
console.log("Some test");<|endoftext|>


<commit_before>/**
* Copyright (c) 2014, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
*    Redistributions of source code must retain the above copyright notice, this list of conditions and the
*    following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*    the following disclaimer in the documentation and/or other materials provided with the distribution.
*
*    Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
*    promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

var expect   = require('chai').expect;
var FuelRest = require('../../lib/fuel-rest');
var FuelAuth = require('fuel-auth');

describe('General Tests', function() {
	'use strict';

	it('should be a constructor', function() {
		expect(FuelRest).to.be.a('function');
	});

	it('should require auth options', function() {
		var RestClient, options;

		options = {
			auth: {
				clientId: 'testing'
				, clientSecret: 'testing'
			}
		};

		try {
			RestClient = new FuelRest();
		} catch(err) {
			expect(err.message).to.equal('clientId or clientSecret is missing or invalid');
		}

		RestClient = new FuelRest(options);

		// rest client should have an instance of an auth client
		expect(RestClient.AuthClient instanceof FuelAuth).to.be.true;
	});

	it('should use already initialized fuel auth client', function() {
		var AuthClient, RestClient, authOptions;

		authOptions = {
			clientId: 'testing'
			, clientSecret: 'testing'
		};

		AuthClient = new FuelAuth(authOptions);

		AuthClient.test = true;

		RestClient = new FuelRest({ auth: AuthClient });

		expect(RestClient.AuthClient.test).to.be.true;
	});

	it('should take a custom rest endpoint', function() {
		var RestClient, options;

		options = {
			auth: {
				clientId: 'testing'
				, clientSecret: 'testing'
			}
		};

		// testing default initialization
		RestClient = new FuelRest(options);

		expect(RestClient.origin).to.equal('https://www.exacttargetapis.com');

		options.origin = 'https://www.exacttarget.com';

		// testing custom endpoint
		RestClient = new FuelRest(options);

		expect(RestClient.origin).to.equal('https://www.exacttarget.com');
	});

	it('should merge module level headers into default headers', function() {
		var RestClient, options;

		options = {
			auth: {
				clientId: 'testing'
				, clientSecret: 'testing'
			}
			, headers: {
				'test': 1
			}
		};

		// testing default initialization
		RestClient = new FuelRest(options);

		expect(RestClient.defaultHeaders.test).to.equal(1);
	});

	it('should have apiRequest on prototype', function() {
		expect(FuelRest.prototype.apiRequest).to.be.a('function');
	});

	it('should have get on prototype', function() {
		expect(FuelRest.prototype.get).to.be.a('function');
	});

	it('should have post on prototype', function() {
		expect(FuelRest.prototype.post).to.be.a('function');
	});

	it('should have put on prototype', function() {
		expect(FuelRest.prototype.put).to.be.a('function');
	});

	it('should have delete on prototype', function() {
		expect(FuelRest.prototype.delete).to.be.a('function');
	});
});
<commit_msg>jscs/test cleanup - general tests<commit_after>/**
* Copyright (c) 2014, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
*    Redistributions of source code must retain the above copyright notice, this list of conditions and the
*    following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*    the following disclaimer in the documentation and/or other materials provided with the distribution.
*
*    Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
*    promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

var expect   = require('chai').expect;
var FuelRest = require('../../lib/fuel-rest');
var FuelAuth = require('fuel-auth');

describe('General Tests', function() {
	'use strict';

	var options;

	beforeEach(function() {
		options = {
			auth: {
				clientId: 'testing'
				, clientSecret: 'testing'
			}
		};
	});

	it('should be a constructor', function() {
		expect(FuelRest).to.be.a('function');
	});

	it('should require auth options', function() {
		var RestClient;

		try {
			RestClient = new FuelRest();
		} catch(err) {
			expect(err.message).to.equal('clientId or clientSecret is missing or invalid');
		}

		RestClient = new FuelRest(options);

		// rest client should have an instance of an auth client
		expect(RestClient.AuthClient instanceof FuelAuth).to.be.true;
	});

	it('should use already initialized fuel auth client', function() {
		var AuthClient, RestClient;

		AuthClient = new FuelAuth(options.auth);

		AuthClient.test = true;

		RestClient = new FuelRest({ auth: AuthClient });

		expect(RestClient.AuthClient.test).to.be.true;
	});

	it('should take a custom rest endpoint', function() {
		var RestClient;

		// testing default initialization
		RestClient = new FuelRest(options);

		expect(RestClient.origin).to.equal('https://www.exacttargetapis.com');

		options.origin = 'https://www.exacttarget.com';

		// testing custom endpoint
		RestClient = new FuelRest(options);

		expect(RestClient.origin).to.equal('https://www.exacttarget.com');
	});

	it('should merge module level headers into default headers', function() {
		var RestClient;

		options.headers = {
			'test': 1
		};

		// testing default initialization
		RestClient = new FuelRest(options);

		expect(RestClient.defaultHeaders.test).to.equal(1);
	});

	it('should have apiRequest on prototype', function() {
		expect(FuelRest.prototype.apiRequest).to.be.a('function');
	});

	it('should have get on prototype', function() {
		expect(FuelRest.prototype.get).to.be.a('function');
	});

	it('should have post on prototype', function() {
		expect(FuelRest.prototype.post).to.be.a('function');
	});

	it('should have put on prototype', function() {
		expect(FuelRest.prototype.put).to.be.a('function');
	});

	it('should have delete on prototype', function() {
		expect(FuelRest.prototype.delete).to.be.a('function');
	});
});
<|endoftext|>


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

  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'))
  } else {
    factory(jQuery)
  }
}(function ($) {
  'use strict';

  var Gist = function (element, options) {
    this.options = options
    this.$gist   = $(element)
    this.request()
  }

  Gist.DEFAULTS = {
    timeout: 1000,
    success: onAjaxSuccess,
    error: onAjaxError
  }

  Gist.prototype.request = function () {
    var gist = this
    var id   = this.$gist.data('gist')
    var file = this.$gist.data('file') || false
    var url  = 'https://gist.github.com/' + id + '.json'

    if (file) {
      url += '?file=' + file
    }

    $.ajax({
      url: url,
      dataType: 'jsonp',
      cache: true,
      timeout: gist.options.timeout,
      success: gist.options.success,
      error: gist.options.error
    })
  }

  Gist.prototype.onAjaxSuccess = function (self, data, textStatus, jqXHR) {
    if (! data || ! 'div' in data) {
      self.onAjaxError()
      return
    }

    // Append the stylesheet if it doesn't exists.
    // Trying to minimize requests.
    if (! $('link[href="' + data.stylesheet + '"]').length) {
      $(document.head).append('<link href="' + data.stylesheet + '" rel="stylesheet">')
    }

    // When loading different files from the same gist
    // on one page, there will be duplicate ids.
    //
    // That should be fixed.
    self.$gist.html(data.div)
  }

  Gist.prototype.onAjaxError = function (self, jqXHR, textStatus, errorThrown) {
    self.$gist.html(':(')
  }

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('gist-initialized')
      var options = $.extend({}, Gist.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (! data) {
        $this.data('gist-initialized', (data = new Gist(this, options)))
      }
    })
  }

  var old = $.fn.gist

  $.fn.gist             = Plugin
  $.fn.gist.Constructor = Gist

  $.fn.gist.noConflict = function () {
    $.fn.gist = old
    return this
  }
}))<commit_msg>Add the current URL and container to the xhr obj<commit_after>(function (factory) {
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'))
  } else {
    factory(jQuery)
  }
}(function ($) {
  'use strict';

  var Gist = function (element, options) {
    this.options = options
    this.$gist   = $(element)
    this.request()
  }

  Gist.DEFAULTS = {
    timeout: 1000,
    success: onAjaxSuccess,
    error: onAjaxError
  }

  Gist.prototype.request = function () {
    var gist = this
    var id   = this.$gist.data('gist')
    var file = this.$gist.data('file') || false
    var url  = 'https://gist.github.com/' + id + '.json'

    if (file) {
      url += '?file=' + file
    }

    $.ajax({
      url: url,
      dataType: 'jsonp',
      cache: true,
      beforeSend: function ( xhr ) {
        xhr.url   = url
        xhr.$gist = gist.$gist
      },
      timeout: gist.options.timeout,
      success: gist.options.success,
      error: gist.options.error
    })
  }

  Gist.prototype.onAjaxSuccess = function (self, data, textStatus, jqXHR) {
    if (! data || ! 'div' in data) {
      self.onAjaxError()
      return
    }

    // Append the stylesheet if it doesn't exists.
    // Trying to minimize requests.
    if (! $('link[href="' + data.stylesheet + '"]').length) {
      $(document.head).append('<link href="' + data.stylesheet + '" rel="stylesheet">')
    }

    // When loading different files from the same gist
    // on one page, there will be duplicate ids.
    //
    // That should be fixed.
    self.$gist.html(data.div)
  }

  Gist.prototype.onAjaxError = function (self, jqXHR, textStatus, errorThrown) {
    self.$gist.html(':(')
  }

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('gist-initialized')
      var options = $.extend({}, Gist.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (! data) {
        $this.data('gist-initialized', (data = new Gist(this, options)))
      }
    })
  }

  var old = $.fn.gist

  $.fn.gist             = Plugin
  $.fn.gist.Constructor = Gist

  $.fn.gist.noConflict = function () {
    $.fn.gist = old
    return this
  }
}))<|endoftext|>


<commit_before>/**
 * @description Модель колонки контрола DataGrid
 * @class DataGridColumnModel
 * @extends Backbone.Model
 */
var DataGridColumnModel = Backbone.Model.extend({

    defaults: {
        resizable: true,
        visible: true,
        itemFormat: null,
        sortable: false
    }

}, {
    SORTING_ASC: 'asc',
    SORTING_DESC: 'desc',
    SORTING_NONE: 'none'
});
<commit_msg>~fix empty column text in DataGrid<commit_after>/**
 * @description Модель колонки контрола DataGrid
 * @class DataGridColumnModel
 * @extends Backbone.Model
 */
var DataGridColumnModel = Backbone.Model.extend({

    defaults: {
        resizable: true,
        visible: true,
        itemFormat: null,
        sortable: false,
        text: ''
    }

}, {
    SORTING_ASC: 'asc',
    SORTING_DESC: 'desc',
    SORTING_NONE: 'none'
});
<|endoftext|>