<commit_before>// Description:
//   Show current reviews api status page
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   hubot status <application> <monitor> [<server>] - Returns the current state of the given application
//   hubot status show aliases - List all aliases
//   hubot set alias <app> <server> <url> - Stores a new alias for the specified application
var Url = require('url'),
    aliases,
    logger;

module.exports = function(robot){
  logger = robot.logger;

  robot.brain.on('loaded', function(){
      aliases = robot.brain.data.apiStatusAliases || {};
  });

  robot.respond(/status ((?![show|set])\S+) (\S+)(?:\s)?([\S|\S]+)?$/i, function(msg){
    status(msg);
  });

  robot.respond(/status show aliases$/i, function(msg){
    showAliases(msg);
  });

  robot.respond(/status set alias (\S+) (\S+) (\S+)$/i, function(msg){
    setAlias(msg, robot);
  });
};

var status = function(msg){
  var bits = {
    app: msg.match[1],
    monitor: msg.match[2],
    server: msg.match[3]
  };

  validateRequest(bits, msg, function(){
    for(var i=0; i<bits.server.length; i++){
        sendRequest(buildUrl(bits.app, bits.monitor, bits.server[i]), msg, bits.server[i], function(status, servername){
            if(!status){
                msg.send("I didn't get a valid response, you're SOL, sorry");
                return;
            }
            if(status === "Unknown"){
                msg.send("That monitor does not exist you wanker");
                return;
            }
            msg.send(bits.app + " " + bits.monitor + " " + servername + ", Current Status: " + status);
        });
    }
  });
},

validateRequest = function(bits, msg, callback){
  if(!aliases[bits.app]){
    msg.send("the alias '" + bits.app + "' does not exist you fuckhead");
    return;
  }
  if(!bits.server){
    bits.server = getServersForAlias(bits.app);
  }
  else if(!aliases[bits.app][bits.server]){
    msg.send("the server '" + bits.server + "' does not exist for app '" + bits.app + "' you tosspot");
    return;
  }
  else{
      bits.server = [bits.server];
  }
  logger.debug(bits);
  callback();
},

buildUrl = function(app, monitor, server){
  return aliases[app][server] + monitor;
},

sendRequest = function(url, msg, servername, cb){
  logger.info(url);
  msg.http(url)
    .get()(function(err, res, body){
      var json = JSON.parse(body);
      cb(json.Status || json.status, servername);
    });
},

showAliases = function(msg){
  var response = '';
  for(var al in aliases){
    response += al + ':\n';
    for(var s in aliases[al]){
      response += "  " + s + ": " + aliases[al][s] + "\n";
    }
  }
  msg.send(response);
},

getServersForAlias = function(app){
  var res = [];
  for(var s in aliases[app]){
    res.push(s);
  }
  return res;
},

setAlias = function(msg, robot){
    var bits = {
        app: msg.match[1],
        server: msg.match[2],
        url: msg.match[3]
    };

    var url = Url.parse(bits.url);

    if(!url.protocol || !url.host){
        msg.send("Check yo damn urls dawg");
        return;
    }

    if(!aliases[bits.app]){
        aliases[bits.app] = {};
    }

    aliases[bits.app][bits.server] = bits.url;
    robot.brain.data.apiStatusAliases = aliases;
    msg.send('Ok, alias for ' + bits.app + ' ' + bits.server + ' was set');
};<commit_msg>add command to clear an alias or all aliases for an app<commit_after>// Description:
//   Show current reviews api status page
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   hubot status <application> <monitor> [<server>] - Returns the current state of the given application
//   hubot status show aliases - List all aliases
//   hubot status set alias <app> <server> <url> - Stores a new alias for the specified application
//   hubot status clear alias <app> [<server] - Clears an alias

var Url = require('url'),
    aliases,
    logger;

module.exports = function(robot){
  logger = robot.logger;

  robot.brain.on('loaded', function(){
      aliases = robot.brain.data.apiStatusAliases || {};
  });

  robot.respond(/status ((?![show|set|clear])\S+) (\S+)(?:\s)?([\S|\S]+)?$/i, function(msg){
    status(msg);
  });

  robot.respond(/status show aliases$/i, function(msg){
    showAliases(msg);
  });

  robot.respond(/status set alias (\S+) (\S+) (\S+)$/i, function(msg){
    setAlias(msg, robot);
  });

  robot.respond(/status clear alias (\S+)(?:\s)?(\S+)?$/i, function(msg){
    clearAlias(msg, robot);
  });
};

var status = function(msg){
  var bits = {
    app: msg.match[1],
    monitor: msg.match[2],
    server: msg.match[3]
  };

  validateRequest(bits, msg, function(){
    for(var i=0; i<bits.server.length; i++){
        sendRequest(buildUrl(bits.app, bits.monitor, bits.server[i]), msg, bits.server[i], function(status, servername){
            if(!status){
                msg.send("I didn't get a valid response, you're SOL, sorry");
                return;
            }
            if(status === "Unknown"){
                msg.send("That monitor does not exist you wanker");
                return;
            }
            msg.send(bits.app + " " + bits.monitor + " " + servername + ", Current Status: " + status);
        });
    }
  });
},

validateRequest = function(bits, msg, callback){
  if(!aliases[bits.app]){
    msg.send("the alias '" + bits.app + "' does not exist you fuckhead");
    return;
  }
  if(!bits.server){
    bits.server = getServersForAlias(bits.app);
  }
  else if(!aliases[bits.app][bits.server]){
    msg.send("the server '" + bits.server + "' does not exist for app '" + bits.app + "' you tosspot");
    return;
  }
  else{
      bits.server = [bits.server];
  }
  logger.debug(bits);
  callback();
},

buildUrl = function(app, monitor, server){
  return aliases[app][server] + monitor;
},

sendRequest = function(url, msg, servername, cb){
  logger.info(url);
  msg.http(url)
    .get()(function(err, res, body){
      var json = JSON.parse(body);
      cb(json.Status || json.status, servername);
    });
},

showAliases = function(msg){
  var response = '';
  for(var al in aliases){
    response += al + ':\n';
    for(var s in aliases[al]){
      response += "  " + s + ": " + aliases[al][s] + "\n";
    }
  }
  msg.send(response);
},

getServersForAlias = function(app){
  var res = [];
  for(var s in aliases[app]){
    res.push(s);
  }
  return res;
},

setAlias = function(msg, robot){
    var bits = {
        app: msg.match[1],
        server: msg.match[2],
        url: msg.match[3]
    };

    var url = Url.parse(bits.url);

    if(!url.protocol || !url.host){
        msg.send("Check yo damn urls dawg");
        return;
    }

    if(!aliases[bits.app]){
        aliases[bits.app] = {};
    }

    aliases[bits.app][bits.server] = bits.url;
    robot.brain.data.apiStatusAliases = aliases;
    msg.send('Ok, alias for ' + bits.app + ' ' + bits.server + ' was set');
},

clearAlias = function(msg, robot){
    var app = msg.match[1],
        server = msg.match[2];

    if(!server){
        delete aliases[app];
        msg.send('Ok, all aliases for ' + app + ' were cleared');
    }
    else{
        delete aliases[app][server];
        msg.send('Ok, alias for ' + app + ' ' + server + ' was cleared');
    }

    robot.brain.data.apiStatusAliases = aliases;
};<|endoftext|>


<commit_before>var author = "Louis Gualtieri",
	version = "0.0.1",
	now = new Date(),
	year = now.getFullYear(),
	class_to_type = {},
	toString = class_to_type.toString,
	expr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;<commit_msg>Updated package<commit_after>var author = "Louis Gualtieri",
	version = "1.0.1",
	now = new Date(),
	year = now.getFullYear(),
	class_to_type = {},
	toString = class_to_type.toString,
	expr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;<|endoftext|>


<commit_before>function getUrlVars() {
  "use strict";
  var vars = {};
  window.location.href.replace(/[?&#]+([^=&]+)=([^&#]*)/gi, function (m, key, value) {
    vars[key] = decodeURIComponent(value);
  });
  return vars;
}

function make_uri(uri, options) {
  "use strict";
  var ops = {};
  $.extend(ops, getUrlVars());
  if (options !== null) {
    $.extend(ops, options);
  }
  var str = $.map(ops, function (val, index) {
    return index + "=" + encodeURIComponent(val).toLowerCase();
  }).join("&");

  return (str === "") ? uri : uri + "?" + str;
}

function reload(extra) {
  "use strict";
  window.location.search = make_uri ("", extra);
}

function update_url(extra) {
  var ops = {};
  $.extend(ops, getUrlVars ());
  if (extra !== null) {
    $.extend(ops, extra);
  }
  window.location.hash = $.map(ops, function (val, index) {
    return val ? (index + "=" + encodeURIComponent(val)) : null;
  }).join("&");
}

function initSingleSelector(selector_id, property, dataSet, update_handler) {
  var values = {};
  var result = [];
  var value, key;

  for (var i = 0; i < dataSet.length; i++) {
    var element = dataSet[i][property];
    if (element instanceof Array) {
      for (key in element)
        if (key) {
          values[element[key]] = element[key];
        }
    } else {
      values[element] = element;
    }
  }

  for (value in values)
    if (value) {
      result.push({"id": value, "text": value});
    }

  $("#" + selector_id).
    val (getUrlVars()[property]).
    on("select2-selecting", function (e) {
      var options = {};
      options[property] = e.val;
      update_url (options);
      update_handler ();
    }).
  on("select2-removed", function (e) {
    var options = {};
    options[property] = '';
    update_url (options);
    update_handler ();
  }).
  select2({data: result, allowClear: true});
}

function filterData (tableData, filters) {
  var filteredData = [];
  var key, column;

  for (var i = 0; i < tableData.length; i++) {
    var row = tableData[i];
    var filtered = true;

    for (column in filters) {
      if (column in row) {
        if (row[column] instanceof Array) {
          filtered = false;
          for (key in row[column])
            if (filters[column] == row[column][key]) {
              filtered = true;
            }
        } else {
          if (filters[column] != row[column]) {
            filtered = false;
          }
        }
      }
      if (filtered == false) {
        break;
      }
    }

    if (filtered) {
      filteredData.push(row);
    }
  }

  return filteredData;
}

