<commit_before>//
//  Module: Tweets
//  ==============
//
//  Convenience methods for Tweets actions directly from [Twitter's API 1.1](https://dev.twitter.com/docs/api/1.1#111).
//
//  + [Retweets](#retweets)
//
var Tweets,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

module.exports = Tweets = (function() {

  //
  //
  //  Constructor
  //  -----------
  //
  function Tweets(uri, opts) {
    this.uri = uri;
    this.opts = opts;

    var tt = require('twitter-rest-lite');

    this.api = tt.API(this.opts);

    /* bindings */
    this.retweets = __bind(this.retweets, this);
    this.show = __bind(this.show, this);
    this.destroy = __bind(this.destroy, this);
    this.update = __bind(this.update, this);
    this.retweet = __bind(this.retweet, this);
    this.updateWithMedia = __bind(this.updateWithMedia, this);
    this.oembed = __bind(this.oembed, this);
    this.retweeters = __bind(this.retweeters, this);
  };

  //
  //
  //  Public: returns a collection of the 100 most recent retweets on specified tweet
  //  ----------------------------------------------------
  //
  //  ### Arguments
  //
  //  + **id**: Status ID
  //  + **params**: Object with params:
  //    - **count**
  //    - **trim_user**
  //  + **callback**: Callback Function
  //
  //### Returns
  //  A callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and an Array with tweets as second parameter.
  //
  Tweets.prototype.retweets = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweets() requires an ID to be provided'
      ));
    }

    self.api.get('/statuses/retweets/' + id + '.json', params, callback);
  };

  /**
   *
   *  Public: returns a single tweet
   *  ------------------------------
   *
   *  id                  - Status ID
   *  params              - Object with params:
   *  - trim_user
   *  - include_my_retweet
   *  - include_entities
   *  callback            - Callback Function
   *
   *  Returns a callback with an Error object as first parameter if there was any
   *  (otherwise just `null`) and a Tweet object as second parameter.
   **/
  Tweets.prototype.show = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.show() requires and ID to be provided'
      ));
    }

    self.api.get('/statuses/show/' + id + '.json', params, callback);
  };

  /**
   *
   *  Public: destroy a single tweet
   *  ------------------------------
   *
   *  This only works with `oauth_token` from the same user.
   *
   *  id                  - Status ID
   *  params              - Object with params:
   *  - trim_user
   *  callback            - Callback Function
   *
   *  Returns a callback with an Error object as first parameter if there was any
   *  (otherwise just `null`) and a Tweet object of the removed status as second
   *  parameter.
   **/
  Tweets.prototype.destroy = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.destroy() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/destroy/' + id + '.json', params, callback);
  };

  /**
   *
   *  Public: creates a tweet
   *  -----------------------
   *
   *  This only works with `oauth_token` from the same user.
   *
   *  params              - Object with params:
   *  - status: [Required]
   *  callback            - Callback Function
   **/
  Tweets.prototype.update = function(params, callback) {
    var self = this;

    if ((params == null) || (params.status == null) || (params.status === '')) {
      return callback(new Error(
        'Twitter:Tweets.update() requires params.status to be defined'
      ));
    }

    if (params.status.length > 140) {
      return callback(new Error(
        'Twitter:Tweets.update(): status is longer than 140 characters'
      ));
    }

    self.api.post('/statuses/update.json', params, callback);
  };

  /**
   *
   *  Public: retweets an status
   *  --------------------------
   *
   *  id                    - ID of the status to be retweeted
   *  params                - Object with params:
   *  callback              - Callback Function
   **/
  Tweets.prototype.retweet = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweet() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/retweet/' + id + '.json', params, callback);
  };

  /**
   *
   *  TODO: Public: update with media
   *  -------------------------------
   **/
  Tweets.prototype.updateWithMedia = function() {
    var self = this;

    // FIXME: IMPLEMENT!
  };

  /**
   *
   *  Public: returns HTML for embedding tweets in websites
   *  -----------------------------------------------------
   *
   *  params                  - Object with params:
   *  id: [Required if `url` is not given]
   *  url: [Required if `id` is not given]
   *  callback                - Callback Function
   **/
  Tweets.prototype.oembed = function(params, callback) {
    var self = this;

    if ((params.id == null) && (params.url == null)) {
      return callback(new Error(
        'Twitter:Tweets.oembed() requires either id or url on the params'
      ));
    }

    self.api.get('/statuses/oembed.json', params, callback);
  };

  /**
   *
   *  Public: get a list of retweeters by ID
   *  --------------------------------------
   *
   *  params                    - Object with params:
   *  id
   *  callback                  - Callback Function
   **/
  Tweets.prototype.retweeters = function(params, callback) {
    var self = this;

    if (params.id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweeters() requires an id on the params'
      ));
    }

    self.api.get('/statuses/retweeters/ids.json', params, callback);
  };

  return Tweets;
})();
<commit_msg>lib/tweets: show() partial docs<commit_after>//
//  Module: Tweets
//  ==============
//
//  Convenience methods for Tweets actions directly from [Twitter's API 1.1](https://dev.twitter.com/docs/api/1.1#111).
//
//  + [Retweets](#retweets)
//
var Tweets,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

