<commit_before>/**
 * @author Manuel Mazzuola
 * https://github.com/manuelmazzuola/angular-ui-router-styles
 * Inspired by https://github.com/tennisgent/angular-route-styles
 */

'use strict';

angular
  .module('uiRouterStyles', ['ui.router'])
  .directive('body', ['$rootScope', '$compile', '$state', '$interpolate', '$timeout',
    function($rootScope, $compile, $state, $interpolate, $timeout) {
      return {
        restrict: 'E',
        link: function(scope, elem){
          var start = $interpolate.startSymbol(),
              end = $interpolate.endSymbol();
          var html = '<link rel="stylesheet" ng-repeat="(k, css) in routeStyles track by k" ng-href="' + start + 'css' + end + '" >';
          elem.append($compile(html)(scope));

          // Get the parent state
          var $$parentState = function(state) {
            // Check if state has explicit parent OR we try guess parent from its name
            var name = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
            // If we were able to figure out parent name then get this state
            return name && $state.get(name);
          };

          var removeOldCSS = function(cssSize) {
            $timeout(function() {
              for(var i = 0; i < cssSize; i++) {
                scope.routeStyles.shift()
              }
              scope.routeStyles.reverse();
            }, 200); // Firefox workaround

          };

          $rootScope.$on('$stateChangeSuccess', function (evt, toState) {
            // From current state to the root
            scope.routeStyles = scope.routeStyles || [];
            var oldStylesSize = scope.routeStyles.length;

            for(var state = toState; state && state.name !== ''; state=$$parentState(state)) {
              if(state && state.data !== undefined && state.data.css) {
                if(!Array.isArray(state.data.css)) {
                  state.data.css = [state.data.css];
                }
                angular.forEach(state.data.css, function(css) {
                  if(scope.routeStyles.indexOf(css) === -1) {
                    scope.routeStyles.push(css);
                  }
                });
              }
            }

            var unWatch = scope.$watch(function() {
              return document.styleSheets.length;
            }, function(cssLoaded) {
              unWatch();
              removeOldCSS(oldStylesSize);
            });
          });
        }
      };
    }
  ]);<commit_msg>Revert "Merge pull request #11 from manuelmazzuola/bug#7"<commit_after>/**
 * @author Manuel Mazzuola
 * https://github.com/manuelmazzuola/angular-ui-router-styles
 * Inspired by https://github.com/tennisgent/angular-route-styles
 */

'use strict';

angular
  .module('uiRouterStyles', ['ui.router'])
  .directive('head', ['$rootScope', '$compile', '$state', '$interpolate',
    function($rootScope, $compile, $state, $interpolate) {
      return {
        restrict: 'E',
        link: function(scope, elem){
          var start = $interpolate.startSymbol(),
              end = $interpolate.endSymbol();
          var html = '<link rel="stylesheet" ng-repeat="(k, css) in routeStyles track by k" ng-href="' + start + 'css' + end + '" >';
          elem.append($compile(html)(scope));

          // Get the parent state
          var $$parentState = function(state) {
            // Check if state has explicit parent OR we try guess parent from its name
            var name = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
            // If we were able to figure out parent name then get this state
            return name && $state.get(name);
          };

          scope.routeStyles = [];
          $rootScope.$on('$stateChangeSuccess', function (evt, toState) {
            // From current state to the root
            scope.routeStyles = [];
            for(var state = toState; state && state.name !== ''; state=$$parentState(state)) {
              if(state && state.data && state.data.css) {
                if(!Array.isArray(state.data.css)) {
                  state.data.css = [state.data.css];
                }
                angular.forEach(state.data.css, function(css) {
                  if(scope.routeStyles.indexOf(css) === -1) {
                    scope.routeStyles.push(css);
                  }
                });
              }
            }
            scope.routeStyles.reverse();
          });
        }
      };
    }
  ]);
<|endoftext|>


<commit_before>module.exports.initCombat = _initCombat;
//TODO: Add strings for sanity damage
var Random = require('./random.js').Random;
var LevelUtil = require('./levels')
  .LevelUtil;
var CommandUtil = require('./command_util')
  .CommandUtil;
var util = require('util');
var statusUtils = require('./status');
var Commands = require('./commands').Commands;

function _initCombat(l10n, npc, player, room, npcs, players, rooms, callback) {
  var locale = player.getLocale();
  player.setInCombat(npc);
  npc.setInCombat(player.getName());

  player.sayL10n(l10n, 'ATTACK', npc.getShortDesc(locale));

  var playerBodyParts = [
    'legs',
    'feet',
    'torso',
    'hands',
    'head'
  ];

  var p = {
    isPlayer: true,
    name: player.getName(),
    speed: player.getAttackSpeed(),
    weapon: player.getEquipped('wield', true),
    locations: playerBodyParts,
    target: player.getPreference('target') || 'body',
  };

  var n = {
    name: npc.getShortDesc(locale),
    speed: npc.getAttackSpeed(),
    weapon: npc.getAttack(locale),
    target: npc.getAttribute('target'),
    locations: npc.getLocations()
  };

  try {
    util.log("Combat begins between " + p.name + " and " + n.name);
    util.log("Weapons are " + p.weapon + ' and ' + n.weapon);
    util.log("Speeds are " + p.speed + ' vs. ' + n.speed)
  } catch (e) { util.log(e); }

  var playerCombat = combatRound.bind(null, player, npc, p, n);
  var npcCombat = combatRound.bind(null, npc, player, n, p);

  p.attackRound = playerCombat;
  n.attackRound = npcCombat;

  setTimeout(npcCombat, n.speed);
  setTimeout(playerCombat, p.speed);

  function combatRound(attacker, defender, a, d) {

    if (!defender.isInCombat() || !attacker.isInCombat())
      return;

    var starting_health = defender.getAttribute('health');
    util.log(a.name + ' health: ' + attacker.getAttribute('health'));
    util.log(d.name + ' health: ' + defender.getAttribute('health'));

    if (d.isPlayer) checkWimpiness(starting_health);

    var damage = attacker.getDamage();
    var defender_sanity = defender.getAttribute('sanity');
    var sanityDamage = a.isPlayer ? 0 : attacker.getSanityDamage();
    var hitLocation = decideHitLocation(d.locations, a.target, isPrecise());

    function isPrecise() {
      return a.isPlayer ? attacker.checkStance('precise') : false;
    }

    if (!damage) {

      if (d.weapon && typeof d.weapon == 'object')
        d.weapon.emit('parry', defender);

      if (a.isPlayer)
        player.sayL10n(l10n, 'PLAYER_MISS', n.name, damage);

      else
        player.sayL10n(l10n, 'NPC_MISS', a.name);

      broadcastExceptPlayer(
        '<bold>' + a.name + ' attacks ' + d.name +
        ' and misses!' + '</bold>');
      util.log(a.name + ' misses ' + d.name);

    } else {

      damage = defender.damage(
        calcRawDamage(damage, defender.getAttribute('health')),
        hitLocation);

      util.log('Targeted ' + a.target + ' and hit ' + hitLocation);
      var damageStr = getDamageString(damage, defender.getAttribute('health'));

      if (a.weapon && typeof a.weapon == 'object')
        a.weapon.emit('hit', player);

      if (d.isPlayer)
        player.sayL10n(l10n, 'DAMAGE_TAKEN', a.name, damageStr, a.weapon, hitLocation);

      else player.sayL10n(l10n, 'DAMAGE_DONE', d.name, damageStr, hitLocation);

      broadcastExceptPlayer('<bold><red>' + a.name + ' attacks ' + d.name +
        ' and ' + damageStr + ' them!' + '</red></bold>');

    }

    if (sanityDamage) {
      sanityDamage = calcRawDamage(sanityDamage, defender_sanity);
      defender.setAttribute('sanity', Math.max(defender_sanity - sanityDamage, 0));
    }

    if (starting_health <= damage) {
      defender.setAttribute('health', 1);
      defender.setAttribute('sanity', 1);
      return combat_end(a.isPlayer);
    }

    player.combatPrompt({
      target_condition: statusUtils.getHealthText(
        npc.getAttribute('max_health'),
        player, npc)(npc.getAttribute('health')),
      player_condition: statusUtils.getHealthText(
        player.getAttribute('max_health'),
        player, false)(player.getAttribute('health'))
    });

    var nearbyFight = [
      "The sounds of a nearby struggle fill the air.",
      "From the sound of it, a mortal struggle is happening nearby.",
      "A cry from nearby! What could it be?",
      "The sounds of a clash echo nearby.",
      "You hear the sounds of flesh being rent, but you cannot tell from where."
    ];

    broadcastToArea(Random.fromArray(nearbyFight));

    setTimeout(a.attackRound, a.speed);
  }

  function decideHitLocation(locations, target, precise) {
    if (precise || Random.coinFlip()) {
      return target;
    } else return Random.fromArray(locations);
  }

  function calcRawDamage(damage, attr) {
    var range = damage.max - damage.min;
    with(Math) {
      return min(
        attr,
        damage.min + max(
          0,
          floor(random() * (range))
        )
      );
    }
  }

  function getPercentage(numerator, denominator) {
    return Math.round((numerator / denominator) * 100);
  }

  function getDamageString(damage, health) {
    var percentage = getPercentage(damage, health);

    var damageStrings = {
      1: 'tickles',
      3: 'scratches',
      8: 'grazes',
      20: 'hits',
      35: 'wounds',
      85: 'maims',
    };

    for (var cutoff in damageStrings) {
      if (percentage <= cutoff) {
        return damageStrings[cutoff];
      }
    }
    return 'crushes';
  }

  function combat_end(success) {

    util.log("*** Combat Over ***");

    player.setInCombat(false);
    npc.setInCombat(false);

    if (success) {

      player.emit('regen');
      room.removeNpc(npc.getUuid());
      npcs.destroy(npc);
      player.sayL10n(l10n, 'WIN', npc.getShortDesc(locale));
      broadcastExceptPlayer('<bold>' + npc.getShortDesc(locale) +
        ' dies.</bold>');

      // hand out experience
      var exp = npc.getAttribute('experience') !== false ?
        npc.getAttribute('experience') : LevelUtil.mobExp(npc.getAttribute('level'));
      util.log("Player wins, exp gain: ", exp);
      player.emit('experience', exp);

    } else {
      util.log("Player death: ", player.getName());
      player.sayL10n(l10n, 'LOSE', npc.getShortDesc(locale));
      player.emit('die');

      broadcastExceptPlayer(player.getName() +
        ' collapses to the ground, life fleeing their body before your eyes.'
      );

      //TODO: consider doing sanity damage to all other players in the room.
      broadcastExceptPlayer('<blue>A horrible feeling gnaws at the pit of your stomach.</blue>');
      npc.setAttribute('health', npc.getAttribute('max_health'));

      broadcastToArea('The gurgles of a dying ' +
        statusUtils.getGenderNoun(player) +
        ' echo from nearby.'
      );
    }
    player.prompt();
    callback(success);
  }

  function checkWimpiness(health) {
    var percentage = getPercentage(health, player.getAttribute('max_health'));
    var wimpiness = player.getPreference('wimpy')
    if (percentage < wimpiness) {
      util.log("Player's wimpiness kicks in...");
      util.log("Health: " + percentage + "% || Wimpiness: " + wimpiness + "%");
      player.say('You panic and try to flee.');
      Commands.player_commands.flee(null, player);
    }
  }

  //TODO: More candidates for utilification, I suppose.

  function broadcastExceptPlayer(msg) {
    players.eachExcept(player, function(p) {
      if (p.getLocation() === player.getLocation()) {
        p.say(msg);
        p.prompt();
      }
    });
  }

  function broadcastToArea(msg) {
    players.eachExcept(player, p => {
      const otherRoom = rooms.getAt(p.getLocation());
      const playerRoom = rooms.getAt(player.getLocation());
      const sameArea = otherRoom.getArea() === playerRoom.getArea();
      const notSameRoom = otherRoom !== playerRoom;

      if (sameArea && notSameRoom) {
        p.say(msg);
        p.prompt();
      }
    });
  }
}
<commit_msg>Fix player weapon logging.<commit_after>module.exports.initCombat = _initCombat;