function populate_table (table_id, table_column_names, tableData)
{
  var tableColumns = [];
  for (var i = 0; i < table_column_names.length; i++) {
    tableColumns.push({"mData": table_column_names[i]});
    for (var j = 0; j < tableData.length; j++) {
      if (!(table_column_names[i] in tableData[j])) {
        tableData[j][table_column_names[i]] = "";
      }
    }
  }

  if (table_id) {
    $("#" + table_id).dataTable({
      "aLengthMenu": [
        [5, 10, 25, 50, -1],
        [5, 10, 25, 50, "All"]
      ],
      "bDestroy": true,
      "iDisplayLength": -1,
      "bAutoWidth": false,
      "bPaginate": true,
      "pagingType": "full_numbers",
      "aaData": tableData,
      "aoColumns": tableColumns
    });
  }
}

function showInfoDialog (tab, info) {
  $("#info-container").empty();
  $("#" + tab + "-info").tmpl(info).appendTo("#info-container");
  $("#info-dialog").dialog("open");
  $("button").focus ();
}

function showInfoPage (tab, info)
{
  $("#info-content").empty();
  $("#" + tab + "-info").tmpl(info).appendTo("#info-content");
  $( ".content" ).hide ();
  $( "#info-page" ).show ();
  update_url ({ tab : tab, asset : info.name});
  $(".value").replaceWith (function(idx, element) {
    return element.replace (/https?:\/\/[^ \t\n\r]+/gi, '$&');
  });
}

function setupInfoHandler (tab, element_id, info) {
  info.name_html = "" + info.name + "";

  $("#" + tab + "-table").on("click", "#" + tab + "-" + element_id, function (event) {
    event.preventDefault();
    event.stopPropagation();

    showInfoPage (tab, info);
  });
}

var glance_images = { assets: [] };

function show_glance_images ()
{
  populate_table ("glance-images-table",
      ["name_html", "description", "disk_format", "license"],
      filterData (glance_images.assets, getUrlVars ()));
}

var heat_templates = { assets: [] };

function show_heat_templates ()
{
  populate_table ("heat-templates-table",
      ["name_html", "description", "release_html", "format"],
      filterData (heat_templates.assets, getUrlVars ()));
}

var murano_apps = { assets: [] };

function show_murano_apps ()
{
  populate_table ("murano-apps-table",
      ["name_html", "description", "release_html", "format"],
      filterData (murano_apps.assets, getUrlVars ()));
}

function initTabs ()
{
  $( "ul.nav > li > a" ).on("click", function (event) {
    event.preventDefault ();
  });
  $( "ul.nav > li" ).not(":last-child").on("click", function (event) {
    update_url ({ tab : this.children[0].hash.substring (1), asset: "" });
  });
  $( "ul.nav > li:last-child").on("click", function (event) {
    window.open('https://wiki.openstack.org/wiki/App-Catalog#How_to_contribute', '_blank');
  });
}

function show_asset (tab, tableData)
{
  var options = getUrlVars ();
  if ((tab == options.tab) && ("asset" in options)) {
    for (var i = 0; i < tableData.length; ++i) {
      if (tableData[i].name == options.asset) {
        showInfoPage (tab, tableData[i]);
      }
    }
  }
}

function initMarketPlace ()
{
  navigate ();
  initTabs ();
  $( ".inner" ).matchHeight ();

  $("#info-dialog").dialog({
    autoOpen: false,
    width: "70%",
    modal: true,
    buttons: {
      Close: function () {
        $(this).dialog("close");
      }
    },
    close: function () { }
  });

  $.ajax({ url: "static/glance_images.yaml" }).
    done (function (data) {
      try {
        glance_images = jsyaml.safeLoad (data);
      } catch (e) {
      }
      var tableData = glance_images.assets;
      for (var i = 0; i < tableData.length; i++) {
        setupInfoHandler ("glance-images", i, tableData[i]);
      }

      show_asset ("glance-images", tableData);
      show_glance_images ();
    });

  $.ajax({ url: "static/heat_templates.yaml" }).
    done (function (data) {
      try {
        heat_templates = jsyaml.safeLoad (data);
      } catch (e) {
      }
      var tableData = heat_templates.assets;
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].release_html = tableData[i].release.join (", ");
        setupInfoHandler ("heat-templates", i, tableData[i]);
      }

      show_asset ("heat-templates", tableData);
      show_heat_templates ();

      initSingleSelector ("heat-release", "release", tableData, show_heat_templates);
    });

  $.ajax({ url: "static/murano_apps.yaml" }).
    done (function (data) {
      try {
        murano_apps = jsyaml.safeLoad (data);
      } catch (e) {
      }
      var tableData = murano_apps.assets;
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].release_html = tableData[i].release.join (", ");
        setupInfoHandler ("murano-apps", i, tableData[i]);
      }

      show_asset ("murano-apps", tableData);
      show_murano_apps ();

      initSingleSelector ("murano-release", "release", tableData, show_murano_apps);
    });
}

function navigate ()
{
  var tabs_list = $("#navbar")[0].children;
  var selected_tab_name = null;
  var options = getUrlVars ();

  $( "ul.nav > li" ).removeClass ("active");
  if ("tab" in options) {
    for (var i = 0; i < tabs_list.length; ++i) {
      var tab_name = tabs_list[i].children[0].hash.substring (1);
      if (tab_name == options.tab) {
        selected_tab_name = tab_name;
        if (!("asset" in options)) {
          tabs_list[i].className = "active";
        }
        break;
      }
    }
  }

  $( ".content" ).hide ();

  if (selected_tab_name === null) {
    $( "#landing-page" ).show ();
  } else if ("asset" in options) {
    show_asset ("murano-apps", murano_apps.assets);
    show_asset ("heat-templates", heat_templates.assets);
    show_asset ("glance-images", glance_images.assets);
  } else {
    $( "#" + selected_tab_name ).show ();
  }
}

window.onhashchange = navigate;
<commit_msg>Restore sorting by format for murano packages<commit_after>function getUrlVars() {
  "use strict";
  var vars = {};
  window.location.href.replace(/[?&#]+([^=&]+)=([^&#]*)/gi, function (m, key, value) {
    vars[key] = decodeURIComponent(value);
  });
  return vars;
}

function make_uri(uri, options) {
  "use strict";
  var ops = {};
  $.extend(ops, getUrlVars());
  if (options !== null) {
    $.extend(ops, options);
  }
  var str = $.map(ops, function (val, index) {
    return index + "=" + encodeURIComponent(val).toLowerCase();
  }).join("&");

  return (str === "") ? uri : uri + "?" + str;
}

function reload(extra) {
  "use strict";
  window.location.search = make_uri ("", extra);
}

function update_url(extra) {
  var ops = {};
  $.extend(ops, getUrlVars ());
  if (extra !== null) {
    $.extend(ops, extra);
  }
  window.location.hash = $.map(ops, function (val, index) {
    return val ? (index + "=" + encodeURIComponent(val)) : null;
  }).join("&");
}

function initSingleSelector(selector_id, property, dataSet, update_handler) {
  var values = {};
  var result = [];
  var value, key;

  for (var i = 0; i < dataSet.length; i++) {
    var element = dataSet[i][property];
    if (element instanceof Array) {
      for (key in element)
        if (key) {
          values[element[key]] = element[key];
        }
    } else {
      values[element] = element;
    }
  }

  for (value in values)
    if (value) {
      result.push({"id": value, "text": value});
    }

  $("#" + selector_id).
    val (getUrlVars()[property]).
    on("select2-selecting", function (e) {
      var options = {};
      options[property] = e.val;
      update_url (options);
      update_handler ();
    }).
  on("select2-removed", function (e) {
    var options = {};
    options[property] = '';
    update_url (options);
    update_handler ();
  }).
  select2({data: result, allowClear: true});
}

function filterData (tableData, filters) {
  var filteredData = [];
  var key, column;

  for (var i = 0; i < tableData.length; i++) {
    var row = tableData[i];
    var filtered = true;

    for (column in filters) {
      if (column in row) {
        if (row[column] instanceof Array) {
          filtered = false;
          for (key in row[column])
            if (filters[column] == row[column][key]) {
              filtered = true;
            }
        } else {
          if (filters[column] != row[column]) {
            filtered = false;
          }
        }
      }
      if (filtered == false) {
        break;
      }
    }

    if (filtered) {
      filteredData.push(row);
    }
  }

  return filteredData;
}

function populate_table (table_id, table_column_names, tableData)
{
  var tableColumns = [];
  for (var i = 0; i < table_column_names.length; i++) {
    tableColumns.push({"mData": table_column_names[i]});
    for (var j = 0; j < tableData.length; j++) {
      if (!(table_column_names[i] in tableData[j])) {
        tableData[j][table_column_names[i]] = "";
      }
    }
  }

  if (table_id) {
    $("#" + table_id).dataTable({
      "aLengthMenu": [
        [5, 10, 25, 50, -1],
        [5, 10, 25, 50, "All"]
      ],
      "bDestroy": true,
      "iDisplayLength": -1,
      "bAutoWidth": false,
      "bPaginate": true,
      "pagingType": "full_numbers",
      "aaData": tableData,
      "aoColumns": tableColumns
    });
  }
}

function showInfoDialog (tab, info) {
  $("#info-container").empty();
  $("#" + tab + "-info").tmpl(info).appendTo("#info-container");
  $("#info-dialog").dialog("open");
  $("button").focus ();
}

function showInfoPage (tab, info)
{
  $("#info-content").empty();
  $("#" + tab + "-info").tmpl(info).appendTo("#info-content");
  $( ".content" ).hide ();
  $( "#info-page" ).show ();
  update_url ({ tab : tab, asset : info.name});
  $(".value").replaceWith (function(idx, element) {
    return element.replace (/https?:\/\/[^ \t\n\r]+/gi, '$&');
  });
}

function setupInfoHandler (tab, element_id, info) {
  info.name_html = "" + info.name + "";

  $("#" + tab + "-table").on("click", "#" + tab + "-" + element_id, function (event) {
    event.preventDefault();
    event.stopPropagation();

    showInfoPage (tab, info);
  });
}

var glance_images = { assets: [] };