module.exports = Tweets = (function() {

  //
  //
  //  Constructor
  //  -----------
  //
  function Tweets(uri, opts) {
    this.uri = uri;
    this.opts = opts;

    var tt = require('twitter-rest-lite');

    this.api = tt.API(this.opts);

    /* bindings */
    this.retweets = __bind(this.retweets, this);
    this.show = __bind(this.show, this);
    this.destroy = __bind(this.destroy, this);
    this.update = __bind(this.update, this);
    this.retweet = __bind(this.retweet, this);
    this.updateWithMedia = __bind(this.updateWithMedia, this);
    this.oembed = __bind(this.oembed, this);
    this.retweeters = __bind(this.retweeters, this);
  };

  //
  //
  //  Public: returns a collection of the 100 most recent retweets on specified tweet
  //  ----------------------------------------------------
  //
  //  ### Arguments
  //
  //  + **id**: Status ID
  //  + **params**: Object with params:
  //    - **count**
  //    - **trim_user**
  //  + **callback**: Callback Function
  //
  //### Returns
  //  A callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and an Array with tweets as second parameter.
  //
  Tweets.prototype.retweets = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweets() requires an ID to be provided'
      ));
    }

    self.api.get('/statuses/retweets/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: returns a single tweet
  //  ------------------------------
  //
  //  ### Arguments
  //
  //  id                  - Status ID
  //  params              - Object with params:
  //  - trim_user
  //  - include_my_retweet
  //  - include_entities
  //  callback            - Callback Function
  //
  //### Returns
  //  Returns a callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and a Tweet object as second parameter.
  //
  Tweets.prototype.show = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.show() requires and ID to be provided'
      ));
    }

    self.api.get('/statuses/show/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: destroy a single tweet
  //  ------------------------------
  //
  //  This only works with `oauth_token` from the same user.
  //
  //  id                  - Status ID
  //  params              - Object with params:
  //  - trim_user
  //  callback            - Callback Function
  //
  //  Returns a callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and a Tweet object of the removed status as second
  //  parameter.
  //
  Tweets.prototype.destroy = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.destroy() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/destroy/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: creates a tweet
  //  -----------------------
  //
  //  This only works with `oauth_token` from the same user.
  //
  //  params              - Object with params:
  //  - status: [Required]
  //  callback            - Callback Function
  //
  Tweets.prototype.update = function(params, callback) {
    var self = this;

    if ((params == null) || (params.status == null) || (params.status === '')) {
      return callback(new Error(
        'Twitter:Tweets.update() requires params.status to be defined'
      ));
    }

    if (params.status.length > 140) {
      return callback(new Error(
        'Twitter:Tweets.update(): status is longer than 140 characters'
      ));
    }

    self.api.post('/statuses/update.json', params, callback);
  };

  //
  //
  //  Public: retweets an status
  //  --------------------------
  //
  //  id                    - ID of the status to be retweeted
  //  params                - Object with params:
  //  callback              - Callback Function
  //
  Tweets.prototype.retweet = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweet() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/retweet/' + id + '.json', params, callback);
  };

  //
  //
  //  TODO: Public: update with media
  //  -------------------------------
  //
  Tweets.prototype.updateWithMedia = function() {
    var self = this;

    /* FIXME: IMPLEMENT! */
  };

  //
  //
  //  Public: returns HTML for embedding tweets in websites
  //  -----------------------------------------------------
  //
  //  params                  - Object with params:
  //  id: [Required if `url` is not given]
  //  url: [Required if `id` is not given]
  //  callback                - Callback Function
  //
  Tweets.prototype.oembed = function(params, callback) {
    var self = this;

    if ((params.id == null) && (params.url == null)) {
      return callback(new Error(
        'Twitter:Tweets.oembed() requires either id or url on the params'
      ));
    }

    self.api.get('/statuses/oembed.json', params, callback);
  };

  //
  //
  //  Public: get a list of retweeters by ID
  //  --------------------------------------
  //
  //  params                    - Object with params:
  //  id
  //  callback                  - Callback Function
  //
  Tweets.prototype.retweeters = function(params, callback) {
    var self = this;

    if (params.id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweeters() requires an id on the params'
      ));
    }

    self.api.get('/statuses/retweeters/ids.json', params, callback);
  };

  return Tweets;
})();
<|endoftext|>


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

    var fn = timbre.fn;
    var timevalue = timbre.utils.timevalue;

    function ParamNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixKR(this);

        this._.value = 0;
        this._.minvalue = -Infinity;
        this._.maxValue = +Infinity;

        this._.eventtype = ParamEvent_None;
        this._.currentTime = 0;
        this._.currentTimeIncr = this.cell.length * 1000 / timbre.samplerate;

        this._.schedules = [];

        this.on("setAdd", __changeWithValue);
        this.on("setMul", __changeWithValue);
    }
    fn.extend(ParamNode);

    function ParamEvent(type, value, time) {
        this.type  = type;
        this.value = value;
        this.time  = time;
    }
    var ParamEvent_None                   = 0;
    var ParamEvent_SetValue               = 1;
    var ParamEvent_LinearRampToValue      = 2;
    var ParamEvent_ExponentialRampToValue = 3;

    var __changeWithValue = fn.changeWithValue;

    var $ = ParamNode.prototype;

    Object.defineProperties($, {
        value: {
            set: function(value) {
                if (typeof value === "number") {
                    var _ = this._;
                    value = (value < _.minvalue) ?
                        _.minvalue : (value > _.maxValue) ? _.maxValue : value;
                    _.value = isNaN(value) ? 0 : value;
                    _.eventtype = ParamEvent_None;
                    __changeWithValue.call(this);
                }
            },
            get: function() {
                return this._.value;
            }
        },
        minValue: {
            set: function(value) {
                if (typeof value === "number") {
                    this._.minValue = value;
                }
            },
            get: function() {
                return this._.minValue;
            }
        },
        maxValue: {
            set: function(value) {
                if (typeof value === "number") {
                    this._.maxValue = value;
                }
            },
            get: function() {
                return this._.maxValue;
            }
        }
    });

    var insertEvent = function(schedules, type, value, time) {
        schedules.push(new ParamEvent(type, value, time));
    };

    $.setValueAtTime = function(value, time) {
        var _ = this._;
        if (typeof time === "string") {
            time = timevalue(time);
        }
        if (typeof value === "number" && typeof time === "number") {
            value = (value < _.minvalue) ?
                _.minvalue : (value > _.maxValue) ? _.maxValue : value;
            insertEvent(_.schedules, ParamEvent_SetValue, value, time);
        }
        return this;
    };
    $.setAt = $.setValueAtTime;

    $.linearRampToValueAtTime = function(value, time) {
        var _ = this._;
        if (typeof time === "string") {
            time = timevalue(time);
        }
        if (typeof value === "number" && typeof time === "number") {
            value = (value < _.minvalue) ?
                _.minvalue : (value > _.maxValue) ? _.maxValue : value;
            insertEvent(_.schedules, ParamEvent_LinearRampToValue, value, time);
        }
        return this;
    };
    $.lineTo = $.linearRampToValueAtTime;

    $.exponentialRampToValueAtTime = function(value, time) {
        var _ = this._;
        if (typeof time === "string") {
            time = timevalue(time);
        }
        if (typeof value === "number" && typeof time === "number") {
            value = (value < _.minvalue) ?
                _.minvalue : (value > _.maxValue) ? _.maxValue : value;
            insertEvent(_.schedules, ParamEvent_ExponentialRampToValue, value, time);
        }
        return this;
    };
    $.expTo = $.exponentialRampToValueAtTime;

    $.cancelScheduledValues = function(time) {
        if (typeof time === "string") {
            time = timevalue(time);
        }
        if (typeof time === "number") {
            var s = this._.schedules;
            for (var i = 0, imax = s.length; i < imax; ++i) {
                if (time <= s[i].time) {
                    s.splice(i);
                    if (i === 0) {
                        this._.eventtype = ParamEvent_None;
                    }
                    break;
                }
            }
        }
        return this;
    };
    $.cancel = $.cancelScheduledValues;

    $.process = function(tickID) {
        var _ = this._;
        var cell = this.cell;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            var schedules = _.schedules;
            var e, samples;

            while (_.eventtype === ParamEvent_None && schedules.length > 0) {
                e = schedules.shift();
                switch (e.type) {
                case ParamEvent_SetValue:
                    _.eventtype = ParamEvent_SetValue;
                    _.goalValue = e.value;
                    _.goalTime  = e.time + _.currentTime;
                    _.isEnded = false;
                    break;
                case ParamEvent_LinearRampToValue:
                    samples = e.time * 0.001 * timbre.samplerate;
                    if (samples > 0) {
                        _.eventtype = ParamEvent_LinearRampToValue;
                        _.goalValue = e.value;
                        _.goalTime  = e.time + _.currentTime;
                        _.variation = (e.value - _.value) / (samples / cell.length);
                        _.isEnded = false;
                    }
                    break;
                case ParamEvent_ExponentialRampToValue:
                    samples = e.time * 0.001 * timbre.samplerate;
                    if (_.value !== 0 && samples > 0) {
                        _.eventtype = ParamEvent_ExponentialRampToValue;
                        _.goalValue = e.value;
                        _.goalTime  = e.time + _.currentTime;
                        _.variation = Math.pow(e.value/_.value, 1/(samples/cell.length));
                        _.isEnded = false;
                    }
                    break;
                }
            }

            var changed = false;
            var i, x;

            if (!_.isEnded) {
                switch (_.eventtype) {
                case ParamEvent_LinearRampToValue:
                    if (_.currentTime < _.goalTime) {
                        _.value += _.variation;
                        changed = true;
                    }
                    break;
                case ParamEvent_ExponentialRampToValue:
                    if (_.currentTime < _.goalTime) {
                        _.value *= _.variation;
                        changed = true;
                    }
                    break;
                }
                _.currentTime += _.currentTimeIncr;

                if (_.eventtype !== ParamEvent_None && _.currentTime >= _.goalTime) {
                    _.value = _.goalValue;
                    if (schedules.length === 0) {
                        fn.nextTick(onended.bind(this));
                    } else {
                        fn.nextTick(onnext.bind(this));
                    }
                    changed = true;
                }

                if (changed) {
                    x = _.value * _.mul + _.add;
                    for (i = cell.length; i--; ) {
                        cell[i] = x;
                    }
                }
            }
        }

        return cell;
    };

    var onended = function() {
        this._.eventtype = ParamEvent_None;
        fn.onended(this);
    };

    var onnext = function() {
        var _ = this._;
        _.eventtype = ParamEvent_None;
        this._.emit("next", _.value);
    };

    fn.register("param", ParamNode);

})(timbre);
<commit_msg>replace T("param")<commit_after>(function(timbre) {
    "use strict";

    var fn = timbre.fn;
    var Envelope = timbre.modules.Envelope;

    function ParamNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixKR(this);

        var _ = this._;
        _.env = new Envelope(timbre.samplerate);
        _.env.step = this.cell.length;
        _.curve = "lin";
    }
    fn.extend(ParamNode);

    var $ = ParamNode.prototype;

    Object.defineProperties($, {
        value: {
            set: function(value) {
                if (typeof value === "number") {
                    var env = this._.env;
                    env.setTable([value]);
                    env.reset();
                    env.status = Envelope.StatusGate;
                }
            },
            get: function() {
                return this._.env.level;
            }
        }
    });

    $.to = function(nextLevel, time, curve) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, curve]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = curve;
        this._.plotFlush = true;
        return this;
    };

    $.setAt = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [env.level, time], [nextLevel, 0]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "set";
        this._.plotFlush = true;
        return this;
    };

    $.linTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "lin"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "lin";
        this._.plotFlush = true;
        return this;
    };

    $.expTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "exp"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "exp";
        this._.plotFlush = true;
        return this;
    };

    $.sinTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "sin"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "sin";
        this._.plotFlush = true;
        return this;
    };

    $.welTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "wel"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "wel";
        this._.plotFlush = true;
        return this;
    };

    $.sqrTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "sqr"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "sqr";
        this._.plotFlush = true;
        return this;
    };

    $.cubTo = function(nextLevel, time) {
        var env = this._.env;
        env.setTable([env.level, [nextLevel, time, "cub"]]);
        env.reset();
        env.status = Envelope.StatusGate;
        this._.curve = "cub";
        this._.plotFlush = true;
        return this;
    };

    $.cancel = function() {
        this._.env.status = Envelope.StatusWait;
        return this;
    };

    $.process = function(tickID) {
        var _ = this._;
        var cell = this.cell;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            var inputs  = this.inputs;
            var i, imax = cell.length;
            var mul = _.mul, add = _.add;

            if (inputs.length) {
                fn.inputSignalAR(this);
            } else {
                for (i = imax; i--; ) {
                    cell[i] = 1;
                }
            }

            var value = _.env.next();

            for (i = imax; i--; ) {
                cell[i] = (cell[i] * value) * mul + add;
            }

            var emit = _.env.emit;
            if (emit) {
                if (emit === "ended") {
                    fn.nextTick(onended.bind(this));
                } else {
                    this._.emit(emit, _.value);
                }
            }
        }

        return cell;
    };

    var onended = function() {
        fn.onended(this);
    };

    var super_plot = timbre.Object.prototype.plot;

    $.plot = function(opts) {
        if (this._.plotFlush) {
            var env = new Envelope(128);

            var table;
            if (this._.curve === "set") {
                table = [0, [0, 900], [1, 0]];
            } else {
                table = [0, [1, 1000, this._.curve]];
            }

            env.setTable(table);
            env.status = Envelope.StatusGate;

            var data = new Float32Array(128);
            var i, imax;

            for (i = 0, imax = data.length; i < imax; ++i) {
                data[i] = env.next();
            }

            this._.plotData  = data;
            this._.plotRange = [0, 1];
            this._.plotFlush = null;
        }
        return super_plot.call(this, opts);
    };

    fn.register("param", ParamNode);

})(timbre);
<|endoftext|>


<commit_before>var util = require('util');
var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;

function JsParser(settings) {
    // this.setup_settings();
    // call parent constructor
    DocsParser.call(this, settings);
}

JsParser.prototype = Object.create(DocsParser.prototype);

JsParser.prototype.setup_settings = function() {
    var identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*';
    this.settings = {
        // curly brackets around the type information
        'curlyTypes': true,
        'typeInfo': true,
        'typeTag': 'type',
        // technically, they can contain all sorts of unicode, but w/e
        'varIdentifier': identifier,
        'fnIdentifier':  identifier,
        'fnOpener': 'function(?:\\s+' + identifier + ')?\\s*\\(',
        'commentCloser': ' */',
        'bool': 'Boolean',
        'function': 'Function'
    };
};

