<commit_before>var es = require("./es");
var ast = require("./ast");

function match(pattern, expression) {
    var id = es.Identifier("$match");
    var expr = wrapExpression(id, pattern, expression);
    var ret = es.ReturnStatement(expr);
    var pred = satisfiesPattern(id, pattern);
    var block = es.BlockStatement([ret]);
    return es.IfStatement(pred, block, null);
}

function esAnd(a, b) {
    return es.LogicalExpression("&&", a, b);
}

function esEq(a, b) {
    return es.BinaryExpression("===", a, b);
}

function esGe(a, b) {
    return es.BinaryExpression(">=", a, b);
}

function esIn(a, b) {
    return es.BinaryExpression("in", a, b);
}

function esSlice(xs, i) {
    var slice = es.Identifier("sqgl$$slice");
    return es.CallExpression(slice, [i, xs]);
}

function esProp(obj, prop) {
    return es.MemberExpression(false, obj, es.Identifier(prop));
}

function esNth(a, i) {
    return es.MemberExpression(true, a, es.Literal(i));
}

function objGet(obj, k) {
    return es.MemberExpression(true, obj, es.Literal(k));
}

function esTypeof(x) {
    return {
        type: "UnaryExpression",
        prefix: true,
        operator: "typeof",
        argument: x,
    };
}

var j = JSON.stringify;

var esTrue = es.Literal(true);

function notEsTrue(x) {
    return !isEsTrue(x);
}

function isEsTrue(x) {
    return x.type === "Literal" && x.value === true;
}