//TODO: Add strings for sanity damage
var Random = require('./random.js').Random;
var LevelUtil = require('./levels')
  .LevelUtil;
var CommandUtil = require('./command_util')
  .CommandUtil;
var util = require('util');
var statusUtils = require('./status');
var Commands = require('./commands').Commands;

function _initCombat(l10n, npc, player, room, npcs, players, rooms, callback) {
  var locale = player.getLocale();
  player.setInCombat(npc);
  npc.setInCombat(player.getName());

  player.sayL10n(l10n, 'ATTACK', npc.getShortDesc(locale));

  var playerBodyParts = [
    'legs',
    'feet',
    'torso',
    'hands',
    'head'
  ];

  var p = {
    isPlayer: true,
    name: player.getName(),
    speed: player.getAttackSpeed(),
    weapon: player.getEquipped('wield', true),
    locations: playerBodyParts,
    target: player.getPreference('target') || 'body',
  };

  var n = {
    name: npc.getShortDesc(locale),
    speed: npc.getAttackSpeed(),
    weapon: npc.getAttack(locale),
    target: npc.getAttribute('target'),
    locations: npc.getLocations()
  };

  try {
    util.log("Combat begins between " + p.name + " and " + n.name);
    util.log("Weapons are " + p.weapon.getShortDesc('en') + ' and ' + n.weapon);
    util.log("Speeds are " + p.speed + ' vs. ' + n.speed)
  } catch (e) { util.log(e); }

  var playerCombat = combatRound.bind(null, player, npc, p, n);
  var npcCombat = combatRound.bind(null, npc, player, n, p);

  p.attackRound = playerCombat;
  n.attackRound = npcCombat;

  setTimeout(npcCombat, n.speed);
  setTimeout(playerCombat, p.speed);

  function combatRound(attacker, defender, a, d) {

    if (!defender.isInCombat() || !attacker.isInCombat())
      return;

    var starting_health = defender.getAttribute('health');
    util.log(a.name + ' health: ' + attacker.getAttribute('health'));
    util.log(d.name + ' health: ' + defender.getAttribute('health'));

    if (d.isPlayer) checkWimpiness(starting_health);

    var damage = attacker.getDamage();
    var defender_sanity = defender.getAttribute('sanity');
    var sanityDamage = a.isPlayer ? 0 : attacker.getSanityDamage();
    var hitLocation = decideHitLocation(d.locations, a.target, isPrecise());

    function isPrecise() {
      return a.isPlayer ? attacker.checkStance('precise') : false;
    }

    if (!damage) {

      if (d.weapon && typeof d.weapon == 'object')
        d.weapon.emit('parry', defender);

      if (a.isPlayer)
        player.sayL10n(l10n, 'PLAYER_MISS', n.name, damage);

      else
        player.sayL10n(l10n, 'NPC_MISS', a.name);

      broadcastExceptPlayer(
        '<bold>' + a.name + ' attacks ' + d.name +
        ' and misses!' + '</bold>');
      util.log(a.name + ' misses ' + d.name);

    } else {

      damage = defender.damage(
        calcRawDamage(damage, defender.getAttribute('health')),
        hitLocation);

      util.log('Targeted ' + a.target + ' and hit ' + hitLocation);
      var damageStr = getDamageString(damage, defender.getAttribute('health'));

      if (a.weapon && typeof a.weapon == 'object')
        a.weapon.emit('hit', player);

      if (d.isPlayer)
        player.sayL10n(l10n, 'DAMAGE_TAKEN', a.name, damageStr, a.weapon, hitLocation);

      else player.sayL10n(l10n, 'DAMAGE_DONE', d.name, damageStr, hitLocation);

      broadcastExceptPlayer('<bold><red>' + a.name + ' attacks ' + d.name +
        ' and ' + damageStr + ' them!' + '</red></bold>');

    }

    if (sanityDamage) {
      sanityDamage = calcRawDamage(sanityDamage, defender_sanity);
      defender.setAttribute('sanity', Math.max(defender_sanity - sanityDamage, 0));
    }

    if (starting_health <= damage) {
      defender.setAttribute('health', 1);
      defender.setAttribute('sanity', 1);
      return combat_end(a.isPlayer);
    }

    player.combatPrompt({
      target_condition: statusUtils.getHealthText(
        npc.getAttribute('max_health'),
        player, npc)(npc.getAttribute('health')),
      player_condition: statusUtils.getHealthText(
        player.getAttribute('max_health'),
        player, false)(player.getAttribute('health'))
    });

    var nearbyFight = [
      "The sounds of a nearby struggle fill the air.",
      "From the sound of it, a mortal struggle is happening nearby.",
      "A cry from nearby! What could it be?",
      "The sounds of a clash echo nearby.",
      "You hear the sounds of flesh being rent, but you cannot tell from where."
    ];

    broadcastToArea(Random.fromArray(nearbyFight));

    setTimeout(a.attackRound, a.speed);
  }

  function decideHitLocation(locations, target, precise) {
    if (precise || Random.coinFlip()) {
      return target;
    } else return Random.fromArray(locations);
  }

  function calcRawDamage(damage, attr) {
    var range = damage.max - damage.min;
    with(Math) {
      return min(
        attr,
        damage.min + max(
          0,
          floor(random() * (range))
        )
      );
    }
  }

  function getPercentage(numerator, denominator) {
    return Math.round((numerator / denominator) * 100);
  }

  function getDamageString(damage, health) {
    var percentage = getPercentage(damage, health);

    var damageStrings = {
      1: 'tickles',
      3: 'scratches',
      8: 'grazes',
      20: 'hits',
      35: 'wounds',
      85: 'maims',
    };

    for (var cutoff in damageStrings) {
      if (percentage <= cutoff) {
        return damageStrings[cutoff];
      }
    }
    return 'crushes';
  }

  function combat_end(success) {

    util.log("*** Combat Over ***");

    player.setInCombat(false);
    npc.setInCombat(false);

    if (success) {

      player.emit('regen');
      room.removeNpc(npc.getUuid());
      npcs.destroy(npc);
      player.sayL10n(l10n, 'WIN', npc.getShortDesc(locale));
      broadcastExceptPlayer('<bold>' + npc.getShortDesc(locale) +
        ' dies.</bold>');

      // hand out experience
      var exp = npc.getAttribute('experience') !== false ?
        npc.getAttribute('experience') : LevelUtil.mobExp(npc.getAttribute('level'));
      util.log("Player wins, exp gain: ", exp);
      player.emit('experience', exp);

    } else {
      util.log("Player death: ", player.getName());
      player.sayL10n(l10n, 'LOSE', npc.getShortDesc(locale));
      player.emit('die');

      broadcastExceptPlayer(player.getName() +
        ' collapses to the ground, life fleeing their body before your eyes.'
      );

      //TODO: consider doing sanity damage to all other players in the room.
      broadcastExceptPlayer('<blue>A horrible feeling gnaws at the pit of your stomach.</blue>');
      npc.setAttribute('health', npc.getAttribute('max_health'));

      broadcastToArea('The gurgles of a dying ' +
        statusUtils.getGenderNoun(player) +
        ' echo from nearby.'
      );
    }
    player.prompt();
    callback(success);
  }

  function checkWimpiness(health) {
    var percentage = getPercentage(health, player.getAttribute('max_health'));
    var wimpiness = player.getPreference('wimpy')
    if (percentage < wimpiness) {
      util.log("Player's wimpiness kicks in...");
      util.log("Health: " + percentage + "% || Wimpiness: " + wimpiness + "%");
      player.say('You panic and try to flee.');
      Commands.player_commands.flee(null, player);
    }
  }

  //TODO: More candidates for utilification, I suppose.

  function broadcastExceptPlayer(msg) {
    players.eachExcept(player, function(p) {
      if (p.getLocation() === player.getLocation()) {
        p.say(msg);
        p.prompt();
      }
    });
  }

  function broadcastToArea(msg) {
    players.eachExcept(player, p => {
      const otherRoom = rooms.getAt(p.getLocation());
      const playerRoom = rooms.getAt(player.getLocation());
      const sameArea = otherRoom.getArea() === playerRoom.getArea();
      const notSameRoom = otherRoom !== playerRoom;

      if (sameArea && notSameRoom) {
        p.say(msg);
        p.prompt();
      }
    });
  }
}
<|endoftext|>