JsParser.prototype.parse_function = function(line) {
    // single quotes indicate what will be matched in each line
    var functionRegex = xregexp(
        // '  'var foo = function bar (baz, quaz) {}
        '^\\s*' +
        //   'var 'foo = function bar (baz, quaz) {}
        '(?:(?:var|let|const)\\s+)?' +
        //   var 'foo = 'function bar (baz, quaz) {}
        '(?:(?P<name1>' + this.settings.varIdentifier + ')\\s*[:=]\\s*)?' +
        //   var foo = 'function 'bar (baz, quaz) {}
        '(?:function\\*?|get|set)\\s+' +
        //   var foo = function 'bar '(baz, quaz) {}
        '(?P<name2>' + this.settings.fnIdentifier + ')?\\s*' +
        //   var foo = function bar '(baz, quaz)' {}
        '\\(\\s*(?P<args>.*?)\\)'
    );

    var arrowFunctionRegex = xregexp(
        // '  'var foo = (bar, baz) => {}
        '^\\s*' +
        //   'var 'foo = (bar, baz) => {}
        '(?:(?:var|let|const)\\s+)?' +
        //   var 'foo = '(bar, baz) => {}
        '(?P<name1>' + identifier + ')\\s*[:=]\\s*' +
        '(?:'+
            //   var foo = '(bar, baz)' => {}
            '\\(\\s*(?P<args>.*?)\\)' +
            '|' +
            //   var foo = 'bar' => {}
            '(?P<args>' + this.settings.varIdentifier + ')' +
            '|' +
            //   var foo = '_' => {}
            '_' +
        ')\\s*' +
        //   var foo = bar '=>' {}
        '=>\\s*'
    );

    var functionMatches = xregexp.exec(line, functionRegex);
    var arrowFunctionMatches = xregexp.exec(line, arrowFunctionRegex);
    var matches = functionMatches || arrowFunctionMatches;

    if(matches === null) {
        return null;
    }
    // grab the name out of "name1 = function name2(foo)" preferring name1
    var name = matches.name1 || matches.name2 || '';
    var args = matches.args;
    return [name, args, null];
};

JsParser.prototype.parse_var = function(line) {
        //   var foo = blah,
        //       foo = blah;
        //   baz.foo = blah;
        //   baz = {
        //        foo : blah
        //   }
    var regex = xregexp('(?P<name>' + this.settings.varIdentifier + ')\\s*[=:]\\s*(?P<val>.*?)(?:[;,]|$)');
    var matches = xregexp.exec(line, regex);
    if(matches === null) {
        return null;
    }
    // variable name, variable value
    return [matches.name, matches.val.trim()];
};

JsParser.prototype.parse_arg = function(arg) {

    var regex = xregexp(
        '(?P<name>' + this.settings.varIdentifier + ')(\\s*=\\s*(?P<value>.*))?'
    );

    return xregexp.exec(arg, regex);
};

JsParser.prototype.get_arg_type = function(arg) {

    var matches = this.parse_arg(arg)

    if(matches.value) {
        return this.guess_type_from_value(matches.value);
    }

    return null;
};

JsParser.prototype.get_arg_name = function(arg) {

    var matches = this.parse_arg(arg)

    if (matches.value) {
      return util.format('[%s=%s]', matches.name, matches.value);
    }

    return matches.name;
};

JsParser.prototype.guess_type_from_value = function(val) {
    var lower_primitives = this.editor_settings.lower_case_primitives || false;
    var short_primitives = this.editor_settings.short_primitives || false;
    var var_type;
    var capitalize = function(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    if(this.is_numeric(val)) {
        var_type = 'number';
        return (lower_primitives ? var_type : capitalize(var_type));
    }
    if((val[0] === '\'') || (val[0] === '"')) {
        var_type = 'string';
        return (lower_primitives ? var_type : capitalize(var_type));
    }
    if(val[0] === '[') {
        return 'Array';
    }
    if(val[0] === '{') {
        return 'Object';
    }
    if((val === 'true') || (val === 'false')) {
        var ret_val = (short_primitives ? 'Bool' : 'Boolean');
        return (lower_primitives ? ret_val : capitalize(ret_val));
    }
    var regex = new RegExp('RegExp\\b|\\\/[^\\/]');
    if(regex.test(val)) {
        return 'RegExp';
    }
    if(val.slice(0, 4) === 'new ') {
        regex = new RegExp('new (' + this.settings.fnIdentifier + ')');
        var matches = regex.exec(val);
        return (matches[0] && matches[1]) || null;
    }
    return null;
};

module.exports = JsParser;
<commit_msg>Fix semicolon errors in JsParser<commit_after>var util = require('util');
var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;

function JsParser(settings) {
    // this.setup_settings();
    // call parent constructor
    DocsParser.call(this, settings);
}

JsParser.prototype = Object.create(DocsParser.prototype);

JsParser.prototype.setup_settings = function() {
    var identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*';
    this.settings = {
        // curly brackets around the type information
        'curlyTypes': true,
        'typeInfo': true,
        'typeTag': 'type',
        // technically, they can contain all sorts of unicode, but w/e
        'varIdentifier': identifier,
        'fnIdentifier':  identifier,
        'fnOpener': 'function(?:\\s+' + identifier + ')?\\s*\\(',
        'commentCloser': ' */',
        'bool': 'Boolean',
        'function': 'Function'
    };
};

JsParser.prototype.parse_function = function(line) {
    // single quotes indicate what will be matched in each line
    var functionRegex = xregexp(
        // '  'var foo = function bar (baz, quaz) {}
        '^\\s*' +
        //   'var 'foo = function bar (baz, quaz) {}
        '(?:(?:var|let|const)\\s+)?' +
        //   var 'foo = 'function bar (baz, quaz) {}
        '(?:(?P<name1>' + this.settings.varIdentifier + ')\\s*[:=]\\s*)?' +
        //   var foo = 'function 'bar (baz, quaz) {}
        '(?:function\\*?|get|set)\\s+' +
        //   var foo = function 'bar '(baz, quaz) {}
        '(?P<name2>' + this.settings.fnIdentifier + ')?\\s*' +
        //   var foo = function bar '(baz, quaz)' {}
        '\\(\\s*(?P<args>.*?)\\)'
    );

    var arrowFunctionRegex = xregexp(
        // '  'var foo = (bar, baz) => {}
        '^\\s*' +
        //   'var 'foo = (bar, baz) => {}
        '(?:(?:var|let|const)\\s+)?' +
        //   var 'foo = '(bar, baz) => {}
        '(?P<name1>' + identifier + ')\\s*[:=]\\s*' +
        '(?:'+
            //   var foo = '(bar, baz)' => {}
            '\\(\\s*(?P<args>.*?)\\)' +
            '|' +
            //   var foo = 'bar' => {}
            '(?P<args>' + this.settings.varIdentifier + ')' +
            '|' +
            //   var foo = '_' => {}
            '_' +
        ')\\s*' +
        //   var foo = bar '=>' {}
        '=>\\s*'
    );

    var functionMatches = xregexp.exec(line, functionRegex);
    var arrowFunctionMatches = xregexp.exec(line, arrowFunctionRegex);
    var matches = functionMatches || arrowFunctionMatches;

    if(matches === null) {
        return null;
    }
    // grab the name out of "name1 = function name2(foo)" preferring name1
    var name = matches.name1 || matches.name2 || '';
    var args = matches.args;
    return [name, args, null];
};

JsParser.prototype.parse_var = function(line) {
        //   var foo = blah,
        //       foo = blah;
        //   baz.foo = blah;
        //   baz = {
        //        foo : blah
        //   }
    var regex = xregexp('(?P<name>' + this.settings.varIdentifier + ')\\s*[=:]\\s*(?P<val>.*?)(?:[;,]|$)');
    var matches = xregexp.exec(line, regex);
    if(matches === null) {
        return null;
    }
    // variable name, variable value
    return [matches.name, matches.val.trim()];
};

JsParser.prototype.parse_arg = function(arg) {

    var regex = xregexp(
        '(?P<name>' + this.settings.varIdentifier + ')(\\s*=\\s*(?P<value>.*))?'
    );

    return xregexp.exec(arg, regex);
};

JsParser.prototype.get_arg_type = function(arg) {

    var matches = this.parse_arg(arg);

    if(matches.value) {
        return this.guess_type_from_value(matches.value);
    }

    return null;
};

JsParser.prototype.get_arg_name = function(arg) {

    var matches = this.parse_arg(arg);

    if (matches.value) {
      return util.format('[%s=%s]', matches.name, matches.value);
    }

    return matches.name;
};

JsParser.prototype.guess_type_from_value = function(val) {
    var lower_primitives = this.editor_settings.lower_case_primitives || false;
    var short_primitives = this.editor_settings.short_primitives || false;
    var var_type;
    var capitalize = function(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    if(this.is_numeric(val)) {
        var_type = 'number';
        return (lower_primitives ? var_type : capitalize(var_type));
    }
    if((val[0] === '\'') || (val[0] === '"')) {
        var_type = 'string';
        return (lower_primitives ? var_type : capitalize(var_type));
    }
    if(val[0] === '[') {
        return 'Array';
    }
    if(val[0] === '{') {
        return 'Object';
    }
    if((val === 'true') || (val === 'false')) {
        var ret_val = (short_primitives ? 'Bool' : 'Boolean');
        return (lower_primitives ? ret_val : capitalize(ret_val));
    }
    var regex = new RegExp('RegExp\\b|\\\/[^\\/]');
    if(regex.test(val)) {
        return 'RegExp';
    }
    if(val.slice(0, 4) === 'new ') {
        regex = new RegExp('new (' + this.settings.fnIdentifier + ')');
        var matches = regex.exec(val);
        return (matches[0] && matches[1]) || null;
    }
    return null;
};

module.exports = JsParser;
<|endoftext|>


<commit_before>/*
  SortTable
  version 2
  7th April 2007
  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/

  Instructions:
  Download this file
  Add <script src="sorttable.js"></script> to your HTML
  Add class="sortable" to any table you'd like to make sortable
  Click on the headers to sort

  Thanks to many, many people for contributions and suggestions.
  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  This basically means: do what you want with it.
*/

sorttable = {
  numberRegExp: /^-?[$]?[\d,.]+%?$/,

  makeSortable: function(table) {
    var i, j;

    if (table.tHead.rows.length !== 1) return;

    headrow = table.tHead.rows[0].cells;

    for (i = 0; i<headrow.length; i++) {
      if (headrow[i].getAttribute('data-sort') !== 'false') {
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) { override = mtch[1]; }
        if (mtch && typeof sorttable["sort_"+override] == 'function') {
          headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
        } else {
          headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
        }
        // make it clickable to sort
        headrow[i].sorttable_columnindex = i;
        headrow[i].sorttable_tbody = table.tBodies[0];
        headrow[i].addEventListener('click', function(e) {

          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
            // if we're already sorted by this column, just
            // reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted',
                                                    'sorttable_sorted_reverse');
            this.removeChild(document.getElementById('sorttable_sortfwdind'));
            sortrevind = document.createElement('span');
            sortrevind.id = "sorttable_sortrevind";
            sortrevind.innerHTML = ' ▴';
            this.appendChild(sortrevind);
            return;
          }
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
            // if we're already sorted by this column in reverse, just
            // re-reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted_reverse',
                                                    'sorttable_sorted');
            this.removeChild(document.getElementById('sorttable_sortrevind'));
            sortfwdind = document.createElement('span');
            sortfwdind.id = "sorttable_sortfwdind";
            sortfwdind.innerHTML = ' ▾';
            this.appendChild(sortfwdind);
            return;
          }

          // remove sorttable_sorted classes
          theadrow = this.parentNode;
          Array.prototype.slice.call(theadrow.childNodes).forEach(function(cell) {
            if (cell.nodeType == 1) { // an element
              cell.className = cell.className.replace('sorttable_sorted_reverse','');
              cell.className = cell.className.replace('sorttable_sorted','');
            }
          });
          sortfwdind = document.getElementById('sorttable_sortfwdind');
          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
          sortrevind = document.getElementById('sorttable_sortrevind');
          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }

          this.className += ' sorttable_sorted';
          sortfwdind = document.createElement('span');
          sortfwdind.id = "sorttable_sortfwdind";
          sortfwdind.innerHTML = ' ▾';
          this.appendChild(sortfwdind);

          // build an array to sort. This is a Schwartzian transform thing,
          // i.e., we "decorate" each row with the actual sort key,
          // sort based on the sort keys, and then put the rows back in order
          // which is a lot faster because you only do getCellValue once per row
          row_array = [];
          col = this.sorttable_columnindex;
          rows = this.sorttable_tbody.rows;
          for (var j=0; j<rows.length; j++) {
            row_array[row_array.length] = [sorttable.getCellValue(rows[j].cells[col]), rows[j]];
          }

          row_array.sort(this.sorttable_sortfunction);

          tb = this.sorttable_tbody;
          for (j = 0; j<row_array.length; j++) {
            tb.appendChild(row_array[j][1]);
          }

          delete row_array;
        });
      }
    }
  },

  guessType: function(table, column) {
    var i, sortfn;

    sortfn = sorttable.sortAlpha;

    for (i = 0; i < table.tBodies[0].rows.length; i++) {
      text = sorttable.getCellValue(table.tBodies[0].rows[i].cells[column]);

      if (text !== '' && text.match(sorttable.numberRegExp)) {
        return sorttable.sortNumeric;
      }
    }

    return sortfn;
  },

  getCellValue: function(node) {
    if (!node) return '';

    if (node.getAttribute('data-value') !== null) {
      return node.getAttribute('data-value');
    }

    return node.innerText.replace(/^\s+|\s+$/g, '');
  },

  reverse: function(tbody) {
    // reverse the rows in a tbody
    var i;
    newrows = [];
    for (i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },

  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sortNumeric: function(a,b) {
    var aa = parseFloat(a[0].replace(/[^0-9.-]/g, '')),
        bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''))
    ;
    if (isNaN(aa)) aa = 0;
    if (isNaN(bb)) bb = 0;
    return aa - bb;
  },

  sortAlpha: function(a, b) {
    var aa = a[0].toLowerCase(),
        bb = b[0].toLowerCase()
    ;
    if (aa === bb) return 0;
    if (aa < bb) return -1;
    return 1;
  }
};<commit_msg>Clearer variable name<commit_after>/*
  SortTable
  version 2
  7th April 2007
  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/

  Instructions:
  Download this file
  Add <script src="sorttable.js"></script> to your HTML
  Add class="sortable" to any table you'd like to make sortable
  Click on the headers to sort

  Thanks to many, many people for contributions and suggestions.
  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  This basically means: do what you want with it.
*/