function show_glance_images ()
{
  populate_table ("glance-images-table",
      ["name_html", "description", "disk_format", "license"],
      filterData (glance_images.assets, getUrlVars ()));
}

var heat_templates = { assets: [] };

function show_heat_templates ()
{
  populate_table ("heat-templates-table",
      ["name_html", "description", "release_html", "format"],
      filterData (heat_templates.assets, getUrlVars ()));
}

var murano_apps = { assets: [] };

function show_murano_apps ()
{
  populate_table ("murano-apps-table",
      ["name_html", "description", "release_html", "service.format"],
      filterData (murano_apps.assets, getUrlVars ()));
}

function initTabs ()
{
  $( "ul.nav > li > a" ).on("click", function (event) {
    event.preventDefault ();
  });
  $( "ul.nav > li" ).not(":last-child").on("click", function (event) {
    update_url ({ tab : this.children[0].hash.substring (1), asset: "" });
  });
  $( "ul.nav > li:last-child").on("click", function (event) {
    window.open('https://wiki.openstack.org/wiki/App-Catalog#How_to_contribute', '_blank');
  });
}

function show_asset (tab, tableData)
{
  var options = getUrlVars ();
  if ((tab == options.tab) && ("asset" in options)) {
    for (var i = 0; i < tableData.length; ++i) {
      if (tableData[i].name == options.asset) {
        showInfoPage (tab, tableData[i]);
      }
    }
  }
}

function initMarketPlace ()
{
  navigate ();
  initTabs ();
  $( ".inner" ).matchHeight ();

  $("#info-dialog").dialog({
    autoOpen: false,
    width: "70%",
    modal: true,
    buttons: {
      Close: function () {
        $(this).dialog("close");
      }
    },
    close: function () { }
  });

  $.ajax({ url: "static/glance_images.yaml" }).
    done (function (data) {
      try {
        glance_images = jsyaml.safeLoad (data);
      } catch (e) {
      }
      var tableData = glance_images.assets;
      for (var i = 0; i < tableData.length; i++) {
        setupInfoHandler ("glance-images", i, tableData[i]);
      }

      show_asset ("glance-images", tableData);
      show_glance_images ();
    });

  $.ajax({ url: "static/heat_templates.yaml" }).
    done (function (data) {
      try {
        heat_templates = jsyaml.safeLoad (data);
      } catch (e) {
      }
      var tableData = heat_templates.assets;
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].release_html = tableData[i].release.join (", ");
        setupInfoHandler ("heat-templates", i, tableData[i]);
      }

      show_asset ("heat-templates", tableData);
      show_heat_templates ();

      initSingleSelector ("heat-release", "release", tableData, show_heat_templates);
    });

  $.ajax({ url: "static/murano_apps.yaml" }).
    done (function (data) {
      try {
        murano_apps = jsyaml.safeLoad (data);
        for (var i = 0; i < murano_apps.assets.length; ++i) {
          if (murano_apps.assets[i].service.type === 'bundle') {
            murano_apps.assets[i].service.format = 'bundle';
          }
        }
      } catch (e) {
      }
      var tableData = murano_apps.assets;
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].release_html = tableData[i].release.join (", ");
        setupInfoHandler ("murano-apps", i, tableData[i]);
      }

      show_asset ("murano-apps", tableData);
      show_murano_apps ();

      initSingleSelector ("murano-release", "release", tableData, show_murano_apps);
    });
}

function navigate ()
{
  var tabs_list = $("#navbar")[0].children;
  var selected_tab_name = null;
  var options = getUrlVars ();

  $( "ul.nav > li" ).removeClass ("active");
  if ("tab" in options) {
    for (var i = 0; i < tabs_list.length; ++i) {
      var tab_name = tabs_list[i].children[0].hash.substring (1);
      if (tab_name == options.tab) {
        selected_tab_name = tab_name;
        if (!("asset" in options)) {
          tabs_list[i].className = "active";
        }
        break;
      }
    }
  }

  $( ".content" ).hide ();

  if (selected_tab_name === null) {
    $( "#landing-page" ).show ();
  } else if ("asset" in options) {
    show_asset ("murano-apps", murano_apps.assets);
    show_asset ("heat-templates", heat_templates.assets);
    show_asset ("glance-images", glance_images.assets);
  } else {
    $( "#" + selected_tab_name ).show ();
  }
}

window.onhashchange = navigate;
<|endoftext|>


<commit_before><commit_msg>deleting test folder<commit_after><|endoftext|>


<commit_before>import {
  applyProp,
  attr,
  attributes,
  elementClose,
  elementOpen,
  elementOpenEnd,
  elementOpenStart,
  skip,
  text
} from 'incremental-dom';

const factories = {};
const slotAttributeName = 'slot-name';
const slotElementName = 'slot';

// Fake fast mode.
window.process = {
  env: {
    NODE_ENV: 'production'
  }
};

attributes.key = attributes.statics = function () {};
attributes.value = applyProp;

function bind (tname) {
  return factories[tname] = function (attrs, chren) {
    const slot = tname === slotElementName;

    if (typeof attrs === 'object') {
      elementOpenStart(tname, attrs.key, attrs.statics);
      for (let a in attrs) {
        attr(slot && a === 'name' ? slotAttributeName : a, attrs[a]);
      }
      elementOpenEnd();
    } else {
      elementOpen(tname);
      chren = attrs;
    }

    if (slot) {
      skip();
    } else {
      const chrenType = typeof chren;
      if (chrenType === 'function') {
        chren();
      } else if (chrenType === 'string' || chrenType === 'number') {
        text(chren);
      }
    }

    return elementClose(tname);
  };
}

export default function (tname, attrs, chren) {
  return (factories[tname] || bind(tname))(attrs, chren);
}

export const a = bind('a');
export const abbr = bind('abbr');
export const address = bind('address');
export const area = bind('area');
export const article = bind('article');
export const aside = bind('aside');
export const audio = bind('audio');
export const b = bind('b');
export const base = bind('base');
export const bdi = bind('bdi');
export const bdo = bind('bdo');
export const bgsound = bind('bgsound');
export const blockquote = bind('blockquote');
export const body = bind('body');
export const br = bind('br');
export const button = bind('button');
export const canvas = bind('canvas');
export const caption = bind('caption');
export const cite = bind('cite');
export const code = bind('code');
export const col = bind('col');
export const colgroup = bind('colgroup');
export const command = bind('command');
export const content = bind('content');
export const data = bind('data');
export const datalist = bind('datalist');
export const dd = bind('dd');
export const del = bind('del');
export const details = bind('details');
export const dfn = bind('dfn');
export const dialog = bind('dialog');
export const div = bind('div');
export const dl = bind('dl');
export const dt = bind('dt');
export const element = bind('element');
export const em = bind('em');
export const embed = bind('embed');
export const fieldset = bind('fieldset');
export const figcaption = bind('figcaption');
export const figure = bind('figure');
export const font = bind('font');
export const footer = bind('footer');
export const form = bind('form');
export const h1 = bind('h1');
export const h2 = bind('h2');
export const h3 = bind('h3');
export const h4 = bind('h4');
export const h5 = bind('h5');
export const h6 = bind('h6');
export const head = bind('head');
export const header = bind('header');
export const hgroup = bind('hgroup');
export const hr = bind('hr');
export const html = bind('html');
export const i = bind('i');
export const iframe = bind('iframe');
export const image = bind('image');
export const img = bind('img');
export const input = bind('input');
export const ins = bind('ins');
export const kbd = bind('kbd');
export const keygen = bind('keygen');
export const label = bind('label');
export const legend = bind('legend');
export const li = bind('li');
export const link = bind('link');
export const main = bind('main');
export const map = bind('map');
export const mark = bind('mark');
export const marquee = bind('marquee');
export const menu = bind('menu');
export const menuitem = bind('menuitem');
export const meta = bind('meta');
export const meter = bind('meter');
export const multicol = bind('multicol');
export const nav = bind('nav');
export const nobr = bind('nobr');
export const noembed = bind('noembed');
export const noframes = bind('noframes');
export const noscript = bind('noscript');
export const object = bind('object');
export const ol = bind('ol');
export const optgroup = bind('optgroup');
export const option = bind('option');
export const output = bind('output');
export const p = bind('p');
export const param = bind('param');
export const picture = bind('picture');
export const pre = bind('pre');
export const progress = bind('progress');
export const q = bind('q');
export const rp = bind('rp');
export const rt = bind('rt');
export const rtc = bind('rtc');
export const ruby = bind('ruby');
export const s = bind('s');
export const samp = bind('samp');
export const script = bind('script');
export const section = bind('section');
export const select = bind('select');
export const shadow = bind('shadow');
export const slot = bind(slotElementName);
export const small = bind('small');
export const source = bind('source');
export const span = bind('span');
export const strong = bind('strong');
export const style = bind('style');
export const sub = bind('sub');
export const summary = bind('summary');
export const sup = bind('sup');
export const table = bind('table');
export const tbody = bind('tbody');
export const td = bind('td');
export const template = bind('template');
export const textarea = bind('textarea');
export const tfoot = bind('tfoot');
export const th = bind('th');
export const thead = bind('thead');
export const time = bind('time');
export const title = bind('title');
export const tr = bind('tr');
export const track = bind('track');
export const u = bind('u');
export const ul = bind('ul');
export const video = bind('video');
export const wbr = bind('wbr');
<commit_msg>Removed faked fast-mode as it's not really slower with it in.<commit_after>import {
  applyProp,
  attr,
  attributes,
  elementClose,
  elementOpen,
  elementOpenEnd,
  elementOpenStart,
  skip,
  text
} from 'incremental-dom';

const factories = {};
const slotAttributeName = 'slot-name';
const slotElementName = 'slot';

attributes.key = attributes.statics = function () {};
attributes.value = applyProp;

function bind (tname) {
  return factories[tname] = function (attrs, chren) {
    const slot = tname === slotElementName;

    if (typeof attrs === 'object') {
      elementOpenStart(tname, attrs.key, attrs.statics);
      for (let a in attrs) {
        attr(slot && a === 'name' ? slotAttributeName : a, attrs[a]);
      }
      elementOpenEnd();
    } else {
      elementOpen(tname);
      chren = attrs;
    }

    if (slot) {
      skip();
    } else {
      const chrenType = typeof chren;
      if (chrenType === 'function') {
        chren();
      } else if (chrenType === 'string' || chrenType === 'number') {
        text(chren);
      }
    }

    return elementClose(tname);
  };
}