<commit_before>//该文件内容为原生对象的扩展

/**
 * 获取对象的值
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Object.values = function(obj){
  'use strict';
  var values = [];
  for(var key in obj){
    if (obj.hasOwnProperty(key)) {
      values.push(obj[key])
    }
  }
  return values;
};
<commit_msg>将use strict移到文件顶部<commit_after>'use strict';

//该文件内容为原生对象的扩展

/**
 * 获取对象的值
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Object.values = function(obj){
  var values = [];
  for(var key in obj){
    if (obj.hasOwnProperty(key)) {
      values.push(obj[key])
    }
  }
  return values;
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message) {
    var embed = new Discord.RichEmbed;
    var games = {};
    var text = '';

    message.guild.members.map(member => {
      if (member.user.presence.game) {
        if (games[member.user.presence.game.name]) {
          games[member.user.presence.game.name]++;
        } else {
          games[member.user.presence.game.name] = 1;
        }
      }
    });

    var sortable = [];

    for (var game in games) {
      sortable.push([game, games[game]]);
    }

    sortable.sort(function(a, b) {
      return b[1] - a[1];
    });

    sortable.map((s, i)=> {
      var place = i + 1;
      text = text + '`#' + place +  '` with `' + s[1] + '` players: **' + s[0] + '**\n';
    })

    embed.addField('Most played games:', text);
    embed.setColor(config.embedColor);
    utils.addRequestedText(embed, message);
    message.channel.send(embed);
  }
};
<commit_msg>Only 10<commit_after>const Discord = require('discord.js');
const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message) {
    var embed = new Discord.RichEmbed;
    var games = {};
    var text = '';

    message.guild.members.map(member => {
      if (member.user.presence.game) {
        if (games[member.user.presence.game.name]) {
          games[member.user.presence.game.name]++;
        } else {
          games[member.user.presence.game.name] = 1;
        }
      }
    });

    var sortable = [];

    for (var game in games) {
      sortable.push([game, games[game]]);
    }

    sortable.sort(function(a, b) {
      return b[1] - a[1];
    });

    var only10 = 0;
    sortable.map((s, i)=> {
      if (only10 == 10) return;
      only10++;
      var place = i + 1;
      text = text + '`#' + place +  '` with `' + s[1] + '` players: **' + s[0] + '**\n';
    })

    embed.addField('Most played games:', text);
    embed.setColor(config.embedColor);
    utils.addRequestedText(embed, message);
    message.channel.send(embed);
  }
};
<|endoftext|>


<commit_before>var expect  = require("chai").expect;
var request = require("request");
// Configure and uncomment the following for local testing:
// var org = "your_org";
// var env = "test";

var url = "https://" + org + "-" + env + ".apigee.net/v0/hello"
describe("Running test for helloworld", function(){
    describe("Doing a GET on " + url, function(){
        it("returns status 200", function(done) {
            request(url, function(error, response, body) {
            expect(response.statusCode).to.equal(200);
            done();
         });
      });
   });
});<commit_msg>internal Seed update<commit_after>var expect  = require("chai").expect;
var request = require("request");
// Configure and uncomment the following for local testing using `npm test`.
// Then comment the org and env variables further down.
// var org = "your_org";
// var env = "test";

// The org and env variables get their values from the Seed Test URL.
// Expected: /v1/o/:orgname/e/:env/samples/:sample/test.html
var pathname = window.location.pathname
var splits = pathname.split('/')
var org = splits[3]
var env = splits[5]
var sample = splits[7]

var url = "https://" + org + "-" + env + ".apigee.net/v0/hello"
describe("Running test for helloworld", function(){
    describe("Doing a GET on " + url, function(){
        it("returns status 200", function(done) {
            request(url, function(error, response, body) {
            expect(response.statusCode).to.equal(200);
            done();
         });
      });
   });
});<|endoftext|>


<commit_before>// 初始化
mui.init({
	keyEventBind : {
		backbutton : false
	}
});

// 所有方法都放到这里
mui.plusReady(function(){
	window.addEventListener('detailItem', detailItemHandler);
});

// 展示待办事项
function detailItemHandler(event){
	qiao.h.indexPage().evalJS("$('#backBtn').show();");

	var page = event.detail.page;
	var detailId =event.detail.id;
	var tableName = (page == 'list') ? 't_plan_day_todo' : 't_plan_day_done';
	var sql = 'select * from ' + tableName + ' where id=' + detailId;
	qiao.h.query(qiao.h.db(), sql, function(res){
		if(res.rows.length > 0){
			var data = res.rows.item(0);
			$('#detailTitle').text(data.plan_title);
			$('#detailContent').text(data.plan_content);

			qiao.h.show('detail');
		}
	});
}<commit_msg>详情页面改为左滑进入<commit_after>// 初始化
mui.init({
	keyEventBind : {
		backbutton : false
	}
});

// 所有方法都放到这里
mui.plusReady(function(){
	window.addEventListener('detailItem', detailItemHandler);
});

// 展示待办事项
function detailItemHandler(event){
	qiao.h.indexPage().evalJS("$('#backBtn').show();");

	var page = event.detail.page;
	var detailId =event.detail.id;
	var tableName = (page == 'list') ? 't_plan_day_todo' : 't_plan_day_done';
	var sql = 'select * from ' + tableName + ' where id=' + detailId;
	qiao.h.query(qiao.h.db(), sql, function(res){
		if(res.rows.length > 0){
			var data = res.rows.item(0);
			$('#detailTitle').text(data.plan_title);
			$('#detailContent').text(data.plan_content);

			qiao.h.show('detail', 'slide-in-right');
		}
	});
}<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var _ = require("underscore")._,
    Tokenizer = require('../tokenizers/regexp_tokenizer').WordTokenizer,
    tokenizer = new Tokenizer(),
    stopwords = require('../util/stopwords').words,
    fs = require('fs');

function buildDocument(text, key) {
    var stopOut;

    if(typeof text === 'string') {
        text = tokenizer.tokenize(text.toLowerCase());
        stopOut = true;
    } else if(!_.isArray(text)) {
        return text;
        stopOut = false;
    }

    return text.reduce(function(document, term) {
        if(!stopOut || stopwords.indexOf(term) < 0)
            document[term] = (document[term] ? document[term] + 1 : 1);

        return document;
    }, {__key: key});
}

function tf(term, document) {
    return document[term] ? document[term]: 0;
}

function documentHasTerm(term, document) {
    return document[term] && document[term] > 0;
}

function TfIdf(deserialized) {
    if(deserialized)
        this.documents = deserialized.documents;
    else
        this.documents = [];
}

module.exports = TfIdf;
TfIdf.tf = tf;

TfIdf.prototype.idf = function(term) {
    var docsWithTerm = this.documents.reduce(function(count, document) {
        return count + (documentHasTerm(term, document) ? 1 : 0);
    }, 0);

    return Math.log((this.documents.length) / (docsWithTerm));
};

TfIdf.prototype.addDocument = function(document, key) {
    this.documents.push(buildDocument(document, key));
};

TfIdf.prototype.addFileSync = function(path, encoding, key) {
    if(encoding)
        encoding = 'UTF-8';

    var document = fs.readFileSync(path, 'UTF-8');
    this.documents.push(buildDocument(document, key));
};

TfIdf.prototype.tfidf = function(terms, d) {
    var _this = this;

    if(!_.isArray(terms))
        terms = tokenizer.tokenize(terms.toString().toLowerCase());

    return terms.reduce(function(value, term) {
        return value + (tf(term, _this.documents[d]) * _this.idf(term));
    }, 0.0);
};

TfIdf.prototype.listTerms = function(d) {
    var terms = [];

    for(var term in this.documents[d]) {
        if(term != '__key')
    	   terms.push({term: term, tfidf: this.tfidf(term, d)})
    }

    return terms.sort(function(x, y) { return y.tfidf - x.tfidf });
}

TfIdf.prototype.tfidfs = function(terms, callback) {
    var tfidfs = new Array(this.documents.length);

    for(var i = 0; i < this.documents.length; i++) {
        tfidfs[i] = this.tfidf(terms, i);

        if(callback)
            callback(i, tfidfs[i], this.documents[i].__key);
    }

    return tfidfs;
};
<commit_msg>added idf cache to seriously speed up tfidf searches when searching large data sets, unit tests on the way<commit_after>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var _ = require("underscore")._,
    Tokenizer = require('../tokenizers/regexp_tokenizer').WordTokenizer,
    tokenizer = new Tokenizer(),
    stopwords = require('../util/stopwords').words,
    fs = require('fs');

function buildDocument(text, key) {
    var stopOut;

    if(typeof text === 'string') {
        text = tokenizer.tokenize(text.toLowerCase());
        stopOut = true;
    } else if(!_.isArray(text)) {
        return text;
        stopOut = false;
    }

    return text.reduce(function(document, term) {
        if(!stopOut || stopwords.indexOf(term) < 0)
            document[term] = (document[term] ? document[term] + 1 : 1);

        return document;
    }, {__key: key});
}

function tf(term, document) {
    return document[term] ? document[term]: 0;
}

function documentHasTerm(term, document) {
    return document[term] && document[term] > 0;
}

function TfIdf(deserialized) {
    if(deserialized)
        this.documents = deserialized.documents;
    else
        this.documents = [];

    this._idfCache = {};
}

module.exports = TfIdf;
TfIdf.tf = tf;

TfIdf.prototype.idf = function(term, force) {

    if(this._idfCache[term] && force !== true)
        return this._idfCache[term];

    var docsWithTerm = this.documents.reduce(function(count, document) {
        return count + (documentHasTerm(term, document) ? 1 : 0);
    }, 0);

    var idf = Math.log((this.documents.length) / (docsWithTerm));
    this._idfCache[term] = idf;
    return idf;
};

TfIdf.prototype.addDocument = function(document, key) {
    this.documents.push(buildDocument(document, key));
};

TfIdf.prototype.addFileSync = function(path, encoding, key) {
    if(encoding)
        encoding = 'UTF-8';

    var document = fs.readFileSync(path, 'UTF-8');
    this.documents.push(buildDocument(document, key));
};

TfIdf.prototype.tfidf = function(terms, d) {
    var _this = this;

    if(!_.isArray(terms))
        terms = tokenizer.tokenize(terms.toString().toLowerCase());

    return terms.reduce(function(value, term) {
        return value + (tf(term, _this.documents[d]) * _this.idf(term));
    }, 0.0);
};

TfIdf.prototype.listTerms = function(d) {
    var terms = [];

    for(var term in this.documents[d]) {
        if(term != '__key')
    	   terms.push({term: term, tfidf: this.tfidf(term, d)})
    }

    return terms.sort(function(x, y) { return y.tfidf - x.tfidf });
}

TfIdf.prototype.tfidfs = function(terms, callback) {
    var tfidfs = new Array(this.documents.length);

    for(var i = 0; i < this.documents.length; i++) {
        tfidfs[i] = this.tfidf(terms, i);

        if(callback)
            callback(i, tfidfs[i], this.documents[i].__key);
    }

    return tfidfs;
};
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");
var Module = require("./Module");
var OriginalSource = require("webpack-sources").OriginalSource;
var RawSource = require("webpack-sources").RawSource;
var AsyncDependenciesBlock = require("./AsyncDependenciesBlock");

function ContextModule(resolveDependencies, context, recursive, regExp, addon, async) {
	Module.call(this);
	this.resolveDependencies = resolveDependencies;
	this.context = context;
	this.recursive = recursive;
	this.regExp = regExp;
	this.addon = addon;
	this.async = !!async;
	this.cacheable = true;
	this.contextDependencies = [context];
	this.built = false;
}
module.exports = ContextModule;

ContextModule.prototype = Object.create(Module.prototype);
ContextModule.prototype.constructor = ContextModule;

ContextModule.prototype.identifier = function() {
	var identifier = "";
	identifier += this.context + " ";
	if(this.async)
		identifier += "async ";
	if(!this.recursive)
		identifier += "nonrecursive ";
	if(this.addon)
		identifier += this.addon;
	if(this.regExp)
		identifier += this.regExp;
	return identifier.replace(/ $/, "");
};

function prettyRegExp(str) {
	return str.substring(1, str.length - 1);
}

ContextModule.prototype.readableIdentifier = function(requestShortener) {
	var identifier = "";
	identifier += requestShortener.shorten(this.context) + " ";
	if(this.async)
		identifier += "async ";
	if(!this.recursive)
		identifier += "nonrecursive ";
	if(this.addon)
		identifier += requestShortener.shorten(this.addon);
	if(this.regExp)
		identifier += prettyRegExp(this.regExp + "");
	return identifier.replace(/ $/, "");
};

function contextify(options, request) {
	return request.split("!").map(function(r) {
		var rp = path.relative(options.context, r);
		if(path.sep === "\\")
			rp = rp.replace(/\\/g, "/");
		if(rp.indexOf("../") !== 0)
			rp = "./" + rp;
		return rp;
	}).join("!");
}

ContextModule.prototype.libIdent = function(options) {
	var identifier = contextify(options, this.context) + " ";
	if(this.async)
		identifier += "async ";
	if(this.recursive)
		identifier += "recursive ";
	if(this.addon)
		identifier += contextify(options, this.addon);
	if(this.regExp)
		identifier += prettyRegExp(this.regExp + "");
	return identifier.replace(/ $/, "");
};

ContextModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
	var ts = contextTimestamps[this.context];
	if(!ts) return true;
	return ts >= this.builtTime;
};

ContextModule.prototype.unbuild = function unbuild() {
	this.built = false;
	Module.prototype.unbuild.call(this);
};

ContextModule.prototype.build = function(options, compilation, resolver, fs, callback) {
	this.built = true;
	this.builtTime = new Date().getTime();
	var addon = this.addon;
	this.resolveDependencies(fs, this.context, this.recursive, this.regExp, function(err, dependencies) {
		if(err) return callback(err);
		if(dependencies) {
			dependencies.forEach(function(dep) {
				dep.loc = dep.userRequest;
				dep.request = addon + dep.request;
			});
		}
		if(this.async) {
			if(dependencies) {
				dependencies.forEach(function(dep) {
					var block = new AsyncDependenciesBlock(null, dep.module, dep.loc);
					block.addDependency(dep);
					this.addBlock(block);
				}, this);
			}
		} else {
			this.dependencies = dependencies;
		}
		callback();
	}.bind(this));
};

ContextModule.prototype.source = function() {
	var str;
	var map = {};
	if(this.dependencies && this.dependencies.length > 0) {
		this.dependencies.slice().sort(function(a, b) {
			if(a.userRequest === b.userRequest) return 0;
			return a.userRequest < b.userRequest ? -1 : 1;
		}).forEach(function(dep) {
			if(dep.module)
				map[dep.userRequest] = dep.module.id;
		});
		str = [
			"var map = ", JSON.stringify(map, null, "\t"), ";\n",
			"function webpackContext(req) {\n",
			"\treturn __webpack_require__(webpackContextResolve(req));\n",
			"};\n",
			"function webpackContextResolve(req) {\n",
			"\tvar id = map[req];\n",
			"\tif(!(id + 1)) // check for number\n",
			"\t\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
			"\treturn id;\n",
			"};\n",
			"webpackContext.keys = function webpackContextKeys() {\n",
			"\treturn Object.keys(map);\n",
			"};\n",
			"webpackContext.resolve = webpackContextResolve;\n",
			"module.exports = webpackContext;\n",
			"webpackContext.id = " + JSON.stringify(this.id) + ";\n"
		];
	} else if(this.blocks && this.blocks.length > 0) {
		var items = this.blocks.map(function(block) {
			return {
				dependency: block.dependencies[0],
				block: block,
				userRequest: block.dependencies[0].userRequest
			};
		}).filter(function(item) {
			return item.dependency.module;
		});
		var hasMultipleChunks = false;
		items.sort(function(a, b) {
			if(a.userRequest === b.userRequest) return 0;
			return a.userRequest < b.userRequest ? -1 : 1;
		}).forEach(function(item) {
			if(item.dependency.module) {
				var chunks = item.block.chunks || [];
				if(chunks.length !== 1)
					hasMultipleChunks = true;
				map[item.userRequest] = [item.dependency.module.id].concat(chunks.map(function(chunk) {
					return chunk.id;
				}));
			}
		});
		str = [
			"var map = ", JSON.stringify(map, null, "\t"), ";\n",
			"function webpackAsyncContext(req) {\n",
			"\tvar ids = map[req];",
			"\tif(!ids)\n",
			"\t\treturn Promise.reject(new Error(\"Cannot find module '\" + req + \"'.\"));\n",
			"\treturn ",
			hasMultipleChunks ?
			"Promise.all(ids.slice(1).map(__webpack_require__.e))" :
			"__webpack_require__.e(ids[1])",
			".then(function() {\n",
			"\t\treturn __webpack_require__(ids[0]);\n",
			"\t});\n",
			"};\n",
			"webpackAsyncContext.keys = function webpackAsyncContextKeys() {\n",
			"\treturn Object.keys(map);\n",
			"};\n",
			"module.exports = webpackAsyncContext;\n",
			"webpackAsyncContext.id = " + JSON.stringify(this.id) + ";\n"
		];
	} else {
		str = [
			"function webpackEmptyContext(req) {\n",
			"\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
			"}\n",
			"webpackEmptyContext.keys = function() { return []; };\n",
			"webpackEmptyContext.resolve = webpackEmptyContext;\n",
			"module.exports = webpackEmptyContext;\n",
			"webpackEmptyContext.id = " + JSON.stringify(this.id) + ";\n"
		];
	}
	if(this.useSourceMap) {
		return new OriginalSource(str.join(""), this.identifier());
	} else {
		return new RawSource(str.join(""));
	}
};

ContextModule.prototype.size = function() {
	return this.dependencies.map(function(dep) {
		return dep.userRequest.length + 5;
	}).reduce(function(a, b) {
		return a + b;
	}, 160);
};
<commit_msg>refactor ContextModule to esnext<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const Module = require("./Module");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");

class ContextModule extends Module {
	constructor(resolveDependencies, context, recursive, regExp, addon, async) {
		super();
		this.resolveDependencies = resolveDependencies;
		this.context = context;
		this.recursive = recursive;
		this.regExp = regExp;
		this.addon = addon;
		this.async = !!async;
		this.cacheable = true;
		this.contextDependencies = [context];
		this.built = false;
	}

	identifier() {
		let identifier = "";
		identifier += this.context + " ";
		if(this.async)
			identifier += "async ";
		if(!this.recursive)
			identifier += "nonrecursive ";
		if(this.addon)
			identifier += this.addon;
		if(this.regExp)
			identifier += this.regExp;
		return identifier.replace(/ $/, "");
	}

	prettyRegExp(str) {
		return str.substring(1, str.length - 1);
	}

	readableIdentifier(requestShortener) {
		let identifier = "";
		identifier += requestShortener.shorten(this.context) + " ";
		if(this.async)
			identifier += "async ";
		if(!this.recursive)
			identifier += "nonrecursive ";
		if(this.addon)
			identifier += requestShortener.shorten(this.addon);
		if(this.regExp)
			identifier += this.prettyRegExp(this.regExp + "");
		return identifier.replace(/ $/, "");
	}

	contextify(options, request) {
		return request.split("!").map(function(r) {
			let rp = path.relative(options.context, r);
			if(path.sep === "\\")
				rp = rp.replace(/\\/g, "/");
			if(rp.indexOf("../") !== 0)
				rp = "./" + rp;
			return rp;
		}).join("!");
	}

	libIdent(options) {
		let identifier = this.contextify(options, this.context) + " ";
		if(this.async)
			identifier += "async ";
		if(this.recursive)
			identifier += "recursive ";
		if(this.addon)
			identifier += this.contextify(options, this.addon);
		if(this.regExp)
			identifier += this.prettyRegExp(this.regExp + "");
		return identifier.replace(/ $/, "");
	}

	needRebuild(fileTimestamps, contextTimestamps) {
		const ts = contextTimestamps[this.context];
		if(!ts) return true;
		return ts >= this.builtTime;
	}

	unbuild() {
		this.built = false;
		super.unbuild();
	}

	build(options, compilation, resolver, fs, callback) {
		this.built = true;
		this.builtTime = new Date().getTime();
		const addon = this.addon;
		this.resolveDependencies(fs, this.context, this.recursive, this.regExp, (err, dependencies) => {
			if(err) return callback(err);

			if(dependencies) {
				dependencies.forEach(function(dep) {
					dep.loc = dep.userRequest;
					dep.request = addon + dep.request;
				});
			}
			if(this.async) {
				if(dependencies) {
					dependencies.forEach(dep => {
						const block = new AsyncDependenciesBlock(null, dep.module, dep.loc);
						block.addDependency(dep);
						this.addBlock(block);
					});
				}
			} else {
				this.dependencies = dependencies;
			}
			callback();
		});
	}

	source() {
		let str;
		const map = {};
		if(this.dependencies && this.dependencies.length > 0) {
			this.dependencies.slice().sort(function(a, b) {
				if(a.userRequest === b.userRequest) return 0;
				return a.userRequest < b.userRequest ? -1 : 1;
			}).forEach(function(dep) {
				if(dep.module)
					map[dep.userRequest] = dep.module.id;
			});
			str = [
				"var map = ", JSON.stringify(map, null, "\t"), ";\n",
				"function webpackContext(req) {\n",
				"\treturn __webpack_require__(webpackContextResolve(req));\n",
				"};\n",
				"function webpackContextResolve(req) {\n",
				"\tvar id = map[req];\n",
				"\tif(!(id + 1)) // check for number\n",
				"\t\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
				"\treturn id;\n",
				"};\n",
				"webpackContext.keys = function webpackContextKeys() {\n",
				"\treturn Object.keys(map);\n",
				"};\n",
				"webpackContext.resolve = webpackContextResolve;\n",
				"module.exports = webpackContext;\n",
				"webpackContext.id = " + JSON.stringify(this.id) + ";\n"
			];
		} else if(this.blocks && this.blocks.length > 0) {
			const items = this.blocks.map(function(block) {
				return {
					dependency: block.dependencies[0],
					block: block,
					userRequest: block.dependencies[0].userRequest
				};
			}).filter(function(item) {
				return item.dependency.module;
			});
			let hasMultipleChunks = false;
			items.sort(function(a, b) {
				if(a.userRequest === b.userRequest) return 0;
				return a.userRequest < b.userRequest ? -1 : 1;
			}).forEach(function(item) {
				if(item.dependency.module) {
					const chunks = item.block.chunks || [];
					if(chunks.length !== 1)
						hasMultipleChunks = true;
					map[item.userRequest] = [item.dependency.module.id].concat(chunks.map(function(chunk) {
						return chunk.id;
					}));
				}
			});
			str = [
				"var map = ", JSON.stringify(map, null, "\t"), ";\n",
				"function webpackAsyncContext(req) {\n",
				"\tvar ids = map[req];",
				"\tif(!ids)\n",
				"\t\treturn Promise.reject(new Error(\"Cannot find module '\" + req + \"'.\"));\n",
				"\treturn ",
				hasMultipleChunks ?
				"Promise.all(ids.slice(1).map(__webpack_require__.e))" :
				"__webpack_require__.e(ids[1])",
				".then(function() {\n",
				"\t\treturn __webpack_require__(ids[0]);\n",
				"\t});\n",
				"};\n",
				"webpackAsyncContext.keys = function webpackAsyncContextKeys() {\n",
				"\treturn Object.keys(map);\n",
				"};\n",
				"module.exports = webpackAsyncContext;\n",
				"webpackAsyncContext.id = " + JSON.stringify(this.id) + ";\n"
			];
		} else {
			str = [
				"function webpackEmptyContext(req) {\n",
				"\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
				"}\n",
				"webpackEmptyContext.keys = function() { return []; };\n",
				"webpackEmptyContext.resolve = webpackEmptyContext;\n",
				"module.exports = webpackEmptyContext;\n",
				"webpackEmptyContext.id = " + JSON.stringify(this.id) + ";\n"
			];
		}
		if(this.useSourceMap) {
			return new OriginalSource(str.join(""), this.identifier());
		} else {
			return new RawSource(str.join(""));
		}
	}

	size() {
		return this.dependencies.map(function(dep) {
			return dep.userRequest.length + 5;
		}).reduce(function(a, b) {
			return a + b;
		}, 160);
	}
}

module.exports = ContextModule;
<|endoftext|>


<commit_before>"use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var schedule;
if (typeof process !== "undefined" && process !== null &&
    typeof process.cwd === "function" &&
    typeof process.nextTick === "function" &&
    typeof process.version === "string") {
    schedule = function Promise$_Scheduler(fn) {
        process.nextTick(fn);
    };
}
else if ((typeof global.MutationObserver === "function" ||
        typeof global.WebkitMutationObserver === "function" ||
        typeof global.WebKitMutationObserver === "function") &&
        typeof document !== "undefined" &&
        typeof document.createElement === "function") {

    schedule = (function(){
        var MutationObserver = global.MutationObserver ||
            global.WebKitMutationObserver;
        var div = document.createElement("div");
        var queuedFn = void 0;
        var observer = new MutationObserver(
            function Promise$_Scheduler() {
                ASSERT(queuedFn !== void 0);
                var fn = queuedFn;
                queuedFn = void 0;
                fn();
            }
       );
        observer.observe(div, {
            attributes: true
        });
        return function Promise$_Scheduler(fn) {
            ASSERT(queuedFn === void 0);
            queuedFn = fn;
            div.setAttribute("class", "foo");
        };

    })();
}
else if (global.setTimeout) {
    schedule = function Promise$_Scheduler(fn) {
        setTimeout(fn, 4);
    };
}
else throw new Error("no async scheduler available");
module.exports = schedule;
<commit_msg>Use a smaller timeout value<commit_after>"use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var schedule;
if (typeof process !== "undefined" && process !== null &&
    typeof process.cwd === "function" &&
    typeof process.nextTick === "function" &&
    typeof process.version === "string") {
    schedule = function Promise$_Scheduler(fn) {
        process.nextTick(fn);
    };
}
else if ((typeof global.MutationObserver === "function" ||
        typeof global.WebkitMutationObserver === "function" ||
        typeof global.WebKitMutationObserver === "function") &&
        typeof document !== "undefined" &&
        typeof document.createElement === "function") {

    schedule = (function(){
        var MutationObserver = global.MutationObserver ||
            global.WebKitMutationObserver;
        var div = document.createElement("div");
        var queuedFn = void 0;
        var observer = new MutationObserver(
            function Promise$_Scheduler() {
                ASSERT(queuedFn !== void 0);
                var fn = queuedFn;
                queuedFn = void 0;
                fn();
            }
       );
        observer.observe(div, {
            attributes: true
        });
        return function Promise$_Scheduler(fn) {
            ASSERT(queuedFn === void 0);
            queuedFn = fn;
            div.setAttribute("class", "foo");
        };

    })();
}
else if (global.setTimeout) {
    schedule = function Promise$_Scheduler(fn) {
        setTimeout(fn, 0);
    };
}
else throw new Error("no async scheduler available");
module.exports = schedule;
<|endoftext|>


<commit_before>import _ from 'lodash';
import { isEntityRtl } from 'react-ftm';
import { Model } from '@alephdata/followthemoney';

import { loadState } from 'reducers/util';
import { entityReferencesQuery, profileReferencesQuery } from 'queries';
import { getRecentlyViewedItem } from 'app/storage';

function selectTimestamp(state) {
  return state.mutation;
}

function selectObject(state, objects, id) {
  if (!id || !_.has(objects, id)) {
    return loadState();
  }
  const obj = objects[id];
  const isLoadable = !obj.isError && !obj.isPending;
  if (isLoadable) {
    const outdated = obj.loadedAt && obj.loadedAt < selectTimestamp(state);
    obj.shouldLoad = obj.shouldLoad || outdated;
  }
  obj.shouldLoadDeep = obj.shouldLoad || (isLoadable && obj.shallow !== false);
  return obj;
}

function selectResult(state, query, expand) {
  if (!query || !query.path) {
    return {
      ...loadState(),
      results: [],
      shouldLoad: false,
      shouldLoadDeep: false,
      isPending: true,
    };
  }
  const result = {
    results: [],
    ...selectObject(state, state.results, query.toKey()),
  };
  if (expand) {
    result.results = result.results
      .map((id) => expand(state, id))
      .filter((r) => r.id !== undefined);
  }
  return result;
}

export function selectLocale(state) {
  // determine the active locale to be used by the user interface. this is
  // either saved in localStorage or extracted from metadata. The initial
  // request to metadata will be sent with unmodified Accept-Language headers
  // allowing the backend to perform language negotiation.
  const role = selectCurrentRole(state);

  if (role.locale) {
    return role.locale;
  }
  const { metadata } = state;
  if (metadata && metadata.app) {
    return metadata.app.locale;
  }

  return 'en';
}

export function selectMetadata(state) {
  const metadata = selectObject(state, state, 'metadata');
  if (!metadata.isPending) {
    const locale = selectLocale(state);
    const localeMismatch = metadata?.app?.locale !== locale;
    metadata.shouldLoad = metadata.shouldLoad || localeMismatch;
    metadata.shouldLoad = metadata.shouldLoad || metadata.isError;
  }
  return metadata;
}

export function selectMessages(state) {
  return selectObject(state, state, 'messages');
}

export function selectPinnedMessage(state) {
  const metadata = selectMetadata(state);
  const { messages, dismissed } = selectMessages(state);

  if (metadata?.app?.banner) {
    return { body: metadata.app.banner };
  }

  if (!messages) {
    return null;
  }

  const activeMessages = messages
    .filter(({ id }) => !dismissed.includes(id))
    .filter(({ displayUntil }) => {
      return !displayUntil || Date.now() <= new Date(displayUntil);
    });

  if (activeMessages.length <= 0) {
    return null;
  }

  return activeMessages[0];
}

export function selectPages(state) {
  return selectMetadata(state).pages;
}

export function selectPage(state, name) {
  return selectPages(state).find((page) => page.name === name);
}

export function selectModel(state) {
  const metadata = selectMetadata(state);
  if (metadata.model && !metadata.ftmModel) {
    metadata.ftmModel = new Model(metadata.model);
  }
  return metadata.ftmModel;
}

export function selectSchema(state, schemaName) {
  return selectModel(state).getSchema(schemaName);
}

export function selectSession(state) {
  return selectObject(state, state, 'session');
}

export function selectCurrentRoleId(state) {
  const session = selectSession(state);
  if (!!session.token) {
    return session.token.split('.', 1);
  }
}

export function selectCurrentRole(state) {
  const roleId = selectCurrentRoleId(state);
  return !!roleId ? selectRole(state, roleId) : {};
}

export function selectTester(state) {
  const role = selectCurrentRole(state);
  /* eslint-disable camelcase */
  return role.is_tester || false;
}