var _satisfiesPattern = {
    MatchPatternSimple: function(root, p) {
        return esTrue;
    },
    MatchPatternLiteral: function(root, p) {
        var lit = es.Literal(p.data.data);
        return es.CallExpression(es.Identifier("sqgl$$is"), [root, lit]);
    },
    MatchPatternArray: function(root, p) {
        var ps = p.patterns;
        var n = ps.length;
        var lengthEq = esEq(esProp(root, "length"), es.Literal(n));
        return ps
            .map(function(x, i) {
                return satisfiesPattern(esNth(root, i), x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, esAnd(root, lengthEq));
    },
    MatchPatternArraySlurpy: function(root, p) {
        var ps = p.patterns;
        var n = ps.length;
        var atLeastLength = esGe(esProp(root, "length"), es.Literal(n));
        var a = ps
            .map(function(x, i) {
                return satisfiesPattern(esNth(root, i), x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, esAnd(root, atLeastLength));
        var n = es.Literal(p.patterns.length);
        var b = satisfiesPattern(esSlice(root, n), p.slurp);
        return esAnd(a, b);
    },
    MatchPatternObject: function(root, p) {
        var t = esTypeof(root);
        var o = es.Literal("object");
        var isObject = es.CallExpression(
            es.Identifier("sqgl$$isObject"),
            [root]
        );
        return p
            .pairs
            .map(function(x) {
                return satisfiesPattern(root, x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, isObject);
    },
    MatchPatternObjectPair: function(root, p) {
        // TODO: Don't assume the key is a string literal.
        var has = esIn(es.Literal(p.key.data), root);
        var rootObj = esNth(root, p.key.data);
        return esAnd(has, satisfiesPattern(rootObj, p.value));
    },
};

function satisfiesPattern(root, p) {
    if (p.type in _satisfiesPattern) {
        return _satisfiesPattern[p.type](root, p);
    }
    throw new Error("can't satisfiesPattern of " + j(p));
}

var __pluckPattern = {
    MatchPatternSimple: function(acc, root, p) {
        acc.identifiers.push(es.Identifier(p.identifier.data));
        acc.expressions.push(root);
        return acc;
    },
    MatchPatternLiteral: function(acc, root, p) {
        // Literals are just for the expression, they don't bind any values.
        return acc;
    },
    MatchPatternArray: function(acc, root, p) {
        p.patterns.forEach(function(x, i) {
            _pluckPattern(acc, esNth(root, i), x);
        });
        return acc;
    },
    MatchPatternArraySlurpy: function(acc, root, p) {
        p.patterns.forEach(function(x, i) {
            _pluckPattern(acc, esNth(root, i), x);
        });
        var n = es.Literal(p.patterns.length);
        _pluckPattern(acc, esSlice(root, n), p.slurp);
        return acc;
    },
    MatchPatternObject: function(acc, root, p) {
        p.pairs.forEach(function(v) {
            _pluckPattern(acc, root, v);
        });
        return acc;
    },
    MatchPatternObjectPair: function(acc, root, p) {
        // TODO: Don't assume p.key is a string literal.
        var objRoot = objGet(root, p.key.data);
        _pluckPattern(acc, objRoot, p.value);
        return acc;
    },
};

function _pluckPattern(acc, root, p) {
    if (p.type in __pluckPattern) {
        return __pluckPattern[p.type](acc, root, p);
    }
    throw new Error("can't pluckPattern of " + j(p));
}

function pluckPattern(root, p) {
    var obj = {identifiers: [], expressions: []};
    return _pluckPattern(obj, root, p);
}

function wrapExpression(root, p, e) {
    var obj = pluckPattern(root, p);
    var ret = es.ReturnStatement(e);
    var block = es.BlockStatement([ret]);
    var fn = es.FunctionExpression(null, obj.identifiers, block);
    return es.CallExpression(fn, obj.expressions);
}

module.exports = match;
<commit_msg>Fixes linter failure<commit_after>var es = require("./es");
var ast = require("./ast");

function match(pattern, expression) {
    var id = es.Identifier("$match");
    var expr = wrapExpression(id, pattern, expression);
    var ret = es.ReturnStatement(expr);
    var pred = satisfiesPattern(id, pattern);
    var block = es.BlockStatement([ret]);
    return es.IfStatement(pred, block, null);
}

function esAnd(a, b) {
    return es.LogicalExpression("&&", a, b);
}

function esEq(a, b) {
    return es.BinaryExpression("===", a, b);
}

function esGe(a, b) {
    return es.BinaryExpression(">=", a, b);
}

function esIn(a, b) {
    return es.BinaryExpression("in", a, b);
}

function esSlice(xs, i) {
    var slice = es.Identifier("sqgl$$slice");
    return es.CallExpression(slice, [i, xs]);
}

function esProp(obj, prop) {
    return es.MemberExpression(false, obj, es.Identifier(prop));
}

function esNth(a, i) {
    return es.MemberExpression(true, a, es.Literal(i));
}

function objGet(obj, k) {
    return es.MemberExpression(true, obj, es.Literal(k));
}

function esTypeof(x) {
    return {
        type: "UnaryExpression",
        prefix: true,
        operator: "typeof",
        argument: x,
    };
}

var j = JSON.stringify;

var esTrue = es.Literal(true);

function notEsTrue(x) {
    return !isEsTrue(x);
}

function isEsTrue(x) {
    return x.type === "Literal" && x.value === true;
}

var _satisfiesPattern = {
    MatchPatternSimple: function(root, p) {
        return esTrue;
    },
    MatchPatternLiteral: function(root, p) {
        var lit = es.Literal(p.data.data);
        return es.CallExpression(es.Identifier("sqgl$$is"), [root, lit]);
    },
    MatchPatternArray: function(root, p) {
        var ps = p.patterns;
        var n = ps.length;
        var lengthEq = esEq(esProp(root, "length"), es.Literal(n));
        return ps
            .map(function(x, i) {
                return satisfiesPattern(esNth(root, i), x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, esAnd(root, lengthEq));
    },
    MatchPatternArraySlurpy: function(root, p) {
        var ps = p.patterns;
        var n = es.Literal(ps.length);
        var atLeastLength = esGe(esProp(root, "length"), n);
        var a = ps
            .map(function(x, i) {
                return satisfiesPattern(esNth(root, i), x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, esAnd(root, atLeastLength));
        var b = satisfiesPattern(esSlice(root, n), p.slurp);
        return esAnd(a, b);
    },
    MatchPatternObject: function(root, p) {
        var t = esTypeof(root);
        var o = es.Literal("object");
        var isObject = es.CallExpression(
            es.Identifier("sqgl$$isObject"),
            [root]
        );
        return p
            .pairs
            .map(function(x) {
                return satisfiesPattern(root, x);
            })
            .filter(notEsTrue)
            .reduce(esAnd, isObject);
    },
    MatchPatternObjectPair: function(root, p) {
        // TODO: Don't assume the key is a string literal.
        var has = esIn(es.Literal(p.key.data), root);
        var rootObj = esNth(root, p.key.data);
        return esAnd(has, satisfiesPattern(rootObj, p.value));
    },
};

function satisfiesPattern(root, p) {
    if (p.type in _satisfiesPattern) {
        return _satisfiesPattern[p.type](root, p);
    }
    throw new Error("can't satisfiesPattern of " + j(p));
}

var __pluckPattern = {
    MatchPatternSimple: function(acc, root, p) {
        acc.identifiers.push(es.Identifier(p.identifier.data));
        acc.expressions.push(root);
        return acc;
    },
    MatchPatternLiteral: function(acc, root, p) {
        // Literals are just for the expression, they don't bind any values.
        return acc;
    },
    MatchPatternArray: function(acc, root, p) {
        p.patterns.forEach(function(x, i) {
            _pluckPattern(acc, esNth(root, i), x);
        });
        return acc;
    },
    MatchPatternArraySlurpy: function(acc, root, p) {
        p.patterns.forEach(function(x, i) {
            _pluckPattern(acc, esNth(root, i), x);
        });
        var n = es.Literal(p.patterns.length);
        _pluckPattern(acc, esSlice(root, n), p.slurp);
        return acc;
    },
    MatchPatternObject: function(acc, root, p) {
        p.pairs.forEach(function(v) {
            _pluckPattern(acc, root, v);
        });
        return acc;
    },
    MatchPatternObjectPair: function(acc, root, p) {
        // TODO: Don't assume p.key is a string literal.
        var objRoot = objGet(root, p.key.data);
        _pluckPattern(acc, objRoot, p.value);
        return acc;
    },
};

function _pluckPattern(acc, root, p) {
    if (p.type in __pluckPattern) {
        return __pluckPattern[p.type](acc, root, p);
    }
    throw new Error("can't pluckPattern of " + j(p));
}

function pluckPattern(root, p) {
    var obj = {identifiers: [], expressions: []};
    return _pluckPattern(obj, root, p);
}

function wrapExpression(root, p, e) {
    var obj = pluckPattern(root, p);
    var ret = es.ReturnStatement(e);
    var block = es.BlockStatement([ret]);
    var fn = es.FunctionExpression(null, obj.identifiers, block);
    return es.CallExpression(fn, obj.expressions);
}

module.exports = match;
<|endoftext|>


<commit_before>'use strict';
/* jshint esversion: 6 */
/* jshint devel:true */
/* jshint node: true */

(function() {

  let images = [];

  let renderImages = function() {
    $('#listings').empty();

    for (let image of images) {
      let $col = $('
');
      let $card = $('
');
      let $content = $('
');
      let $title = $('
');

      $title.attr({
        'data-position': 'top',
        'data-tooltip': image.title
      });

      $title.tooltip({delay: 50});
      $title.text(image.title);

      let $picture = $('');

      $picture.attr({
        src: image.thumbURL,
        alt: `${image.thumbURL}`
      });

      $content.append($title, $picture);
      $card.append($content);

      let $action = $('
');
      let $selected = $('');

      $selected.attr('href', `index.ejs?img=${image.imageURL}`);

      $selected.text('Select');

      $action.append($selected);
      $card.append($action);
      $col.append($card);

      $('#listings').append($col);
    }
  };

  window.onload = doAjax;

  //==============================================================================
  // makes the AJAX request to the flickr API
  function doAjax(event) {
    event.preventDefault();

    // The object we use to start the AJAX request using JQuery's format
    let requestObject = {
      url: `https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=5b7fd66b51d24258c6135f2647adfb3f&extras=url_q,url_c&per_page=30&format=json&nojsoncallback=1`,
      method: "GET",
      success: handleSuccess,
      error: handleError
    };

    // Actually start the AJAX request
    $.ajax(requestObject);
  }

  //==============================================================================
  // The event handler for a successful ajax request, used in doAjax
  function handleSuccess(data) {
    let imageArray = data.photos.photo;

    var PhotoImage = function(id, height, width, owner, title, server, farm, secret, thumbURL, imageURL) {
      this.id = id || '';
      this.height = Number(height) || 0;
      this.width = Number(width) || 0;
      this.owner = owner || '';
      this.title = title || 'Untitled';
      this.server = server || '';
      this.farm = farm || 0;
      this.secret = secret || '';
      this.thumbURL = thumbURL || '';
      this.imageURL = imageURL || '';
    };

    for (let i = 0; i < imageArray.length; i++) {
      let imageElement = new PhotoImage (imageArray[i].id, imageArray[i].height_c,
        imageArray[i].width_c, imageArray[i].owner,
        imageArray[i].title, imageArray[i].server, imageArray[i].farm,
        imageArray[i].secret, imageArray[i].url_q, imageArray[i].url_c);

      // console.log(imageElement);

      if (imageArray[i].height_c > 0 || imageArray[i].width_c > 0) {
        images.push(imageElement);
      }
    }
    // console.log(imageArray.length, images.length);
    document.getElementById('listings').value = '';
    renderImages();
  }

  //==============================================================================
  // The event handler for a failed ajax request, used in doAjax
  function handleError(err) {
    console.log('AJAX FAILURE, WILL ROBINSON! FAILURE!');
    console.log(err);
  }
})();
<commit_msg>tweak quotes<commit_after>'use strict';
/* jshint esversion: 6 */
/* jshint devel:true */
/* jshint node: true */
/* jshint browser: true */
/* jshint jquery: true */

(function() {

  let images = [];

  let renderImages = function() {
    $('#listings').empty();

    for (let image of images) {
      let $col = $('
');
      let $card = $('
');
      let $content = $('
');
      let $title = $('
');

      $title.attr({
        'data-position': 'top',
        'data-tooltip': image.title
      });

      $title.tooltip({delay: 50});
      $title.text(image.title);

      let $picture = $('');

      $picture.attr({
        src: image.thumbURL,
        alt: `${image.thumbURL}`
      });

      $content.append($title, $picture);
      $card.append($content);

      let $action = $('
');
      let $selected = $('');

      $selected.attr('href', `index.ejs?img=${image.imageURL}`);

      $selected.text('Select');

      $action.append($selected);
      $card.append($action);
      $col.append($card);

      $('#listings').append($col);
    }
  };

  window.onload = doAjax;

  //==============================================================================
  // makes the AJAX request to the flickr API
  function doAjax(event) {
    event.preventDefault();

    // The object we use to start the AJAX request using JQuery's format
    let requestObject = {
      url: `https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=5b7fd66b51d24258c6135f2647adfb3f&extras=url_q,url_c&per_page=30&format=json&nojsoncallback=1`,
      method: "GET",
      success: handleSuccess,
      error: handleError
    };

    // Actually start the AJAX request
    $.ajax(requestObject);
  }

  //==============================================================================
  // The event handler for a successful ajax request, used in doAjax
  function handleSuccess(data) {
    let imageArray = data.photos.photo;

    var PhotoImage = function(id, height, width, owner, title, server, farm, secret, thumbURL, imageURL) {
      this.id = id || '';
      this.height = Number(height) || 0;
      this.width = Number(width) || 0;
      this.owner = owner || '';
      this.title = title || 'Untitled';
      this.server = server || '';
      this.farm = farm || 0;
      this.secret = secret || '';
      this.thumbURL = thumbURL || '';
      this.imageURL = imageURL || '';
    };

    for (let i = 0; i < imageArray.length; i++) {
      let imageElement = new PhotoImage (imageArray[i].id, imageArray[i].height_c,
        imageArray[i].width_c, imageArray[i].owner,
        imageArray[i].title, imageArray[i].server, imageArray[i].farm,
        imageArray[i].secret, imageArray[i].url_q, imageArray[i].url_c);

      // console.log(imageElement);

      if (imageArray[i].height_c > 0 || imageArray[i].width_c > 0) {
        images.push(imageElement);
      }
    }
    // console.log(imageArray.length, images.length);
    document.getElementById('listings').value = '';
    renderImages();
  }

  //==============================================================================
  // The event handler for a failed ajax request, used in doAjax
  function handleError(err) {
    console.log('AJAX FAILURE, WILL ROBINSON! FAILURE!');
    console.log(err);
  }
})();
<|endoftext|>


<commit_before>import http   from "http";
import typeis from "type-is";

export default {
    // Request prototype:
    __proto__ : http.IncomingMessage.prototype,

    /**
     * Returns request header. The `Referrer` header field is special-cased,
     * both `Referrer` and `Referer` are interchangeable.
     *
     * @param   {string}    name
     * @return  {string}
     * @access  public
     */
    get( header ) {
        const lower = header.toLowerCase();

        switch( lower ) {
            case "referer":
            case "referrer":
                return this.headers.referrer || this.headers.referer;

            default:
                return this.headers[ lower ];
        }
    },

    /**
     * Check if the incoming request contains the "Content-Type" header field,
     * and it contains the give mime `type`.
     *
     * @param   {string|array}      types...
     * @return  {string|false|null}
     * @access  public
     */
    is( ...types ) {
        return typeis( this, types );
    },

    /**
     * Return the value of param `name` when present or `defaultValue`:
     * - checks route placeholders, ex: `user/[all:username]`;
     * - checks body params, ex: `id=12, {"id":12}`;
     * - checks query string params, ex: `?id=12`;
     *
     * @param   {string}    name
     * @param   {mixed}     defaultValue
     * @return  {string}
     * @access  public
     */
    param( name, defaultValue ) {
        const params = this.params || {};
        const body   = this.body   || {};
        const query  = this.query  || {};

        if ( null != params[ name ] ) return params[ name ];
        if ( null != query[ name ] )  return query[ name ];
        if ( null != body[ name ] )   return body[ name ];

        return defaultValue;
    }
};
<commit_msg>Validate data in get method<commit_after>import http   from "http";
import typeis from "type-is";

export default {
    // Request prototype:
    __proto__ : http.IncomingMessage.prototype,

    /**
     * Returns request header. The `Referrer` header field is special-cased,
     * both `Referrer` and `Referer` are interchangeable.
     *
     * @param   {string}    name
     * @return  {string}
     * @access  public
     */
    get( header ) {
        if ( !header ) {
            throw new TypeError( "Name argument is required to req.get" );
        }

        if ( typeof name !== "string" ) {
            throw new TypeError( "Name must be a string to req.get" );
        }

        const lower = header.toLowerCase();

        switch( lower ) {
            case "referer":
            case "referrer":
                return this.headers.referrer || this.headers.referer;

            default:
                return this.headers[ lower ];
        }
    },

    /**
     * Check if the incoming request contains the "Content-Type" header field,
     * and it contains the give mime `type`.
     *
     * @param   {string|array}      types...
     * @return  {string|false|null}
     * @access  public
     */
    is( ...types ) {
        return typeis( this, types );
    },

    /**
     * Return the value of param `name` when present or `defaultValue`:
     * - checks route placeholders, ex: `user/[all:username]`;
     * - checks body params, ex: `id=12, {"id":12}`;
     * - checks query string params, ex: `?id=12`;
     *
     * @param   {string}    name
     * @param   {mixed}     defaultValue
     * @return  {string}
     * @access  public
     */
    param( name, defaultValue ) {
        const params = this.params || {};
        const body   = this.body   || {};
        const query  = this.query  || {};

        if ( null != params[ name ] ) return params[ name ];
        if ( null != query[ name ] )  return query[ name ];
        if ( null != body[ name ] )   return body[ name ];

        return defaultValue;
    }
};
<|endoftext|>


<commit_before>// Components of API URL to look up parking violations.
var url_base = 'https://data.albanyny.gov/resource/474r-rd62.json?license_plate_number=';

// Method to make API call.
function requestJSON(url, callback) {
$.ajax({
  url: url,
  beforeSend: function() {
    clearContents();
    $(".working").show();
  },
  complete: function(xhr) {
     $(".working").hide();
    callback.call(null, xhr.responseJSON);
  }
});
}

// Clear the contents of the results section & search field.
function clearContents() {
$("#results").empty();
$(".about").hide();
$("#plate").val('');
}

$(document).ready(function() {

  // Hide the lookup prompt on page load.
  $('.working, .about').hide();

  // Handler for search button
  $("#search").click(function() {
    var searchText = $("#plate").val();
      if(searchText == "") {
        $(".form-control").addClass("error");
      }
      else {
        url = url_base + searchText;
        requestJSON(url, function(json) {
          if(json.length == 0) {
            $("#results").append('
No tickets found.
');
          }
          else {
            details = Handlebars.templates.details({ Details : json[0] });
            $("#results").append(details);
          }
        });
      }
  });

  // User presses enter.
  $("#plate").keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
      $("#search").trigger('click');
    }
  });

  // Handler for focus on test input field.
  $("#plate").focus(function(){
    $(this).removeClass("error");
  });

  $("#about").click(function() {
    $('.about').show();
  });

});<commit_msg>Small refactor<commit_after>// Components of API URL to look up parking violations.
var url_base = 'https://data.albanyny.gov/resource/474r-rd62.json?license_plate_number=';

// Method to make API call.
function requestJSON(url, callback) {
$.ajax({
  url: url,
  beforeSend: function() {
    clearContents();
    $(".working").show();
  },
  complete: function(xhr) {
     $(".working").hide();
    callback.call(null, xhr.responseJSON);
  }
});
}

// Clear the contents of the results section, about section & search field.
function clearContents() {
  $("#results").empty();
  $(".about").hide();
  $("#plate").val('');
}

$(document).ready(function() {

  // Hide the lookup prompt & about section on page load.
  $('.working, .about').hide();

  // Handler for search button
  $("#search").click(function() {
    var searchText = $("#plate").val();
      if(searchText == "") {
        $(".form-control").addClass("error");
      }
      else {
        url = url_base + searchText;
        requestJSON(url, function(json) {
          if(json.length == 0) {
            $("#results").append('
No tickets found.
');
          }
          else {
            details = Handlebars.templates.details({ Details : json[0] });
            $("#results").append(details);
          }
        });
      }
  });

  // User presses enter.
  $("#plate").keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
      $("#search").trigger('click');
    }
  });

  // Handler for focus on text input field.
  $("#plate").focus(function(){
    $(this).removeClass("error");
  });

  // Show the about section.
  $("#about").click(function() {
    $('.about').show();
  });

});<|endoftext|>


<commit_before>Package.describe({
  summary: 'Accounts Templates styled for Ratchet.',
  version: '1.13.0',
  name: 'useraccounts:ratchet',
  git: 'https://github.com/meteor-useraccounts/ratchet.git',
});

Package.on_use(function(api, where) {
  api.versionsFrom('METEOR@1.0');

  api.use([
    'templating',
    'underscore',
  ], 'client');

  api.use([
    'useraccounts:core',
  ], ['client', 'server']);

  // Requires all routing packages loads before this asking for weak dependencies.
  api.use('useraccounts:flow-routing@1.12.1', ['client', 'server'], {weak: true});
  api.use('useraccounts:iron-routing@1.12.1', ['client', 'server'], {weak: true});

  api.imply([
    'useraccounts:core@1.13.0',
  ], ['client', 'server']);

  api.add_files([
    'lib/at_error.html',
    'lib/at_error.js',
    'lib/at_form.html',
    'lib/at_form.js',
    'lib/at_input.html',
    'lib/at_input.js',
    'lib/at_message.html',
    'lib/at_message.js',
    'lib/at_nav_button.html',
    'lib/at_nav_button.js',
    'lib/at_oauth.html',
    'lib/at_oauth.js',
    'lib/at_pwd_form.html',
    'lib/at_pwd_form.js',
    'lib/at_pwd_form_btn.html',
    'lib/at_pwd_form_btn.js',
    'lib/at_pwd_link.html',
    'lib/at_pwd_link.js',
    'lib/at_reCaptcha.html',
    'lib/at_reCaptcha.js',
    'lib/at_result.html',
    'lib/at_result.js',
    'lib/at_sep.html',
    'lib/at_sep.js',
    'lib/at_signin_link.html',
    'lib/at_signin_link.js',
    'lib/at_signup_link.html',
    'lib/at_signup_link.js',
    'lib/at_social.html',
    'lib/at_social.js',
    'lib/at_terms_link.html',
    'lib/at_terms_link.js',
    'lib/at_resend_verification_email_link.html',
    'lib/at_resend_verification_email_link.js',
    'lib/at_title.html',
    'lib/at_title.js',
    'lib/full_page_at_form.html',
    'lib/at_ratchet.css',
  ], ['client']);
});

Package.on_test(function(api) {
  api.use([
    'useraccounts:ratchet',
    'useraccounts:core@1.13.0',
  ]);

  api.use([
    'accounts-password',
    'tinytest',
    'test-helpers'
  ], ['client', 'server']);

  api.add_files([
    'tests/tests.js'
  ], ['client', 'server']);
});
<commit_msg>patch release - Bump to version 1.13.1<commit_after>Package.describe({
  summary: 'Accounts Templates styled for Ratchet.',
  version: '1.13.1',
  name: 'useraccounts:ratchet',
  git: 'https://github.com/meteor-useraccounts/ratchet.git',
});

Package.on_use(function(api, where) {
  api.versionsFrom('METEOR@1.0');

  api.use([
    'templating',
    'underscore',
  ], 'client');

  api.use([
    'useraccounts:core',
  ], ['client', 'server']);

  // Requires all routing packages loads before this asking for weak dependencies.
  api.use('useraccounts:flow-routing@1.12.1', ['client', 'server'], {weak: true});
  api.use('useraccounts:iron-routing@1.12.1', ['client', 'server'], {weak: true});

  api.imply([
    'useraccounts:core@1.13.1',
  ], ['client', 'server']);

  api.add_files([
    'lib/at_error.html',
    'lib/at_error.js',
    'lib/at_form.html',
    'lib/at_form.js',
    'lib/at_input.html',
    'lib/at_input.js',
    'lib/at_message.html',
    'lib/at_message.js',
    'lib/at_nav_button.html',
    'lib/at_nav_button.js',
    'lib/at_oauth.html',
    'lib/at_oauth.js',
    'lib/at_pwd_form.html',
    'lib/at_pwd_form.js',
    'lib/at_pwd_form_btn.html',
    'lib/at_pwd_form_btn.js',
    'lib/at_pwd_link.html',
    'lib/at_pwd_link.js',
    'lib/at_reCaptcha.html',
    'lib/at_reCaptcha.js',
    'lib/at_result.html',
    'lib/at_result.js',
    'lib/at_sep.html',
    'lib/at_sep.js',
    'lib/at_signin_link.html',
    'lib/at_signin_link.js',
    'lib/at_signup_link.html',
    'lib/at_signup_link.js',
    'lib/at_social.html',
    'lib/at_social.js',
    'lib/at_terms_link.html',
    'lib/at_terms_link.js',
    'lib/at_resend_verification_email_link.html',
    'lib/at_resend_verification_email_link.js',
    'lib/at_title.html',
    'lib/at_title.js',
    'lib/full_page_at_form.html',
    'lib/at_ratchet.css',
  ], ['client']);
});

Package.on_test(function(api) {
  api.use([
    'useraccounts:ratchet',
    'useraccounts:core@1.13.1',
  ]);

  api.use([
    'accounts-password',
    'tinytest',
    'test-helpers'
  ], ['client', 'server']);

  api.add_files([
    'tests/tests.js'
  ], ['client', 'server']);
});
<|endoftext|>


<commit_before>/* http://upload.wikimedia.org/wikipedia/commons/0/01/2007-02-20_time_zones.svg */
/*
  In the northern emisphere, january is in winter and july is in summer.
  In the southern emisphere, january is in summer and july is in winter.
  A daylight saving time offset is always -1, so standard time is always
  the greatest of two offsets.
*/
(function() {
  var jsk = {
    /******* PROPERTIES *******/
    breakingMonth : 0,
    testMonth0Offset : null,
    testMonth6Offset : null,
    timeSepator : "",
    /******* PRIVATE *******/
    getDateOffset : function getDate(month) {
      return new Date((new Date()).getFullYear(), month, 0).getTimezoneOffset();
    },
    getMonth0Offset : function() {
      return jsk.testMonth0Offset !== null ?
        jsk.testMonth0Offset :
        jsk.getDateOffset(jsk.breakingMonth);
    },
    getMonth6Offset : function() {
      return jsk.testMonth6Offset !== null ?
        jsk.testMonth6Offset :
        jsk.getDateOffset(jsk.breakingMonth+6);
    },
    offsetToString : function(offset, timeSeparator) {
      timeSeparator = timeSeparator || jsk.timeSeparator || "";

      var parts = [];

      var st = offset/60.0;
      parts.push(st >= 0 ? "+" : "-");

      var hour = Math.floor(Math.abs(st));
      parts.push((hour <= 9 ? "0" : "") + hour);

      parts.push(timeSeparator);

      var min = Math.abs(st%1.0)*60;
      parts.push((min <= 9 ? "0" : "") + min);

      return parts.join("");
    },
    /******* PUBLIC *******/
    // Force some test offsets
    testOffset : function testOffset(month0Offset, month6Offset) {
      jsk.testMonth0Offset = month0Offset;
      jsk.testMonth6Offset = month6Offset;
    },
    // the timezone has daylight saving
    hasDst : function() {
      return jsk.st() != jsk.dst();
    },
    // Returns the standard time offset (inverted)
    invertedSt : function invertedSt() {
      return Math.max(jsk.getMonth0Offset(), jsk.getMonth6Offset());
    },
    // Returns the daylight saving time offset (inverted)
    invertedDst : function invertedDst() {
      return Math.min(jsk.getMonth0Offset(), jsk.getMonth6Offset());
    },
    // Returns the standard time offset
    st : function st() {
      return 0-jsk.invertedSt();
    },
    // Returns standard to string
    stToString : function(timeSeparator) {
      return jsk.offsetToString(jsk.st(), timeSeparator);
    },
    // Returns the standard time offset
    dst : function dst() {
      return 0-jsk.invertedDst();
    },
    // Returns daylight saving to string
    dstToString : function(timeSeparator) {
      return jsk.offsetToString(jsk.dst(), timeSeparator);
    },
    iHateTheLastComma : true // this line exists because I hate the last comma
  };

  // Creates the base namespaces
  if (typeof(window.javascriptKataDotCom) == "undefined") { window.javascriptKataDotCom = {}; }
  if (typeof(window.jsKata) == "undefined") { window.jsKata = window.javascriptKataDotCom; }
  if (typeof(window.jsk) == "undefined") { window.jsk = window.javascriptKataDotCom; }
  if (typeof(window._) == "undefined") { window._ = window.javascriptKataDotCom; }

  window.javascriptKataDotCom.timezone = jsk;
  window.javascriptKataDotCom.tz = jsk;
})()
<commit_msg>everything is ok<commit_after>/* http://upload.wikimedia.org/wikipedia/commons/0/01/2007-02-20_time_zones.svg */
/*
  In the northern emisphere, january is in winter and july is in summer.
  In the southern emisphere, january is in summer and july is in winter.
  A daylight saving time offset is always -1, so standard time is always
  the greatest of two offsets.
*/
(function() {
  var jsk = {
    /******* PROPERTIES *******/
    breakingMonth : 0,
    testMonth0Offset : null,
    testMonth6Offset : null,
    timeSepator : "",
    /******* PRIVATE *******/
    getDateOffset : function getDate(month) {
      return new Date((new Date()).getFullYear(), month, 0).getTimezoneOffset();
    },
    getMonth0Offset : function() {
      return jsk.testMonth0Offset !== null ?
        jsk.testMonth0Offset :
        jsk.getDateOffset(jsk.breakingMonth);
    },
    getMonth6Offset : function() {
      return jsk.testMonth6Offset !== null ?
        jsk.testMonth6Offset :
        jsk.getDateOffset(jsk.breakingMonth+6);
    },
    offsetToString : function(offset, timeSeparator) {
      timeSeparator = timeSeparator || jsk.timeSeparator || "";

      var parts = [];

      var st = offset/60.0;
      parts.push(st >= 0 ? "+" : "-");

      var hour = Math.floor(Math.abs(st));
      parts.push((hour <= 9 ? "0" : "") + hour);

      parts.push(timeSeparator);

      var min = Math.abs(st%1.0)*60;
      parts.push((min <= 9 ? "0" : "") + min);

      return parts.join("");
    },
    /******* PUBLIC *******/
    // Force some test offsets
    testOffset : function testOffset(month0Offset, month6Offset) {
      jsk.testMonth0Offset = month0Offset;
      jsk.testMonth6Offset = month6Offset;
    },
    // the timezone has daylight saving
    hasDst : function() {
      return jsk.st() != jsk.dst();
    },
    // Returns the standard time offset (inverted)
    invertedSt : function invertedSt() {
      return Math.max(jsk.getMonth0Offset(), jsk.getMonth6Offset());
    },
    // Returns the daylight saving time offset (inverted)
    invertedDst : function invertedDst() {
      return Math.min(jsk.getMonth0Offset(), jsk.getMonth6Offset());
    },
    // Returns the standard time offset
    st : function st() {
      return 0-jsk.invertedSt();
    },
    // Returns standard to string
    stToString : function(timeSeparator) {
      return jsk.offsetToString(jsk.st(), timeSeparator);
    },
    // Returns the standard time offset
    dst : function dst() {
      return 0-jsk.invertedDst();
    },
    // Returns daylight saving to string
    dstToString : function(timeSeparator) {
      return jsk.offsetToString(jsk.dst(), timeSeparator);
    },
    iHateTheLastComma : true // this line exists because I hate the last comma
  };

  // Creates the base namespaces
  if (typeof(window.javascriptKataDotCom) == "undefined") { window.javascriptKataDotCom = {}; }
  if (typeof(window.jsKata) == "undefined") { window.jsKata = window.javascriptKataDotCom; }
  if (typeof(window.jsk) == "undefined") { window.jsk = window.javascriptKataDotCom; }
  if (typeof(window._) == "undefined") { window._ = window.javascriptKataDotCom; }

  window.javascriptKataDotCom.timezone = jsk;
  window.javascriptKataDotCom.tz = jsk;
})();
<|endoftext|>


<commit_before>/**
 * This object export is used to fix title typos from Ethio-Yellow pages
 * so Lethal Weapon 5 can do its thing
 *
 * Structure:
 * { [Typo Movie]: "Correct Movie Title" }
 */

const typos = {
  'Guardians of the Galaxy2': 'Guardians of the Galaxy Vol. 2',
  'Guardians of the Galaxy 2': 'Guardians of the Galaxy Vol. 2',
  'King Arthur: The Legend of the Sword': 'King Arthur: Legend of the Sword',
};

module.exports = (title) => {
  const keys = Object.keys(typos); // DJ Khaled
  const smallKeys = keys.map(key => key.toLowerCase());
  const movieIndex = smallKeys.indexOf(title.toLowerCase());

  if (movieIndex === -1) {
    return title;
  }

  return typos[keys[movieIndex]];
};
<commit_msg>Alien<commit_after>/**
 * This object export is used to fix title typos from Ethio-Yellow pages
 * so Lethal Weapon 5 can do its thing
 *
 * Structure:
 * { [Typo Movie]: "Correct Movie Title" }
 */

const typos = {
  'Guardians of the Galaxy2': 'Guardians of the Galaxy Vol. 2',
  'Guardians of the Galaxy 2': 'Guardians of the Galaxy Vol. 2',
  'King Arthur: The Legend of the Sword': 'King Arthur: Legend of the Sword',
  'Alien Covenant': 'Alien: Covenant',
};

module.exports = (title) => {
  const keys = Object.keys(typos); // DJ Khaled
  const smallKeys = keys.map(key => key.toLowerCase());
  const movieIndex = smallKeys.indexOf(title.toLowerCase());

  if (movieIndex === -1) {
    return title;
  }

  return typos[keys[movieIndex]];
};
<|endoftext|>


<commit_before>/**
 * Location
 *
 * @class Backbone model representing a location on the map.
 * @author Joakim Lundin
 * @type {Backbone.Model}
 */
var Location = Backbone.Model.extend(
    /** @lends Location */
    {
      defaults: {
        id: 0,
        campus: 'unknown',
        type: 'unknown',
        subType: null,
        shape: "point",
        text: "",
        coords: [],
        directionAware: true,
        hasIcon: false,
        pin: new google.maps.MarkerImage(
            'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkw' +
                'AAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wKExQWIJ3tCJcAAAC/SURBVAjXNc4/jgFRAMDh3/tj8oaJKchENBRsQTZ2VCpncAFO4A' +
                'QkDqB0AYnCCfRuQGYzhUypUWzEyEp072n4TvABUNS6Hxmzqfl+Ehmz9pX6BhAlrQejZnM/7XZNKwzJ8pxVmj525/NQlwqF+SyOTadScVgrqv' +
                'W6Czwv2F8uCynh5ysMwVoBgLWiXS4joSctHE55DlI6AKR02f2OhaNykP09n+NGEHieUvxer2KZJP/p7TbhvY0jY7bv7eazfQE67zjGgilfew' +
                'AAAABJRU5ErkJggg==')
      },

      /**
       * Get google points for this location.
       *
       * @return {Array} an array of google.maps.LatLng representing the points for this location.
       */
      getGPoints: function () {
        var points = [];

        $.each(this.get("coords"), function (index, point) {
          var coord = new google.maps.LatLng(point[0], point[1]);
          points.push(coord);
        });

        return points;
      },

      /**
       * Get a generated poi-type.
       * @return {string} the poi-type
       */
      getPoiType: function () {
        return this.get('campus') + "." + this.get('type');
      }
    });

/**
 * Collection of locations.
 *
 * @class Backbone collection of Locations
 * @author Joakim Lundin
 * @type {Backbone.Collection}
 */
var Locations = Backbone.Collection.extend(
    /** @lends Locations */
    {
      /** The model used for this Location. */
      model: Location,
      bounds: null,
      campuses: null,

      /**
       * Intercept method performed after fetch().
       * In this method the bounds and campuses variable are set.
       */
      parse: function(response) {
        this.bounds = response.bounds;
        this.campuses = response.campuses;
        return response.locations;
      },

      /**
       * Constructs the URL used for getting locations.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/poi';
      },

      /**
       * Filter Locations by campus.
       *
       * @param {string} campus the Campus to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byCampus: function (campus) {
        return _(this.filter(function (data) {
          return data.get("campus") == campus;
        }));
      },

      /**
       * Filter Locations by type.
       *
       * @param {string} type the type to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byType: function (type) {
        return _(this.filter(function (data) {
          return data.get("type") == type;
        }));
      },

      /**
       * Filter Locations by campus and types.
       *
       * @param {string} campus the Campus to filter by.
       * @param {Array} types an array of types to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byCampusAndType: function (campus, types) {
        var ret = this.byCampus(campus);
        return _(ret.filter(function (data) {
          return _.contains(types, data.get("type"));
        }));
      }
    });

/**
 * A collection of searchresults for Locations.
 *
 * @class Backbone collection of Locations
 * @type {Backbone.Collection}
 */
var LocationSearchResult = Backbone.Collection.extend(
    /** @lends LocationSearchResult */
    {
      /** The model used for this collection. */
      model: Location,
      bounds: null,
      campuses: null,

      /**
       * Intercept method performed after fetch().
       * In this method the bounds and campuses variable are set.
       */
      parse: function(response) {
        this.bounds = response.bounds;
        this.campuses = response.campuses;
        return response.locations;
      },

      /**
       * Constructs the URL used for getting search results.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/search';
      }
    });
<commit_msg>Removed tab.<commit_after>/**
 * Location
 *
 * @class Backbone model representing a location on the map.
 * @author Joakim Lundin
 * @type {Backbone.Model}
 */
var Location = Backbone.Model.extend(
    /** @lends Location */
    {
      defaults: {
        id: 0,
        campus: 'unknown',
        type: 'unknown',
        subType: null,
        shape: "point",
        text: "",
        coords: [],
        directionAware: true,
        hasIcon: false,
        pin: new google.maps.MarkerImage(
            'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkw' +
                'AAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wKExQWIJ3tCJcAAAC/SURBVAjXNc4/jgFRAMDh3/tj8oaJKchENBRsQTZ2VCpncAFO4A' +
                'QkDqB0AYnCCfRuQGYzhUypUWzEyEp072n4TvABUNS6Hxmzqfl+Ehmz9pX6BhAlrQejZnM/7XZNKwzJ8pxVmj525/NQlwqF+SyOTadScVgrqv' +
                'W6Czwv2F8uCynh5ysMwVoBgLWiXS4joSctHE55DlI6AKR02f2OhaNykP09n+NGEHieUvxer2KZJP/p7TbhvY0jY7bv7eazfQE67zjGgilfew' +
                'AAAABJRU5ErkJggg==')
      },

      /**
       * Get google points for this location.
       *
       * @return {Array} an array of google.maps.LatLng representing the points for this location.
       */
      getGPoints: function () {
        var points = [];

        $.each(this.get("coords"), function (index, point) {
          var coord = new google.maps.LatLng(point[0], point[1]);
          points.push(coord);
        });

        return points;
      },

      /**
       * Get a generated poi-type.
       * @return {string} the poi-type
       */
      getPoiType: function () {
        return this.get('campus') + "." + this.get('type');
      }
    });

/**
 * Collection of locations.
 *
 * @class Backbone collection of Locations
 * @author Joakim Lundin
 * @type {Backbone.Collection}
 */
var Locations = Backbone.Collection.extend(
    /** @lends Locations */
    {
      /** The model used for this Location. */
      model: Location,
      bounds: null,
      campuses: null,

      /**
       * Intercept method performed after fetch().
       * In this method the bounds and campuses variable are set.
       */
      parse: function (response) {
        this.bounds = response.bounds;
        this.campuses = response.campuses;
        return response.locations;
      },

      /**
       * Constructs the URL used for getting locations.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/poi';
      },

      /**
       * Filter Locations by campus.
       *
       * @param {string} campus the Campus to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byCampus: function (campus) {
        return _(this.filter(function (data) {
          return data.get("campus") == campus;
        }));
      },

      /**
       * Filter Locations by type.
       *
       * @param {string} type the type to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byType: function (type) {
        return _(this.filter(function (data) {
          return data.get("type") == type;
        }));
      },

      /**
       * Filter Locations by campus and types.
       *
       * @param {string} campus the Campus to filter by.
       * @param {Array} types an array of types to filter by.
       * @return {Array} an array of filtered Locations.
       */
      byCampusAndType: function (campus, types) {
        var ret = this.byCampus(campus);
        return _(ret.filter(function (data) {
          return _.contains(types, data.get("type"));
        }));
      }
    });

/**
 * A collection of searchresults for Locations.
 *
 * @class Backbone collection of Locations
 * @type {Backbone.Collection}
 */
var LocationSearchResult = Backbone.Collection.extend(
    /** @lends LocationSearchResult */
    {
      /** The model used for this collection. */
      model: Location,
      bounds: null,
      campuses: null,

      /**
       * Intercept method performed after fetch().
       * In this method the bounds and campuses variable are set.
       */
      parse: function (response) {
        this.bounds = response.bounds;
        this.campuses = response.campuses;
        return response.locations;
      },

      /**
       * Constructs the URL used for getting search results.
       *
       * @return {string} the URL.
       */
      url: function () {
        return 'http://pgbroker-dev.it.su.se/geo/search';
      }
    });
<|endoftext|>


<commit_before>/**
 * @author Alex Furey
 * @version 1.0.1
 * @requires serializeObject
 */
!function(n){function t(t){n.each(n.fn.ac.config.responseHandlers,function(e,a){e in t&&(n.isPlainObject(t[e])||n.isArray(t[e])?n.each(t[e],a):a.call(t[e],t[e]))})}function e(e){return n.ajax(n.extend(!0,{},n.fn.ac.config.ajaxDefaults,e)).done(t).done(n.fn.ac.config.doneHandler).fail(n.fn.ac.config.errorHandler).always(n.fn.ac.config.alwaysHandler)}function a(t,a){var o=function(t){return!1!==t&&null!==t&&(!(!n.fn.ac.config.alertAllowEmpty&&""===t)&&("string"==typeof t&&(i(a,"data")[n.fn.ac.config.alertInputDataKey]=t),void e(a)))};t=n.extend(!0,{},n.fn.ac.config.alertDefaults,t),"function"==typeof n.fn.ac.config.swal?n.fn.ac.config.swal(t,o):"type"in t&&"input"===t.type?o(prompt(t.title+(t.text?"\n"+t.text:""),"inputValue"in t?t.inputValue:"")):"showCancelButton"in t&&t.showCancelButton?o(confirm(t.title+(t.text?"\n"+t.text:""))):(alert(t.title+(t.text?"\n"+t.text:"")),o())}function i(n,t,e){return void 0===e&&(e={}),t in n||(n[t]=e),n[t]}function o(t,e,a){n.isPlainObject(a)&&e in t&&n.isPlainObject(t[e])?n.extend(!0,t[e],a):n.isArray(a)&&e in t&&n.isArray(t[e])?t.push.apply(t[e],a):t[e]=a}function r(t,e){var a={};return n.each(n(t).data(),function(t,r){var c,l,f=t.match(e);if(f)if((f=f.filter(function(n){return n})).length>1){l=a;for(var u=1;u<f.length;u++)f[u]&&(c=f[u].charAt(0).toLowerCase()+f[u].slice(1),u<f.length-1?l=i(l,c):o(l,c,r))}else n.isPlainObject(r)&&n.extend(!0,a,r)}),a}function c(t,e){"FORM"===n(e).prop("tagName")&&(t.ajax.url=n(e).attr("action")||t.ajax.url,t.ajax.method=n(e).attr("method")||t.ajax.method,n.extend(!0,i(t.ajax,"data"),n.fn.ac.config.serializeObject.call(n(e))))}function l(t,e){n.extend(!0,i(t,d),r(e,n.fn.ac.config.alertAttrRegex)),n.extend(!0,i(t,s),r(e,n.fn.ac.config.ajaxAttrRegex)),c(t,e)}function f(t){var i=n.extend(!0,{},t.data),o=this;return o!==t.delegateTarget&&l(i,t.delegateTarget),l(i,o),d in i&&i[d]&&!n.isEmptyObject(i[d])?a(i[d],i[s]):e(i[s]),n.fn.ac.config.stopPropagation&&t.stopPropagation(),n.fn.ac.config.preventDefault&&t.preventDefault(),n.fn.ac.config.eventReturn}function u(t,e,a,i){var o={};return o[s]=a,o[d]=i,n(this).on(t+n.fn.ac.config.eventSuffix,e,o,f),this}n.fn.ac=function(){for(var t=[],e=0;e<arguments.length;e++)1===e&&n.isPlainObject(arguments[e])&&t.push(null),t.push(arguments[e]);return this.each(function(){u.apply(this,t)})},n.fn.ac.config={doneHandler:null,errorHandler:null,alwaysHandler:null,responseHandlers:{content:function(t,e){n(t).html(e)},remove:function(t,e){n(e).remove()},hide:function(t,e){n(e).hide()},show:function(t,e){n(e).show()},hideModal:function(t,e){n(e).modal("hide")},showMOdal:function(t,e){n(e).modal("show")},append:function(t,e){n(t).append(e)},prepend:function(t,e){n(t).prepend(e)}},ajaxAttrRegex:/acAjax(Accepts|Contents|Context|Converters|Data|Headers|StatusCode|XhrFields)?([a-z]*)/i,alertAttrRegex:/acAlert([a-z]*)/i,eventSuffix:".ac",preventDefault:!0,stopPropagation:!1,eventReturn:!0,alertInputDataKey:"input",alertAllowEmpty:!0,ajaxDefaults:{dataType:"json"},alertDefaults:{title:"Are you sure?",type:"warning",showCancelButton:!0},swal:"function"==typeof swal?swal:null,serializeObject:function(){var t={};return n.each(this.serializeArray(),function(n,e){var a=t[e.name];t[e.name]=void 0!==a&&null!==a?a+","+e.value:e.value}),t}};var s="ajax",d="alert"}(jQuery);
<commit_msg>Added response handlers<commit_after>/**
 * @author Alex Furey
 * @version 1.0.2
 * @requires serializeObject
 */
!function(n){function t(t){n.each(n.fn.ac.config.responseHandlers,function(e,a){e in t&&(n.isPlainObject(t[e])||n.isArray(t[e])?n.each(t[e],a):a.call(t[e],t[e]))})}function e(e){return n.ajax(n.extend(!0,{},n.fn.ac.config.ajaxDefaults,e)).done(t).done(n.fn.ac.config.doneHandler).fail(n.fn.ac.config.errorHandler).always(n.fn.ac.config.alwaysHandler)}function a(t,a){var o=function(t){return!1!==t&&null!==t&&(!(!n.fn.ac.config.alertAllowEmpty&&""===t)&&("string"==typeof t&&(i(a,"data")[n.fn.ac.config.alertInputDataKey]=t),void e(a)))};t=n.extend(!0,{},n.fn.ac.config.alertDefaults,t),"function"==typeof n.fn.ac.config.swal?n.fn.ac.config.swal(t,o):"type"in t&&"input"===t.type?o(prompt(t.title+(t.text?"\n"+t.text:""),"inputValue"in t?t.inputValue:"")):"showCancelButton"in t&&t.showCancelButton?o(confirm(t.title+(t.text?"\n"+t.text:""))):(alert(t.title+(t.text?"\n"+t.text:"")),o())}function i(n,t,e){return void 0===e&&(e={}),t in n||(n[t]=e),n[t]}function o(t,e,a){n.isPlainObject(a)&&e in t&&n.isPlainObject(t[e])?n.extend(!0,t[e],a):n.isArray(a)&&e in t&&n.isArray(t[e])?t.push.apply(t[e],a):t[e]=a}function r(t,e){var a={};return n.each(n(t).data(),function(t,r){var c,l,f=t.match(e);if(f)if((f=f.filter(function(n){return n})).length>1){l=a;for(var u=1;u<f.length;u++)f[u]&&(c=f[u].charAt(0).toLowerCase()+f[u].slice(1),u<f.length-1?l=i(l,c):o(l,c,r))}else n.isPlainObject(r)&&n.extend(!0,a,r)}),a}function c(t,e){"FORM"===n(e).prop("tagName")&&(t.ajax.url=n(e).attr("action")||t.ajax.url,t.ajax.method=n(e).attr("method")||t.ajax.method,n.extend(!0,i(t.ajax,"data"),n.fn.ac.config.serializeObject.call(n(e))))}function l(t,e){n.extend(!0,i(t,d),r(e,n.fn.ac.config.alertAttrRegex)),n.extend(!0,i(t,s),r(e,n.fn.ac.config.ajaxAttrRegex)),c(t,e)}function f(t){var i=n.extend(!0,{},t.data),o=this;return o!==t.delegateTarget&&l(i,t.delegateTarget),l(i,o),d in i&&i[d]&&!n.isEmptyObject(i[d])?a(i[d],i[s]):e(i[s]),n.fn.ac.config.stopPropagation&&t.stopPropagation(),n.fn.ac.config.preventDefault&&t.preventDefault(),n.fn.ac.config.eventReturn}function u(t,e,a,i){var o={};return o[s]=a,o[d]=i,n(this).on(t+n.fn.ac.config.eventSuffix,e,o,f),this}n.fn.ac=function(){for(var t=[],e=0;e<arguments.length;e++)1===e&&n.isPlainObject(arguments[e])&&t.push(null),t.push(arguments[e]);return this.each(function(){u.apply(this,t)})},n.fn.ac.config={doneHandler:null,errorHandler:null,alwaysHandler:null,responseHandlers:{content:function(t,e){n(t).html(e)},remove:function(t,e){n(e).remove()},hide:function(t,e){n(e).hide()},show:function(t,e){n(e).show()},hideModal:function(t,e){n(e).modal("hide")},showMOdal:function(t,e){n(e).modal("show")},append:function(t,e){n(t).append(e)},prepend:function(t,e){n(t).prepend(e)}},ajaxAttrRegex:/acAjax(Accepts|Contents|Context|Converters|Data|Headers|StatusCode|XhrFields)?([a-z]*)/i,alertAttrRegex:/acAlert([a-z]*)/i,eventSuffix:".ac",preventDefault:!0,stopPropagation:!1,eventReturn:!0,alertInputDataKey:"input",alertAllowEmpty:!0,ajaxDefaults:{dataType:"json"},alertDefaults:{title:"Are you sure?",type:"warning",showCancelButton:!0},swal:"function"==typeof swal?swal:null,serializeObject:function(){var t={};return n.each(this.serializeArray(),function(n,e){var a=t[e.name];t[e.name]=void 0!==a&&null!==a?a+","+e.value:e.value}),t}};var s="ajax",d="alert"}(jQuery);
<|endoftext|>


<commit_before>
// DEFINITION
// ==========

// Function to enable event for show and hide of the section
(function ($) {
    $.each(['show', 'hide'], function (i, ev) {
        var el = $.fn[ev];
        $.fn[ev] = function () {
            this.trigger(ev);
            return el.apply(this, arguments);
        };
    });
})(jQuery);

// Global constants
var pages = ['home', 'nodes', 'reports', 'configurations', 'modules'];

// NAVIGATION
// ==========

// Click events for the navigation
pages.forEach(function (value, index, array) {
    $('#' + value + '-nav').click(function () { navigate(value); });
});

// Navigation function
function navigate(section) {

    // Hide all pages and remove navigation active highlighting
    pages.forEach(function (value, index, array) {
        $('#' + value + '-section').hide();
        $('#' + value + '-nav').parent().removeClass("active");
    });

    // Show the target page and mark the navigation as active
    $('#' + section + '-section').show();
    $('#' + section + '-nav').parent().addClass("active");

    // Hide the toggle navbar is needed
    if ($('.navbar-toggle').css('display') !== 'none') {
        $('.navbar-toggle').click();
    }
}

// Events for the content show (navigate to)
$('#home-section').on('show', function () { });
$('#nodes-section').on('show', function () { uiUpdateTable('nodes-id'); uiUpdateTable('nodes-names'); });
$('#reports-section').on('show', function () { uiUpdateTable('reports'); });
$('#configurations-section').on('show', function () { uiUpdateTable('configurations'); });
$('#modules-section').on('show', function () { uiUpdateTable('modules'); });

// Events for the content hide (navigate from)
$('#home-section').on('hide', function () { });
$('#nodes-section').on('hide', function () { uiClearTable('nodes-id'); uiUpdateTable('nodes-names'); });
$('#reports-section').on('hide', function () { uiClearTable('reports'); });
$('#configurations-section').on('hide', function () { uiClearTable('configurations'); });
$('#modules-section').on('hide', function () { uiClearTable('modules'); });

// USER INTERFACE
// ==============

$('#modal').on('hidden.bs.modal', function (e) {
    $('#modal-title').html('');
    $('#modal-text').html('');
});

function uiShowModal(title, text) {
    $('#modal-title').html(title);
    $('#modal-text').html(text);
    $('#modal').modal();
}

function uiShowModalHttpRequestError(xhr, message) {
    var verbose = "

";
    try {
        var responseObject = JSON.parse(xhr.responseText);
        verbose += "Message: " + responseObject.Message + "
";
        verbose += "Exception: " + responseObject.ExceptionMessage + "
";
        verbose += "Type: " + responseObject.ExceptionType + "

";
        verbose += "Stack Trace: " + responseObject.StackTrace + "
";
    }
    catch (error) {
        // No verbose message available
    }

    title = xhr.status + ' ' + xhr.statusText;
    text = message + '
' + verbose;

    uiShowModal(title, text);
}

function uiUpdateTable(page) {
    uiShowTableLoader(page);
    uiClearTable(page);
    $.getJSON('/api/v1/' + page.replace("-", "/"))
        .done(function (data) {
            $.each(data, function (key, item) {
                $('#table-' + page + '-content > div > table > tbody').append(uiCreateTableRow(page, item));
            });
        })
        .fail(function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Unable to refresh the ' + page + '.');
        });
    uiShowTableContent(page);
}

function uiClearTable(page) {
    $('#table-' + page + '-content > div > table > tbody').empty();
}

function uiShowTableLoader(page) {
    $('#table-' + page + '-content').hide();
    $('#table-' + page + '-loader').show();
}

function uiShowTableContent(page) {
    $('#table-' + page + '-loader').hide();
    $('#table-' + page + '-content').show();
}

function uiCreateTableRow(page, item) {
    var html;
    switch (page) {
        case "nodes-id":
            html += uiCreateTableCell(item.ConfigurationID);
            html += uiCreateTableCell(item.TargetName);
            html += uiCreateTableCell(item.NodeCompliant);
            html += uiCreateTableCell(item.Dirty);
            html += uiCreateTableCell(item.StatusCode);
            html += uiCreateTableCell(uiFormatDateTime(item.LastHeartbeatTime));
            html += uiCreateTableCell(uiFormatDateTime(item.LastComplianceTime));
            break;
        case "nodes-names":
            html += uiCreateTableCell(item.AgentId);
            html += uiCreateTableCell(item.NodeName);
            html += uiCreateTableCell(item.ConfigurationNames);
            html += uiCreateTableCell(uiFormatIPAddress(item.IPAddress));
            html += uiCreateTableCell(item.LCMVersion);
            break;
        case "reports":
            html += uiCreateTableCell(item.Id);
            html += uiCreateTableCell(item.NodeName);
            html += uiCreateTableCell(item.OperationType);
            html += uiCreateTableCell(uiFormatDateTime(item.StartTime));
            html += uiCreateTableCell(item.Status);
            break;
        case "configurations":
            html += uiCreateTableCell(item.Name);
            html += uiCreateTableCell(uiFormatSize(item.Size));
            html += uiCreateTableCell(uiFormatDateTime(item.Created));
            html += uiCreateTableCell(uiFormatChecksum(item.Checksum));
            html += uiCreateTableCell(uiFormatChecksumStatus(item.ChecksumStatus));
            html += uiCreateTableCell(
                uiCreateTableButtonDownload(page, item.Name, item.Name + '.mof') + ' ' +
                uiCreateTableButtonHash('apiHashConfiguration(\'' + item.Name + '\')') + ' ' +
                uiCreateTableButtonRemove('apiDeleteConfiguration(\'' + item.Name + '\')')
            );
            break;
        case 'modules':
            html += uiCreateTableCell(item.Name);
            html += uiCreateTableCell(item.Version);
            html += uiCreateTableCell(uiFormatSize(item.Size));
            html += uiCreateTableCell(uiFormatDateTime(item.Created));
            html += uiCreateTableCell(uiFormatChecksum(item.Checksum));
            html += uiCreateTableCell(uiFormatChecksumStatus(item.ChecksumStatus));
            html += uiCreateTableCell(
                uiCreateTableButtonDownload(page, item.Name + '/' + item.Version, item.Name + '_' + item.Version + '.zip') + ' ' +
                uiCreateTableButtonHash('apiHashModule(\'' + item.Name + '\', \'' + item.Version + '\')') + ' ' +
                uiCreateTableButtonRemove('apiDeleteModule(\'' + item.Name + '\', \'' + item.Version + '\')')
            );
            break;
    }
    return '
' + html + '
';
}

function uiCreateTableCell(html) {
    return '' + html + '	';
}

function uiCreateTableButtonDownload(page, relative, filename) {
    return '';
}

function uiCreateTableButtonHash(callback) {
    return '<button type="button" class="btn btn-default btn-xs" title="Calculate Checksum" onclick="' + callback + '"></button>';
}

function uiCreateTableButtonRemove(callback) {
    return '<button type="button" class="btn btn-danger btn-xs" title="Remove" onclick="' + callback + '"></button>';
}

function uiFormatDateTime(datetime) {
    return $.format.date(new Date(datetime), 'yyyy-MM-dd HH:mm:ss');
}

function uiFormatSize(size) {
    return Math.round(size / 1024) + ' KB';
}

function uiFormatChecksum(checksum) {
    return '' + checksum.substring(0, 8).toLowerCase() + '' + checksum.toLowerCase() + '';
}

function uiFormatChecksumStatus(checksumStatus) {
    switch (checksumStatus) {
        case 'Valid':
            style = 'success';
            break;
        case 'Invalid':
            style = 'danger';
            break;
        case 'Missing':
            style = 'warning';
            break;
        default:
            style = 'default';
    }
    return '' + checksumStatus + '';
}

function uiFormatIPAddress(ipAddress) {
    var ipAddresses = new Array();
    ipAddress.split(";").forEach(function (value, index, array) {
        if (value !== '::1' && value !== '127.0.0.1' && value !== '::2000:0:0:0' && value.lastIndexOf('fe80:', 0) !== 0) {
            ipAddresses.push(value);
        }
    });
    return ipAddresses.join("
")
}

// EVENT LISTENERS: NODES
// ===============================

$('#nodesIdRefreshButton').on("click", function (e) {
    uiUpdateTable('nodes-id');
});

$('#nodesNamesRefreshButton').on("click", function (e) {
    uiUpdateTable('nodes-names');
});

// EVENT LISTENERS: REPORTS
// ===============================

$('#reportsRefreshButton').on("click", function (e) {
    uiUpdateTable('reports');
});

// EVENT LISTENERS: CONFIGURATIONS
// ===============================

$('#configurationsUploadButton').on('change', function (e) {
    if (e.target.files.length !== 1) {
        uiShowModal('Configuration Upload Failed', 'Please select exactly one file to upload.');
        return;
    }
    if (this.value.lastIndexOf('.mof') === -1) {
        uiShowModal('Configuration Upload Failed', 'Please select a valid MOF-file with the extension .mof.');
        return;
    }
    if (window.FormData === undefined) {
        uiShowModal('Configuration Upload Failed', 'This browser doesn\'t support HTML5 file uploads.');
        return;
    }
    apiUploadConfiguration(e.target.files[0]);
    $('#configurationsUploadButton').val('');
});

$('#configurationsRefreshButton').on("click", function (e) {
    uiUpdateTable('configurations');
});

// EVENT LISTENERS: MODULES
// ========================

$('#modulesUploadButton').on('change', function (e) {
    if (e.target.files.length !== 1) {
        uiShowModal('Module Upload Failed', 'Please select exactly one file to upload.');
        return;
    }
    if (this.value.lastIndexOf('.zip') === -1) {
        uiShowModal('Module Upload Failed', 'Please select a valid zip-file with the extension .zip.');
        return;
    }
    if (window.FormData === undefined) {
        uiShowModal('Module Upload Failed', 'This browser doesn\'t support HTML5 file uploads.');
        return;
    }
    apiUploadModule(e.target.files[0]);
    $('#modulesUploadButton').val('');
});

$('#modulesRefreshButton').on("click", function (e) {
    uiUpdateTable('modules');
});

// WEB API CALLS: CONFIGURATIONS
// =============================

function apiUploadConfiguration(file) {
    var name = file.name.substring(0, file.name.length - 4);
    $.ajax({
        type: "PUT",
        url: '/api/v1/configurations/' + name,
        contentType: false,
        processData: false,
        data: file,
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to upload the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

function apiHashConfiguration(name) {
    $.ajax({
        url: '/api/v1/configurations/' + name + '/checksum',
        type: 'PATCH',
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to hash the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

function apiDeleteConfiguration(name) {
    $.ajax({
        url: '/api/v1/configurations/' + name,
        type: 'DELETE',
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to delete the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

// WEB API CALLS: MODULES
// ======================

function apiUploadModule(file) {
    var parts = file.name.substring(0, file.name.length - 4).split('_', 2);
    var name    = parts[0];
    var version = parts[1];
    $.ajax({
        type: "PUT",
        url: '/api/v1/modules/' + name + '/' + version,
        contentType: false,
        processData: false,
        data: file,
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to upload the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

function apiHashModule(name, version) {
    $.ajax({
        url: '/api/v1/modules/' + name + '/' + version + '/checksum',
        type: 'PATCH',
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to hash the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

function apiDeleteModule(name, version) {
    $.ajax({
        url: '/api/v1/modules/' + name + '/' + version,
        type: 'DELETE',
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to delete the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

<commit_msg>Fixes #2<commit_after>
// DEFINITION
// ==========

// Function to enable event for show and hide of the section
(function ($) {
    $.each(['show', 'hide'], function (i, ev) {
        var el = $.fn[ev];
        $.fn[ev] = function () {
            this.trigger(ev);
            return el.apply(this, arguments);
        };
    });
})(jQuery);

// Global constants
var pages = ['home', 'nodes', 'reports', 'configurations', 'modules'];

// NAVIGATION
// ==========

// Click events for the navigation
pages.forEach(function (value, index, array) {
    $('#' + value + '-nav').click(function () { navigate(value); });
});

// Navigation function
function navigate(section) {

    // Hide all pages and remove navigation active highlighting
    pages.forEach(function (value, index, array) {
        $('#' + value + '-section').hide();
        $('#' + value + '-nav').parent().removeClass("active");
    });

    // Show the target page and mark the navigation as active
    $('#' + section + '-section').show();
    $('#' + section + '-nav').parent().addClass("active");

    // Hide the toggle navbar is needed
    if ($('.navbar-toggle').css('display') !== 'none') {
        $('.navbar-toggle').click();
    }
}

// Events for the content show (navigate to)
$('#home-section').on('show', function () { });
$('#nodes-section').on('show', function () { uiUpdateTable('nodes-id'); uiUpdateTable('nodes-names'); });
$('#reports-section').on('show', function () { uiUpdateTable('reports'); });
$('#configurations-section').on('show', function () { uiUpdateTable('configurations'); });
$('#modules-section').on('show', function () { uiUpdateTable('modules'); });

// Events for the content hide (navigate from)
$('#home-section').on('hide', function () { });
$('#nodes-section').on('hide', function () { uiClearTable('nodes-id'); uiUpdateTable('nodes-names'); });
$('#reports-section').on('hide', function () { uiClearTable('reports'); });
$('#configurations-section').on('hide', function () { uiClearTable('configurations'); });
$('#modules-section').on('hide', function () { uiClearTable('modules'); });

// USER INTERFACE
// ==============

$('#modal').on('hidden.bs.modal', function (e) {
    $('#modal-title').html('');
    $('#modal-text').html('');
});

function uiShowModal(title, text) {
    $('#modal-title').html(title);
    $('#modal-text').html(text);
    $('#modal').modal();
}

function uiShowModalHttpRequestError(xhr, message) {
    var verbose = "

";
    try {
        var responseObject = JSON.parse(xhr.responseText);
        verbose += "Message: " + responseObject.Message + "
";
        verbose += "Exception: " + responseObject.ExceptionMessage + "
";
        verbose += "Type: " + responseObject.ExceptionType + "

";
        verbose += "Stack Trace: " + responseObject.StackTrace + "
";
    }
    catch (error) {
        // No verbose message available
    }

    title = xhr.status + ' ' + xhr.statusText;
    text = message + '
' + verbose;

    uiShowModal(title, text);
}

function uiUpdateTable(page) {
    uiShowTableLoader(page);
    uiClearTable(page);
    $.getJSON('/api/v1/' + page.replace("-", "/"))
        .done(function (data) {
            $.each(data, function (key, item) {
                $('#table-' + page + '-content > div > table > tbody').append(uiCreateTableRow(page, item));
            });
        })
        .fail(function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Unable to refresh the ' + page + '.');
        });
    uiShowTableContent(page);
}

function uiClearTable(page) {
    $('#table-' + page + '-content > div > table > tbody').empty();
}

function uiShowTableLoader(page) {
    $('#table-' + page + '-content').hide();
    $('#table-' + page + '-loader').show();
}

function uiShowTableContent(page) {
    $('#table-' + page + '-loader').hide();
    $('#table-' + page + '-content').show();
}

function uiCreateTableRow(page, item) {
    var html;
    switch (page) {
        case "nodes-id":
            html += uiCreateTableCell(item.ConfigurationID);
            html += uiCreateTableCell(item.TargetName);
            html += uiCreateTableCell(item.NodeCompliant);
            html += uiCreateTableCell(item.Dirty);
            html += uiCreateTableCell(item.StatusCode);
            html += uiCreateTableCell(uiFormatDateTime(item.LastHeartbeatTime));
            html += uiCreateTableCell(uiFormatDateTime(item.LastComplianceTime));
            break;
        case "nodes-names":
            html += uiCreateTableCell(item.AgentId);
            html += uiCreateTableCell(item.NodeName);
            html += uiCreateTableCell(item.ConfigurationNames);
            html += uiCreateTableCell(uiFormatIPAddress(item.IPAddress));
            html += uiCreateTableCell(item.LCMVersion);
            break;
        case "reports":
            html += uiCreateTableCell(item.Id);
            html += uiCreateTableCell(item.NodeName);
            html += uiCreateTableCell(item.OperationType);
            html += uiCreateTableCell(uiFormatDateTime(item.StartTime));
            html += uiCreateTableCell(item.Status);
            break;
        case "configurations":
            html += uiCreateTableCell(item.Name);
            html += uiCreateTableCell(uiFormatSize(item.Size));
            html += uiCreateTableCell(uiFormatDateTime(item.Created));
            html += uiCreateTableCell(uiFormatChecksum(item.Checksum));
            html += uiCreateTableCell(uiFormatChecksumStatus(item.ChecksumStatus));
            html += uiCreateTableCell(
                uiCreateTableButtonDownload(page, item.Name, item.Name + '.mof') + ' ' +
                uiCreateTableButtonHash('apiHashConfiguration(\'' + item.Name + '\')') + ' ' +
                uiCreateTableButtonRemove('apiDeleteConfiguration(\'' + item.Name + '\')')
            );
            break;
        case 'modules':
            html += uiCreateTableCell(item.Name);
            html += uiCreateTableCell(item.Version);
            html += uiCreateTableCell(uiFormatSize(item.Size));
            html += uiCreateTableCell(uiFormatDateTime(item.Created));
            html += uiCreateTableCell(uiFormatChecksum(item.Checksum));
            html += uiCreateTableCell(uiFormatChecksumStatus(item.ChecksumStatus));
            html += uiCreateTableCell(
                uiCreateTableButtonDownload(page, item.Name + '/' + item.Version, item.Name + '_' + item.Version + '.zip') + ' ' +
                uiCreateTableButtonHash('apiHashModule(\'' + item.Name + '\', \'' + item.Version + '\')') + ' ' +
                uiCreateTableButtonRemove('apiDeleteModule(\'' + item.Name + '\', \'' + item.Version + '\')')
            );
            break;
    }
    return '
' + html + '
';
}

function uiCreateTableCell(html) {
    return '' + html + '	';
}

function uiCreateTableButtonDownload(page, relative, filename) {
    return '';
}

function uiCreateTableButtonHash(callback) {
    return '<button type="button" class="btn btn-default btn-xs" title="Calculate Checksum" onclick="' + callback + '"></button>';
}

function uiCreateTableButtonRemove(callback) {
    return '<button type="button" class="btn btn-danger btn-xs" title="Remove" onclick="' + callback + '"></button>';
}

function uiFormatDateTime(datetime) {
    return $.format.date(new Date(datetime), 'yyyy-MM-dd HH:mm:ss');
}

function uiFormatSize(size) {
    return Math.round(size / 1024) + ' KB';
}

function uiFormatChecksum(checksum) {
    return '' + checksum.substring(0, 8).toLowerCase() + '' + checksum.toLowerCase() + '';
}

function uiFormatChecksumStatus(checksumStatus) {
    switch (checksumStatus) {
        case 'Valid':
            style = 'success';
            break;
        case 'Invalid':
            style = 'danger';
            break;
        case 'Missing':
            style = 'warning';
            break;
        default:
            style = 'default';
    }
    return '' + checksumStatus + '';
}

function uiFormatIPAddress(ipAddress) {
    var ipAddresses = new Array();
    ipAddress.split(";").forEach(function (value, index, array) {
        if (value !== '::1' && value !== '127.0.0.1' && value !== '::2000:0:0:0' && value.lastIndexOf('fe80:', 0) !== 0) {
            ipAddresses.push(value);
        }
    });
    return ipAddresses.join("
")
}

// EVENT LISTENERS: NODES
// ===============================

$('#nodesIdRefreshButton').on("click", function (e) {
    uiUpdateTable('nodes-id');
});

$('#nodesNamesRefreshButton').on("click", function (e) {
    uiUpdateTable('nodes-names');
});

// EVENT LISTENERS: REPORTS
// ===============================

$('#reportsRefreshButton').on("click", function (e) {
    uiUpdateTable('reports');
});

// EVENT LISTENERS: CONFIGURATIONS
// ===============================

$('#configurationsUploadButton').on('change', function (e) {
    if (e.target.files.length === 0) {
        // No file selected
        return
    }
    if (e.target.files.length !== 1) {
        uiShowModal('Configuration Upload Failed', 'Please select exactly one file to upload.');
        return;
    }
    if (this.value.lastIndexOf('.mof') === -1) {
        uiShowModal('Configuration Upload Failed', 'Please select a valid MOF-file with the extension .mof.');
        return;
    }
    if (window.FormData === undefined) {
        uiShowModal('Configuration Upload Failed', 'This browser doesn\'t support HTML5 file uploads.');
        return;
    }
    apiUploadConfiguration(e.target.files[0]);
    $('#configurationsUploadButton').val('');
});

$('#configurationsRefreshButton').on("click", function (e) {
    uiUpdateTable('configurations');
});

// EVENT LISTENERS: MODULES
// ========================

$('#modulesUploadButton').on('change', function (e) {
    if (e.target.files.length === 0) {
        // No file selected
        return
    }
    if (e.target.files.length !== 1) {
        uiShowModal('Module Upload Failed', 'Please select exactly one file to upload.');
        return;
    }
    if (this.value.lastIndexOf('.zip') === -1) {
        uiShowModal('Module Upload Failed', 'Please select a valid zip-file with the extension .zip.');
        return;
    }
    if (window.FormData === undefined) {
        uiShowModal('Module Upload Failed', 'This browser doesn\'t support HTML5 file uploads.');
        return;
    }
    apiUploadModule(e.target.files[0]);
    $('#modulesUploadButton').val('');
});

$('#modulesRefreshButton').on("click", function (e) {
    uiUpdateTable('modules');
});

// WEB API CALLS: CONFIGURATIONS
// =============================

function apiUploadConfiguration(file) {
    var name = file.name.substring(0, file.name.length - 4);
    $.ajax({
        type: "PUT",
        url: '/api/v1/configurations/' + name,
        contentType: false,
        processData: false,
        data: file,
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to upload the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

function apiHashConfiguration(name) {
    $.ajax({
        url: '/api/v1/configurations/' + name + '/checksum',
        type: 'PATCH',
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to hash the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

function apiDeleteConfiguration(name) {
    $.ajax({
        url: '/api/v1/configurations/' + name,
        type: 'DELETE',
        success: function (result) {
            uiUpdateTable('configurations');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to delete the configuration ' + name + '.');
            uiUpdateTable('configurations');
        }
    });
}

// WEB API CALLS: MODULES
// ======================

function apiUploadModule(file) {
    var parts = file.name.substring(0, file.name.length - 4).split('_', 2);
    var name    = parts[0];
    var version = parts[1];
    $.ajax({
        type: "PUT",
        url: '/api/v1/modules/' + name + '/' + version,
        contentType: false,
        processData: false,
        data: file,
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to upload the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

function apiHashModule(name, version) {
    $.ajax({
        url: '/api/v1/modules/' + name + '/' + version + '/checksum',
        type: 'PATCH',
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to hash the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

function apiDeleteModule(name, version) {
    $.ajax({
        url: '/api/v1/modules/' + name + '/' + version,
        type: 'DELETE',
        success: function (result) {
            uiUpdateTable('modules');
        },
        error: function (xhr) {
            uiShowModalHttpRequestError(xhr, 'Failed to delete the module ' + name + ' with version ' + version + '.');
            uiUpdateTable('modules');
        }
    });
}

<|endoftext|>


<commit_before>import warning from 'warning'
import { pipe } from './utils'
import { normalizeHref, parseQS } from './utils-path'
import { prefixSpec } from './spec'

/*
function findPath(specs, pathKey) {
  let result
  specs.find(spec => !!(result = spec.find(pathKey)))
  return result
}

function addPrefix(prefix, path) {
  return isStr(prefix) && path.indexOf(prefix) !== 0 ? `${prefix}${path}` : path
}

function linkFromPathKey(specs, prefix, pathKey, values = [], usePrefix = true) {
  let link, path = findPath(specs, pathKey)
  if (usePrefix && path) link = addPrefix(prefix, path.makeLink(values))
  return link || ''
}
*/

function toggle(match) {
  let { off } = match, on = off
  if (!off) {
    on = { $off: match, match: () => false, resolve: () => false }
  }
  return on
}

function matcher(specs, checks, msg) {
  let spec, result, { href } = msg
  spec = specs.find(spec => !!(result = spec.match(checks, href)))
  let success = spec && spec.success(result)
  result = Object.assign({}, msg, result)
  return { result, success, spec }
}

function resolve({ result, success, spec }) {
  warning(!(spec && !success), 'Resolve location with a partial match: %s', result && result.href)
  return spec ? spec.resolve(result, success) : false
}

function matchPrefix(matcher) {
  let { prefix, match, checks } = matcher, result = matcher
  if (prefix) {
    let pspec = prefixSpec(prefix, match)
    result.match = pspec.match.bind(pspec, checks)
  }
  return result
}

function prematch(specCheck, msg) {
  let { prefix, href, path, qs } = msg
  href = normalizeHref(prefix)(href)
  path = normalizeHref(prefix)(path)
  if (specCheck) {
    href = normalizeHref()(specCheck(parseQS.bind(null, qs), path, href))
  }
  return href === msg.href ? msg : Object.assign({}, msg, { href })
}

export function match(specs, checks = {}, prefix, specCheck, key) {
  if (!Array.isArray(specs)) specs = [].concat(specs)
  let match = pipe(prematch.bind(null, specCheck), result.bind(null, specs, checks))
  let result = { match, resolve, prefix, specs, checks, key }
  return matchPrefix(Object.assign(result, { toggle: toggle.bind(null, result) }))
}
<commit_msg>bug fixes in toggle wip<commit_after>import warning from 'warning'
import { pipe } from './utils'
import { normalizeHref, parseQS } from './utils-path'
import { prefixSpec } from './spec'

/*
function findPath(specs, pathKey) {
  let result
  specs.find(spec => !!(result = spec.find(pathKey)))
  return result
}

function addPrefix(prefix, path) {
  return isStr(prefix) && path.indexOf(prefix) !== 0 ? `${prefix}${path}` : path
}

function linkFromPathKey(specs, prefix, pathKey, values = [], usePrefix = true) {
  let link, path = findPath(specs, pathKey)
  if (usePrefix && path) link = addPrefix(prefix, path.makeLink(values))
  return link || ''
}
*/

function toggle(match) {
  let { off, key } = match, on = off
  if (!off) {
    on = { key, off: match, match: () => false, resolve: () => false }
    on.toggle = toggle.bind(null, on)
  }
  return on
}

function matcher(specs, checks, msg) {
  let spec, result, { href } = msg
  spec = specs.find(spec => !!(result = spec.match(checks, href)))
  let success = spec && spec.success(result)
  result = Object.assign({}, msg, result)
  return { result, success, spec }
}

function resolve({ result, success, spec }) {
  warning(!(spec && !success), 'Resolve location with a partial match: %s', result && result.href)
  return spec ? spec.resolve(result, success) : false
}

function matchPrefix(matcher) {
  let { prefix, match, checks } = matcher, result = matcher
  if (prefix) {
    let pspec = prefixSpec(prefix, match)
    result.match = pspec.match.bind(pspec, checks)
  }
  return result
}

function prematch(specCheck, msg) {
  let { prefix, href, path, qs } = msg
  href = normalizeHref(prefix)(href)
  path = normalizeHref(prefix)(path)
  if (specCheck) {
    href = normalizeHref()(specCheck(parseQS.bind(null, qs), path, href))
  }
  return href === msg.href ? msg : Object.assign({}, msg, { href })
}

export function match(specs, checks = {}, prefix, specCheck, key) {
  if (!Array.isArray(specs)) specs = [].concat(specs)
  let match = pipe(prematch.bind(null, specCheck), matcher.bind(null, specs, checks))
  let result = { match, resolve, prefix, specs, checks, key }
  return matchPrefix(Object.assign({ toggle: toggle.bind(null, result) }, result))
}
<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    var emotions = JSON.parse($("#emotionJSON").val());
    addGraph(emotions);

})

function addGraph(emotions) {
  var data = emotions.slice();
  for(var i = 0; i < data.length; i++) {
    if (data[i]['_id']=='default') {
      data.splice(i, 1);
      break;
    }
  }
  var w = 300;
  var h = 400;
  var x = d3.scale.linear()
    .domain([0, d3.max(data, function(d) {return d.count; })])
    .range([0, w-90]);

  var canvas = d3.select(".container").append("svg")
                .attr("width", w)
                .attr("height", h)
              .append("g")
                //.attr("transform", "translate(20,0)");

  var bars = canvas.selectAll(".bar")
     .data(data)
     .enter().append("g")
     .attr("class", "bar")
     //.attr("transform", function(d, i ) {return "translate("+0+","+(i*50) + ")"});

  bars.append("rect")
   .on("click", function(d){click(d)})
   .attr("y", function(d,i) {return i * 50;})
   .attr("width", 0)
   .attr("height", 45)
   .attr("fill", "white")
   .transition()
    .duration(300)
    //.ease("quad")
    .attr("width", function(d) {return x(d.count); });

  bars.append("text")
       .attr("x", function(d) {return x(d.count); })
       .attr("dx", 10)
       .attr("y", function(d,i) {return i * 50 + 25;})
       .attr("text-anchor", "start")
       .attr("fill", "#196966")
       .text(function (d) {return d._id+" ("+d.count+")"; });

  function click(d) {
    window.location.href="/search?queryString="+d._id+"&queryField=emotion";
  }
}<commit_msg>speed<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    var emotions = JSON.parse($("#emotionJSON").val());
    addGraph(emotions);

})

function addGraph(emotions) {
  var data = emotions.slice();
  for(var i = 0; i < data.length; i++) {
    if (data[i]['_id']=='default') {
      data.splice(i, 1);
      break;
    }
  }
  var w = 300;
  var h = 400;
  var x = d3.scale.linear()
    .domain([0, d3.max(data, function(d) {return d.count; })])
    .range([0, w-90]);

  var canvas = d3.select(".container").append("svg")
                .attr("width", w)
                .attr("height", h)
              .append("g")
                //.attr("transform", "translate(20,0)");

  var bars = canvas.selectAll(".bar")
     .data(data)
     .enter().append("g")
     .attr("class", "bar")
     //.attr("transform", function(d, i ) {return "translate("+0+","+(i*50) + ")"});

  bars.append("rect")
   .on("click", function(d){click(d)})
   .attr("y", function(d,i) {return i * 50;})
   .attr("width", 0)
   .attr("height", 45)
   .attr("fill", "white")
   .transition()
    .duration(500)
    //.ease("quad")
    .attr("width", function(d) {return x(d.count); });

  bars.append("text")
       .attr("x", function(d) {return x(d.count); })
       .attr("dx", 10)
       .attr("y", function(d,i) {return i * 50 + 25;})
       .attr("text-anchor", "start")
       .attr("fill", "#196966")
       .text(function (d) {return d._id+" ("+d.count+")"; });

  function click(d) {
    window.location.href="/search?queryString="+d._id+"&queryField=emotion";
  }
}<|endoftext|>