export default function (tname, attrs, chren) {
  return (factories[tname] || bind(tname))(attrs, chren);
}

export const a = bind('a');
export const abbr = bind('abbr');
export const address = bind('address');
export const area = bind('area');
export const article = bind('article');
export const aside = bind('aside');
export const audio = bind('audio');
export const b = bind('b');
export const base = bind('base');
export const bdi = bind('bdi');
export const bdo = bind('bdo');
export const bgsound = bind('bgsound');
export const blockquote = bind('blockquote');
export const body = bind('body');
export const br = bind('br');
export const button = bind('button');
export const canvas = bind('canvas');
export const caption = bind('caption');
export const cite = bind('cite');
export const code = bind('code');
export const col = bind('col');
export const colgroup = bind('colgroup');
export const command = bind('command');
export const content = bind('content');
export const data = bind('data');
export const datalist = bind('datalist');
export const dd = bind('dd');
export const del = bind('del');
export const details = bind('details');
export const dfn = bind('dfn');
export const dialog = bind('dialog');
export const div = bind('div');
export const dl = bind('dl');
export const dt = bind('dt');
export const element = bind('element');
export const em = bind('em');
export const embed = bind('embed');
export const fieldset = bind('fieldset');
export const figcaption = bind('figcaption');
export const figure = bind('figure');
export const font = bind('font');
export const footer = bind('footer');
export const form = bind('form');
export const h1 = bind('h1');
export const h2 = bind('h2');
export const h3 = bind('h3');
export const h4 = bind('h4');
export const h5 = bind('h5');
export const h6 = bind('h6');
export const head = bind('head');
export const header = bind('header');
export const hgroup = bind('hgroup');
export const hr = bind('hr');
export const html = bind('html');
export const i = bind('i');
export const iframe = bind('iframe');
export const image = bind('image');
export const img = bind('img');
export const input = bind('input');
export const ins = bind('ins');
export const kbd = bind('kbd');
export const keygen = bind('keygen');
export const label = bind('label');
export const legend = bind('legend');
export const li = bind('li');
export const link = bind('link');
export const main = bind('main');
export const map = bind('map');
export const mark = bind('mark');
export const marquee = bind('marquee');
export const menu = bind('menu');
export const menuitem = bind('menuitem');
export const meta = bind('meta');
export const meter = bind('meter');
export const multicol = bind('multicol');
export const nav = bind('nav');
export const nobr = bind('nobr');
export const noembed = bind('noembed');
export const noframes = bind('noframes');
export const noscript = bind('noscript');
export const object = bind('object');
export const ol = bind('ol');
export const optgroup = bind('optgroup');
export const option = bind('option');
export const output = bind('output');
export const p = bind('p');
export const param = bind('param');
export const picture = bind('picture');
export const pre = bind('pre');
export const progress = bind('progress');
export const q = bind('q');
export const rp = bind('rp');
export const rt = bind('rt');
export const rtc = bind('rtc');
export const ruby = bind('ruby');
export const s = bind('s');
export const samp = bind('samp');
export const script = bind('script');
export const section = bind('section');
export const select = bind('select');
export const shadow = bind('shadow');
export const slot = bind(slotElementName);
export const small = bind('small');
export const source = bind('source');
export const span = bind('span');
export const strong = bind('strong');
export const style = bind('style');
export const sub = bind('sub');
export const summary = bind('summary');
export const sup = bind('sup');
export const table = bind('table');
export const tbody = bind('tbody');
export const td = bind('td');
export const template = bind('template');
export const textarea = bind('textarea');
export const tfoot = bind('tfoot');
export const th = bind('th');
export const thead = bind('thead');
export const time = bind('time');
export const title = bind('title');
export const tr = bind('tr');
export const track = bind('track');
export const u = bind('u');
export const ul = bind('ul');
export const video = bind('video');
export const wbr = bind('wbr');
<|endoftext|>


<commit_before>OMAR.models.BBOX = Backbone.Model.extend(
    {
        defaults:{
            "minx": -180.0,
            "miny": -90.0,
            "maxx": 180.0,
            "maxy": 90.0
        },
        initialize:function(options)
        {
        },
        intersects:function(bbox)
        {
            var maxOfMinx = Math.max(this.attributes.minx, bbox.attributes.minx);
            var minOfMaxx = Math.min(this.attributes.maxx, bbox.attributes.maxx);
            var minOfMaxy = Math.min(this.attributes.maxy, bbox.attributes.maxy);
            var maxOfMiny = Math.max(this.attributes.miny, bbox.attributes.miny);
            return ((maxOfMinx <= minOfMaxx)&&
                    (minOfMaxy >= maxOfMiny));
        },
        intersect:function(bbox)
        {
            var result = null;

            var maxOfMinx = Math.max(this.attributes.minx, bbox.attributes.minx);
            var minOfMaxy = Math.min(this.attributes.maxy, bbox.attributes.maxy);
            var minOfMaxx = Math.min(this.attributes.maxx, bbox.attributes.maxx);
            var maxOfMiny = Math.max(this.attributes.miny, bbox.attributes.miny);

            if( minOfMaxx < maxOfMinx || maxOfMiny > minOfMaxy )
            {
                return null;
            }

            return new OMAR.models.BBOX({minx: maxOfMinx
                                         ,miny: maxOfMiny
                                         ,maxx: minOfMaxx
                                         ,maxy: minOfMaxy
                                         });
        },
        toWmsString:function()
        {
            return (this.get("minx") + "," + this.get("miny") + "," +
                this.get("maxx") + "," + this.get("maxy"));
        },
        setFromWfsFeatureGeom:function(tempGeom)
        {
            var geom = null
            var minx = 9e20;
            var maxx = -9e20;
            var miny = 9e20;
            var maxy = -9e20;

            if(typeof tempGeom == "string")
            {
                geom = JSON.parse(tempGeom);
            }
            else
            {
                geom = tempGeom;
            }
            switch(geom.type.toLowerCase())
            {
                case "polygon":
                    $(geom.coordinates).each(function(idx,v){
                        $(v).each(function(idx, v){
                            if(v[0] < minx) minx = v[0];
                            if(v[0] > maxx) maxx = v[0];
                            if(v[1] < miny) miny = v[1];
                            if(v[1] > maxy) maxy = v[1];
                            });
                    });
                    break;
                case "multipolygon":
                    $(geom.coordinates).each(function(idx,v){
                           $(v).each(function(idx, v)
                           {
                                $(v).each(function(idx, v){
                                    if(v[0] < minx) minx = v[0];
                                    if(v[0] > maxx) maxx = v[0];
                                    if(v[1] < miny) miny = v[1];
                                    if(v[1] > maxy) maxy = v[1];
                                })
                            })
                        }
                    );
                    break;
            }

            this.set({"minx":minx
                ,"maxx":maxx
                ,"miny":miny
                ,"maxy":maxy
            });
        },
        getCenter: function(){
            var result = {
                x:(this.get("minx")+this.get("maxx"))*0.5,
                y:(this.get("miny")+this.get("maxy"))*0.5
            };
            return result;
        },
        validate:function(attrs)
        {
            if(attrs.minx && (!OMAR.isFloat(attrs.minx.toString())))
            {
                return ("Minx value is invalid: " + attrs.minx);
            }
            if(attrs.miny && (!OMAR.isFloat(attrs.miny.toString())))
            {
                return ("Miny value is invalid: " + attrs.miny);
            }
            if(attrs.maxx && (!OMAR.isFloat(attrs.maxx.toString())))
            {
                return ("Maxx value is invalid: " + attrs.maxx);
            }
            if(attrs.maxy && (!OMAR.isFloat(attrs.maxy.toString())))
            {
                return ("Maxy value is invalid: " + attrs.maxy);
            }
            return null;
        },
        setFromWmsString:function(s)
        {
            var splitBounds = s.split(",");
            if(splitBounds.length == 4)
            {
                this.minx = parseFloat(splitBounds[0]);
                this.miny = parseFloat(splitBounds[1]);
                this.maxx = parseFloat(splitBounds[2]);
                this.maxy = parseFloat(splitBounds[3]);
            }
            return this;
        },
        toCql:function(columnName)
        {
            var result = "";
            var bad = this.validate(this.attributes);
            if(!bad)
            {
                result = "BBOX(" + columnName + "," + this.toWmsString() + ")";
            }
            return result;
        }
    }
);

