<commit_before>/**
 * Contains the objects that are used for Muut Latest Comments widget.
 * Version 1.0
 * Requires jQuery
 *
 * Copyright (c) 2014 Moot, Inc.
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 */

jQuery(document).ready(function($) {

  // Once Muut is loaded...
  muutObj().on('load', function() {
    // Set the latest comments wrapper object.

    var widget_latest_comments_wrapper = $('#muut-widget-latest-comments-wrapper');

    var widget_latest_comments_current_list_elements = $(widget_latest_comments_wrapper).find('.muut_recentcomments');

    var widget_latest_comments_num_showing = widget_latest_comments_current_list_elements.length;

    var muut_comments_root_path = muutObj().path + '/' + muut_latest_comments_path;

    // Init all of the facelink functionality (tooltips and such).
    widget_latest_comments_wrapper.facelinkinit();

    // Get new results from the server.
    var muut_poll_wordpress_cache = function( timeout ) {
      setTimeout( function() {
        jQuery.ajax({
          url: muut_latest_comments_request_endpoint,
          async: false,
          cache: false,
          dataType: 'json',
          success: function(data) {
            var old_data = muut_latest_comments_json;
            muut_latest_comments_json = data;
            widget_latest_comments_wrapper.trigger('json_update', [ muut_latest_comments_json, old_data ] );
            if ( timeout >= 1000 ) {
              muut_poll_wordpress_cache( timeout );
            }
          }
        });
      }, timeout);
    };

    // Check to update the timestamps every minute.
    var update_time_displays = function() {
      setTimeout( function() {
        if ( Date.now() - last_update < 60000 ) {
          widget_latest_comments_current_list_elements = $(widget_latest_comments_current_list_elements.selector);
        }
        widget_latest_comments_current_list_elements.each(function(index, element) {
          var difference_timestamp = Date.now() - ( muut_latest_comments_json.latest_comments_posts[index].timestamp * 1000 );
          var new_display_time = muut_time_format( difference_timestamp );
          $(this).find('.muut-post-time-since').text(new_display_time);
        });
        update_time_displays();
      }, 60000);
    };
    var last_update = Date.now();
    update_time_displays();

    // Find out if a thread path is a WP Post commenting path.
    // Return the WP post id on success, or false on failure.
    var muut_is_wp_commenting_thread = function(path) {
      // The commenting base path.
      var path_post_id_re = new RegExp( muut_comments_root_path + '/([0-9]+)');
      // If the string lines up with the commenting base path.
      if(path.search(muut_comments_root_path) != -1) {
        // Do the regular expression comparison to get the WP Post id the path references.
        matches = path_post_id_re.exec(path);
        if ( matches && typeof matches[1] != 'undefined' ) {
          return parseInt(matches[1]);;
        }
      }
      return false;
    };

    // Get the array of currently locally cached WP *post ids* (in same order as they are stored).
    var muut_get_cached_post_ids = function() {
      var current_post_ids = [];
      for (i = 0; i < muut_latest_comments_json.latest_comments_posts.length; i++) {
        current_post_ids.push(muut_latest_comments_json.latest_comments_posts[i].post_id);
      }
      return current_post_ids;
    };

    // Check if a given post id is already stored locally, and if so what the index is in the locally cached array.
    // Return the index OR -1 if there is no match.
    var muut_post_id_is_cached_locally = function(post_id){
      var current_post_ids = muut_get_cached_post_ids();
      return $.inArray(post_id, current_post_ids);;
    };

    // If we are going to poll the server for new posts...
    // The poll time must be greater than 1 second (1000 milliseconds).
    if ( muut_latest_comments_poll_time >= 1000 ) {
      // Poll the WP server to get the new JSON for the widget every <timeout> seconds.
      muut_poll_wordpress_cache( muut_latest_comments_poll_time );
    } else {
      // When a reply event comes through the websocket.
      muutRpc.on('reply', function( path, reply_object ) {
        var post_id = muut_is_wp_commenting_thread(path);
        if (post_id != 'false') {
          var new_data = $.extend(true,{},muut_latest_comments_json);
          var index_match = muut_post_id_is_cached_locally(post_id);
          if ( index_match >= 0 ) {
            var post_data = new_data.latest_comments_posts[index_match];
            new_object = {
              post_id: post_id,
              post_permalink: post_data.post_permalink,
              post_title: post_data.post_title,
              timestamp: Math.floor(Date.now() / 1000).toString(),
              user: {
                displayname: reply_object.user.displayname,
                img: reply_object.user.img,
                path: reply_object.user.path
              }
            };
            new_data.latest_comments_posts.splice( index_match, 1 );
            new_data.latest_comments_posts.unshift(new_object);
            widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
          } else {
            setTimeout( function() {
                muut_poll_wordpress_cache(0);
              }, 4000
            );
          }
        }
      });

      muutRpc.on('post', function( location, post_object ) {
        // If the path shows that it is a comment on a post...
        var post_id = muut_is_wp_commenting_thread(location.path);
        if (post_id != 'false') {
          var new_data = $.extend(true,{},muut_latest_comments_json);
          var index_match = muut_post_id_is_cached_locally(post_id);
          if ( index_match >= 0 ) {
            var post_data = new_data.latest_comments_posts[index_match];
            new_object = {
              post_id: post_id,
              post_permalink: post_data.post_permalink,
              post_title: post_data.post_title,
              timestamp: Math.floor(Date.now() / 1000).toString(),
              user: {
                displayname: post_object.user.displayname,
                img: post_object.user.img,
                path: post_object.user.path
              }
            };
            new_data.latest_comments_posts.splice( index_match, 1 );
            new_data.latest_comments_posts.unshift(new_object);
            widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
          } else {
            setTimeout( function() {
                muut_poll_wordpress_cache(0);
              }, 4000
            );
          }
        }
      });

      muutRpc.on('send', function(event, object) {
        if ( ( event == 'reply' || event == 'createMoot' ) && typeof object[0] != 'undefined' && typeof muut_wp_post_id != 'undefined' ) {
          if(muut_is_wp_commenting_thread(object[0].path)) {
            var new_data = $.extend(true,{},muut_latest_comments_json);
            var current_post_ids = [];
            for (i = 0; i < muut_latest_comments_json.latest_comments_posts.length; i++) {
              current_post_ids.push(muut_latest_comments_json.latest_comments_posts[i].post_id);
            }
            var index_match = muut_post_id_is_cached_locally(muut_wp_post_id);
            if ( index_match >= 0 ) {
              new_data.latest_comments_posts.splice( index_match, 1 );
            } else if (new_data.latest_comments_posts.length == 10 )  {
              new_data.latest_comments_posts.splice( 9, 1 );
            }
            new_object = {
              post_id: muut_wp_post_id,
              post_permalink: muut_wp_post_permalink,
              post_title: muut_wp_post_title,
              timestamp: Math.floor(Date.now() / 1000).toString(),
              user: {
                displayname: muutObj().user.displayname,
                img: muutObj().user.img,
                path: muutObj().user.path
              }
            };
            new_data.latest_comments_posts.unshift(new_object);
            widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
          }
        }
      });
    }

    // Listen for the json_update event so that we can compare data and act accordingly.
    widget_latest_comments_wrapper.on('json_update', function( event, new_obj, old_obj ) {
      last_update = Date.now();
      widget_latest_comments_num_showing = widget_latest_comments_current_list_elements.length;
      muut_latest_comments_json = new_obj;
      new_obj = new_obj.latest_comments_posts;
      old_obj = old_obj.latest_comments_posts;
      var new_post_ids = [];
      for (i = 0; i < new_obj.length; i++) {
        new_post_ids.push(new_obj[i].post_id);
      }
      var num_new_items = false;
      var post_ids_to_delete = [];
      for(i = 0; i < widget_latest_comments_num_showing; i++) {
        var index_match = $.inArray(old_obj[i].post_id, new_post_ids);
        var old_string = JSON.stringify(old_obj[i]);
        var new_string = JSON.stringify(new_obj[index_match]);

        // If there is a match and it is identical to the old one, we know that the list has new items above it, but
        // it remains the top relating to the "old list".
        if(index_match >= 0 && old_string == new_string && num_new_items === false){
          num_new_items = index_match;
          // If there is a match, but it is different, then the element has had a new post. Continue to the next one to
        // see if it should be functioning as the new "top of previous list" item.
        } else if(index_match >= 0 && old_string != new_string) {
          post_ids_to_delete.push(old_obj[i].post_id);
        // If there is no post id match, that means ALL elements have been replaced by the new list.
        // Skip the rest of the loop.
        } else if (index_match == '-1' && num_new_items == 0){
          num_new_items = old_obj.length;
          break;
        }
      }

      // Delete the posts that are being replaced by updates to them (i.e. being moved to the top).
      for(i = 0; i < post_ids_to_delete.length; i++) {
        widget_latest_comments_wrapper.find('.muut_recentcomments[data-post-id="' + post_ids_to_delete[i] + '"]').remove();
      }
      // Refresh the current list of items and get figure out how many to remove from the bottom.
      widget_latest_comments_num_showing = widget_latest_comments_num_showing - post_ids_to_delete.length;
      var difference_count_from_new_items = muut_latest_comments_num_posts - num_new_items;
      for(i = 0; i < widget_latest_comments_num_showing - difference_count_from_new_items; i++) {
        $(widget_latest_comments_current_list_elements.get(-1)).remove();
      }

      // Generate the HTML for the new elements and prepend it to the list.
      var new_item_html = '';
      for(i = 0; i < num_new_items; i++) {
        // Get the pretty timestamp.
        var timestamp = Date.now() - (new_obj[i].timestamp * 1000);
        var list_time = muut_time_format( timestamp );
        // Generate the HTML.
        new_item_html += muut_latest_comments_row_template.replace(/%USER_PATH%/g, new_obj[i].user.path)
          .replace(/%USER_DISPLAYNAME%/g, new_obj[i].user.displayname)
          .replace(/%USER_IMAGEURL%/g, new_obj[i].user.img)
          .replace(/%POSTID%/g, new_obj[i].post_id)
          .replace(/%TIMESTAMP%/g, timestamp)
          .replace(/%LISTTIME%/g, list_time)
          .replace(/%POST_PERMALINK%/g, new_obj[i].post_permalink)
          .replace(/%POST_TITLE%/g, new_obj[i].post_title);
      }
      // Append the HTML.
      $('#muut-recentcomments').prepend(new_item_html).facelinkinit();
    });
  });
});
<commit_msg>Run check to make sure the Latest Comments widget exists on a page before executing JS.<commit_after>/**
 * Contains the objects that are used for Muut Latest Comments widget.
 * Version 1.0
 * Requires jQuery
 *
 * Copyright (c) 2014 Moot, Inc.
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 */