export function selectAdmin(state) {
  const role = selectCurrentRole(state);
  /* eslint-disable camelcase */
  return role.is_admin || false;
}

export function selectAlertResult(state, query) {
  return selectResult(state, query);
}

export function selectStatistics(state) {
  return selectObject(state, state, 'statistics');
}

export function selectSystemStatus(state) {
  return selectObject(state, state, 'systemStatus');
}

export function selectRole(state, roleId) {
  return selectObject(state, state.roles, roleId);
}

export function selectEntitySets(state) {
  return state.entitySets;
}

export function selectCollection(state, collectionId) {
  const collection = selectObject(state, state.collections, collectionId);
  const status = collection.status || {};
  status.pending = status.pending || 0;
  status.running = status.running || 0;
  status.finished = status.finished || 0;
  status.active = status.pending + status.running;
  status.total = status.active + status.finished;
  status.progress = status.finished / status.total;
  status.percent = Math.round(status.progress * 100);
  collection.status = status;
  return collection;
}

export function selectEntity(state, entityId) {
  const entity = selectObject(state, state.entities, entityId);
  const lastViewed = getRecentlyViewedItem(entityId);

  if (!entity.selectorCache) {
    const model = selectModel(state);
    if (!entity.schema || !model) {
      return entity;
    }
    entity.selectorCache = model.getEntity(entity);
  }

  const result = entity.selectorCache;
  result.safeHtml = entity.safeHtml;
  result.collection = entity.collection;
  result.role = entity.role;
  result.createdAt = entity.created_at;
  result.updatedAt = entity.updated_at;
  result.highlight = entity.highlight;
  result.latinized = entity.latinized;
  result.isPending = !!entity.isPending;
  result.isError = !!entity.isError;
  result.shouldLoad = !!entity.shouldLoad;
  result.shouldLoadDeep = !!entity.shouldLoadDeep;
  result.shallow = !!entity.shallow;
  result.error = entity.error;
  result.links = entity.links;
  result.profileId = entity.profile_id;
  result.lastViewed = lastViewed;
  result.writeable = entity.writeable;

  return result;
}