OMAR.views.BBOX = Backbone.View.extend({
    el:"#boundBoxId",
    initialize: function(params)
    {
        this.setElement(this.el);
        this.model = new OMAR.models.BBOX();
        this.lowerLeftBboxEl = $("#lowerLeftBbox");
        this.upperRightBboxEl = $("#upperRightBbox");
        this.model.on("error",
            function(model,err) {
                alert("BBOX Has errors: " + err);
            });
        this.model.on('change', this.bboxModelChange, this);
    },
    events:{
        "change #lowerLeftBbox": "llOnChange",
        "change #upperRightBbox": "urOnChange"
    },
    bboxModelChange: function() {
        this.render();
    },
    llOnChange: function(e){
        var v = this.lowerLeftBboxEl.val();
        var values = v.split(",");
        if(values.length ==2)
        {
            this.model.off("change", this.bboxModelChange, this);
            this.model.set({minx:values[1],miny:values[0]});
            this.model.on("change", this.bboxModelChange, this);
        }
        this.render();
    },
    urOnChange: function(e){
        var v = this.upperRightBboxEl.val();
        var values = v.split(",");
        if(values.length ==2)
        {
            this.model.off("change", this.bboxModelChange, this);
            this.model.set({maxx:values[1],maxy:values[0]});
            this.model.on("change", this.bboxModelChange, this);
        }
        this.render();
    },
    bboxError:function(model, err){
    },
    render:function()
    {
        this.lowerLeftBboxEl.val(this.model.get("miny") + ","
            + this.model.get("minx"));
        this.upperRightBboxEl.val(this.model.get("maxy") + ","
            + this.model.get("maxx"));
    }
});<commit_msg>Updated with spacing<commit_after>OMAR.models.BBOX = Backbone.Model.extend(
    {
        defaults:{
            "minx": -180.0,
            "miny": -90.0,
            "maxx": 180.0,
            "maxy": 90.0
        },
        initialize:function(options)
        {
        },
        intersects:function(bbox)
        {
            var maxOfMinx = Math.max(this.attributes.minx, bbox.attributes.minx);
            var minOfMaxx = Math.min(this.attributes.maxx, bbox.attributes.maxx);
            var minOfMaxy = Math.min(this.attributes.maxy, bbox.attributes.maxy);
            var maxOfMiny = Math.max(this.attributes.miny, bbox.attributes.miny);
            return ((maxOfMinx <= minOfMaxx)&&
                    (minOfMaxy >= maxOfMiny));
        },
        intersect:function(bbox)
        {
            var result = null;

            var maxOfMinx = Math.max(this.attributes.minx, bbox.attributes.minx);
            var minOfMaxy = Math.min(this.attributes.maxy, bbox.attributes.maxy);
            var minOfMaxx = Math.min(this.attributes.maxx, bbox.attributes.maxx);
            var maxOfMiny = Math.max(this.attributes.miny, bbox.attributes.miny);

            if( minOfMaxx < maxOfMinx || maxOfMiny > minOfMaxy )
            {
                return null;
            }

            return new OMAR.models.BBOX({minx: maxOfMinx
                                         ,miny: maxOfMiny
                                         ,maxx: minOfMaxx
                                         ,maxy: minOfMaxy
                                         });
        },
        toWmsString:function()
        {
            return (this.get("minx") + "," + this.get("miny") + "," +
                this.get("maxx") + "," + this.get("maxy"));
        },
        setFromWfsFeatureGeom:function(tempGeom)
        {
            var geom = null
            var minx = 9e20;
            var maxx = -9e20;
            var miny = 9e20;
            var maxy = -9e20;

            if(typeof tempGeom == "string")
            {
                geom = JSON.parse(tempGeom);
            }
            else
            {
                geom = tempGeom;
            }
            switch(geom.type.toLowerCase())
            {
                case "polygon":
                    $(geom.coordinates).each(function(idx,v){
                        $(v).each(function(idx, v){
                            if(v[0] < minx) minx = v[0];
                            if(v[0] > maxx) maxx = v[0];
                            if(v[1] < miny) miny = v[1];
                            if(v[1] > maxy) maxy = v[1];
                            });
                    });
                    break;
                case "multipolygon":
                    $(geom.coordinates).each(function(idx,v){
                           $(v).each(function(idx, v)
                           {
                                $(v).each(function(idx, v){
                                    if(v[0] < minx) minx = v[0];
                                    if(v[0] > maxx) maxx = v[0];
                                    if(v[1] < miny) miny = v[1];
                                    if(v[1] > maxy) maxy = v[1];
                                })
                            })
                        }
                    );
                    break;
            }

            this.set({"minx":minx
                ,"maxx":maxx
                ,"miny":miny
                ,"maxy":maxy
            });
        },
        getCenter: function(){
            var result = {
                x:(this.get("minx")+this.get("maxx"))*0.5,
                y:(this.get("miny")+this.get("maxy"))*0.5
            };
            return result;
        },
        validate:function(attrs)
        {
            if(attrs.minx && (!OMAR.isFloat(attrs.minx.toString())))
            {
                return ("Minx value is invalid: " + attrs.minx);
            }
            if(attrs.miny && (!OMAR.isFloat(attrs.miny.toString())))
            {
                return ("Miny value is invalid: " + attrs.miny);
            }
            if(attrs.maxx && (!OMAR.isFloat(attrs.maxx.toString())))
            {
                return ("Maxx value is invalid: " + attrs.maxx);
            }
            if(attrs.maxy && (!OMAR.isFloat(attrs.maxy.toString())))
            {
                return ("Maxy value is invalid: " + attrs.maxy);
            }
            return null;
        },
        setFromWmsString:function(s)
        {
            var splitBounds = s.split(",");
            if(splitBounds.length == 4)
            {
                this.minx = parseFloat(splitBounds[0]);
                this.miny = parseFloat(splitBounds[1]);
                this.maxx = parseFloat(splitBounds[2]);
                this.maxy = parseFloat(splitBounds[3]);
            }
            return this;
        },
        toCql:function(columnName)
        {
            var result = "";
            var bad = this.validate(this.attributes);
            if(!bad)
            {
                result = "BBOX(" + columnName + "," + this.toWmsString() + ")";
            }
            return result;
        }
    }
);

OMAR.views.BBOX = Backbone.View.extend({
    el:"#boundBoxId",
    initialize: function(params)
    {
        this.setElement(this.el);
        this.model = new OMAR.models.BBOX();
        this.lowerLeftBboxEl = $("#lowerLeftBbox");
        this.upperRightBboxEl = $("#upperRightBbox");

        this.model.on("error",
            function(model,err) {
                alert("BBOX Has errors: " + err);
            });
        this.model.on('change', this.bboxModelChange, this);
    },
    events:{
        "change #lowerLeftBbox": "llOnChange",
        "change #upperRightBbox": "urOnChange"
    },
    bboxModelChange: function() {
        this.render();
    },
    llOnChange: function(e){
        var v = this.lowerLeftBboxEl.val();
        var values = v.split(",");
        if(values.length ==2)
        {
            this.model.off("change", this.bboxModelChange, this);
            this.model.set({minx:values[1],miny:values[0]});
            this.model.on("change", this.bboxModelChange, this);
        }
        this.render();
    },
    urOnChange: function(e){
        var v = this.upperRightBboxEl.val();
        var values = v.split(",");
        if(values.length ==2)
        {
            this.model.off("change", this.bboxModelChange, this);
            this.model.set({maxx:values[1],maxy:values[0]});
            this.model.on("change", this.bboxModelChange, this);
        }
        this.render();
    },
    bboxError:function(model, err){
    },
    render:function()
    {
        this.lowerLeftBboxEl.val(this.model.get("miny") + ","
            + this.model.get("minx"));
        this.upperRightBboxEl.val(this.model.get("maxy") + ","
            + this.model.get("maxx"));
    }
});<|endoftext|>


<commit_before>'use strict';

// dependencies
import * as riot from 'riot';

var mixin = {
  observable: riot.observable()
}

mixin.observable.on('sendSignin', function(data) {
  console.log('on sendSignin: ' + data);
});

module.exports = mixin;
<commit_msg>Log observer emmits<commit_after>'use strict';

// dependencies
import * as riot from 'riot';

var mixin = {
  observable: riot.observable()
}

// TODO: no se respeta el orden de invocación de emisiones
mixin.observable.on('*', (event, args) => {
  console.log('Emmit: `' + event + '` ', args || null);
});

module.exports = mixin;
<|endoftext|>


<commit_before>import MockRequest from './mocks/mock-request'
import MockResource from './mocks/mock-resource'
import MockGateway from './gateway/mock'
import { configs } from './index'
import { toQueryString } from './utils'

let store = []
let ids = 1
let originalGateway = null

/**
 * High level abstraction, it works directly on your client mocking
 * the resources and their methods.
 * @param {Object} client - the client generated by {@link forge}
 *
 * @return {MockAssert}
 */
export const mockClient = (client) => {
  const entry = new MockResource(ids++, client)
  store.push(entry)
  return entry
}

/**
 * Low level abstraction, very useful for automations
 * @param {Object} props
 *   @param {String} props.method - request method (get, post, etc)
 *   @param {String} props.url - request url (http://example.com)
 *   @param {String} props.body - request body
 *   @param {String} props.response
 *     @param {String} props.response.status
 *     @param {String} props.response.headers
 *     @param {String} props.response.body
 *
 * @return {MockAssert}
 */
export const mockRequest = (props) => {
  const entry = new MockRequest(ids++, props)
  store.push(entry)
  return entry.assertObject()
}

/**
 * Setup the test library
 */
export const install = () => {
  originalGateway = configs.gateway
  configs.gateway = MockGateway
}

/**
 * Teardown the test library
 */
export const uninstall = () => {
  clear()
  if (originalGateway) {
    configs.gateway = originalGateway
    originalGateway = null
  }
}

/**
 * Cleans up all mocks
 */
export const clear = () => {
  store = []
}

/**
 * Returns number of unused mocks
 * @returns {Number}
 */
export const unusedMocks = () => {
  const mocks = store.map((mock) => mock.toMockRequest())
  let count = 0
  mocks.forEach(mock => {
    if (mock.calls.length === 0) count++
  })
  return count
}

/**
 * Similar to "lookupResponse" but it also runs the request/prepareRequest phase of the middleware
 * stack
 *
 * @param {Request} request
 * @return {Promise<Response>}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponseAsync = (request) => {
  const mocksPendingMiddlewareExecution = store.filter(mock => mock.pendingMiddlewareExecution)
  return configs
    .Promise.all(mocksPendingMiddlewareExecution.map(mock => mock.executeMiddlewareStack()))
    .then(() => lookupResponse(request))
}

/**
 * @param {Request} request
 * @return {Response}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponse = (request) => {
  const mocks = store.map((mock) => mock.toMockRequest())

  const exactMatch = mocks
    .filter((mock) => mock.isExactMatch(request))
    .pop()

  if (exactMatch) {
    return exactMatch.call(request)
  }

  const partialMatch = mocks
    .filter((mock) => mock.isPartialMatch(request))
    .pop()

  if (partialMatch) {
    throw new Error(
      `[Mappersmith Test] No exact match found for ${requestToLog(request)}, partial match with ${mockToLog(partialMatch)}, check your mock definition`
    )
  }

  throw new Error(
    `[Mappersmith Test] No match found for ${requestToLog(request)}, check your mock definition`
  )
}

/**
 * List of match functions
 */