jQuery(document).ready(function($) {

  // Once Muut is loaded...
  muutObj().on('load', function() {
    // Set the latest comments wrapper object.

    var widget_latest_comments_wrapper = $('#muut-widget-latest-comments-wrapper');

    // If the widget exists...
    if ( widget_latest_comments_wrapper.length > 0 ) {

      var widget_latest_comments_current_list_elements = $(widget_latest_comments_wrapper).find('.muut_recentcomments');

      var widget_latest_comments_num_showing = widget_latest_comments_current_list_elements.length;

      var muut_comments_root_path = muutObj().path + '/' + muut_latest_comments_path;

      // Init all of the facelink functionality (tooltips and such).
      widget_latest_comments_wrapper.facelinkinit();

      // Get new results from the server.
      var muut_poll_wordpress_cache = function( timeout ) {
        setTimeout( function() {
          jQuery.ajax({
            url: muut_latest_comments_request_endpoint,
            async: false,
            cache: false,
            dataType: 'json',
            success: function(data) {
              var old_data = muut_latest_comments_json;
              muut_latest_comments_json = data;
              widget_latest_comments_wrapper.trigger('json_update', [ muut_latest_comments_json, old_data ] );
              if ( timeout >= 1000 ) {
                muut_poll_wordpress_cache( timeout );
              }
            }
          });
        }, timeout);
      };

      // Check to update the timestamps every minute.
      var update_time_displays = function() {
        setTimeout( function() {
          if ( Date.now() - last_update < 60000 ) {
            widget_latest_comments_current_list_elements = $(widget_latest_comments_current_list_elements.selector);
          }
          widget_latest_comments_current_list_elements.each(function(index, element) {
            var difference_timestamp = Date.now() - ( muut_latest_comments_json.latest_comments_posts[index].timestamp * 1000 );
            var new_display_time = muut_time_format( difference_timestamp );
            $(this).find('.muut-post-time-since').text(new_display_time);
          });
          update_time_displays();
        }, 60000);
      };
      var last_update = Date.now();
      update_time_displays();

      // Find out if a thread path is a WP Post commenting path.
      // Return the WP post id on success, or false on failure.
      var muut_is_wp_commenting_thread = function(path) {
        // The commenting base path.
        var path_post_id_re = new RegExp( muut_comments_root_path + '/([0-9]+)');
        // If the string lines up with the commenting base path.
        if(path.search(muut_comments_root_path) != -1) {
          // Do the regular expression comparison to get the WP Post id the path references.
          matches = path_post_id_re.exec(path);
          if ( matches && typeof matches[1] != 'undefined' ) {
            return parseInt(matches[1]);;
          }
        }
        return false;
      };

      // Get the array of currently locally cached WP *post ids* (in same order as they are stored).
      var muut_get_cached_post_ids = function() {
        var current_post_ids = [];
        for (i = 0; i < muut_latest_comments_json.latest_comments_posts.length; i++) {
          current_post_ids.push(muut_latest_comments_json.latest_comments_posts[i].post_id);
        }
        return current_post_ids;
      };

      // Check if a given post id is already stored locally, and if so what the index is in the locally cached array.
      // Return the index OR -1 if there is no match.
      var muut_post_id_is_cached_locally = function(post_id){
        var current_post_ids = muut_get_cached_post_ids();
        return $.inArray(post_id, current_post_ids);;
      };

      // If we are going to poll the server for new posts...
      // The poll time must be greater than 1 second (1000 milliseconds).
      if ( muut_latest_comments_poll_time >= 1000 ) {
        // Poll the WP server to get the new JSON for the widget every <timeout> seconds.
        muut_poll_wordpress_cache( muut_latest_comments_poll_time );
      } else {
        // When a reply event comes through the websocket.
        muutRpc.on('reply', function( path, reply_object ) {
          var post_id = muut_is_wp_commenting_thread(path);
          if (post_id != 'false') {
            var new_data = $.extend(true,{},muut_latest_comments_json);
            var index_match = muut_post_id_is_cached_locally(post_id);
            if ( index_match >= 0 ) {
              var post_data = new_data.latest_comments_posts[index_match];
              new_object = {
                post_id: post_id,
                post_permalink: post_data.post_permalink,
                post_title: post_data.post_title,
                timestamp: Math.floor(Date.now() / 1000).toString(),
                user: {
                  displayname: reply_object.user.displayname,
                  img: reply_object.user.img,
                  path: reply_object.user.path
                }
              };
              new_data.latest_comments_posts.splice( index_match, 1 );
              new_data.latest_comments_posts.unshift(new_object);
              widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
            } else {
              setTimeout( function() {
                  muut_poll_wordpress_cache(0);
                }, 4000
              );
            }
          }
        });

        muutRpc.on('post', function( location, post_object ) {
          // If the path shows that it is a comment on a post...
          var post_id = muut_is_wp_commenting_thread(location.path);
          if (post_id != 'false') {
            var new_data = $.extend(true,{},muut_latest_comments_json);
            var index_match = muut_post_id_is_cached_locally(post_id);
            if ( index_match >= 0 ) {
              var post_data = new_data.latest_comments_posts[index_match];
              new_object = {
                post_id: post_id,
                post_permalink: post_data.post_permalink,
                post_title: post_data.post_title,
                timestamp: Math.floor(Date.now() / 1000).toString(),
                user: {
                  displayname: post_object.user.displayname,
                  img: post_object.user.img,
                  path: post_object.user.path
                }
              };
              new_data.latest_comments_posts.splice( index_match, 1 );
              new_data.latest_comments_posts.unshift(new_object);
              widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
            } else {
              setTimeout( function() {
                  muut_poll_wordpress_cache(0);
                }, 4000
              );
            }
          }
        });

        muutRpc.on('send', function(event, object) {
          if ( ( event == 'reply' || event == 'createMoot' ) && typeof object[0] != 'undefined' && typeof muut_wp_post_id != 'undefined' ) {
            if(muut_is_wp_commenting_thread(object[0].path)) {
              var new_data = $.extend(true,{},muut_latest_comments_json);
              var current_post_ids = [];
              for (i = 0; i < muut_latest_comments_json.latest_comments_posts.length; i++) {
                current_post_ids.push(muut_latest_comments_json.latest_comments_posts[i].post_id);
              }
              var index_match = muut_post_id_is_cached_locally(muut_wp_post_id);
              if ( index_match >= 0 ) {
                new_data.latest_comments_posts.splice( index_match, 1 );
              } else if (new_data.latest_comments_posts.length == 10 )  {
                new_data.latest_comments_posts.splice( 9, 1 );
              }
              new_object = {
                post_id: muut_wp_post_id,
                post_permalink: muut_wp_post_permalink,
                post_title: muut_wp_post_title,
                timestamp: Math.floor(Date.now() / 1000).toString(),
                user: {
                  displayname: muutObj().user.displayname,
                  img: muutObj().user.img,
                  path: muutObj().user.path
                }
              };
              new_data.latest_comments_posts.unshift(new_object);
              widget_latest_comments_wrapper.trigger('json_update', [ new_data, muut_latest_comments_json ] );
            }
          }
        });
      }

      // Listen for the json_update event so that we can compare data and act accordingly.
      widget_latest_comments_wrapper.on('json_update', function( event, new_obj, old_obj ) {
        last_update = Date.now();
        widget_latest_comments_num_showing = widget_latest_comments_current_list_elements.length;
        muut_latest_comments_json = new_obj;
        new_obj = new_obj.latest_comments_posts;
        old_obj = old_obj.latest_comments_posts;
        var new_post_ids = [];
        for (i = 0; i < new_obj.length; i++) {
          new_post_ids.push(new_obj[i].post_id);
        }
        var num_new_items = false;
        var post_ids_to_delete = [];
        for(i = 0; i < widget_latest_comments_num_showing; i++) {
          var index_match = $.inArray(old_obj[i].post_id, new_post_ids);
          var old_string = JSON.stringify(old_obj[i]);
          var new_string = JSON.stringify(new_obj[index_match]);

          // If there is a match and it is identical to the old one, we know that the list has new items above it, but
          // it remains the top relating to the "old list".
          if(index_match >= 0 && old_string == new_string && num_new_items === false){
            num_new_items = index_match;
            // If there is a match, but it is different, then the element has had a new post. Continue to the next one to
          // see if it should be functioning as the new "top of previous list" item.
          } else if(index_match >= 0 && old_string != new_string) {
            post_ids_to_delete.push(old_obj[i].post_id);
          // If there is no post id match, that means ALL elements have been replaced by the new list.
          // Skip the rest of the loop.
          } else if (index_match == '-1' && num_new_items == 0){
            num_new_items = old_obj.length;
            break;
          }
        }

        // Delete the posts that are being replaced by updates to them (i.e. being moved to the top).
        for(i = 0; i < post_ids_to_delete.length; i++) {
          widget_latest_comments_wrapper.find('.muut_recentcomments[data-post-id="' + post_ids_to_delete[i] + '"]').remove();
        }
        // Refresh the current list of items and get figure out how many to remove from the bottom.
        widget_latest_comments_num_showing = widget_latest_comments_num_showing - post_ids_to_delete.length;
        var difference_count_from_new_items = muut_latest_comments_num_posts - num_new_items;
        for(i = 0; i < widget_latest_comments_num_showing - difference_count_from_new_items; i++) {
          $(widget_latest_comments_current_list_elements.get(-1)).remove();
        }

        // Generate the HTML for the new elements and prepend it to the list.
        var new_item_html = '';
        for(i = 0; i < num_new_items; i++) {
          // Get the pretty timestamp.
          var timestamp = Date.now() - (new_obj[i].timestamp * 1000);
          var list_time = muut_time_format( timestamp );
          // Generate the HTML.
          new_item_html += muut_latest_comments_row_template.replace(/%USER_PATH%/g, new_obj[i].user.path)
            .replace(/%USER_DISPLAYNAME%/g, new_obj[i].user.displayname)
            .replace(/%USER_IMAGEURL%/g, new_obj[i].user.img)
            .replace(/%POSTID%/g, new_obj[i].post_id)
            .replace(/%TIMESTAMP%/g, timestamp)
            .replace(/%LISTTIME%/g, list_time)
            .replace(/%POST_PERMALINK%/g, new_obj[i].post_permalink)
            .replace(/%POST_TITLE%/g, new_obj[i].post_title);
        }
        // Append the HTML.
        $('#muut-recentcomments').prepend(new_item_html).facelinkinit();
      });
    }
  });
});
<|endoftext|>