sorttable = {
  numberRegExp: /^-?[$]?[\d,.]+%?$/,

  makeSortable: function(table) {
    var i, j;

    if (table.tHead.rows.length !== 1) return;

    tHeadRow = table.tHead.rows[0].cells;

    for (i = 0; i<tHeadRow.length; i++) {
      if (tHeadRow[i].getAttribute('data-sort') !== 'false') {
        mtch = tHeadRow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) { override = mtch[1]; }
        if (mtch && typeof sorttable["sort_"+override] == 'function') {
          tHeadRow[i].sorttable_sortfunction = sorttable["sort_"+override];
        } else {
          tHeadRow[i].sorttable_sortfunction = sorttable.guessType(table,i);
        }
        // make it clickable to sort
        tHeadRow[i].sorttable_columnindex = i;
        tHeadRow[i].sorttable_tbody = table.tBodies[0];
        tHeadRow[i].addEventListener('click', function(e) {

          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
            // if we're already sorted by this column, just
            // reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted',
                                                    'sorttable_sorted_reverse');
            this.removeChild(document.getElementById('sorttable_sortfwdind'));
            sortrevind = document.createElement('span');
            sortrevind.id = "sorttable_sortrevind";
            sortrevind.innerHTML = ' ▴';
            this.appendChild(sortrevind);
            return;
          }
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
            // if we're already sorted by this column in reverse, just
            // re-reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted_reverse',
                                                    'sorttable_sorted');
            this.removeChild(document.getElementById('sorttable_sortrevind'));
            sortfwdind = document.createElement('span');
            sortfwdind.id = "sorttable_sortfwdind";
            sortfwdind.innerHTML = ' ▾';
            this.appendChild(sortfwdind);
            return;
          }

          // remove sorttable_sorted classes
          theadrow = this.parentNode;
          Array.prototype.slice.call(theadrow.childNodes).forEach(function(cell) {
            if (cell.nodeType == 1) { // an element
              cell.className = cell.className.replace('sorttable_sorted_reverse','');
              cell.className = cell.className.replace('sorttable_sorted','');
            }
          });
          sortfwdind = document.getElementById('sorttable_sortfwdind');
          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
          sortrevind = document.getElementById('sorttable_sortrevind');
          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }

          this.className += ' sorttable_sorted';
          sortfwdind = document.createElement('span');
          sortfwdind.id = "sorttable_sortfwdind";
          sortfwdind.innerHTML = ' ▾';
          this.appendChild(sortfwdind);

          // build an array to sort. This is a Schwartzian transform thing,
          // i.e., we "decorate" each row with the actual sort key,
          // sort based on the sort keys, and then put the rows back in order
          // which is a lot faster because you only do getCellValue once per row
          row_array = [];
          col = this.sorttable_columnindex;
          rows = this.sorttable_tbody.rows;
          for (var j=0; j<rows.length; j++) {
            row_array[row_array.length] = [sorttable.getCellValue(rows[j].cells[col]), rows[j]];
          }

          row_array.sort(this.sorttable_sortfunction);

          tb = this.sorttable_tbody;
          for (j = 0; j<row_array.length; j++) {
            tb.appendChild(row_array[j][1]);
          }

          delete row_array;
        });
      }
    }
  },

  guessType: function(table, column) {
    var i, sortfn;

    sortfn = sorttable.sortAlpha;

    for (i = 0; i < table.tBodies[0].rows.length; i++) {
      text = sorttable.getCellValue(table.tBodies[0].rows[i].cells[column]);

      if (text !== '' && text.match(sorttable.numberRegExp)) {
        return sorttable.sortNumeric;
      }
    }

    return sortfn;
  },

  getCellValue: function(node) {
    if (!node) return '';

    if (node.getAttribute('data-value') !== null) {
      return node.getAttribute('data-value');
    }

    return node.innerText.replace(/^\s+|\s+$/g, '');
  },

  reverse: function(tbody) {
    // reverse the rows in a tbody
    var i;
    newrows = [];
    for (i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },

  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sortNumeric: function(a,b) {
    var aa = parseFloat(a[0].replace(/[^0-9.-]/g, '')),
        bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''))
    ;
    if (isNaN(aa)) aa = 0;
    if (isNaN(bb)) bb = 0;
    return aa - bb;
  },

  sortAlpha: function(a, b) {
    var aa = a[0].toLowerCase(),
        bb = b[0].toLowerCase()
    ;
    if (aa === bb) return 0;
    if (aa < bb) return -1;
    return 1;
  }
};<|endoftext|>