export const m = {
  stringMatching: (regexp) => {
    if (!(regexp instanceof RegExp)) {
      throw new Error(`[Mappersmith Test] "stringMatching" received an invalid regexp (${regexp})`)
    }
    return (string) => regexp.test(string)
  },

  stringContaining: (sample) => {
    if (typeof sample !== 'string') {
      throw new Error(`[Mappersmith Test] "stringContaining" received an invalid string (${sample})`)
    }

    return (string) => stringIncludes(string, sample)
  },

  uuid4: () => {
    // NOTE: based on https://github.com/chriso/validator.js/blob/3443132beccddf06c3f0a5e88c1dd2ee6513b612/src/lib/isUUID.js
    const uuid4Rx = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i

    return string => uuid4Rx.test(string)
  },

  anything: () => () => true
}

const requestToLog = (request) => (
  `"${request.method().toUpperCase()} ${request.url()}" (body: "${toQueryString(request.body())}"; headers: ${toQueryString(request.headers())})`
)
const mockToLog = (requestMock) => (
  `"${requestMock.method.toUpperCase()} ${requestMock.url}" (body: "${requestMock.body}"; headers: "${requestMock.headers}")`
)

const stringIncludes = (str, search, start) => {
  if (typeof start !== 'number') {
    start = 0
  }

  if (typeof str.includes === 'function') {
    return str.includes(search, start)
  }

  if (start + search.length > str.length) {
    return false
  }

  return str.indexOf(search, start) !== -1
}
<commit_msg>Add missing quotes to new log message<commit_after>import MockRequest from './mocks/mock-request'
import MockResource from './mocks/mock-resource'
import MockGateway from './gateway/mock'
import { configs } from './index'
import { toQueryString } from './utils'

let store = []
let ids = 1
let originalGateway = null

/**
 * High level abstraction, it works directly on your client mocking
 * the resources and their methods.
 * @param {Object} client - the client generated by {@link forge}
 *
 * @return {MockAssert}
 */
export const mockClient = (client) => {
  const entry = new MockResource(ids++, client)
  store.push(entry)
  return entry
}

/**
 * Low level abstraction, very useful for automations
 * @param {Object} props
 *   @param {String} props.method - request method (get, post, etc)
 *   @param {String} props.url - request url (http://example.com)
 *   @param {String} props.body - request body
 *   @param {String} props.response
 *     @param {String} props.response.status
 *     @param {String} props.response.headers
 *     @param {String} props.response.body
 *
 * @return {MockAssert}
 */
export const mockRequest = (props) => {
  const entry = new MockRequest(ids++, props)
  store.push(entry)
  return entry.assertObject()
}

/**
 * Setup the test library
 */
export const install = () => {
  originalGateway = configs.gateway
  configs.gateway = MockGateway
}

/**
 * Teardown the test library
 */
export const uninstall = () => {
  clear()
  if (originalGateway) {
    configs.gateway = originalGateway
    originalGateway = null
  }
}

/**
 * Cleans up all mocks
 */
export const clear = () => {
  store = []
}

/**
 * Returns number of unused mocks
 * @returns {Number}
 */
export const unusedMocks = () => {
  const mocks = store.map((mock) => mock.toMockRequest())
  let count = 0
  mocks.forEach(mock => {
    if (mock.calls.length === 0) count++
  })
  return count
}

/**
 * Similar to "lookupResponse" but it also runs the request/prepareRequest phase of the middleware
 * stack
 *
 * @param {Request} request
 * @return {Promise<Response>}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponseAsync = (request) => {
  const mocksPendingMiddlewareExecution = store.filter(mock => mock.pendingMiddlewareExecution)
  return configs
    .Promise.all(mocksPendingMiddlewareExecution.map(mock => mock.executeMiddlewareStack()))
    .then(() => lookupResponse(request))
}

/**
 * @param {Request} request
 * @return {Response}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponse = (request) => {
  const mocks = store.map((mock) => mock.toMockRequest())

  const exactMatch = mocks
    .filter((mock) => mock.isExactMatch(request))
    .pop()

  if (exactMatch) {
    return exactMatch.call(request)
  }

  const partialMatch = mocks
    .filter((mock) => mock.isPartialMatch(request))
    .pop()

  if (partialMatch) {
    throw new Error(
      `[Mappersmith Test] No exact match found for ${requestToLog(request)}, partial match with ${mockToLog(partialMatch)}, check your mock definition`
    )
  }

  throw new Error(
    `[Mappersmith Test] No match found for ${requestToLog(request)}, check your mock definition`
  )
}

/**
 * List of match functions
 */
export const m = {
  stringMatching: (regexp) => {
    if (!(regexp instanceof RegExp)) {
      throw new Error(`[Mappersmith Test] "stringMatching" received an invalid regexp (${regexp})`)
    }
    return (string) => regexp.test(string)
  },

  stringContaining: (sample) => {
    if (typeof sample !== 'string') {
      throw new Error(`[Mappersmith Test] "stringContaining" received an invalid string (${sample})`)
    }

    return (string) => stringIncludes(string, sample)
  },

  uuid4: () => {
    // NOTE: based on https://github.com/chriso/validator.js/blob/3443132beccddf06c3f0a5e88c1dd2ee6513b612/src/lib/isUUID.js
    const uuid4Rx = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i

    return string => uuid4Rx.test(string)
  },

  anything: () => () => true
}

const requestToLog = (request) => (
  `"${request.method().toUpperCase()} ${request.url()}" (body: "${toQueryString(request.body())}"; headers: "${toQueryString(request.headers())}")`
)
const mockToLog = (requestMock) => (
  `"${requestMock.method.toUpperCase()} ${requestMock.url}" (body: "${requestMock.body}"; headers: "${requestMock.headers}")`
)

const stringIncludes = (str, search, start) => {
  if (typeof start !== 'number') {
    start = 0
  }

  if (typeof str.includes === 'function') {
    return str.includes(search, start)
  }

  if (start + search.length > str.length) {
    return false
  }

  return str.indexOf(search, start) !== -1
}
<|endoftext|>


<commit_before>export function vec3_create(x, y, z) {
  return {
    x: x || 0,
    y: y || 0,
    z: z || 0,
  };
}

export function vec3_clone(v) {
  return vec3_create(v.x, v.y, v.z);
}

export function vec3_copy(a, b) {
  a.x = b.x;
  a.y = b.y;
  a.z = b.z;
  return a;
}

export function vec3_add(a, b) {
  a.x += b.x;
  a.y += b.y;
  a.z += b.z;
  return a;
}

export function vec3_sub(a, b) {
  a.x -= b.x;
  a.y -= b.y;
  a.z -= b.z;
  return a;
}

export function vec3_subVectors(v, a, b) {
  v.x = a.x - b.x;
  v.y = a.y - b.y;
  v.z = a.z - b.z;
  return v;
}

export function vec3_multiplyScalar(v, scalar) {
  v.x *= scalar;
  v.y *= scalar;
  v.z *= scalar;
  return v;
}

export function vec3_transformDirection(v, m) {
  // input: THREE.Matrix4 affine matrix
  // vector interpreted as a direction

  var x = v.x, y = v.y, z = v.z;

  v.x = m[0] * x + m[4] * y + m[8] * z;
  v.y = m[1] * x + m[5] * y + m[9] * z;
  v.z = m[2] * x + m[6] * y + m[10] * z;

  return vec3_normalize(v);
}

export function vec3_divideScalar(v, scalar) {
  return vec3_multiplyScalar(v, 1 / scalar);
}

export function vec3_cross(a, b) {
  var x = a.x;
  var y = a.y;
  var z = a.z;

  a.x = y * b.z - z * b.y;
  a.y = z * b.x - x * b.z;
  a.z = x * b.y - y * b.x;

  return a;
}

export function vec3_crossVectors(v, a, b) {
  var ax = a.x;
  var ay = a.y;
  var az = a.z;

  var bx = b.x;
  var by = b.y;
  var bz = b.z;

  v.x = ay * bz - az * by;
  v.y = az * bx - ax * bz;
  v.z = ax * by - ay * bx;

  return v;
}

export function vec3_length(v) {
  return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}

export function vec3_normalize(v) {
  return vec3_divideScalar(v, vec3_length(v));
}

export function vec3_applyQuaternion(v, q) {
  var x = v.x, y = v.y, z = v.z;
  var qx = q.x, qy = q.y, qz = q.z, qw = q.w;

  // calculate quat * vector

  var ix = qw * x + qy * z - qz * y;
  var iy = qw * y + qz * x - qx * z;
  var iz = qw * z + qx * y - qy * x;
  var iw = -qx * x - qy * y - qz * z;

  // calculate result * inverse quat

  v.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  v.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  v.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;

  return v;
}

export function vec3_setFromMatrixPosition(v, m) {
  v.x = m[12];
  v.y = m[13];
  v.z = m[14];
  return v;
}

export var vec3_X = vec3_create(1, 0, 0);
export var vec3_Y = vec3_create(0, 1, 0);
export var vec3_Z = vec3_create(0, 0, 1);
<commit_msg>Add Vector3#multiply()<commit_after>export function vec3_create(x, y, z) {
  return {
    x: x || 0,
    y: y || 0,
    z: z || 0,
  };
}

export function vec3_clone(v) {
  return vec3_create(v.x, v.y, v.z);
}

export function vec3_copy(a, b) {
  a.x = b.x;
  a.y = b.y;
  a.z = b.z;
  return a;
}

export function vec3_add(a, b) {
  a.x += b.x;
  a.y += b.y;
  a.z += b.z;
  return a;
}

export function vec3_sub(a, b) {
  a.x -= b.x;
  a.y -= b.y;
  a.z -= b.z;
  return a;
}

export function vec3_subVectors(v, a, b) {
  v.x = a.x - b.x;
  v.y = a.y - b.y;
  v.z = a.z - b.z;
  return v;
}

export function vec3_multiply(a, b) {
  a.x *= b.x;
  a.y *= b.y;
  a.z *= b.z;
  return a;
}

export function vec3_multiplyScalar(v, scalar) {
  v.x *= scalar;
  v.y *= scalar;
  v.z *= scalar;
  return v;
}

export function vec3_transformDirection(v, m) {
  // input: THREE.Matrix4 affine matrix
  // vector interpreted as a direction

  var x = v.x, y = v.y, z = v.z;

  v.x = m[0] * x + m[4] * y + m[8] * z;
  v.y = m[1] * x + m[5] * y + m[9] * z;
  v.z = m[2] * x + m[6] * y + m[10] * z;

  return vec3_normalize(v);
}