export function selectEntityDirectionality(state, entity) {
  const isRtl = isEntityRtl(entity, selectLocale(state), selectModel(state));
  return isRtl ? 'rtl' : 'ltr';
}

export function selectEntitySet(state, entitySetId) {
  return selectObject(state, state.entitySets, entitySetId);
}

export function selectEntitySetItem(state, itemId) {
  const item = selectObject(state, state.entitySetItems, itemId);
  item.entity = selectEntity(state, item.entityId || item.entity?.id);
  return item;
}

export function selectMappingsResult(state, query) {
  return selectResult(state, query, selectEntityMapping);
}

export function selectProfile(state, entitySetId) {
  const profile = selectObject(state, state.entitySets, entitySetId);
  if (profile?.merged?.schema && !profile?.entity?.id) {
    const model = selectModel(state);
    profile.entity = model.getEntity(profile.merged);
    profile.entity.latinized = profile.merged.latinized;
  }
  return profile;
}

export function selectDocumentContent(state, documentId) {
  return selectObject(state, state.documentContent, documentId);
}

export function selectCollectionsResult(state, query) {
  return selectResult(state, query, selectCollection);
}

export function selectRolesResult(state, query) {
  return selectResult(state, query, selectRole);
}

export function selectEntitiesResult(state, query) {
  return selectResult(state, query, selectEntity);
}