<commit_before>// Lots of code from http://jsfromhell.com/classes/binary-parser
//    Jonas Raoni Soares Silva
//    http://jsfromhell.com/classes/binary-parser [v1.0]

var END_OF_SEQUENCE = '\xa5\x00\x00\x00';
var START_OF_SEQUENCE = '\x5a\x00\x00\x00';

function dapUnpacker(xdrdata, dapvar) {
    this._buf = xdrdata;
    this.dapvar = dapvar;

    this._pos = 0;

    this.getValue = function() {
        var i = this._pos;
        var type = this.dapvar.type.toLowerCase();

        if (this._buf.substr(i, 4) == END_OF_SEQUENCE) {
            return [];
        } else if (this._buf.substr(i, 4) == START_OF_SEQUENCE) {
            var mark = this._unpack_uint32();
            var out = [], tmp;
            //while (mark != 2768240640) {
            while (mark != 4244635648) {
                tmp = this.getValue();
                out.push(tmp);
                mark = this._unpack_uint32();
            }
            return out;
        } else if (type == 'structure' || type == 'dataset' || type == 'sequence') {
            var out = [], tmp;
            dapvar = this.dapvar;
            for (child in dapvar) {
                if (dapvar[child].type) {
                    this.dapvar = dapvar[child];
                    tmp = this.getValue();
                    out.push(tmp);
                }
            }
            this.dapvar = dapvar;
            return out;
        } else if (type == 'grid') {
            var out = [], tmp;
            dapvar = this.dapvar;

            this.dapvar = dapvar.array;
            tmp = this.getValue();
            out.push(tmp);

            for (map in dapvar.maps) {
                this.dapvar = dapvar.maps[map];
                tmp = this.getValue();
                out.push(tmp);
            }

            this.dapvar = dapvar;
            return out;
        }

        var n = 1;
        if (this.dapvar.shape.length) {
            n = this._unpack_uint32();
            if (type != 'url' && type != 'string') {
                this._unpack_uint32();
            }
        }

        // Bytes?
        var out;
        if (type == 'byte') {
            out = this._unpack_bytes(n);
        // String?
        } else if (type == 'url' || type == 'string') {
            out = this._unpack_string(n);
        } else {
            out = [];
            var func;
            switch (type) {
                case 'float32': func = '_unpack_float32'; break;
                case 'float64': func = '_unpack_float64'; break;
                case 'int'    : func = '_unpack_int32'; break;
                case 'uint'   : func = '_unpack_uint32'; break;
                case 'int16'  : func = '_unpack_int16'; break;
                case 'uint16' : func = '_unpack_uint16'; break;
                case 'int32'  : func = '_unpack_int32'; break;
                case 'uint32' : func = '_unpack_uint32'; break;
            }
            for (var i=0; i<n; i++) {
                out.push(this[func]());
            }
        }

        if (this.dapvar.shape) {
            out = reshape(out, this.dapvar.shape);
        } else {
            out = out[0];
        }

        return out;
    }

    this._unpack_byte = function() {
        var bytes = 1;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_uint16 = function() {
        var bytes = 4;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_uint32 = function() {
        var bytes = 4;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_int16 = function() {
        var bytes = 4;
        var signed = true;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_int32 = function() {
        var bytes = 4;
        var signed = true;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_float32 = function() {
        var precision = 23;
        var exponent = 8;
        var bytes = 4;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeFloat(data, precision, exponent);
    }

    this._unpack_float64 = function() {
        var precision = 52;
        var exponent = 11;
        var bytes = 8;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeFloat(data, precision, exponent);
    }

    this._unpack_bytes = function(count) {
        var i = this._pos;
        var out = [];
        for (var c=0; c<count; c++) {
            out.push(this._unpack_byte());
        }
        var padding = (4 - (n % 4)) % 4;
        this._pos = i + n + padding;

        return out
    }

    this._unpack_string = function(count) {
        var out = [];
        var n, i, j;
        for (var c=0; c<count; c++) {
            n = this._unpack_uint32();
            i = this._pos;
            data = this._buf.substr(i, n);

            padding = (4 - (n % 4)) % 4;
            this._pos = i + n + padding;

            out.push(data);
        }

        return out;
    }
}

function reshape(array, shape) {
    if (!shape.length) return array[0];
    var out = [];
    var size, start, stop;
    for (var i=0; i<shape[0]; i++) {
        size = array.length / shape[0];
        start = i * size;
        stop = start + size;
        out.push(reshape(array.slice(start, stop), shape.slice(1)));
    }
    return out;
}

function shl(a, b){
    for(++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
    return a;
}

function readBits(buffer, start, length) {
    if (start < 0 || length <= 0) return 0;

    for(var offsetLeft, offsetRight = start % 8, curByte = buffer.length - (start >> 3) - 1,
        lastByte = buffer.length + (-(start + length) >> 3), diff = curByte - lastByte,
        sum = ((buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1))
        + (diff && (offsetLeft = (start + length) % 8) ? (buffer[ lastByte++ ] & ((1 << offsetLeft) - 1))
        << (diff-- << 3) - offsetRight : 0); diff; sum += shl(buffer[ lastByte++ ], (diff-- << 3) - offsetRight));
    return sum;
}

function getBuffer(data) {
    var b = new Array(data.length);
    for (var i=0; i<data.length; i++) {
        b[i] = data.charCodeAt(i) & 0xff;;
    }
    if (!b.length) throw new Error("stop!");
    return b;
}

function decodeInt(data, bytes, signed) {
    var x = readBits(getBuffer(data), 0, bytes*8);
    var max = Math.pow(2, bytes*8);
    var int;
    if (signed && x >= (max / 2)) {
        int = x - max;
    } else {
        int = x;
    }
    return int;
}

function decodeFloat(data, precisionBits, exponentBits) {
    var buffer = getBuffer(data);

    var bias = Math.pow(2, exponentBits - 1) - 1;
    var signal = readBits(buffer, precisionBits + exponentBits, 1);
    var exponent = readBits(buffer, precisionBits, exponentBits);
    var significand = 0;
    var divisor = 2;
    var curByte = buffer.length + (-precisionBits >> 3) - 1;
    var byteValue, startBit, mask;

    do
        for(byteValue = buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit;
            mask >>= 1; (byteValue & mask) && (significand += 1 / divisor), divisor *= 2);
    while (precisionBits -= startBit);

    return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
        : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
        : Math.pow(2, exponent - bias) * (1 + significand) : 0);
}
<commit_msg>Working! :-D<commit_after>// Lots of code from http://jsfromhell.com/classes/binary-parser
//    Jonas Raoni Soares Silva
//    http://jsfromhell.com/classes/binary-parser [v1.0]

var END_OF_SEQUENCE = '\xa5\x00\x00\x00';
var START_OF_SEQUENCE = '\x5a\x00\x00\x00';

function dapUnpacker(xdrdata, dapvar) {
    this._buf = xdrdata;
    this.dapvar = dapvar;

    this._pos = 0;

    this.getValue = function() {
        var i = this._pos;
        var type = this.dapvar.type.toLowerCase();

        if (this._buf.substr(i, 4) == END_OF_SEQUENCE) {
            return [];
        } else if (this._buf.substr(i, 4) == START_OF_SEQUENCE) {
            var mark = this._unpack_uint32();
            var out = [], tmp;
            while (mark != 2768240640) {
                tmp = this.getValue();
                out.push(tmp);
                mark = this._unpack_uint32();
            }
            return out;
        } else if (type == 'structure' || type == 'dataset' || type == 'sequence') {
            var out = [], tmp;
            dapvar = this.dapvar;
            for (child in dapvar) {
                if (dapvar[child].type) {
                    this.dapvar = dapvar[child];
                    tmp = this.getValue();
                    out.push(tmp);
                }
            }
            this.dapvar = dapvar;
            return out;
        } else if (type == 'grid') {
            var out = [], tmp;
            dapvar = this.dapvar;

            this.dapvar = dapvar.array;
            tmp = this.getValue();
            out.push(tmp);

            for (map in dapvar.maps) {
                this.dapvar = dapvar.maps[map];
                tmp = this.getValue();
                out.push(tmp);
            }

            this.dapvar = dapvar;
            return out;
        }

        var n = 1;
        if (this.dapvar.shape.length) {
            n = this._unpack_uint32();
            if (type != 'url' && type != 'string') {
                this._unpack_uint32();
            }
        }

        // Bytes?
        var out;
        if (type == 'byte') {
            out = this._unpack_bytes(n);
        // String?
        } else if (type == 'url' || type == 'string') {
            out = this._unpack_string(n);
        } else {
            out = [];
            var func;
            switch (type) {
                case 'float32': func = '_unpack_float32'; break;
                case 'float64': func = '_unpack_float64'; break;
                case 'int'    : func = '_unpack_int32'; break;
                case 'uint'   : func = '_unpack_uint32'; break;
                case 'int16'  : func = '_unpack_int16'; break;
                case 'uint16' : func = '_unpack_uint16'; break;
                case 'int32'  : func = '_unpack_int32'; break;
                case 'uint32' : func = '_unpack_uint32'; break;
            }
            for (var i=0; i<n; i++) {
                out.push(this[func]());
            }
        }

        if (this.dapvar.shape) {
            out = reshape(out, this.dapvar.shape);
        } else {
            out = out[0];
        }

        return out;
    }

    this._unpack_byte = function() {
        var bytes = 1;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_uint16 = function() {
        var bytes = 4;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_uint32 = function() {
        var bytes = 4;
        var signed = false;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_int16 = function() {
        var bytes = 4;
        var signed = true;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_int32 = function() {
        var bytes = 4;
        var signed = true;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeInt(data, bytes, signed);
    }

    this._unpack_float32 = function() {
        var precision = 23;
        var exponent = 8;
        var bytes = 4;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeFloat(data, precision, exponent);
    }

    this._unpack_float64 = function() {
        var precision = 52;
        var exponent = 11;
        var bytes = 8;

        var i = this._pos;
        this._pos = i+bytes;
        data = this._buf.substr(i, bytes);
        return decodeFloat(data, precision, exponent);
    }

    this._unpack_bytes = function(count) {
        var i = this._pos;
        var out = [];
        for (var c=0; c<count; c++) {
            out.push(this._unpack_byte());
        }
        var padding = (4 - (n % 4)) % 4;
        this._pos = i + n + padding;

        return out
    }

    this._unpack_string = function(count) {
        var out = [];
        var n, i, j;
        for (var c=0; c<count; c++) {
            n = this._unpack_uint32();
            i = this._pos;
            data = this._buf.substr(i, n);

            padding = (4 - (n % 4)) % 4;
            this._pos = i + n + padding;

            out.push(data);
        }

        return out;
    }
}

function reshape(array, shape) {
    if (!shape.length) return array[0];
    var out = [];
    var size, start, stop;
    for (var i=0; i<shape[0]; i++) {
        size = array.length / shape[0];
        start = i * size;
        stop = start + size;
        out.push(reshape(array.slice(start, stop), shape.slice(1)));
    }
    return out;
}

function shl(a, b){
    for(++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
    return a;
}

function readBits(buffer, start, length) {
    if (start < 0 || length <= 0) return 0;

    for(var offsetLeft, offsetRight = start % 8, curByte = buffer.length - (start >> 3) - 1,
        lastByte = buffer.length + (-(start + length) >> 3), diff = curByte - lastByte,
        sum = ((buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1))
        + (diff && (offsetLeft = (start + length) % 8) ? (buffer[ lastByte++ ] & ((1 << offsetLeft) - 1))
        << (diff-- << 3) - offsetRight : 0); diff; sum += shl(buffer[ lastByte++ ], (diff-- << 3) - offsetRight));
    return sum;
}

function getBuffer(data) {
    var b = new Array(data.length);
    for (var i=0; i<data.length; i++) {
        b[i] = data.charCodeAt(i) & 0xff;;
    }
    return b;
}

function decodeInt(data, bytes, signed) {
    var x = readBits(getBuffer(data), 0, bytes*8);
    var max = Math.pow(2, bytes*8);
    var int;
    if (signed && x >= (max / 2)) {
        int = x - max;
    } else {
        int = x;
    }
    return int;
}

function decodeFloat(data, precisionBits, exponentBits) {
    var buffer = getBuffer(data);

    var bias = Math.pow(2, exponentBits - 1) - 1;
    var signal = readBits(buffer, precisionBits + exponentBits, 1);
    var exponent = readBits(buffer, precisionBits, exponentBits);
    var significand = 0;
    var divisor = 2;
    var curByte = buffer.length + (-precisionBits >> 3) - 1;
    var byteValue, startBit, mask;

    do
        for(byteValue = buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit;
            mask >>= 1; (byteValue & mask) && (significand += 1 / divisor), divisor *= 2);
    while (precisionBits -= startBit);

    return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
        : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
        : Math.pow(2, exponent - bias) * (1 + significand) : 0);
}
<|endoftext|>


<commit_before>"use strict";

var expect = require("expect.js"),
    rewire = require("rewire");

var Response = require("../../../../../lib/server/request/Response.class.js");
var Request = require("../../../../../lib/server/request/Request.class.js");

describe("httpAdapter", function(){

    afterEach(function() {
        rewire.reset();
    });

    var httpAdapter = rewire("../../../../../lib/server/transport/http/middleware/httpAdapter.js", false);

    it("should hand the request on to the httpAdapter if everything is alright", function (done) {

        var dummyData = { "da" : "ta" };

        var req = {
            "url" : "http://mydomain.com/services/blogpost",
            headers : [],
            parsedURL : {
                pathname : "/services/blogpost"
            },
            method : "PUT",
            body : dummyData,
            getSession : function() {
                return { "sessionData" : "blabla" };
            }
        };

        var res = {
            headers : [],
            write : function(data, encoding) {
                expect(data).to.contain(JSON.stringify(dummyData));
                expect(encoding).to.be("utf-8");
            },
            writeHead : function() {

            },
            end : function() {
                done();
            }
        };

        httpAdapter.__set__("handleRequest", function(aReq, callback) {

            var aRes = new Response();
            aRes.setData({ "da" : "ta"});
            aRes.setStatus("success");

            callback(null, aReq, aRes);
        });

        /*
        httpAdapter.__set__("Request", function(method, path, data){
            expect(method).to.be("update");
            expect(path).to.be("/services/blogpost");
            expect(data).to.be(dummyData);
        });
        */

        httpAdapter.__set__("Request", Request);

        httpAdapter(req, res, function(err) {
            if(err !== null){
                //this case should not happen
                done(err);
            }
        });
    });

    it("should next with an error if the request could not be converted", function (done) {

        var req = {
            "url" : "http://mydomain.com/services/blogpost",
            headers : [],
            parsedURL : {
                pathname : "/services/blogpost"
            },
            method : "BLA",
            body : { "bla" : "bla" }
        };

        var res = {
            headers : [],
            write : function() {
            },
            end : function() {
                done(new Error("This path should not be reached"));
            }
        };

        httpAdapter.__set__("Request", function(){
            throw new Error("Wrong params");
        });

        httpAdapter(req, res, function(err) {
            expect(err).to.be.an("object");
            done();
        });
    });
});<commit_msg>- removed rewire.reset() as this is no longer supported<commit_after>"use strict";

var expect = require("expect.js"),
    rewire = require("rewire");

var Response = require("../../../../../lib/server/request/Response.class.js");
var Request = require("../../../../../lib/server/request/Request.class.js");

describe("httpAdapter", function(){

    var httpAdapter = rewire("../../../../../lib/server/transport/http/middleware/httpAdapter.js", false);

    it("should hand the request on to the httpAdapter if everything is alright", function (done) {

        var dummyData = { "da" : "ta" };

        var req = {
            "url" : "http://mydomain.com/services/blogpost",
            headers : [],
            parsedURL : {
                pathname : "/services/blogpost"
            },
            method : "PUT",
            body : dummyData,
            getSession : function() {
                return { "sessionData" : "blabla" };
            }
        };

        var res = {
            headers : [],
            write : function(data, encoding) {
                expect(data).to.contain(JSON.stringify(dummyData));
                expect(encoding).to.be("utf-8");
            },
            writeHead : function() {

            },
            end : function() {
                done();
            }
        };

        httpAdapter.__set__("handleRequest", function(aReq, callback) {

            var aRes = new Response();
            aRes.setData({ "da" : "ta"});
            aRes.setStatus("success");

            callback(null, aReq, aRes);
        });

        /*
        httpAdapter.__set__("Request", function(method, path, data){
            expect(method).to.be("update");
            expect(path).to.be("/services/blogpost");
            expect(data).to.be(dummyData);
        });
        */

        httpAdapter.__set__("Request", Request);

        httpAdapter(req, res, function(err) {
            if(err !== null){
                //this case should not happen
                done(err);
            }
        });
    });

    it("should next with an error if the request could not be converted", function (done) {

        var req = {
            "url" : "http://mydomain.com/services/blogpost",
            headers : [],
            parsedURL : {
                pathname : "/services/blogpost"
            },
            method : "BLA",
            body : { "bla" : "bla" }
        };

        var res = {
            headers : [],
            write : function() {
            },
            end : function() {
                done(new Error("This path should not be reached"));
            }
        };

        httpAdapter.__set__("Request", function(){
            throw new Error("Wrong params");
        });

        httpAdapter(req, res, function(err) {
            expect(err).to.be.an("object");
            done();
        });
    });
});<|endoftext|>


<commit_before>/**
 * @fileOverview Main test
 */
var Promise = require('bluebird');
var chai = require('chai');
var expect = chai.expect;

var idify = require('../..');

describe('Idify Main', function() {
  var testIdify;
  beforeEach(function(done) {
    testIdify = idify({
      prefix: 'test',
      name: 'test',
    });
    testIdify.connect().then(done.bind(null, null), done);
  });

  it('Will create a unique id', function(done) {
    testIdify.get().then(function(id) {
      expect(id).to.be.a('string');
      expect(id).to.have.length(5);
    }).then(done, done);
  });
});
<commit_msg>add test for uri connection<commit_after>/**
 * @fileOverview Main test
 */
var Promise = require('bluebird');
var chai = require('chai');
var expect = chai.expect;

var idify = require('../..');

describe('Idify Main', function() {
  var testIdify;
  beforeEach(function(done) {
    testIdify = idify({
      prefix: 'test',
      name: 'test',
    });
    testIdify.connect().then(done.bind(null, null), done);
  });

  it('Will create a unique id', function(done) {
    testIdify.get().then(function(id) {
      expect(id).to.be.a('string');
      expect(id).to.have.length(5);
    }).then(done, done);
  });
});

describe('Connection', function() {
  var testIdify;
  it('Will establish connection successfully using a URI', function(done) {
    testIdify = idify({
      prefix: 'test',
      name: 'test',
      redis: {
        uri: 'redis://localhost:6379',
      },
    });
    testIdify.connect().then(done.bind(null, null), done);
  });
});
<|endoftext|>


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

describe('nblog', function() {
  describe('#init()', function() {
    var params = {
      dev: {
        user: 'user',
        pass: 'password',
        port: '3001',
        db:   'mongodb://localhost/test'
      }
    };
    params.prod = params.dev;

    it('should initialise the app without an error', function(done) {
      nblog.init(params);
      done();
    });
  });

  describe('#data()', function() {
    var prefs;
    beforeEach(function() {
      prefs = {
        settings: {
          name: 'name',
          description: 'desc',
          keywords: 'keywords',
        }
      };
    });

    it('should build a data object using prefs as defaults', function(done) {
      var c = {
        field: 'field'
      };
      // var data = nblog.data(prefs, false, c);
      // console.log(data);
      // data.should.be.a('object');
      // data.should.have.property('title', 'name');
      // data.should.have.property('description', 'desc');
      // data.should.have.property('keywords', 'keywords');
      // data.should.have.property('loggedin', false);
      // data.should.have.property('field', 'field');
      done();
    });

    // it('should build a data object overiding title', function(done) {
    //   var c = {
    //     title: 'title'
    //   };
    //   var data = nblog.data(prefs, false, c);
    //   data.should.be.a('object');
    //   data.should.have.property('title', 'title');
    //   done();
    // });
  });

});
<commit_msg>Test for nblog.js<commit_after>var nblog = require('../../lib/nblog'),
    server = require('../../lib/server');

describe('nblog', function() {
  describe('when initialising the app', function() {
    var params = {
      dev: {
        user: 'user',
        pass: 'password',
        port: '3001',
        db:   'mongodb://localhost/test'
      }
    };
    params.prod = params.dev;

    it('should initialise the app without an error', function(done) {
      nblog.init(params);
      done();
    });
  });

  describe('when logged in should proceed to next function', function() {
    beforeEach(function() {
      spyOn(server, 'checkLoggedIn').andReturn(true);
      next = jasmine.createSpy('next');
      var data = nblog.checkAccess(null, null, next);
    });

    it('should build a data object using prefs as defaults', function(done) {
      expect(next).toHaveBeenCalled();
      done();
    });
  });

  describe('when not logged in should redirect to login page', function() {
    beforeEach(function() {
      spyOn(server, 'checkLoggedIn').andReturn(false);
      res = {
        redirect: function(value) {}
      };
      spyOn(res, 'redirect');
      var data = nblog.checkAccess(null, res, null);
    });

    it('should build a data object using prefs as defaults', function(done) {
      expect(res.redirect).toHaveBeenCalledWith('/login');
      done();
    });
  });

});
<|endoftext|>


<commit_before>function extractRegExp(r) {
    return {
        source: r.source,
        global: r.global,
        multiline: r.multiline,
        ignoreCase: r.ignoreCase
    };
}

function compareRegExp(a, b) {
    expect(extractRegExp(a)).to.be.eql(extractRegExp(b));
}

// ----------------------------------------------------------------------------------------------------------------- //

describe('router: new route parsing method', function() {

    beforeEach(function() {
        ns.router.init();
    });

    afterEach(function() {
        delete ns.router._routes;
        delete ns.router.routes;
    });

    describe('parse parameter', function() {
        var _tests = {
            'param':            { name: 'param', type: 'id', default_value: undefined, is_optional: false },
            'param=':           { name: 'param', type: 'id', default_value: '', is_optional: true },
            'param:int':        { name: 'param', type: 'int', default_value: undefined, is_optional: false },
            'param=:int':       { name: 'param', type: 'int', default_value: '', is_optional: true },
            'param=value':      { name: 'param', type: 'id', default_value: 'value', is_optional: true },
            'param=value:int':  { name: 'param', type: 'int', default_value: 'value', is_optional: true },
            'param==':          { throw: /^\[ns\.router\] Parameter 'param' value must be specified$/ },
            'param==:int':      { throw: /^\[ns\.router\] Parameter 'param' value must be specified$/ },
            'param==value':     { name: 'param', type: 'id', default_value: 'value', is_optional: false },
            'param==value:int': { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            'param==123:int':   { name: 'param', type: 'int', default_value: '123', is_optional: false }
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._parseParam(test); }).to.throwError(result.throw);
                    } else {
                        expect(ns.router._parseParam(test)).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('generate parameter regexp', function() {
        // 'id': '[A-Za-z_][A-Za-z0-9_-]*',
        // 'int': '[0-9]+'

        var _tests = {
            'param':                 '([A-Za-z_][A-Za-z0-9_-]*)',
            'param=':                '(?:([A-Za-z_][A-Za-z0-9_-]*))?',
            'param:int':             '([0-9]+)',
            'param=:int':            '(?:([0-9]+))?',
            'param=value':           '(?:([A-Za-z_][A-Za-z0-9_-]*))?',
            'param=value:int':       '(?:([0-9]+))?',
            'param:new-type':        { throw: /^\[ns\.router\] Could not find regexp for type 'new\-type'!$/ },
            'param==value':          '(value)',
            'param==123:int':        '(123)',
            'param==value:int':      { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            'param==value:new-type': { throw: /^\[ns\.router\] Could not find regexp for type 'new\-type'!$/ },
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._generateParamRegexp(ns.router._parseParam(test)); }).to.throwError(result.throw);
                    } else {
                        expect(ns.router._generateParamRegexp(ns.router._parseParam(test))).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('parse section', function() {
        var _tests = {
            'static':                     { is_optional: false, items: [ { default_value: 'static' } ]  },
            '{param}':                    { is_optional: false, items: [ { name: 'param', type: 'id', default_value: undefined, is_optional: false } ] },
            '{param=}':                   { is_optional: true, items: [ { name: 'param', type: 'id', default_value: '', is_optional: true } ] },
            '{param:int}':                { is_optional: false, items: [ { name: 'param', type: 'int', default_value: undefined, is_optional: false } ] },
            '{param=:int}':               { is_optional: true, items: [ { name: 'param', type: 'int', default_value: '', is_optional: true } ] },
            '{param=value}':              { is_optional: true, items: [ { name: 'param', type: 'id', default_value: 'value', is_optional: true } ] },
            '{param=value:int}':          { is_optional: true, items: [ { name: 'param', type: 'int', default_value: 'value', is_optional: true } ] },
            '{param==value:int}':         { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            '{param==123:int}':           { is_optional: false, items: [ { name: 'param', type: 'int', default_value: '123', is_optional: false } ] },
            'prefix-{param:int}':         { is_optional: false, items: [ { default_value: 'prefix-' }, { name: 'param', type: 'int', default_value: undefined, is_optional: false } ] },
            'prefix-{part1:int}{part2=}': {
                is_optional: false,
                items: [
                    { default_value: 'prefix-' },
                    { name: 'part1', type: 'int', default_value: undefined, is_optional: false },
                    { name: 'part2', type: 'id', default_value: '', is_optional: true },
                ]
            },
            'some{thing': { throw: /^\[ns\.router\] could not parse parameter in url section: some{thing$/ }
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._parseSection(test); }).to.throwError(result);
                    } else {
                        expect(ns.router._parseSection(test)).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('generate section regexp', function() {
        var _tests = {
            '{param}':            '/([A-Za-z_][A-Za-z0-9_-]*)',
            '{param:int}':        '/([0-9]+)',
            '{param=value:int}':  '(?:/(?!/)(?:([0-9]+))?)?',
            '{param==value}':     '/(value)',
            '{param==123:int}':   '/(123)'
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    expect( ns.router._generateSectionRegexp( ns.router._parseSection(test) )).to.be(_tests[test] );
                });
            })(test);
        }
    });

    describe('complex url 1', function() {
        it('/{context=contest}/{contest-id:int}/users/{author-login}/album/', function() {
            var route = '/{context=contest}/{contest-id:int}/users/{author-login}/album/';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^(?:/(?!/)(?:([A-Za-z_][A-Za-z0-9_-]*))?)?/([0-9]+)/users/([A-Za-z_][A-Za-z0-9_-]*)/album/?(?:\\?(.*))?$') );
        });
    });

    describe('complex url 2', function() {
        it('/{context=}/users/{login}/view/{id:int}', function() {
            var route = '/{context=}/users/{login}/view/{id:int}';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^(?:/(?!/)(?:([A-Za-z_][A-Za-z0-9_-]*))?)?/users/([A-Za-z_][A-Za-z0-9_-]*)/view/([0-9]+)/?(?:\\?(.*))?$') );
        });
    });

    describe('complex url 3', function() {
        it('/message/{id=:int}', function() {
            var route = '/message/{id=:int}';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^/message(?:/(?!/)(?:([0-9]+))?)?/?(?:\\?(.*))?$') ); // TODO проверить, что не получится 2 слеша на конце
        });
    });

    describe('ns.router.generateUrl()', function() {
        beforeEach(function() {
            ns.router.routes = {
                route: {
                    '/{context==search}/{query}/image/{id:int}': 'view',
                    '/{context==tag}/{tag}/image/{id:int}': 'view',
                    '/{context==top}/image/{id:int}': 'view',
                    '/test/{id}': 'test'
                }
            };
            ns.router.init();
        });

        afterEach(function() {
            ns.router.undefine();
        });

        var _tests = [
            {
                name: 'should throw error for unknown route',
                id: 'test-no-such-route',
                params: {},
                result: { throw: /^\[ns\.router\] Could not find route with id 'test-no-such-route'!$/ }
            },
            {
                name: 'should throw error when not enough params',
                id: 'test',
                params: {},
                result: { throw: /^\[ns\.router\] Could not generate url for layout id 'test'!$/ }
            },
            {
                name: 'generate route for parameter with filter 1',
                id: 'view',
                params: { context: 'top', id: 1 },
                result: '/top/image/1'
            },
            {
                name: 'generate route for parameter with filter 2',
                id: 'view',
                params: { context: 'search', query: 'airport', id: 2 },
                result: '/search/airport/image/2'
            },
            {
                name: 'generate route for parameter with filter 3',
                id: 'view',
                params: { context: 'tag', tag: 'summer', id: 3 },
                result: '/tag/summer/image/3'
            }
        ];

        for (var i = 0; i < _tests.length; i++) {
            (function(test) {
                it(test.name, function() {
                    if (test.result.throw) {
                        expect(function() { ns.router.generateUrl(test.id, test.params); }).to.throwError(test.result.throw);
                    } else {
                        expect(ns.router.generateUrl(test.id, test.params)).to.be.eql(test.result);
                    }
                });
            })(_tests[i]);
        }
    });

    // describe('ns.router.compare()', function() {
    //     // does not throw exceptoin when cannot generate url
    //     // ignore query

    // })

});
<commit_msg>one more little test<commit_after>function extractRegExp(r) {
    return {
        source: r.source,
        global: r.global,
        multiline: r.multiline,
        ignoreCase: r.ignoreCase
    };
}

function compareRegExp(a, b) {
    expect(extractRegExp(a)).to.be.eql(extractRegExp(b));
}

// ----------------------------------------------------------------------------------------------------------------- //

describe('router: new route parsing method', function() {

    beforeEach(function() {
        ns.router.init();
    });

    afterEach(function() {
        delete ns.router._routes;
        delete ns.router.routes;
    });

    describe('parse parameter', function() {
        var _tests = {
            'param':            { name: 'param', type: 'id', default_value: undefined, is_optional: false },
            'param=':           { name: 'param', type: 'id', default_value: '', is_optional: true },
            'param:int':        { name: 'param', type: 'int', default_value: undefined, is_optional: false },
            'param=:int':       { name: 'param', type: 'int', default_value: '', is_optional: true },
            'param=value':      { name: 'param', type: 'id', default_value: 'value', is_optional: true },
            'param=value:int':  { name: 'param', type: 'int', default_value: 'value', is_optional: true },
            'param==':          { throw: /^\[ns\.router\] Parameter 'param' value must be specified$/ },
            'param==:int':      { throw: /^\[ns\.router\] Parameter 'param' value must be specified$/ },
            'param==value':     { name: 'param', type: 'id', default_value: 'value', is_optional: false },
            'param==value:int': { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            'param==123:int':   { name: 'param', type: 'int', default_value: '123', is_optional: false }
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._parseParam(test); }).to.throwError(result.throw);
                    } else {
                        expect(ns.router._parseParam(test)).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('generate parameter regexp', function() {
        // 'id': '[A-Za-z_][A-Za-z0-9_-]*',
        // 'int': '[0-9]+'

        var _tests = {
            'param':                 '([A-Za-z_][A-Za-z0-9_-]*)',
            'param=':                '(?:([A-Za-z_][A-Za-z0-9_-]*))?',
            'param:int':             '([0-9]+)',
            'param=:int':            '(?:([0-9]+))?',
            'param=value':           '(?:([A-Za-z_][A-Za-z0-9_-]*))?',
            'param=value:int':       '(?:([0-9]+))?',
            'param:new-type':        { throw: /^\[ns\.router\] Could not find regexp for type 'new\-type'!$/ },
            'param==value':          '(value)',
            'param==123:int':        '(123)',
            'param==value:int':      { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            'param==value:new-type': { throw: /^\[ns\.router\] Could not find regexp for type 'new\-type'!$/ },
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._generateParamRegexp(ns.router._parseParam(test)); }).to.throwError(result.throw);
                    } else {
                        expect(ns.router._generateParamRegexp(ns.router._parseParam(test))).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('parse section', function() {
        var _tests = {
            'static':                     { is_optional: false, items: [ { default_value: 'static' } ]  },
            '{param}':                    { is_optional: false, items: [ { name: 'param', type: 'id', default_value: undefined, is_optional: false } ] },
            '{param=}':                   { is_optional: true, items: [ { name: 'param', type: 'id', default_value: '', is_optional: true } ] },
            '{param:int}':                { is_optional: false, items: [ { name: 'param', type: 'int', default_value: undefined, is_optional: false } ] },
            '{param=:int}':               { is_optional: true, items: [ { name: 'param', type: 'int', default_value: '', is_optional: true } ] },
            '{param=value}':              { is_optional: true, items: [ { name: 'param', type: 'id', default_value: 'value', is_optional: true } ] },
            '{param=value:int}':          { is_optional: true, items: [ { name: 'param', type: 'int', default_value: 'value', is_optional: true } ] },
            '{param==value:int}':         { throw: /^\[ns\.router\] Wrong value for 'param' parameter$/ },
            '{param==123:int}':           { is_optional: false, items: [ { name: 'param', type: 'int', default_value: '123', is_optional: false } ] },
            'prefix-{param:int}':         { is_optional: false, items: [ { default_value: 'prefix-' }, { name: 'param', type: 'int', default_value: undefined, is_optional: false } ] },
            'prefix-{part1:int}{part2=}': {
                is_optional: false,
                items: [
                    { default_value: 'prefix-' },
                    { name: 'part1', type: 'int', default_value: undefined, is_optional: false },
                    { name: 'part2', type: 'id', default_value: '', is_optional: true },
                ]
            },
            'some{thing': { throw: /^\[ns\.router\] could not parse parameter in url section: some{thing$/ }
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    var result = _tests[test];
                    if (result.throw) {
                        expect(function() { ns.router._parseSection(test); }).to.throwError(result);
                    } else {
                        expect(ns.router._parseSection(test)).to.be.eql(result);
                    }
                });
            })(test);
        }
    });

    describe('generate section regexp', function() {
        var _tests = {
            '{param}':            '/([A-Za-z_][A-Za-z0-9_-]*)',
            '{param:int}':        '/([0-9]+)',
            '{param=value:int}':  '(?:/(?!/)(?:([0-9]+))?)?',
            '{param==value}':     '/(value)',
            '{param==123:int}':   '/(123)'
        };

        for (var test in _tests) {
            (function(test) {
                it(test, function() {
                    expect( ns.router._generateSectionRegexp( ns.router._parseSection(test) )).to.be(_tests[test] );
                });
            })(test);
        }
    });

    describe('complex url 1', function() {
        it('/{context=contest}/{contest-id:int}/users/{author-login}/album/', function() {
            var route = '/{context=contest}/{contest-id:int}/users/{author-login}/album/';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^(?:/(?!/)(?:([A-Za-z_][A-Za-z0-9_-]*))?)?/([0-9]+)/users/([A-Za-z_][A-Za-z0-9_-]*)/album/?(?:\\?(.*))?$') );
        });
    });

    describe('complex url 2', function() {
        it('/{context=}/users/{login}/view/{id:int}', function() {
            var route = '/{context=}/users/{login}/view/{id:int}';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^(?:/(?!/)(?:([A-Za-z_][A-Za-z0-9_-]*))?)?/users/([A-Za-z_][A-Za-z0-9_-]*)/view/([0-9]+)/?(?:\\?(.*))?$') );
        });
    });

    describe('complex url 3', function() {
        it('/message/{id=:int}', function() {
            var route = '/message/{id=:int}';
            var regexp = ns.router.compile(route).regexp;
            compareRegExp( regexp, new RegExp('^/message(?:/(?!/)(?:([0-9]+))?)?/?(?:\\?(.*))?$') ); // TODO проверить, что не получится 2 слеша на конце
        });
    });

    describe('ns.router.generateUrl()', function() {
        beforeEach(function() {
            ns.router.routes = {
                route: {
                    '/{context==search}/{query}/image/{id:int}': 'view',
                    '/{context==tag}/{tag}/image/{id:int}': 'view',
                    '/{context==top}/image/{id:int}': 'view',
                    '/{context}/image/{id:int}': 'view',
                    '/test/{id}': 'test'
                }
            };
            ns.router.init();
        });

        afterEach(function() {
            ns.router.undefine();
        });

        var _tests = [
            {
                name: 'should throw error for unknown route',
                id: 'test-no-such-route',
                params: {},
                result: { throw: /^\[ns\.router\] Could not find route with id 'test-no-such-route'!$/ }
            },
            {
                name: 'should throw error when not enough params',
                id: 'test',
                params: {},
                result: { throw: /^\[ns\.router\] Could not generate url for layout id 'test'!$/ }
            },
            {
                name: 'generate route for parameter with filter 1',
                id: 'view',
                params: { context: 'top', id: 1 },
                result: '/top/image/1'
            },
            {
                name: 'generate route for parameter with filter 2',
                id: 'view',
                params: { context: 'search', query: 'airport', id: 2 },
                result: '/search/airport/image/2'
            },
            {
                name: 'generate route for parameter with filter 3',
                id: 'view',
                params: { context: 'tag', tag: 'summer', id: 3 },
                result: '/tag/summer/image/3'
            },
            {
                name: 'generate route for parameter with filter 4',
                id: 'view',
                params: { context: 'new-context', id: 4 },
                result: '/new-context/image/4'
            }
        ];

        for (var i = 0; i < _tests.length; i++) {
            (function(test) {
                it(test.name, function() {
                    if (test.result.throw) {
                        expect(function() { ns.router.generateUrl(test.id, test.params); }).to.throwError(test.result.throw);
                    } else {
                        expect(ns.router.generateUrl(test.id, test.params)).to.be.eql(test.result);
                    }
                });
            })(_tests[i]);
        }
    });

    // describe('ns.router.compare()', function() {
    //     // does not throw exceptoin when cannot generate url
    //     // ignore query

    // })

});
<|endoftext|>


<commit_before>
describe("Lists", function(){

   it("can use cons, head and tail", function() {
      var emptyList = emptyList;

      var listA   = cons('a', emptyList);
      var listBA  = cons('b', listA);
      var listCBA = cons('c', listBA);

      expect(head(listCBA)).toBe('c');
      expect(head(tail(listCBA))).toBe('b');
      expect(head(tail(tail(listCBA)))).toBe('a');
   });

   it("can convert to an array", function() {

      var listCBA = cons('c', cons('b', cons('a', emptyList)));

      assertEquals(['c','b','a'], listAsArray(listCBA));
   });

   it("can convert empty list to an array", function(){
      assertEquals([], listAsArray(emptyList));
   });

   it("can reverse the order of a list", function() {
      var listCBA = cons('c', cons('b', cons('a', emptyList)));

      assertEquals(['a','b','c'], listAsArray(reverseList(listCBA)));
   });

   it("can map over a list", function() {
      var naturals = cons(1, cons(2, cons(3, emptyList)));
      var evens = cons(2, cons(4, cons(6, emptyList)));

      function doubleIt(n){return n * 2}

      assertEquals(evens, map(doubleIt, naturals));
   });

   it("can convert non empty list to an array", function(){
      assertEquals(['a','b','c'], listAsArray( asList(['a','b','c']) )  );
   });

   it("can convert empty array to list", function() {
      assertEquals([], listAsArray( asList([]) )  );
   });

   it("can assert every item in a list holds for a given test", function(){
      var l = list(1,2,3,4,5,6,7,8,9,10);

      function isANumber(n) {
         return typeof n == 'number';
      }

      function isOdd(n) {
         return n % 2 == 0;
      }

      function isLessThanTen(n) {
         return n < 10;
      }

      function isLessThanOrEqualToTen(n) {
         return n <= 10;
      }

      assertTrue(  listEvery(isANumber,                l ));
      assertFalse( listEvery(isOdd,                    l ));
      assertFalse( listEvery(isLessThanTen,            l ));
      assertTrue(  listEvery(isLessThanOrEqualToTen,   l ));
   });

   it("can fold list where order doesnt matter", function(){
      function add(n, m){ return n+m }

      var sum = foldR(add, 0, list(1,2,3,4));

      assertEquals(10, sum);
   });

   it("can fold list where start value matters", function(){
      function divide(n, m){ return n / m }

      var result = foldR(divide, 100, list(2, 2));

      //   (100/2) / 2  = 25
      assertEquals(25, result);
   });

   it("can fold list in the correct order", function(){
      function functionString(stringSoFar, fnName){ return fnName + '(' + stringSoFar + ')' }

      var functionStringResult = foldR(functionString, 'x', list('a', 'b', 'c'));

      // if order were wrong, might give c(b(a(x)))

      assertEquals('a(b(c(x)))', functionStringResult);
   });
});
<commit_msg>change assert to expect<commit_after>
describe("Lists", function(){

   it("can use cons, head and tail", function() {
      var emptyList = emptyList;

      var listA   = cons('a', emptyList);
      var listBA  = cons('b', listA);
      var listCBA = cons('c', listBA);

      expect(head(listCBA)).toBe('c');
      expect(head(tail(listCBA))).toBe('b');
      expect(head(tail(tail(listCBA)))).toBe('a');
   });

   it("can convert to an array", function() {

      var listCBA = cons('c', cons('b', cons('a', emptyList)));

      expect( listAsArray(listCBA) ).toEqual( ['c','b','a'] );
   });

   it("can convert empty list to an array", function(){
      expect( listAsArray(emptyList) ).toEqual([]);
   });

   it("can reverse the order of a list", function() {
      var listCBA = cons('c', cons('b', cons('a', emptyList)));

      expect( listAsArray(reverseList(listCBA)) ).toEqual( ['a','b','c'] );
   });

   it("can map over a list", function() {
      var naturals = cons(1, cons(2, cons(3, emptyList)));
      var evens = cons(2, cons(4, cons(6, emptyList)));

      function doubleIt(n){return n * 2}

      expect( map(doubleIt, naturals) ).toEqual( evens );
   });

   it("can convert non empty list to an array", function(){

      expect( listAsArray( asList(['a','b','c']) ) ).toEqual( ['a','b','c'] );
   });

   it("can convert empty array to list", function() {

      expect( listAsArray( asList([]) ) ).toEqual( [] );
   });

   it("can assert every item in a list holds for a given test", function(){
      var l = list(1,2,3,4,5,6,7,8,9,10);

      function isANumber(n) {
         return typeof n == 'number';
      }

      function isOdd(n) {
         return n % 2 == 0;
      }

      function isLessThanTen(n) {
         return n < 10;
      }

      function isLessThanOrEqualToTen(n) {
         return n <= 10;
      }

      expect( listEvery(isANumber,                l )).toBe(true);
      expect( listEvery(isOdd,                    l )).toBe(false);
      expect( listEvery(isLessThanTen,            l )).toBe(false);
      expect( listEvery(isLessThanOrEqualToTen,   l )).toBe(true);
   });

   it("can fold list where order doesnt matter", function(){
      function add(n, m){ return n+m }

      var sum = foldR(add, 0, list(1,2,3,4));

      expect( sum ).toEqual( 1 + 2 + 3 + 4 );
   });

   it("can fold list where start value matters", function(){
      function divide(n, m){ return n / m }

      var result = foldR(divide, 100, list(2, 2));

      expect( result ).toBe( 25 );  //   (100/2) / 2  = 25
   });

   it("can fold list in the correct order", function(){
      function functionString(param, fnName){ return fnName + '(' + param + ')' }

      var functionStringResult = foldR(functionString, 'x', list('a', 'b', 'c'));

      // if order were wrong, might give c(b(a(x)))

      expect( functionStringResult ).toEqual( 'a(b(c(x)))' );
   });
});
<|endoftext|>


<commit_before>describe('Stash::Item', function () {
  var pool = new Stash.Pool();
  var driver = pool.drivers[0];
  var foo = pool.getItem('foo');

  context('#_calculateExpiration_', function () {
    it('should return false for false expiration', function () {
      expect(Stash.Item._calculateExpiration_(false)).to.be.false;
    });

    it('should return the time for Date values', function () {
      var date = new Date();

      expect(Stash.Item._calculateExpiration_(date))
        .to.be.equal(date.getTime());
    });

    it('should increase Date.now by seconds', function () {
      var date = Date.now() + 100 * 1000;

      expect(Stash.Item._calculateExpiration_(100) - date)
        .to.be.lt(100);
    });
  });

  context('#get', function () {
    it('should return null if no data is saved', function (done) {
      foo.get().then(function (data) {
        catching(done, function () {
          expect(data).to.be.null;
        });
      });
    });

    it('should use SP_NONE as default cache policy', function (done) {
      foo.get().then(function () {
        catching(done, function () {
          expect(foo.cachePolicy).to.be.equal(Stash.Item.SP_NONE);
        });
      });
    });

    it('should call callback with data', function (done) {
      foo.set('bar')
      .then(function () {
        return foo.get();
      })
      .then(function (data) {
        catching(done, function () {
          expect(data).to.be.equal('bar');
        });
      });
    });
  });

  context('#set', function () {
    it('should set a value to an item', function (done) {
      foo.set('bar').then(function () {
        return foo.get();
      })
      .then(function (data) {
          expect(data).to.be.equal('bar');
          done();
      });
    });

    it('should unlock cache', function (done) {
      foo.lock().then(function () {
        return foo.set('baz', 'bar');
      }).then(function () {
        return foo.isLocked(foo.key);
      }).then(function (locked) {
        catching(done, function () {
          expect(locked).to.be.false;
        });
      });
    });

    it('should call the callback', function (done) {
      foo.set('baz')
      .then(function (err) {
        catching(done, function () {});
      });
    });
  });

  context('#isMiss', function () {
    it('should return true if cache is expired', function (done) {
      foo.set('bar', -1)
      .then(function () {
        return foo.isMiss();
      })
      .then(function (missed) {
        catching(done, function () {
          expect(missed).to.be.true;
        });
      });
    });

    it('should return false when it is still valid', function (done) {
      foo.set('bar', 100)
      .then(function () {
        return foo.isMiss();
      })
      .then(function (missed) {
        catching(done, function () {
          expect(missed).to.be.false;
        });
      })
    });

    it('should accept an expiration Date', function () {
      foo.set('bar', new Date(Date.now() + 1000));
      expect(foo.isMiss()).to.be.false;

      foo.set('bar', new Date(Date.now() - 100));
      expect(foo.isMiss()).to.be.true;
    });

    context('Expired & Locked', function () {
      context('SP_NONE', function (done) {
        it('should be the default cache policy', function () {
          foo.get()
          .then(function () {
            catching(done, function () {
              expect(foo.cachePolicy).to.be.equal(Stash.Item.SP_NONE);
            });
          });
        });

        it('should return true', function (done) {
          foo.set('bar', -1).then(function () {
            return foo.lock();
          }).then(function () {
            return foo.get(Stash.Item.SP_NONE);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.true;
            });
          });
        });
      });

      context('SP_OLD', function (done) {
        it('should return false if cache is locked', function () {
          foo.lock().then(function () {
            return foo.get(Stash.Item.SP_OLD);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.false;
            });
          });
        });
      });

      context('SP_PRECOMPUTE', function () {
        it('should return true before expiration for a single instance', function (done) {
          var bar;

          foo.set('bar', 100).then(function () {
            return foo.get(Stash.Item.SP_PRECOMPUTE, 110);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            try {
              expect(missed).to.be.true;
            } catch (err) {
              done(err);
            }
          }).then(function () {
            return foo.lock();
          }).then(function () {
            bar = pool.getItem(foo.key);
            return bar.get(Stash.Item.SP_PRECOMPUTE, 110);
          }).then(function () {
            return bar.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.false;
            });
          });
        });
      });

      context('SP_VALUE', function () {
        it('should return the specified value when locked', function () {
          foo.set('bar');
          foo.lock();
          expect(foo.get(Stash.Item.SP_VALUE, 'baz')).to.be.equal('baz');
        });
      });
    });
  });

  context('#clear', function () {
    it('should immediately invalidate a key', function () {
      foo.set('bar', 1000);
      foo.clear();
      expect(foo.get()).to.be.null;
    });
  });

  context('#lock', function () {
    it('should set cache as locked', function () {
      foo.lock();
      expect(foo.pool.drivers[0].get(foo.key).locked)
        .to.be.true;
    });
  });
});
<commit_msg>fix test parameter<commit_after>describe('Stash::Item', function () {
  var pool = new Stash.Pool();
  var driver = pool.drivers[0];
  var foo = pool.getItem('foo');

  context('#_calculateExpiration_', function () {
    it('should return false for false expiration', function () {
      expect(Stash.Item._calculateExpiration_(false)).to.be.false;
    });

    it('should return the time for Date values', function () {
      var date = new Date();

      expect(Stash.Item._calculateExpiration_(date))
        .to.be.equal(date.getTime());
    });

    it('should increase Date.now by seconds', function () {
      var date = Date.now() + 100 * 1000;

      expect(Stash.Item._calculateExpiration_(100) - date)
        .to.be.lt(100);
    });
  });

  context('#get', function () {
    it('should return null if no data is saved', function (done) {
      foo.get().then(function (data) {
        catching(done, function () {
          expect(data).to.be.null;
        });
      });
    });

    it('should use SP_NONE as default cache policy', function (done) {
      foo.get().then(function () {
        catching(done, function () {
          expect(foo.cachePolicy).to.be.equal(Stash.Item.SP_NONE);
        });
      });
    });

    it('should call callback with data', function (done) {
      foo.set('bar')
      .then(function () {
        return foo.get();
      })
      .then(function (data) {
        catching(done, function () {
          expect(data).to.be.equal('bar');
        });
      });
    });
  });

  context('#set', function () {
    it('should set a value to an item', function (done) {
      foo.set('bar').then(function () {
        return foo.get();
      })
      .then(function (data) {
          expect(data).to.be.equal('bar');
          done();
      });
    });

    it('should unlock cache', function (done) {
      foo.lock().then(function () {
        return foo.set('baz');
      }).then(function () {
        return foo.isLocked(foo.key);
      }).then(function (locked) {
        catching(done, function () {
          expect(locked).to.be.false;
        });
      });
    });

    it('should call the callback', function (done) {
      foo.set('baz')
      .then(function (err) {
        catching(done, function () {});
      });
    });
  });

  context('#isMiss', function () {
    it('should return true if cache is expired', function (done) {
      foo.set('bar', -1)
      .then(function () {
        return foo.isMiss();
      })
      .then(function (missed) {
        catching(done, function () {
          expect(missed).to.be.true;
        });
      });
    });

    it('should return false when it is still valid', function (done) {
      foo.set('bar', 100)
      .then(function () {
        return foo.isMiss();
      })
      .then(function (missed) {
        catching(done, function () {
          expect(missed).to.be.false;
        });
      })
    });

    it('should accept an expiration Date', function () {
      foo.set('bar', new Date(Date.now() + 1000));
      expect(foo.isMiss()).to.be.false;

      foo.set('bar', new Date(Date.now() - 100));
      expect(foo.isMiss()).to.be.true;
    });

    context('Expired & Locked', function () {
      context('SP_NONE', function (done) {
        it('should be the default cache policy', function () {
          foo.get()
          .then(function () {
            catching(done, function () {
              expect(foo.cachePolicy).to.be.equal(Stash.Item.SP_NONE);
            });
          });
        });

        it('should return true', function (done) {
          foo.set('bar', -1).then(function () {
            return foo.lock();
          }).then(function () {
            return foo.get(Stash.Item.SP_NONE);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.true;
            });
          });
        });
      });

      context('SP_OLD', function (done) {
        it('should return false if cache is locked', function () {
          foo.lock().then(function () {
            return foo.get(Stash.Item.SP_OLD);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.false;
            });
          });
        });
      });

      context('SP_PRECOMPUTE', function () {
        it('should return true before expiration for a single instance', function (done) {
          var bar;

          foo.set('bar', 100).then(function () {
            return foo.get(Stash.Item.SP_PRECOMPUTE, 110);
          }).then(function () {
            return foo.isMiss();
          }).then(function (missed) {
            try {
              expect(missed).to.be.true;
            } catch (err) {
              done(err);
            }
          }).then(function () {
            return foo.lock();
          }).then(function () {
            bar = pool.getItem(foo.key);
            return bar.get(Stash.Item.SP_PRECOMPUTE, 110);
          }).then(function () {
            return bar.isMiss();
          }).then(function (missed) {
            catching(done, function () {
              expect(missed).to.be.false;
            });
          });
        });
      });

      context('SP_VALUE', function () {
        it('should return the specified value when locked', function () {
          foo.set('bar');
          foo.lock();
          expect(foo.get(Stash.Item.SP_VALUE, 'baz')).to.be.equal('baz');
        });
      });
    });
  });

  context('#clear', function () {
    it('should immediately invalidate a key', function () {
      foo.set('bar', 1000);
      foo.clear();
      expect(foo.get()).to.be.null;
    });
  });

  context('#lock', function () {
    it('should set cache as locked', function () {
      foo.lock();
      expect(foo.pool.drivers[0].get(foo.key).locked)
        .to.be.true;
    });
  });
});
<|endoftext|>


<commit_before>var curry = require('./curry'),
	map = require('./map'),
	each = require('./each'),
	json = require('./json')

module.exports = {
	request: request,
	get: curry(request, 'get'),
	post: curry(request, 'post'),
	jsonGet: curry(sendJSON, 'get'),
	jsonPost: curry(sendJSON, 'post')
}

var XHR = window.XMLHttpRequest || function() { return new ActiveXObject("Msxml2.XMLHTTP"); }

var onBeforeUnloadFired = false
function onBeforeUnload() {
	onBeforeUnloadFired = true
	setTimeout(function(){ onBeforeUnloadFired = false }, 100)
}

if (window.addEventListener) { window.addEventListener('beforeunload', onBeforeUnload, false) }
else { window.attachEvent('onbeforeunload', onBeforeUnload) }

function request(method, url, params, callback, headers, opts) {
	var xhr = new XHR()
	method = method.toUpperCase()
	headers = headers || {}
	opts = opts || {}
	xhr.onreadystatechange = function() {
		var err, result
		try {
			if (xhr.readyState != 4) { return }
			if (onBeforeUnloadFired) { return }
			if (xhr.status != 200) { return callback(new Error(xhr.responseText)) }
			result = (opts.json ? json.parse(xhr.responseText) : xhr.responseText)
			if (xhr.getResponseHeader('Content-Type') == 'application/json') { result = json.parse(result) }
		} catch(e) {
			err = e
		}
		if (err || typeof result != undefined) {
			_abortXHR(xhr)
			callback(err, result)
		}
	}

	var data = null

	if (method == 'GET') {
		var encode = (opts.encode !== false),
			queryArr = map(params, function(value, key) { return (encode ? encodeURIComponent(key) : key) + '=' + (encode ? encodeURIComponent(value) : value) })
			url += (url.indexOf('?') == -1 && queryArr.length ? '?' : '') + queryArr.join('&')
	} else if (method == 'POST') {
		data = json.stringify(params)
	}
	xhr.open(method, url, true)
	if (method == 'POST') {
		if (!headers['Content-Type']) { headers['Content-Type'] = "application/x-www-form-urlencoded" }
	}
	each(headers, function(val, key) { xhr.setRequestHeader(key, val) })
	xhr.send(data)
}

function sendJSON(method, url, params, callback) {
	return request(method, url, params, callback, { 'Content-Type':'application/json' }, { json:true })
}

function _abortXHR(xhr) {
	try {
		if('onload' in xhr) {
			xhr.onload = xhr.onerror = xhr.ontimeout = null;
		} else if('onreadystatechange' in xhr) {
			xhr.onreadystatechange = null;
		}
		if(xhr.abort) { xhr.abort(); }
	} catch(e) {}
}
<commit_msg>Allow for url encoded post body content<commit_after>var curry = require('./curry'),
	map = require('./map'),
	each = require('./each'),
	json = require('./json')

module.exports = {
	request: request,
	get: curry(request, 'get'),
	post: curry(request, 'post'),
	jsonGet: curry(sendJSON, 'get'),
	jsonPost: curry(sendJSON, 'post')
}

var XHR = window.XMLHttpRequest || function() { return new ActiveXObject("Msxml2.XMLHTTP"); }

var onBeforeUnloadFired = false
function onBeforeUnload() {
	onBeforeUnloadFired = true
	setTimeout(function(){ onBeforeUnloadFired = false }, 100)
}

if (window.addEventListener) { window.addEventListener('beforeunload', onBeforeUnload, false) }
else { window.attachEvent('onbeforeunload', onBeforeUnload) }

function request(method, url, params, callback, headers, opts) {
	var xhr = new XHR()
	method = method.toUpperCase()
	headers = headers || {}
	opts = opts || {}
	xhr.onreadystatechange = function() {
		var err, result
		try {
			if (xhr.readyState != 4) { return }
			if (onBeforeUnloadFired) { return }
			if (xhr.status != 200) { return callback(new Error(xhr.responseText)) }
			// result = (opts.json ? json.parse(xhr.responseText) : xhr.responseText)
			if (xhr.getResponseHeader('Content-Type') == 'application/json') { result = json.parse(xhr.responseText) }
		} catch(e) {
			err = e
		}
		if (err || typeof result != undefined) {
			_abortXHR(xhr)
			callback(err, result)
		}
	}

	var uriEncode = (opts.encode === false
		? function(params) { return map(params, function(val, key) { return key+'='+val }).join('&') }
		: function(params) { return map(params, function(val, key) { return encodeURIComponent(key)+'='+encodeURIComponent(val) }).join('&') })

	var data = ''
	if (method == 'GET') {
		var queryParams = uriEncode(params)
		url += (url.indexOf('?') == -1 && queryParams ? '?' : '') + queryParams
	} else if (method == 'POST') {
		var contentType = headers['Content-Type']
		if (!contentType) {
			contentType = headers['Content-Type'] = 'application/x-www-form-urlencoded'
		}
		if (contentType == 'application/x-www-form-urlencoded') {
			data = uriEncode(params)
		} else if (contentType == 'application/json') {
			data = json.stringify(params)
		}
	}
	xhr.open(method, url, true)
	each(headers, function(val, key) { xhr.setRequestHeader(key, val) })
	xhr.send(data)
}

function sendJSON(method, url, params, callback) {
	return request(method, url, params, callback, { 'Content-Type':'application/json' }, { json:true })
}

function _abortXHR(xhr) {
	try {
		if('onload' in xhr) {
			xhr.onload = xhr.onerror = xhr.ontimeout = null;
		} else if('onreadystatechange' in xhr) {
			xhr.onreadystatechange = null;
		}
		if(xhr.abort) { xhr.abort(); }
	} catch(e) {}
}
<|endoftext|>


<commit_before>import cheerio from 'cheerio';
import request from 'request';

class PoiCollector {

	collect( poi ) {

	}

}<commit_msg>Discovering url reviews<commit_after>import cheerio from 'cheerio';
import request from 'request';

const TRIP_ADVISOR_URL = "https://www.tripadvisor.com";
const TRIP_ADVISOR_SEARCH = ( criteria ) => ( `${TRIP_ADVISOR_URL}/Search?q=${criteria}` );

export default class PoiCollector {

	collect( poi ) {

		this.discoverUrl(poi).then( ( url ) => {

			return new Promise( ( resolve, reject ) => {

				request.get( `${TRIP_ADVISOR_URL}${url}`, ( error, response, body ) => {

				} );

			} );

		}, ( error ) => {

			console.log(error);
		} );
	}

	discoverUrl( poi ) {

		return new Promise( (resolve, reject) => {

			const searchUrl = TRIP_ADVISOR_SEARCH( poi );
			request.get( searchUrl, (error, response, body) => {

				if(error)
					reject(error);

				const $ = cheerio.load(body);

				const results = $('#search_result');

				const poi_result =  results.children().get(1).children[0].children[0]; //results.children[1].children[0].children[0];
				const poi_reviews = poi_result.children[1].children[1];

				const reviews_url = poi_reviews.children[1].attribs.href;

				resolve(reviews_url);
			} );

		} );

	}

}<|endoftext|>