export function vec3_divideScalar(v, scalar) {
  return vec3_multiplyScalar(v, 1 / scalar);
}

export function vec3_cross(a, b) {
  var x = a.x;
  var y = a.y;
  var z = a.z;

  a.x = y * b.z - z * b.y;
  a.y = z * b.x - x * b.z;
  a.z = x * b.y - y * b.x;

  return a;
}

export function vec3_crossVectors(v, a, b) {
  var ax = a.x;
  var ay = a.y;
  var az = a.z;

  var bx = b.x;
  var by = b.y;
  var bz = b.z;

  v.x = ay * bz - az * by;
  v.y = az * bx - ax * bz;
  v.z = ax * by - ay * bx;

  return v;
}

export function vec3_length(v) {
  return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}

export function vec3_normalize(v) {
  return vec3_divideScalar(v, vec3_length(v));
}

export function vec3_applyQuaternion(v, q) {
  var x = v.x, y = v.y, z = v.z;
  var qx = q.x, qy = q.y, qz = q.z, qw = q.w;

  // calculate quat * vector

  var ix = qw * x + qy * z - qz * y;
  var iy = qw * y + qz * x - qx * z;
  var iz = qw * z + qx * y - qy * x;
  var iw = -qx * x - qy * y - qz * z;

  // calculate result * inverse quat

  v.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  v.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  v.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;

  return v;
}

export function vec3_setFromMatrixPosition(v, m) {
  v.x = m[12];
  v.y = m[13];
  v.z = m[14];
  return v;
}

export var vec3_X = vec3_create(1, 0, 0);
export var vec3_Y = vec3_create(0, 1, 0);
export var vec3_Z = vec3_create(0, 0, 1);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
  FlatList,
  StyleSheet,
  View,
  ScrollView,
  Text,
  Dimensions,
  Platform,
  TouchableHighlight,
  ImageBackground
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import axios from 'axios';
import FastImage from 'react-native-fast-image';
import Swiper from 'react-native-swiper';
import moment from 'moment';
require('moment/locale/zh-cn');

import normalize from '../../wdui/helpers/normalizeText';
import Loading from '../../wdui/loading/Loading';
import {URL} from '../../constants';
import {
  Divider,
  Button
} from 'react-native-elements';

const deviceWidth = Dimensions.get('window').width;

class HomeView extends Component {
  static displayName = 'HomeView';

  static navigationOptions = {
    header: <View style={{
      backgroundColor: '#384452',
      flexDirection: 'row',
      height: Platform.OS === 'ios' ? 64 : 56
    }}
     />,
    title: '首页推荐',
    tabBarIcon: (props) => (
        <Icon name='home' size={24} color={props.tintColor} />
      )
  };

  static propTypes = {
    navigation: React.PropTypes.object.isRequired,
    navigate: PropTypes.func.isRequired
  };

  constructor() {
    super();
    this.state = {
      loading: false,
      isRefreshing: false,
      data: []
    };
  }

  componentWillMount() {
    this.fetchData();
  }

  onRefresh() {
    this.setState({
      isRefreshing: true
    });
    this.fetchData();
  }

  fetchData() {
    this.setState({
      loading: true
    });
    axios.get(URL.HOME)
      .then(response => {
        this.setState({
          data: response.data,
          isRefreshing: false,
          loading: false
        });
      });
  }

  keyExtractor = (item, index) => `key${index}`;

  renderList = ({item}) => {
    const {navigate} = this.props.navigation;

    return (
      <TouchableHighlight
        onPress={() => navigate('PlayDetailView', item)}
        key={this.keyExtractor}>
        <View style={styles.card}>
          <View style={styles.article}>
            <View>
              <Text style={styles.author}>
                {item.user} 发表于 {moment(item.updated).fromNow()}
              </Text>
            </View>
            <View>
              <Text numberOfLines={2} style={styles.description}>
                {item.description}
              </Text>
              <Divider />
            </View>
          </View>
          <View>
            {item.featured_image
              ? <FastImage
                style={{width: deviceWidth * 0.3, height: deviceWidth * 0.3}}
                resizeMode={FastImage.resizeMode.cover}
                source={{
                  uri: URL.IMAGE_BASE + item.featured_image
                }}
              />
              : <View/>
            }
          </View>
        </View>
      </TouchableHighlight>
    );
  };

  render() {
    if (this.state.loading) {
      return <Loading text={'数据加载中'} />;
    }
    const {top} = this.state.data;
    const {navigate} = this.props.navigation;

    let topElems = [];
    for (let i = 0; i < top.length; i++) {
      let topData = top[i];
      let topElem = (<View key={i} style={styles.slide1}>
        <TouchableHighlight onPress={() => navigate('PlayDetailView', topData)}>
          <ImageBackground
            style={{width: deviceWidth, height: deviceWidth * 0.6}}
            source={{
              uri: URL.IMAGE_BASE + topData.featured_image
            }}
          >
            <View style={styles.textView}>
              <View style={styles.textbg}>
                <Text style={styles.text}>{topData.title}</Text>
              </View>
            </View>
          </ImageBackground>
        </TouchableHighlight>
      </View>);

      topElems.push(topElem);
    }

    return (
      <ScrollView style={styles.container}>
        <View>
          <Swiper style={styles.wrapper} showsButtons={false} height={deviceWidth * 0.6}>
            {topElems}
          </Swiper>
        </View>
        <View style={styles.newTitle}>
          <Divider />
          <Text>最受欢迎玩法</Text>
          <Divider />
        </View>
        <View>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={this.state.data.hot}
            refreshing={this.state.isRefreshing}
            renderItem={this.renderList}
            onRefresh={this.onRefresh.bind(this)}
          />
        </View>
        <View style={styles.newTitle}>
          <Divider />
          <Text>最新玩法</Text>
          <Divider />
        </View>
        <View>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={this.state.data.new}
            refreshing={this.state.isRefreshing}
            renderItem={this.renderList}
            onRefresh={this.onRefresh.bind(this)}
          />
        </View>
        <View class={styles.findMore}>
          <Button backgroundColor={'#00b3fe'} class={styles.moreButton} title={'查看更多'} onPress={() => navigate('Play')} />
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  wrapper: {
    height: deviceWidth * 0.4
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  slide2: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  slide3: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textbg: {
    width: deviceWidth,
    backgroundColor: 'rgba(255, 255, 255, 0.5)'
  },
  text: {
    color: '#384452',
    padding: 10,
    fontSize: normalize(18),
    textAlign: 'center'
  },
  newTitle: {
    paddingTop: 25,
    paddingBottom: 0,
    paddingLeft: 15,
    alignItems: 'flex-start'
  },
  findMore: {
    marginTop: 15,
    marginBottom: 15
  },
  moreButton: {
    marginTop: 15,
    marginBottom: 15
  },
  card: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
    marginTop: 15,
    flexDirection: 'row'
  },
  article: {
    flex: 1
  },
  author: {
    color: '#384452',
    marginBottom: 10,
    fontSize: normalize(12),
    lineHeight: normalize(18)
  },
  description: {
    color: '#384452',
    marginBottom: 5,
    paddingRight: 5,
    fontSize: normalize(10),
    lineHeight: normalize(18)
  }
});

export default HomeView;
<commit_msg>[HOME] update styles<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
  FlatList,
  StyleSheet,
  View,
  ScrollView,
  Text,
  Dimensions,
  Platform,
  TouchableHighlight,
  ImageBackground
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import axios from 'axios';
import FastImage from 'react-native-fast-image';
import Swiper from 'react-native-swiper';
import moment from 'moment';
require('moment/locale/zh-cn');

import normalize from '../../wdui/helpers/normalizeText';
import Loading from '../../wdui/loading/Loading';
import {URL} from '../../constants';
import {
  Divider,
  Button
} from 'react-native-elements';

const deviceWidth = Dimensions.get('window').width;

class HomeView extends Component {
  static displayName = 'HomeView';

  static navigationOptions = {
    header: <View style={{
      backgroundColor: '#384452',
      flexDirection: 'row',
      height: Platform.OS === 'ios' ? 64 : 56
    }}
     />,
    title: '首页推荐',
    tabBarIcon: (props) => (
        <Icon name='home' size={24} color={props.tintColor} />
      )
  };

  static propTypes = {
    navigation: React.PropTypes.object.isRequired,
    navigate: PropTypes.func.isRequired
  };

  constructor() {
    super();
    this.state = {
      loading: false,
      isRefreshing: false,
      data: []
    };
  }

  componentWillMount() {
    this.fetchData();
  }

  onRefresh() {
    this.setState({
      isRefreshing: true
    });
    this.fetchData();
  }

  fetchData() {
    this.setState({
      loading: true
    });
    axios.get(URL.HOME)
      .then(response => {
        this.setState({
          data: response.data,
          isRefreshing: false,
          loading: false
        });
      });
  }

  keyExtractor = (item, index) => `key${index}`;

  renderList = ({item}) => {
    const {navigate} = this.props.navigation;

    return (
      <TouchableHighlight
        onPress={() => navigate('PlayDetailView', item)}
        key={this.keyExtractor}>
        <View style={styles.card}>
          <View style={styles.article}>
            <View>
              <Text style={styles.author}>
                {item.user} 发表于 {moment(item.updated).fromNow()}
              </Text>
            </View>
            <View>
              <Text numberOfLines={2} style={styles.description}>
                {item.description}
              </Text>
            </View>
          </View>
          <View>
            {item.featured_image
              ? <FastImage
                style={{width: deviceWidth * 0.3, height: deviceWidth * 0.3}}
                resizeMode={FastImage.resizeMode.cover}
                source={{
                  uri: URL.IMAGE_BASE + item.featured_image
                }}
              />
              : <View/>
            }
          </View>
        </View>
      </TouchableHighlight>
    );
  };