<commit_before>const FILE = 'FILE'
const EMAIL = 'test@mailjet.com'
const EMAIL2 = 'test2@mailjet.com'
const NAME = 'name'
const SUBJECT = 'subject'
const TEXT_PART = 'text'
const VAR = {'Key1': 'Value1', 'Key2': 'Value2'}
const SIMPLE_RECIPIENTS = [{email: EMAIL}, {email: EMAIL2}]
const UNIQUE_RECIPIENT = [{email: EMAIL}]
const RECIPIENTS_NAME = [{email: EMAIL, name: NAME}, {email: EMAIL2, name: NAME}]
const RECIPIENTS_VARS = [{email: EMAIL, vars: VAR}]
const API_KEY = process.env.MJ_APIKEY_PUBLIC
const API_SECRET = process.env.MJ_APIKEY_PRIVATE

var Mailjet = require('../mailjet-client')
var chai = require('chai')
var expect = chai.expect
var should = chai.should() // eslint-disable-line no-unused-vars
var Promise = require('bluebird')
if (typeof API_KEY === 'undefined' || typeof API_SECRET === 'undefined') {
  throw new Error('Mailjet API_KEY and API_SECRET are required, respectively ' + API_KEY + ' and ' + API_SECRET + ' given ')
}

describe('Basic Usage', function () {
  var client = Mailjet.connect(API_KEY, API_SECRET)

  describe('connection', function () {
    it('creates an instance of the client', function () {
      var connectionType1 = new Mailjet(API_KEY, API_SECRET)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET)

      expect('' + connectionType1.apiKey + connectionType1.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType2.apiKey + connectionType2.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType3.apiKey + connectionType3.apiSecret).to.equal('' + API_KEY + API_SECRET)
    })

    it('creates an instance of the client with options', function () {
      var proxyUrl = 'http://localhost:3128'
      var expectedMembers = { apiKey: API_KEY, apiSecret: API_SECRET, proxyUrl: proxyUrl }

      var connectionType1 = new Mailjet(API_KEY, API_SECRET, { proxyUrl: proxyUrl })
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET, { proxyUrl: proxyUrl })
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET, { proxyUrl: proxyUrl })

      var connections = [connectionType1, connectionType2, connectionType3]
      connections.forEach(function (connection) {
        expect(connection).to.have.property('apiKey', API_KEY)
        expect(connection).to.have.property('apiSecret', API_SECRET)
        expect(connection.options).to.have.property('proxyUrl', proxyUrl)
      })
    })
  })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact ressource instance whith no parameters', function (done) {
        contact.request()
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.equal(200)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
      })

      it('calls the contact ressource instance whith parameters', function (done) {
        var promise = contact.request({Name: 'Guillaume Badi'})
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.be.within(200, 201)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
        expect(Promise.prototype.isPrototypeOf(promise)).to.equal(true)
      })

      it('calls the contact ressource instance with empty parameters', function (done) {
        contact.request({}).then(function (result) {
          result.body.should.be.a('object')
          expect(result.response.statusCode).to.be.within(200, 201)
          done()
        })
      })
    })

    describe('post', function () {
      var sender = client.post('sender')

      it('calls the sender ressource instance whith no parameters', function (done) {
        sender.request().catch(function (reason) {
          reason.statusCode.should.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith invalid parameters', function (done) {
        sender.request({Name: 'Guillaume Badi'}).catch(function (reason) {
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith valid parameters', function (done) {
        sender.request({email: 'gbadi@mailjet.com'})
          .then(function (result) {
            expect(result.response.statusCode).to.equal(201)
            done()
          })
          .catch(function (reason) {
            // if it fails because the sender already exist. should be 400
            expect(reason.statusCode).to.equal(400)
            done()
          })
      })

      it('calls the sender resource with empty parameters', function (done) {
        sender.request({}).catch(function (reason) {
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })
    })
  })
})

describe('Advanced API Calls', function () {
  function Example (fn, payload) {
    this.fn = fn
    this.payload = payload
    this.format = function (obj) { return JSON.stringify(obj).match(/\S+/g).join('') }
    this.call = function () {
      var res = this.fn.request(this.payload)
      var ret = res[0] + ' ' + this.format(res[1])
      return ret
    }
  }

  var client2 = new Mailjet(API_KEY, API_SECRET, null, true)

  const EXAMPLES_SET = [
    new Example(client2.get('contact')),
    new Example(client2.get('contact').id(2)),
    new Example(client2.get('contact/2')),
    new Example(client2.get('contact').id(3).action('getcontactslist')),
    new Example(client2.get('contact'), {countOnly: 1}),
    new Example(client2.get('contact'), {limit: 2}),
    new Example(client2.get('contact'), {offset: 233}),
    new Example(client2.get('contact'), {contatctList: 34}),
    new Example(client2.post('contactslist').id(34).action('managecontact'), {email: EMAIL}),
    new Example(client2.post('contactslist').id(34).action('csvdata'), FILE),
    new Example(client2.get('newsletter'), {filters: {CountOnly: 1}}),
    new Example(client2.get('batchjob').action('csverror')),
    new Example(client2.post('contact'), {email: EMAIL}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': UNIQUE_RECIPIENT}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': SIMPLE_RECIPIENTS}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_NAME}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_VARS})
  ]

  const EXPECTED_SET = [
    'https://api.mailjet.com/v3/REST/contact {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/3/getcontactslist {}',
    'https://api.mailjet.com/v3/REST/contact/?countOnly=1 {}',
    'https://api.mailjet.com/v3/REST/contact/?limit=2 {}',
    'https://api.mailjet.com/v3/REST/contact/?offset=233 {}',
    'https://api.mailjet.com/v3/REST/contact/?contatctList=34 {}',
    'https://api.mailjet.com/v3/REST/contactslist/34/managecontact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/DATA/contactslist/34/csvdata "FILE"',
    'https://api.mailjet.com/v3/REST/newsletter/?CountOnly=1 {}',
    'https://api.mailjet.com/v3/DATA/batchjob/csverror {}',
    'https://api.mailjet.com/v3/REST/contact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"},{"email":"test2@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","name":"name"},{"email":"test2@mailjet.com","name":"name"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","vars":{"Key1":"Value1","Key2":"Value2"}}]}'
  ]

  EXPECTED_SET.forEach(function (test, index) {
    it('should output: ' + test, function () {
      EXAMPLES_SET[index].call().should.equal(test)
    })
  })
})
<commit_msg>Trim client options test case a bit<commit_after>const FILE = 'FILE'
const EMAIL = 'test@mailjet.com'
const EMAIL2 = 'test2@mailjet.com'
const NAME = 'name'
const SUBJECT = 'subject'
const TEXT_PART = 'text'
const VAR = {'Key1': 'Value1', 'Key2': 'Value2'}
const SIMPLE_RECIPIENTS = [{email: EMAIL}, {email: EMAIL2}]
const UNIQUE_RECIPIENT = [{email: EMAIL}]
const RECIPIENTS_NAME = [{email: EMAIL, name: NAME}, {email: EMAIL2, name: NAME}]
const RECIPIENTS_VARS = [{email: EMAIL, vars: VAR}]
const API_KEY = process.env.MJ_APIKEY_PUBLIC
const API_SECRET = process.env.MJ_APIKEY_PRIVATE

var Mailjet = require('../mailjet-client')
var chai = require('chai')
var expect = chai.expect
var should = chai.should() // eslint-disable-line no-unused-vars
var Promise = require('bluebird')
if (typeof API_KEY === 'undefined' || typeof API_SECRET === 'undefined') {
  throw new Error('Mailjet API_KEY and API_SECRET are required, respectively ' + API_KEY + ' and ' + API_SECRET + ' given ')
}

describe('Basic Usage', function () {
  var client = Mailjet.connect(API_KEY, API_SECRET)

  describe('connection', function () {
    it('creates an instance of the client', function () {
      var connectionType1 = new Mailjet(API_KEY, API_SECRET)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET)

      expect('' + connectionType1.apiKey + connectionType1.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType2.apiKey + connectionType2.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType3.apiKey + connectionType3.apiSecret).to.equal('' + API_KEY + API_SECRET)
    })

    it('creates an instance of the client with options', function () {
      var options = { proxyUrl: 'http://localhost:3128' }

      var connectionType1 = new Mailjet(API_KEY, API_SECRET, options)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET, options)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET, options)

      var connections = [connectionType1, connectionType2, connectionType3]
      connections.forEach(function (connection) {
        expect(connection).to.have.property('apiKey', API_KEY)
        expect(connection).to.have.property('apiSecret', API_SECRET)
        expect(connection.options).to.have.property('proxyUrl', options.proxyUrl)
      })
    })
  })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact ressource instance whith no parameters', function (done) {
        contact.request()
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.equal(200)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
      })

      it('calls the contact ressource instance whith parameters', function (done) {
        var promise = contact.request({Name: 'Guillaume Badi'})
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.be.within(200, 201)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
        expect(Promise.prototype.isPrototypeOf(promise)).to.equal(true)
      })

      it('calls the contact ressource instance with empty parameters', function (done) {
        contact.request({}).then(function (result) {
          result.body.should.be.a('object')
          expect(result.response.statusCode).to.be.within(200, 201)
          done()
        })
      })
    })

    describe('post', function () {
      var sender = client.post('sender')

      it('calls the sender ressource instance whith no parameters', function (done) {
        sender.request().catch(function (reason) {
          reason.statusCode.should.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith invalid parameters', function (done) {
        sender.request({Name: 'Guillaume Badi'}).catch(function (reason) {
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith valid parameters', function (done) {
        sender.request({email: 'gbadi@mailjet.com'})
          .then(function (result) {
            expect(result.response.statusCode).to.equal(201)
            done()
          })
          .catch(function (reason) {
            // if it fails because the sender already exist. should be 400
            expect(reason.statusCode).to.equal(400)
            done()
          })
      })

      it('calls the sender resource with empty parameters', function (done) {
        sender.request({}).catch(function (reason) {
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })
    })
  })
})

describe('Advanced API Calls', function () {
  function Example (fn, payload) {
    this.fn = fn
    this.payload = payload
    this.format = function (obj) { return JSON.stringify(obj).match(/\S+/g).join('') }
    this.call = function () {
      var res = this.fn.request(this.payload)
      var ret = res[0] + ' ' + this.format(res[1])
      return ret
    }
  }

  var client2 = new Mailjet(API_KEY, API_SECRET, null, true)

  const EXAMPLES_SET = [
    new Example(client2.get('contact')),
    new Example(client2.get('contact').id(2)),
    new Example(client2.get('contact/2')),
    new Example(client2.get('contact').id(3).action('getcontactslist')),
    new Example(client2.get('contact'), {countOnly: 1}),
    new Example(client2.get('contact'), {limit: 2}),
    new Example(client2.get('contact'), {offset: 233}),
    new Example(client2.get('contact'), {contatctList: 34}),
    new Example(client2.post('contactslist').id(34).action('managecontact'), {email: EMAIL}),
    new Example(client2.post('contactslist').id(34).action('csvdata'), FILE),
    new Example(client2.get('newsletter'), {filters: {CountOnly: 1}}),
    new Example(client2.get('batchjob').action('csverror')),
    new Example(client2.post('contact'), {email: EMAIL}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': UNIQUE_RECIPIENT}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': SIMPLE_RECIPIENTS}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_NAME}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_VARS})
  ]

  const EXPECTED_SET = [
    'https://api.mailjet.com/v3/REST/contact {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/3/getcontactslist {}',
    'https://api.mailjet.com/v3/REST/contact/?countOnly=1 {}',
    'https://api.mailjet.com/v3/REST/contact/?limit=2 {}',
    'https://api.mailjet.com/v3/REST/contact/?offset=233 {}',
    'https://api.mailjet.com/v3/REST/contact/?contatctList=34 {}',
    'https://api.mailjet.com/v3/REST/contactslist/34/managecontact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/DATA/contactslist/34/csvdata "FILE"',
    'https://api.mailjet.com/v3/REST/newsletter/?CountOnly=1 {}',
    'https://api.mailjet.com/v3/DATA/batchjob/csverror {}',
    'https://api.mailjet.com/v3/REST/contact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"},{"email":"test2@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","name":"name"},{"email":"test2@mailjet.com","name":"name"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","vars":{"Key1":"Value1","Key2":"Value2"}}]}'
  ]

  EXPECTED_SET.forEach(function (test, index) {
    it('should output: ' + test, function () {
      EXAMPLES_SET[index].call().should.equal(test)
    })
  })
})
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