function buildReferences(references, schema) {
  if (!schema) {
    return { ...references, results: [] };
  }
  references.results = references.results || [];
  references.results = references.results.map((ref) => {
    if (!!ref.schema) {
      return ref;
    }
    const reverse = schema.getProperty(ref.property);
    const property = reverse.getReverse();
    return {
      schema: property.schema,
      property,
      reverse,
      count: ref.count,
    };
  });
  references.results = references.results.filter(
    (ref) => ref.reverse.stub && !ref.reverse.hidden
  );
  references.total = references.results.length;
  return references;
}

export function selectEntityExpandResult(state, query) {
  return selectObject(state, state.results, query.toKey());
}

export function selectEntityReferences(state, entityId) {
  const entity = selectEntity(state, entityId);
  const query = entityReferencesQuery(entityId);
  const references = selectEntityExpandResult(state, query);
  return buildReferences(references, entity?.schema);
}

export function selectEntityReference(state, entityId, qname) {
  const references = selectEntityReferences(state, entityId);
  return references.results.find((ref) => ref.property.qname === qname);
}

export function selectProfileExpandResult(state, query) {
  return selectObject(state, state.results, query.toKey());
}

export function selectProfileReferences(state, profileId) {
  const profile = selectProfile(state, profileId);
  const query = profileReferencesQuery(profileId);
  const references = selectProfileExpandResult(state, query);
  return buildReferences(references, profile?.entity?.schema);
}