  render() {
    if (this.state.loading) {
      return <Loading text={'数据加载中'} />;
    }
    const {top} = this.state.data;
    const {navigate} = this.props.navigation;

    let topElems = [];
    for (let i = 0; i < top.length; i++) {
      let topData = top[i];
      let topElem = (<View key={i} style={styles.slide1}>
        <TouchableHighlight onPress={() => navigate('PlayDetailView', topData)}>
          <ImageBackground
            style={{width: deviceWidth, height: deviceWidth * 0.6}}
            source={{
              uri: URL.IMAGE_BASE + topData.featured_image
            }}
          >
            <View style={styles.textView}>
              <View style={styles.textbg}>
                <Text style={styles.text}>{topData.title}</Text>
              </View>
            </View>
          </ImageBackground>
        </TouchableHighlight>
      </View>);

      topElems.push(topElem);
    }

    return (
      <ScrollView style={styles.container}>
        <View>
          <Swiper style={styles.wrapper} showsButtons={false} height={deviceWidth * 0.6}>
            {topElems}
          </Swiper>
        </View>
        <View style={styles.newTitle}>
          <Text style={{paddingLeft: 15}}>最受欢迎玩法</Text>
        </View>
        <View>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={this.state.data.hot}
            refreshing={this.state.isRefreshing}
            renderItem={this.renderList}
            onRefresh={this.onRefresh.bind(this)}
          />
        </View>
        <View style={styles.newTitle}>
          <Text style={{paddingLeft: 15}}>最新玩法</Text>
        </View>
        <View>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={this.state.data.new}
            refreshing={this.state.isRefreshing}
            renderItem={this.renderList}
            onRefresh={this.onRefresh.bind(this)}
          />
        </View>
        <View class={styles.findMore}>
          <Button backgroundColor={'#00b3fe'} class={styles.moreButton} title={'查看更多'} onPress={() => navigate('Play')} />
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  wrapper: {
    height: deviceWidth * 0.4
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  slide2: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  slide3: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textbg: {
    width: deviceWidth,
    backgroundColor: 'rgba(255, 255, 255, 0.5)'
  },
  text: {
    color: '#384452',
    padding: 10,
    fontSize: normalize(18),
    textAlign: 'center'
  },
  newTitle: {
    marginTop: 25,
    paddingBottom: 0,
    marginLeft: 15,
    borderLeftWidth: 2,
    borderLeftColor: '#51c4fe',
    alignItems: 'flex-start'
  },
  findMore: {
    marginTop: 15,
    marginBottom: 15
  },
  moreButton: {
    marginTop: 15,
    marginBottom: 15
  },
  card: {
    flex: 1,
    marginLeft: 15,
    marginRight: 15,
    marginTop: 15,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0, 0, 0, 0.3)',
    flexDirection: 'row'
  },
  article: {
    flex: 1
  },
  author: {
    color: '#384452',
    marginBottom: 10,
    fontSize: normalize(12),
    lineHeight: normalize(18)
  },
  description: {
    color: '#384452',
    marginBottom: 5,
    paddingRight: 5,
    fontSize: normalize(10),
    lineHeight: normalize(18)
  }
});

export default HomeView;
<|endoftext|>


<commit_before>Minionette.View = Backbone.View.extend({
    constructor: function(options) {
        options || (options = {});

        // Ensure we have a Region to initialize
        // new regions from.
        this._ensureRegion(options);
        this._initializeRegions(options);

        Backbone.View.apply(this, arguments);

        // Have the view listenTo the model and collection.
        this._listenToEvents(this.model, _.result(this, 'modelEvents'));
        this._listenToEvents(this.collection, _.result(this, 'collectionEvents'));
    },

    // A default template that will clear this.$el.
    // Override this in a subclass to something useful.
    template: function() { return ''; },

    // A default function that will have it's return passed
    // to this.template
    // Override this in a subclass to something useful.
    serialize: function() {
        return {};
    },

    // The actual "serialize" that is fed into the this.template.
    // Used so a subclass can override this.serialize and still
    // have the `view` helper.
    _serialize: function() {
        return _.extend({view: _.bind(this._viewHelper, this)}, this.serialize());
    },

    // A useful remove method to that triggers events.
    remove: function() {
        if (!this._isRemoving) {
            this._isRemoving = true;
            this.trigger('remove');

            this._removeFromParent();
            _.invoke(this._regions, 'remove');

            Minionette.View.__super__.remove.apply(this, arguments);

            this.unbind();
        }
    },

    // A useful default render method.
    render: function() {
        this.trigger('render');

        // Detach all our regions, so they don't need to be re-rendered.
        _.invoke(this._regions, 'detach');

        this.$el.html(this.template(this._serialize()));

        // Reattach all our regions
        _.invoke(this._regions, 'reattach');

        return this;
    },

    // Adds the region "name" to this as this[name].
    // Also attaches it to this._regions[name], for
    // internal management.
    addRegion: function(name, view) {
        var region = new this.Region({view: view});
        // Remove the region, if it exists already
        attempt(this._regions[name], 'remove');

        region.name = name;
        region._parent = this;
        this[name] = this._regions[name] = region;

        return region;
    },

    // Adds multiple regions to the view. Takes
    // an object with {regioneName: view} syntax
    addRegions: function(regions) {
        _.each(regions, function(view, name) {
            this.addRegion(name, view);
        }, this);
    },

    // A remove helper to remove this view from it's parent
    _removeFromParent: function() {
        // Remove this view from _parent, if it exists
        attempt(this._parent, '_removeView', this);
        this._parent = null;
    },

    _removeRegion: function(region) {
        if (this._regions[region.name]) {
            delete this[region.name];
            delete this._regions[region.name];
        }
    },

    // Loop through the events given, and listen to
    // entity's event.
    _listenToEvents: function(entity, events) {
        if (!entity) { return; }
        _.each(events, function(method, event) {
            if (!_.isFunction(method)) { method = this[method]; }
            this.listenTo(entity, event, method);
        }, this);
    },

    // Sets this.Region. Prioritizes instantiated options.Region,
    // then a subclass' prototype Region, and defaults to Minionette.Region
    _ensureRegion: function(options) {
        this.Region = options.Region || this.Region || Minionette.Region;
    },

    // Takes the #regions object and creates the regions,
    // using the keys as the name and the values as the original
    // view. Keys are all that is required, passing in a false-y
    // value will make Region use a placeholder span element.
    _initializeRegions: function(options) {
        // Initialize our regions object
        this._regions = {};

        // Pull regions from instantiated options.
        var regions = _.result(this, 'regions');
        if (options.regions) { regions = options.regions; }

        // Add the regions
        this.addRegions(regions);
    },

    // A helper that is passed to #template() that will
    // render regions inline.
    _viewHelper: function(view) {
        var region = this._regions[view];
        if (region) {
            return region.render().el.outerHTML;
        }
        return '';
    }
});
<commit_msg>Fix comment in View<commit_after>Minionette.View = Backbone.View.extend({
    constructor: function(options) {
        options || (options = {});

        // Ensure we have a Region to initialize
        // new regions from.
        this._ensureRegion(options);
        this._initializeRegions(options);

        Backbone.View.apply(this, arguments);

        // Have the view listenTo the model and collection.
        this._listenToEvents(this.model, _.result(this, 'modelEvents'));
        this._listenToEvents(this.collection, _.result(this, 'collectionEvents'));
    },

    // A default template that will clear this.$el.
    // Override this in a subclass to something useful.
    template: function() { return ''; },

    // A default function that will have it's return passed
    // to this.template
    // Override this in a subclass to something useful.
    serialize: function() {
        return {};
    },

    // The actual "serialize" that is fed into the this.template.
    // Used so a subclass can override this.serialize and still
    // have the `view` helper.
    _serialize: function() {
        return _.extend({view: _.bind(this._viewHelper, this)}, this.serialize());
    },

    // A useful remove method that triggers events.
    remove: function() {
        if (!this._isRemoving) {
            this._isRemoving = true;
            this.trigger('remove');

            this._removeFromParent();
            _.invoke(this._regions, 'remove');

            Minionette.View.__super__.remove.apply(this, arguments);

            this.unbind();
        }
    },

    // A useful default render method.
    render: function() {
        this.trigger('render');

        // Detach all our regions, so they don't need to be re-rendered.
        _.invoke(this._regions, 'detach');

        this.$el.html(this.template(this._serialize()));

        // Reattach all our regions
        _.invoke(this._regions, 'reattach');

        return this;
    },

    // Adds the region "name" to this as this[name].
    // Also attaches it to this._regions[name], for
    // internal management.
    addRegion: function(name, view) {
        var region = new this.Region({view: view});
        // Remove the region, if it exists already
        attempt(this._regions[name], 'remove');

        region.name = name;
        region._parent = this;
        this[name] = this._regions[name] = region;

        return region;
    },

    // Adds multiple regions to the view. Takes
    // an object with {regioneName: view} syntax
    addRegions: function(regions) {
        _.each(regions, function(view, name) {
            this.addRegion(name, view);
        }, this);
    },

    // A remove helper to remove this view from it's parent
    _removeFromParent: function() {
        // Remove this view from _parent, if it exists
        attempt(this._parent, '_removeView', this);
        this._parent = null;
    },

    _removeRegion: function(region) {
        if (this._regions[region.name]) {
            delete this[region.name];
            delete this._regions[region.name];
        }
    },

    // Loop through the events given, and listen to
    // entity's event.
    _listenToEvents: function(entity, events) {
        if (!entity) { return; }
        _.each(events, function(method, event) {
            if (!_.isFunction(method)) { method = this[method]; }
            this.listenTo(entity, event, method);
        }, this);
    },

    // Sets this.Region. Prioritizes instantiated options.Region,
    // then a subclass' prototype Region, and defaults to Minionette.Region
    _ensureRegion: function(options) {
        this.Region = options.Region || this.Region || Minionette.Region;
    },

    // Takes the #regions object and creates the regions,
    // using the keys as the name and the values as the original
    // view. Keys are all that is required, passing in a false-y
    // value will make Region use a placeholder span element.
    _initializeRegions: function(options) {
        // Initialize our regions object
        this._regions = {};

        // Pull regions from instantiated options.
        var regions = _.result(this, 'regions');
        if (options.regions) { regions = options.regions; }

        // Add the regions
        this.addRegions(regions);
    },

    // A helper that is passed to #template() that will
    // render regions inline.
    _viewHelper: function(view) {
        var region = this._regions[view];
        if (region) {
            return region.render().el.outerHTML;
        }
        return '';
    }
});
<|endoftext|>