class ModuleDependencyTemplateAsRequireId {

	apply(dep, source, outputOptions, requestShortener) {
		if(!dep.range) return;
		let comment = "";
		if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
		let content;
		if(dep.module)
			content = "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")";
		else
			content = require("./WebpackMissingModule").module(dep.request);
		source.replace(dep.range[0], dep.range[1] - 1, content);
	}
}
module.exports = ModuleDependencyTemplateAsRequireId;
<commit_msg>use template strings<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

class ModuleDependencyTemplateAsRequireId {

	apply(dep, source, outputOptions, requestShortener) {
		if(!dep.range) return;
		let comment = "";
		if(outputOptions.pathinfo) comment = `/*! ${requestShortener.shorten(dep.request)} */ `;
		let content;
		if(dep.module)
			content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`;
		else
			content = require("./WebpackMissingModule").module(dep.request);
		source.replace(dep.range[0], dep.range[1] - 1, content);
	}
}
module.exports = ModuleDependencyTemplateAsRequireId;
<|endoftext|>


<commit_before>var sqlite = require('../sqlite');

sqlite.connect('test/test.db');
// sqlite.debug = true;

var res = sqlite.run("CREATE TABLE COMPANYS(ID  INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL);");
console.log(res)

sqlite.run('SELECT * FROM COMPANYS', function(res){
	if(res.error)
		throw (res.error)
	console.log(res)
});

sqlite.close();<commit_msg>Testing transactions<commit_after>var sqlite = require('../sqlite');

sqlite.connect('test/test.db');
// sqlite.debug = true;

var res = sqlite.run("CREATE TABLE COMPANYS(ID  INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL);");

sqlite.insert("COMPANYS",{NAME:"TESTE"}, function(res){

});

sqlite.run("BEGIN; DELETE FROM COMPANYS WHERE ID = 6; ROLLBACK;");

sqlite.run('SELECT * FROM COMPANYS', function(res){
	if(res.error)
		throw (res.error)
	console.log(res)
});

sqlite.close();<|endoftext|>


<commit_before>import fs from 'fs'
import test from 'ava'
import colorFunction from 'postcss-color-function'

import tachyonsBuildCss from '../'

const input = fs.readFileSync('test/fixtures/input.css', 'utf8')
const cssOutput = fs.readFileSync('test/fixtures/output.css', 'utf8')
const cssMinOutput = fs.readFileSync('test/fixtures/output.min.css', 'utf8')
const cssRepeatOutput = fs.readFileSync('test/fixtures/output.repeat.css', 'utf8')
const inputColorFunction = fs.readFileSync('test/fixtures/input_color_function.css', 'utf8')
const cssColorFunctionOutput = fs.readFileSync('test/fixtures/output_color_function.css', 'utf8')

test.cb('processes source code', t => {
  testFixture(t, input, cssOutput)
})

test.cb('processes source code and minifies css', t => {
  testFixture(t, input, cssMinOutput, { minify: true })
})

test.cb('processes source code and repeats classes', t => {
  testFixture(t, input, cssRepeatOutput, { repeat: 4 })
})

test.cb('processes source code with custom plugins', t => {
  testFixture(t, inputColorFunction, cssColorFunctionOutput, { plugins: [colorFunction()] })
})

function testFixture (t, input, output, opts) {
  tachyonsBuildCss(input, opts).then(result => {
    t.deepEqual(result.css.trim(), output.trim())
    t.end()
  })
}
<commit_msg>add tests for getPlugins function<commit_after>import fs from 'fs'
import test from 'ava'
import colorFunction from 'postcss-color-function'

import tachyonsBuildCss, { getPlugins } from '../'

const input = fs.readFileSync('test/fixtures/input.css', 'utf8')
const cssOutput = fs.readFileSync('test/fixtures/output.css', 'utf8')
const cssMinOutput = fs.readFileSync('test/fixtures/output.min.css', 'utf8')
const cssRepeatOutput = fs.readFileSync('test/fixtures/output.repeat.css', 'utf8')
const inputColorFunction = fs.readFileSync('test/fixtures/input_color_function.css', 'utf8')
const cssColorFunctionOutput = fs.readFileSync('test/fixtures/output_color_function.css', 'utf8')

test.cb('processes source code', t => {
  testFixture(t, input, cssOutput)
})

test.cb('processes source code and minifies css', t => {
  testFixture(t, input, cssMinOutput, { minify: true })
})

test.cb('processes source code and repeats classes', t => {
  testFixture(t, input, cssRepeatOutput, { repeat: 4 })
})

test.cb('processes source code with custom plugins', t => {
  testFixture(t, inputColorFunction, cssColorFunctionOutput, { plugins: [colorFunction()] })
})

test.cb('getPlugins returns array of plugins', t => {
  const plugins = getPlugins()

  t.true(Array.isArray(plugins), 'returns an array')
  t.true(plugins.every(plugin => typeof plugin === 'function'), 'all plugins are functions')

  t.end()
})

function testFixture (t, input, output, opts) {
  tachyonsBuildCss(input, opts).then(result => {
    t.deepEqual(result.css.trim(), output.trim())
    t.end()
  })
}
<|endoftext|>


<commit_before>function simpleBar() {
	var data = [{year: 2006, books: 54},
            {year: 2007, books: 43},
            {year: 2008, books: 41},
            {year: 2009, books: 44},
            {year: 2010, books: 35}];

	var barWidth = 40;
	var width = (barWidth + 10) * data.length;
	var height = 200;

	var x = d3.scaleLinear().domain([0, data.length]).range([0, width]);
	var y = d3.scaleLinear().domain([0, d3.max(data, function(datum) { return datum.books; })]).
	  rangeRound([0, height]);

	// add the canvas to the DOM
	var barDemo = d3.select("#example").
	  append("svg:svg").
	  attr("width", width).
	  attr("height", height).
	  attr("style", "display:block; margin:auto;");

	barDemo.selectAll("rect").
	  data(data).
	  enter().
	  append("svg:rect").
	  attr("x", function(datum, index) { return x(index); }).
	  attr("y", function(datum) { return height - y(datum.books); }).
	  attr("height", function(datum) { return y(datum.books); }).
	  attr("width", barWidth).
	  attr("fill", "#2d578b");
};

function interactiveBar() {
	var sales = [
		{ product: 'Hoodie',  count: 7 },
		{ product: 'Jacket',  count: 6 },
		{ product: 'Snuggie', count: 9 },
	];

	var barDemo = d3.select("#interactiveExample").
		append("svg:svg").
		attr("style", "display:block; margin:auto;");

	var rects = barDemo.selectAll("rect")
		.data(sales);

	var newRects = rects.enter();

	// recall that scales are functions that map from
	// data space to screen space
	var maxCount = d3.max(sales, function(d, i) {
	  return d.count;
	});
	var x = d3.scaleLinear()
	  .range([0, 300])
	  .domain([0, maxCount]);
	var y = d3.scaleOrdinal()
	  .rangeRoundBands([0, 75])
	  .domain(sales.map(function(d, i) {
		return d.product;
	  }));

	newRects.append('rect')
	  .attr('x', x(0))
	  .attr('y', function(d, i) {
		return y(d.product);
	  })
	  .attr('height', y.rangeBand())
	  .attr('width', function(d, i) {
		return x(d.count);
	  });
};

function pageSVGSetup() {
	simpleBar();
	interactiveBar();
};

window.onload = pageSVGSetup;<commit_msg>d3 4.0 update to rangeRoundBands<commit_after>function simpleBar() {
	var data = [{year: 2006, books: 54},
            {year: 2007, books: 43},
            {year: 2008, books: 41},
            {year: 2009, books: 44},
            {year: 2010, books: 35}];

	var barWidth = 40;
	var width = (barWidth + 10) * data.length;
	var height = 200;

	var x = d3.scaleLinear().domain([0, data.length]).range([0, width]);
	var y = d3.scaleLinear().domain([0, d3.max(data, function(datum) { return datum.books; })]).
	  rangeRound([0, height]);

	// add the canvas to the DOM
	var barDemo = d3.select("#example").
	  append("svg:svg").
	  attr("width", width).
	  attr("height", height).
	  attr("style", "display:block; margin:auto;");

	barDemo.selectAll("rect").
	  data(data).
	  enter().
	  append("svg:rect").
	  attr("x", function(datum, index) { return x(index); }).
	  attr("y", function(datum) { return height - y(datum.books); }).
	  attr("height", function(datum) { return y(datum.books); }).
	  attr("width", barWidth).
	  attr("fill", "#2d578b");
};

function interactiveBar() {
	var sales = [
		{ product: 'Hoodie',  count: 7 },
		{ product: 'Jacket',  count: 6 },
		{ product: 'Snuggie', count: 9 },
	];

	var barDemo = d3.select("#interactiveExample").
		append("svg:svg").
		attr("style", "display:block; margin:auto;");

	var rects = barDemo.selectAll("rect")
		.data(sales);

	var newRects = rects.enter();

	// recall that scales are functions that map from
	// data space to screen space
	var maxCount = d3.max(sales, function(d, i) {
	  return d.count;
	});
	var x = d3.scaleLinear()
	  .range([0, 300])
	  .domain([0, maxCount]);
	var y = d3.scaleBand()
	  .rangeRound([0, 75])
	  .domain(sales.map(function(d, i) {
		return d.product;
	  }));

	newRects.append('rect')
	  .attr('x', x(0))
	  .attr('y', function(d, i) {
		return y(d.product);
	  })
	  .attr('height', y.rangeBand())
	  .attr('width', function(d, i) {
		return x(d.count);
	  });
};

function pageSVGSetup() {
	simpleBar();
	interactiveBar();
};

window.onload = pageSVGSetup;<|endoftext|>


<commit_before>describe('dom', function() {
  describe('isCorrectSoundCloudURL', function() {
    it('should return false when soundcloud url is incorrect', function() {
      expect(dom.util.isCorrectSoundCloudURL('test')).to.be.false;
    });
    it('should return true when soundcloud url is correct', function() {
      expect(dom.util.isCorrectSoundCloudURL('https://soundcloud.com/swindail/turbine-blue-swindail-remix')).to.be.true;
    });
  });

  describe('query', function() {
    it('should return correct "HTMLElement" when call query function with className selector', function() {
      expect(dom.query('.layer__title').outerHTML).to.equal('
 This browser is not supported
');
    });
  });

  describe('toogle', function() {
    it('className should "ctrgroup" when first call toggle function with "ctrgroup--hidden"', function() {
      dom.util.toggle(dom.query('.ctrgroup'), 'ctrgroup--hidden');
      expect(dom.query('.ctrgroup').className).to.equal('ctrgroup');
    });
  });
});

describe('sound and sona', function() {
  var soundcloud = sound(dom.query('.ctrgroup__player__audio'));
  describe('sound_init', function() {
    it('have to exist audio analyser when init sound.js', function() {
      expect(soundcloud.analyser).to.be.exist;
    });
  });
  describe('play', function() {
    it('should play audio when call soundcloud play function', function() {
      var stream_url = "https://api.soundcloud.com/tracks/293573440/stream?client_id=802c2f1c80c96881ff265799929e8a2c";
      soundcloud.play(stream_url);
      expect(!dom.query('.ctrgroup__player__audio').paused).to.be.true;
    });
  });
  describe('sona_init', function() {
    it('have to exist fgCanvas when init sona.js', function() {
      var option = {
        'analyser' : soundcloud.analyser,
        'canvas': dom.query('.visualPanel')
      };
      sona.init(option);
      expect(dom.query('.fgCanvas')).to.be.exist;
    });
  });
  describe('drawAlbumImg', function() {
    it('should set tag of img tag when call drawAlbumImg with imgurl', function() {
      var imgUrl = "https://i1.sndcdn.com/artworks-000194108151-qw9zbv-large.jpg";
      sona.drawAlbumImg(imgUrl);
      expect(dom.query('.imgCanvas').src).to.equal(imgUrl);
    });
  });
  //TODO search test
  // describe('search', function() {
  //   it('should get error message when call soundcloud search function with soundcloud forbidden url', function(done) {
  //     var trackUrl = "https://soundcloud.com/lukasgraham/mama-said";
  //   });
  // });
});
<commit_msg>fix: travis.yml<commit_after>var audioContext = new AudioContext();
describe('dom', function() {
  describe('isCorrectSoundCloudURL', function() {
    it('should return false when soundcloud url is incorrect', function() {
      expect(dom.util.isCorrectSoundCloudURL('test')).to.be.false;
    });
    it('should return true when soundcloud url is correct', function() {
      expect(dom.util.isCorrectSoundCloudURL('https://soundcloud.com/swindail/turbine-blue-swindail-remix')).to.be.true;
    });
  });

  describe('query', function() {
    it('should return correct "HTMLElement" when call query function with className selector', function() {
      expect(dom.query('.layer__title').outerHTML).to.equal('
 This browser is not supported
');
    });
  });

  describe('toogle', function() {
    it('className should "ctrgroup" when first call toggle function with "ctrgroup--hidden"', function() {
      dom.util.toggle(dom.query('.ctrgroup'), 'ctrgroup--hidden');
      expect(dom.query('.ctrgroup').className).to.equal('ctrgroup');
    });
  });
});

describe('sound and sona', function() {
  var soundcloud = sound(dom.query('.ctrgroup__player__audio'));
  describe('sound_init', function() {
    it('have to exist audio analyser when init sound.js', function() {
      expect(soundcloud.analyser).to.be.exist;
    });
  });
  describe('play', function() {
    it('should play audio when call soundcloud play function', function() {
      var stream_url = "https://api.soundcloud.com/tracks/293573440/stream?client_id=802c2f1c80c96881ff265799929e8a2c";
      soundcloud.play(stream_url);
      expect(!dom.query('.ctrgroup__player__audio').paused).to.be.true;
    });
  });
  describe('sona_init', function() {
    it('have to exist fgCanvas when init sona.js', function() {
      var option = {
        'analyser' : soundcloud.analyser,
        'canvas': dom.query('.visualPanel')
      };
      sona.init(option);
      expect(dom.query('.fgCanvas')).to.be.exist;
    });
  });
  describe('drawAlbumImg', function() {
    it('should set tag of img tag when call drawAlbumImg with imgurl', function() {
      var imgUrl = "https://i1.sndcdn.com/artworks-000194108151-qw9zbv-large.jpg";
      sona.drawAlbumImg(imgUrl);
      expect(dom.query('.imgCanvas').src).to.equal(imgUrl);
    });
  });
  //TODO search test
  // describe('search', function() {
  //   it('should get error message when call soundcloud search function with soundcloud forbidden url', function(done) {
  //     var trackUrl = "https://soundcloud.com/lukasgraham/mama-said";
  //   });
  // });
});
<|endoftext|>


<commit_before>function changeFontSize(newSize)
{
    document.getElementById("singlentry").style.fontSize = newSize + "px";
}<commit_msg>Not used any more<commit_after><|endoftext|>


<commit_before>var test = require("tape")
var perm = require("permutation-rank")
var invPerm = require("invert-permutation")
var dup = require("dup")
var ndarray = require("../ndarray.js")

test("ndarray", function(t) {

  var p = ndarray(new Float32Array([1,2,3,4]), [2,2])
  t.equals(p.shape.length, 2)
  t.equals(p.shape[0], 2)
  t.equals(p.shape[1], 2)
  t.equals(p.stride[0], 2)
  t.equals(p.stride[1], 1)

  t.end()
})

test("order", function(t) {
  t.same(ndarray([0]).pick(0).order, [])
  var f = 1
  for(var d=1; d<=5; ++d) {
    f *= d
    for(var r=0; r<f; ++r) {
      var p = perm.unrank(d, r)
      var x = ndarray([1], dup(f), p)
      t.same(x.order, invPerm(p.slice(0)), x.stride.join(","))
    }
  }
  t.end()
})

test("pick", function(t) {

  var x = ndarray(new Float32Array(25), [5, 5])

  x.set(0, 0, 1)
  x.set(4, 0, 5)
  x.set(0, 4, 10)

  var y = x.pick(0)
  t.equals(y.get(0), 1)
  t.equals(y.get(1), 0)
  t.equals(y.get(2), 0)
  t.equals(y.get(3), 0)
  t.equals(y.get(4), 10)
  t.equals(y.shape.join(","), "5")

  y = x.pick(-1, 0)
  t.equals(y.get(0), 1)
  t.equals(y.get(1), 0)
  t.equals(y.get(2), 0)
  t.equals(y.get(3), 0)
  t.equals(y.get(4), 5)
  t.equals(y.shape.join(","), "5")

  t.end()
})

test("accessor", function(t) {
  for(var d=1; d<5; ++d) {
    var shape = new Array(d)
    for(var i=0; i<d; ++i) {
      shape[i] = 3
    }
    var x = ndarray(new Float32Array(1000), shape)
    x.set(1,1,1,1,1,1,1,1,1)
    t.equals(x.get(1,1,1,1,1,1,1), 1, "get/set array d=" + d)

    var array1D = ndarray(new Int8Array(1000))
    var x = ndarray(array1D, shape)
    x.set(1,1,1,1,1,1,1,1,1)
    t.equals(x.get(1,1,1,1,1,1,1), 1, "get/set generic d=" + d)
  }

  t.end()
})

test("size", function(t) {
  var x = ndarray(new Float32Array(100), [2, 3, 5])
  t.equals(x.size, 2*3*5)
  t.equals(x.pick(0,0,0).size, 0)
  for(var d=1; d<5; ++d) {
    var x = ndarray(new Float32Array(256), dup(d,2))
    t.equals(x.size, 1<<d, "size d="+d)
  }
  t.end()
})

test("lo", function(t) {

  var x = ndarray(new Float32Array(9), [3, 3])
    , y = x.lo(1, 2)
  t.equals(y.shape.join(","), "2,1")
  t.equals(y.stride.join(","), x.stride.join(","))
  t.equals(y.offset, 3+2)

  y.set(0, 0, 1)
  t.equals(x.get(1, 2), 1)

  t.end()
})

test("hi", function(t) {
  var x = ndarray(new Float32Array(9), [3, 3])
    , y = x.hi(1, 2)
  t.equals(y.shape.join(","), "1,2")
  t.equals(y.stride.join(","), x.stride.join(","))
  t.equals(y.offset, 0)

  y.set(0, 1, 1)
  t.equals(x.get(0, 1), 1)

  t.end()
})<commit_msg>added test cases for step()<commit_after>var test = require("tape")
var perm = require("permutation-rank")
var invPerm = require("invert-permutation")
var dup = require("dup")
var ndarray = require("../ndarray.js")

test("ndarray", function(t) {

  var p = ndarray(new Float32Array([1,2,3,4]), [2,2])
  t.equals(p.shape.length, 2)
  t.equals(p.shape[0], 2)
  t.equals(p.shape[1], 2)
  t.equals(p.stride[0], 2)
  t.equals(p.stride[1], 1)

  t.end()
})

test("order", function(t) {
  t.same(ndarray([0]).pick(0).order, [])
  var f = 1
  for(var d=1; d<=5; ++d) {
    f *= d
    for(var r=0; r<f; ++r) {
      var p = perm.unrank(d, r)
      var x = ndarray([1], dup(f), p)
      t.same(x.order, invPerm(p.slice(0)), x.stride.join(","))
    }
  }
  t.end()
})

test("pick", function(t) {

  var x = ndarray(new Float32Array(25), [5, 5])

  x.set(0, 0, 1)
  x.set(4, 0, 5)
  x.set(0, 4, 10)

  var y = x.pick(0)
  t.equals(y.get(0), 1)
  t.equals(y.get(1), 0)
  t.equals(y.get(2), 0)
  t.equals(y.get(3), 0)
  t.equals(y.get(4), 10)
  t.equals(y.shape.join(","), "5")

  y = x.pick(-1, 0)
  t.equals(y.get(0), 1)
  t.equals(y.get(1), 0)
  t.equals(y.get(2), 0)
  t.equals(y.get(3), 0)
  t.equals(y.get(4), 5)
  t.equals(y.shape.join(","), "5")

  t.end()
})

test("accessor", function(t) {
  for(var d=1; d<5; ++d) {
    var shape = new Array(d)
    for(var i=0; i<d; ++i) {
      shape[i] = 3
    }
    var x = ndarray(new Float32Array(1000), shape)
    x.set(1,1,1,1,1,1,1,1,1)
    t.equals(x.get(1,1,1,1,1,1,1), 1, "get/set array d=" + d)

    var array1D = ndarray(new Int8Array(1000))
    var x = ndarray(array1D, shape)
    x.set(1,1,1,1,1,1,1,1,1)
    t.equals(x.get(1,1,1,1,1,1,1), 1, "get/set generic d=" + d)
  }

  t.end()
})

test("size", function(t) {
  var x = ndarray(new Float32Array(100), [2, 3, 5])
  t.equals(x.size, 2*3*5)
  t.equals(x.pick(0,0,0).size, 0)
  for(var d=1; d<5; ++d) {
    var x = ndarray(new Float32Array(256), dup(d,2))
    t.equals(x.size, 1<<d, "size d="+d)
  }
  t.end()
})

test("lo", function(t) {

  var x = ndarray(new Float32Array(9), [3, 3])
    , y = x.lo(1, 2)
  t.equals(y.shape.join(","), "2,1")
  t.equals(y.stride.join(","), x.stride.join(","))
  t.equals(y.offset, 3+2)

  y.set(0, 0, 1)
  t.equals(x.get(1, 2), 1)

  t.end()
})

test("hi", function(t) {
  var x = ndarray(new Float32Array(9), [3, 3])
    , y = x.hi(1, 2)
  t.equals(y.shape.join(","), "1,2")
  t.equals(y.stride.join(","), x.stride.join(","))
  t.equals(y.offset, 0)

  y.set(0, 1, 1)
  t.equals(x.get(0, 1), 1)

  t.end()
})

test("step", function(t) {

  var x = ndarray(new Float32Array(10))
  for(var i=0; i<10; ++i) {
    x.set(i, i)
  }

  var y = x.step(-1)
  for(var i=0; i<10; ++i) {
    t.equals(y.get(i), (9-i))
  }

  var z = y.step(-1)
  for(var i=0; i<10; ++i) {
    t.equals(z.get(i), i)
  }

  var w = x.step(2)
  t.equals(w.shape[0], 5)
  for(var i=0; i<5; ++i) {
    t.equals(w.get(i), 2*i)
  }

  t.end()
})<|endoftext|>


<commit_before>var util             = require('util'),
    AbstractGeocoder = require('./abstractgeocoder');

/**
 * Constructor
 * @param <object> httpAdapter Http Adapter
 * @param <object> options     Options (language, clientId, apiKey)
 */
var YandexGeocoder = function YandexGeocoder(httpAdapter, options) {

    YandexGeocoder.super_.call(this, httpAdapter, options);
};

util.inherits(YandexGeocoder, AbstractGeocoder);

var _findKey = function(result, wantedKey) {
    var val = null;
    Object.keys(result).every(function(key) {

        if (key === wantedKey) {
            val = result[key];
            return false;
        }

        if (typeof result[key] === 'object') {
            val = _findKey(result[key], wantedKey);

            return val === null ? true : false;
        }

        return true;
    });
    console.log(val);
    return val;
};

var _formatResult = function(result) {
    var position = result.GeoObject.Point.pos.split(' ');
    result = result.GeoObject.metaDataProperty.GeocoderMetaData.AddressDetails;

    return {
        'latitude' : position[0],
        'longitude' : position[1],
        'city' : _findKey(result, 'LocalityName'),
        'state' : _findKey(result, 'AdministrativeAreaName'),
        'streetName': _findKey(result, 'ThoroughfareName'),
        'streetNumber' : _findKey(result, 'PremiseNumber'),
        'countryCode' : _findKey(result, 'CountryNameCode'),
        'country' : _findKey(result, 'CountryName')
    };
};

// Yandex geocoding API endpoint
YandexGeocoder.prototype._endpoint = 'https://geocode-maps.yandex.ru/1.x/';

/**
* Geocode
* @param <string>   value    Value to geocode (Address)
* @param <function> callback Callback method
*/
YandexGeocoder.prototype._geocode = function(value, callback) {
    var params = {
        geocode : value,
        format: 'json'
    };

    if (this.options.language) {
        params.lang = this.options.language;
    }

    this.httpAdapter.get(this._endpoint, params, function(err, result) {
        if (err) {
            return callback(err);
        } else {
            var results = [];

            result.response.GeoObjectCollection.featureMember.forEach(function(geopoint) {
                results.push(_formatResult(geopoint));
            });

            results.raw = result;
            callback(false, results);
        }
    });
};

module.exports = YandexGeocoder;
<commit_msg>remove console.log in yandex geocoder<commit_after>var util             = require('util'),
    AbstractGeocoder = require('./abstractgeocoder');

/**
 * Constructor
 * @param <object> httpAdapter Http Adapter
 * @param <object> options     Options (language, clientId, apiKey)
 */
var YandexGeocoder = function YandexGeocoder(httpAdapter, options) {

    YandexGeocoder.super_.call(this, httpAdapter, options);
};

util.inherits(YandexGeocoder, AbstractGeocoder);

var _findKey = function(result, wantedKey) {
    var val = null;
    Object.keys(result).every(function(key) {

        if (key === wantedKey) {
            val = result[key];
            return false;
        }

        if (typeof result[key] === 'object') {
            val = _findKey(result[key], wantedKey);

            return val === null ? true : false;
        }

        return true;
    });

    return val;
};

var _formatResult = function(result) {
    var position = result.GeoObject.Point.pos.split(' ');
    result = result.GeoObject.metaDataProperty.GeocoderMetaData.AddressDetails;

    return {
        'latitude' : position[0],
        'longitude' : position[1],
        'city' : _findKey(result, 'LocalityName'),
        'state' : _findKey(result, 'AdministrativeAreaName'),
        'streetName': _findKey(result, 'ThoroughfareName'),
        'streetNumber' : _findKey(result, 'PremiseNumber'),
        'countryCode' : _findKey(result, 'CountryNameCode'),
        'country' : _findKey(result, 'CountryName')
    };
};

// Yandex geocoding API endpoint
YandexGeocoder.prototype._endpoint = 'https://geocode-maps.yandex.ru/1.x/';

/**
* Geocode
* @param <string>   value    Value to geocode (Address)
* @param <function> callback Callback method
*/
YandexGeocoder.prototype._geocode = function(value, callback) {
    var params = {
        geocode : value,
        format: 'json'
    };

    if (this.options.language) {
        params.lang = this.options.language;
    }

    this.httpAdapter.get(this._endpoint, params, function(err, result) {
        if (err) {
            return callback(err);
        } else {
            var results = [];

            result.response.GeoObjectCollection.featureMember.forEach(function(geopoint) {
                results.push(_formatResult(geopoint));
            });

            results.raw = result;
            callback(false, results);
        }
    });
};

module.exports = YandexGeocoder;
<|endoftext|>