export function selectProfileReference(state, profileId, qname) {
  const references = selectProfileReferences(state, profileId);
  return references.results.find((ref) => ref.property.qname === qname);
}

export function selectNotificationsResult(state, query) {
  const model = selectModel(state);
  const result = selectResult(
    state,
    query,
    (stateInner, id) => stateInner.notifications[id]
  );
  result.results.forEach((notif) => {
    Object.entries(notif.event.params).forEach(([field, type]) => {
      if (type === 'entity' && notif.params[field]) {
        notif.params[field] = model.getEntity(notif.params[field]);
      }
    });
  });
  return result;
}

export function selectEntitySetsResult(state, query) {
  return selectResult(state, query, selectEntitySet);
}

export function selectEntitySetItemsResult(state, query) {
  return selectResult(state, query, selectEntitySetItem);
}

export function selectEntityTags(state, entityId) {
  return selectObject(state, state.entityTags, entityId);
}

export function selectProfileTags(state, profileId) {
  return selectEntityTags(state, profileId);
}

export function selectExports(state) {
  return state.exports;
}

export function selectValueCount(state, prop, value) {
  if (!prop.matchable || !prop.type.grouped) {
    return null;
  }
  return state.values[`${prop.type.group}:${value}`] || null;
}

export function selectEntityView(state, entityId, mode, isPreview) {
  if (mode) {
    return mode;
  }
  const { schema } = selectEntity(state, entityId);
  if (
    schema &&
    schema.isAny(['Email', 'HyperText', 'Image', 'Pages', 'Table'])
  ) {
    return 'view';
  }
  if (schema && schema.isA('Folder')) {
    return 'browse';
  }
  if (schema && schema.isDocument()) {
    return 'view';
  }
  if (isPreview) {
    return 'info';
  }
  const references = selectEntityReferences(state, entityId);
  if (references?.results?.length) {
    return references.results[0].property.qname;
  }
  return 'similar';
}

export function selectProfileView(state, profileId, mode) {
  return mode ? mode : 'items';
}

export function selectCollectionPermissions(state, collectionId) {
  return selectObject(state, state.collectionPermissions, collectionId);
}

export function selectEntityMapping(state, entityId) {
  return selectObject(state, state.entityMappings, entityId);
}

export function selectCollectionXref(state, xrefId) {
  return selectObject(state, state.collectionXref, xrefId);
}

export function selectCollectionXrefResult(state, query) {
  const result = selectResult(state, query, undefined);
  result.results.forEach((xref) => {
    xref.match = selectEntity(state, xref.matchId);
    xref.entity = selectEntity(state, xref.entityId);
  });
  return result;
}

export function selectSimilarResult(state, query) {
  const result = selectResult(state, query, undefined);
  result.results.forEach((obj) => {
    obj.entity = selectEntity(state, obj.entityId);
  });
  return result;
}

export function selectQueryLog(state) {
  return selectObject(state, state, 'queryLogs');
}

export function selectQueryLogsLimited(state, limit = 9) {
  const queryLogs = selectQueryLog(state);
  let results = [];
  if (queryLogs && !!queryLogs.results) {
    results = queryLogs.results.slice(0, limit);
  }
  return {
    ...queryLogs,
    results,
  };
}

export function selectBookmarks(state) {
  return selectObject(state, state, 'bookmarks');
}

export function selectBookmark(state, entity) {
  const bookmarks = selectBookmarks(state);
  return bookmarks.find(({ id }) => id === entity.id);
}

export function selectEntityBookmarked(state, entity) {
  const bookmark = selectBookmark(state, entity);
  return bookmark !== undefined;
}
<commit_msg>Sort bookmarks in inverse-chronological order<commit_after>import _ from 'lodash';
import { isEntityRtl } from 'react-ftm';
import { Model } from '@alephdata/followthemoney';

import { loadState } from 'reducers/util';
import { entityReferencesQuery, profileReferencesQuery } from 'queries';
import { getRecentlyViewedItem } from 'app/storage';

function selectTimestamp(state) {
  return state.mutation;
}

function selectObject(state, objects, id) {
  if (!id || !_.has(objects, id)) {
    return loadState();
  }
  const obj = objects[id];
  const isLoadable = !obj.isError && !obj.isPending;
  if (isLoadable) {
    const outdated = obj.loadedAt && obj.loadedAt < selectTimestamp(state);
    obj.shouldLoad = obj.shouldLoad || outdated;
  }
  obj.shouldLoadDeep = obj.shouldLoad || (isLoadable && obj.shallow !== false);
  return obj;
}

function selectResult(state, query, expand) {
  if (!query || !query.path) {
    return {
      ...loadState(),
      results: [],
      shouldLoad: false,
      shouldLoadDeep: false,
      isPending: true,
    };
  }
  const result = {
    results: [],
    ...selectObject(state, state.results, query.toKey()),
  };
  if (expand) {
    result.results = result.results
      .map((id) => expand(state, id))
      .filter((r) => r.id !== undefined);
  }
  return result;
}

export function selectLocale(state) {
  // determine the active locale to be used by the user interface. this is
  // either saved in localStorage or extracted from metadata. The initial
  // request to metadata will be sent with unmodified Accept-Language headers
  // allowing the backend to perform language negotiation.
  const role = selectCurrentRole(state);

  if (role.locale) {
    return role.locale;
  }
  const { metadata } = state;
  if (metadata && metadata.app) {
    return metadata.app.locale;
  }

  return 'en';
}

export function selectMetadata(state) {
  const metadata = selectObject(state, state, 'metadata');
  if (!metadata.isPending) {
    const locale = selectLocale(state);
    const localeMismatch = metadata?.app?.locale !== locale;
    metadata.shouldLoad = metadata.shouldLoad || localeMismatch;
    metadata.shouldLoad = metadata.shouldLoad || metadata.isError;
  }
  return metadata;
}

export function selectMessages(state) {
  return selectObject(state, state, 'messages');
}

export function selectPinnedMessage(state) {
  const metadata = selectMetadata(state);
  const { messages, dismissed } = selectMessages(state);

  if (metadata?.app?.banner) {
    return { body: metadata.app.banner };
  }

  if (!messages) {
    return null;
  }

  const activeMessages = messages
    .filter(({ id }) => !dismissed.includes(id))
    .filter(({ displayUntil }) => {
      return !displayUntil || Date.now() <= new Date(displayUntil);
    });

  if (activeMessages.length <= 0) {
    return null;
  }

  return activeMessages[0];
}

export function selectPages(state) {
  return selectMetadata(state).pages;
}

export function selectPage(state, name) {
  return selectPages(state).find((page) => page.name === name);
}

export function selectModel(state) {
  const metadata = selectMetadata(state);
  if (metadata.model && !metadata.ftmModel) {
    metadata.ftmModel = new Model(metadata.model);
  }
  return metadata.ftmModel;
}

export function selectSchema(state, schemaName) {
  return selectModel(state).getSchema(schemaName);
}

export function selectSession(state) {
  return selectObject(state, state, 'session');
}

export function selectCurrentRoleId(state) {
  const session = selectSession(state);
  if (!!session.token) {
    return session.token.split('.', 1);
  }
}

export function selectCurrentRole(state) {
  const roleId = selectCurrentRoleId(state);
  return !!roleId ? selectRole(state, roleId) : {};
}

export function selectTester(state) {
  const role = selectCurrentRole(state);
  /* eslint-disable camelcase */
  return role.is_tester || false;
}

export function selectAdmin(state) {
  const role = selectCurrentRole(state);
  /* eslint-disable camelcase */
  return role.is_admin || false;
}

export function selectAlertResult(state, query) {
  return selectResult(state, query);
}

export function selectStatistics(state) {
  return selectObject(state, state, 'statistics');
}

export function selectSystemStatus(state) {
  return selectObject(state, state, 'systemStatus');
}

export function selectRole(state, roleId) {
  return selectObject(state, state.roles, roleId);
}

export function selectEntitySets(state) {
  return state.entitySets;
}

export function selectCollection(state, collectionId) {
  const collection = selectObject(state, state.collections, collectionId);
  const status = collection.status || {};
  status.pending = status.pending || 0;
  status.running = status.running || 0;
  status.finished = status.finished || 0;
  status.active = status.pending + status.running;
  status.total = status.active + status.finished;
  status.progress = status.finished / status.total;
  status.percent = Math.round(status.progress * 100);
  collection.status = status;
  return collection;
}

export function selectEntity(state, entityId) {
  const entity = selectObject(state, state.entities, entityId);
  const lastViewed = getRecentlyViewedItem(entityId);

  if (!entity.selectorCache) {
    const model = selectModel(state);
    if (!entity.schema || !model) {
      return entity;
    }
    entity.selectorCache = model.getEntity(entity);
  }

  const result = entity.selectorCache;
  result.safeHtml = entity.safeHtml;
  result.collection = entity.collection;
  result.role = entity.role;
  result.createdAt = entity.created_at;
  result.updatedAt = entity.updated_at;
  result.highlight = entity.highlight;
  result.latinized = entity.latinized;
  result.isPending = !!entity.isPending;
  result.isError = !!entity.isError;
  result.shouldLoad = !!entity.shouldLoad;
  result.shouldLoadDeep = !!entity.shouldLoadDeep;
  result.shallow = !!entity.shallow;
  result.error = entity.error;
  result.links = entity.links;
  result.profileId = entity.profile_id;
  result.lastViewed = lastViewed;
  result.writeable = entity.writeable;

  return result;
}

export function selectEntityDirectionality(state, entity) {
  const isRtl = isEntityRtl(entity, selectLocale(state), selectModel(state));
  return isRtl ? 'rtl' : 'ltr';
}

export function selectEntitySet(state, entitySetId) {
  return selectObject(state, state.entitySets, entitySetId);
}

export function selectEntitySetItem(state, itemId) {
  const item = selectObject(state, state.entitySetItems, itemId);
  item.entity = selectEntity(state, item.entityId || item.entity?.id);
  return item;
}

export function selectMappingsResult(state, query) {
  return selectResult(state, query, selectEntityMapping);
}

export function selectProfile(state, entitySetId) {
  const profile = selectObject(state, state.entitySets, entitySetId);
  if (profile?.merged?.schema && !profile?.entity?.id) {
    const model = selectModel(state);
    profile.entity = model.getEntity(profile.merged);
    profile.entity.latinized = profile.merged.latinized;
  }
  return profile;
}

export function selectDocumentContent(state, documentId) {
  return selectObject(state, state.documentContent, documentId);
}

export function selectCollectionsResult(state, query) {
  return selectResult(state, query, selectCollection);
}

export function selectRolesResult(state, query) {
  return selectResult(state, query, selectRole);
}

export function selectEntitiesResult(state, query) {
  return selectResult(state, query, selectEntity);
}

function buildReferences(references, schema) {
  if (!schema) {
    return { ...references, results: [] };
  }
  references.results = references.results || [];
  references.results = references.results.map((ref) => {
    if (!!ref.schema) {
      return ref;
    }
    const reverse = schema.getProperty(ref.property);
    const property = reverse.getReverse();
    return {
      schema: property.schema,
      property,
      reverse,
      count: ref.count,
    };
  });
  references.results = references.results.filter(
    (ref) => ref.reverse.stub && !ref.reverse.hidden
  );
  references.total = references.results.length;
  return references;
}

export function selectEntityExpandResult(state, query) {
  return selectObject(state, state.results, query.toKey());
}

export function selectEntityReferences(state, entityId) {
  const entity = selectEntity(state, entityId);
  const query = entityReferencesQuery(entityId);
  const references = selectEntityExpandResult(state, query);
  return buildReferences(references, entity?.schema);
}

export function selectEntityReference(state, entityId, qname) {
  const references = selectEntityReferences(state, entityId);
  return references.results.find((ref) => ref.property.qname === qname);
}

export function selectProfileExpandResult(state, query) {
  return selectObject(state, state.results, query.toKey());
}

export function selectProfileReferences(state, profileId) {
  const profile = selectProfile(state, profileId);
  const query = profileReferencesQuery(profileId);
  const references = selectProfileExpandResult(state, query);
  return buildReferences(references, profile?.entity?.schema);
}

export function selectProfileReference(state, profileId, qname) {
  const references = selectProfileReferences(state, profileId);
  return references.results.find((ref) => ref.property.qname === qname);
}

export function selectNotificationsResult(state, query) {
  const model = selectModel(state);
  const result = selectResult(
    state,
    query,
    (stateInner, id) => stateInner.notifications[id]
  );
  result.results.forEach((notif) => {
    Object.entries(notif.event.params).forEach(([field, type]) => {
      if (type === 'entity' && notif.params[field]) {
        notif.params[field] = model.getEntity(notif.params[field]);
      }
    });
  });
  return result;
}

export function selectEntitySetsResult(state, query) {
  return selectResult(state, query, selectEntitySet);
}

export function selectEntitySetItemsResult(state, query) {
  return selectResult(state, query, selectEntitySetItem);
}

export function selectEntityTags(state, entityId) {
  return selectObject(state, state.entityTags, entityId);
}

export function selectProfileTags(state, profileId) {
  return selectEntityTags(state, profileId);
}

export function selectExports(state) {
  return state.exports;
}

export function selectValueCount(state, prop, value) {
  if (!prop.matchable || !prop.type.grouped) {
    return null;
  }
  return state.values[`${prop.type.group}:${value}`] || null;
}

export function selectEntityView(state, entityId, mode, isPreview) {
  if (mode) {
    return mode;
  }
  const { schema } = selectEntity(state, entityId);
  if (
    schema &&
    schema.isAny(['Email', 'HyperText', 'Image', 'Pages', 'Table'])
  ) {
    return 'view';
  }
  if (schema && schema.isA('Folder')) {
    return 'browse';
  }
  if (schema && schema.isDocument()) {
    return 'view';
  }
  if (isPreview) {
    return 'info';
  }
  const references = selectEntityReferences(state, entityId);
  if (references?.results?.length) {
    return references.results[0].property.qname;
  }
  return 'similar';
}

export function selectProfileView(state, profileId, mode) {
  return mode ? mode : 'items';
}

export function selectCollectionPermissions(state, collectionId) {
  return selectObject(state, state.collectionPermissions, collectionId);
}

export function selectEntityMapping(state, entityId) {
  return selectObject(state, state.entityMappings, entityId);
}

export function selectCollectionXref(state, xrefId) {
  return selectObject(state, state.collectionXref, xrefId);
}

export function selectCollectionXrefResult(state, query) {
  const result = selectResult(state, query, undefined);
  result.results.forEach((xref) => {
    xref.match = selectEntity(state, xref.matchId);
    xref.entity = selectEntity(state, xref.entityId);
  });
  return result;
}

export function selectSimilarResult(state, query) {
  const result = selectResult(state, query, undefined);
  result.results.forEach((obj) => {
    obj.entity = selectEntity(state, obj.entityId);
  });
  return result;
}

export function selectQueryLog(state) {
  return selectObject(state, state, 'queryLogs');
}

export function selectQueryLogsLimited(state, limit = 9) {
  const queryLogs = selectQueryLog(state);
  let results = [];
  if (queryLogs && !!queryLogs.results) {
    results = queryLogs.results.slice(0, limit);
  }
  return {
    ...queryLogs,
    results,
  };
}

export function selectBookmarks(state) {
  const bookmarks = selectObject(state, state, 'bookmarks');
  return bookmarks.sort((a, b) => b.bookmarkedAt - a.bookmarkedAt);
}

export function selectBookmark(state, entity) {
  const bookmarks = selectBookmarks(state);
  return bookmarks.find(({ id }) => id === entity.id);
}

export function selectEntityBookmarked(state, entity) {
  const bookmark = selectBookmark(state, entity);
  return bookmark !== undefined;
}
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 15,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    "hyper-monokai-extended",
    "hyper-savetext",
    "hypercwd",
    "hyper-dark-scrollbar"
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<commit_msg>Added some hyper plugins<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 15,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    "hyper-monokai-extended",
    "hyper-savetext",
    "hypercwd",
    "hyper-dark-scrollbar",
    "hyper-tab-icons",
    "hyper-tabs-enhanced"
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<|endoftext|>