<commit_before>jQuery(function($)
{
  function init()
  {
    var arrMaximDefault = [
      "To me, ideas are worth nothing unless executed. They are just a multiplier. Execution is worth millions.	@Derek Sivers",
      "兴趣是最好的老师。	@Albert Einstein",
      "Innovation is not about saying yes to everything. It’s about saying NO to all but the most crucial features.	@Steve Jobs",
      "Stay hungry. Stay foolish.	@Steve Jobs",
      "这辈子没法做太多的事情, 所以每一件都要做到精彩绝伦!	@Steve Jobs",
      "我每天都自问: '如果今天是我生命的最后一天, 我还会做今天打算做的事情吗?'	@Steve Jobs",
      "没有人可以回到过去重新开始, 但谁都可以从现在开始, 书写一个全然不同的结局!",
      "想得到你从未拥有过的东西, 就必须去做你从未做过的事情。",
      "我唯一能确定的就是自己的无知!	@Socrates",
      "不要盲目地崇拜任何权威, 因为你总能找到相反的权威。	@Bertrand Arthur William Russell",
      "许多人宁愿死, 也不愿思考 -- 事实上他们也确实到死都没有思考。	@Bertrand Arthur William Russell",
      "编程的艺术就是处理复杂性的艺术。	@Edsger Dijkstra (图灵奖得主)",
      "简单是可靠的先决条件!	Simplicity is prerequisite for reliability.	@Edsger Dijkstra (图灵奖得主)",
      "设计软件有两种方法: 一种是简单到极致而明显没有缺陷; 另一种是复杂到极致以至于没有明显的缺陷。前者要难得多!	@C.A.R.Hoare",
      "好的程序代码本身就是最好的文档!	@Steve McConnell (《代码大全》作者)",
      "你写下的任何代码, 在六个月以后去看的话, 都像是别人写的。	@Tom Cargill",
      "程序必须首先让人类可以理解, 然后顺便让机器能执行。	@Abelson / Sussman",
      "过早的优化是万恶之源!	Premature optimization is the root of all evil.	@Donald Knuth (算法大牛 图灵奖得主)",
      "在进度落后的项目中增加人手只会导致进度更加落后!	@Fred Brooks (图灵奖得主 《人月神话》作者)",
      "用代码行数测算软件开发进度如同按重量测算飞机的制造进度。	@Bill Gates",
      "如果调试(Debug)是去除Bug的过程, 那么编程就是制造Bug的过程。	@Edsger Dijkstra (图灵奖得主)",
      "软件就像'性'一样, 免费的时候更好!	Software is like sex; it's better when it's free.	@Linus Torvalds (Linux之父)",
      "若批评不自由, 则赞美无意义!	@法国《费加罗报》的宗旨",
      "牺牲基本自由来换取暂时的安全, 最后既得不到安全也得不到自由!	@Benjamin Franklin",
      "在大欺骗的时代, 说出真相就是革命行为!	@George Orwell (《1984》作者)",
      "如果政府不能解决问题, 那它本身就成为问题!	@Ronald Wilson Reagan (美国前总统)",
      "将愚人从他们所敬拜的锁链下解放出来是非常困难的。	@Voltaire (法国启蒙思想家)",
      "解放一个习惯于被奴役的民族比奴役一个习惯于自由的民族更难!	@Charles de Secondat, Baron de Montesquieu (法国启蒙思想家)",
      "你可以暂时地蒙骗所有人, 也可以永久地蒙骗部分人, 但不可能永久地蒙骗所有人。	You can fool all the people some of the time, some of the people all the time, but you cannot fool all the people all the time.	@Abraham Lincoln (美国前总统)",
      "古代愚民政策是不许人民受教育, 现代愚民政策是只许人民受洗脑教育",
      "全中国只有一所学校, 就是党校 -- 其它的学校都是分校!	@陈丹青",
      "小时候一个劲地教你做好人, 长大了一个劲地教你做坏人	这就是中国式教育",
      "以前学英语是为了更好地了解外国, 现在学英语是为了更好地了解中国!",
      "专政与民主是对立的统一, 人民民主是基础, 只有充分民主才能有专政, 离开民主就是法西斯专政!	@胡耀邦",
      "如果人民不欢迎我们, 我们就该下台了!	@胡耀邦",
      "当你试图了解你的祖国, 你已经走上了犯罪道路!	@艾未未 (艺术家 政治异议人士)",
      "既千方百计阻止你知道真相, 又千方百计指责你不明真相 :)",
      "天朝知识分子分三类: 1 沉默的大多数 2 公共知识分子 3 '公公'知识分子",
      "中国人最悲哀的就是: 刚被历史的车轮碾过, 还没来得及爬起来, 发现历史在倒车...",
      "罗马城之所以是这样的罗马城是因为市民就是这样的市民!	This City is what it is because our citizens are what they are.	@Plato",
      "雪崩时, 没有一片雪花觉得自己有责任。	@Voltaire",
      "千万别以为自己可以逃避, 我们的每一步都决定着最后的结局, 我们的脚正在走向自己选定的终点。	@Milan Kundera (作家)",
      "真正的猛士敢于在一个不正常的国家做一个正常的人",
      "每当有事情发生: 懦夫会问: '这么做安全吗?' 患得患失者会问: '这么做明智吗?' 虚荣者会问: '这么做受欢迎吗?' 但是良知只会问: '这么做正确吗?'	@Martin Luther King, Jr. (美国人权领袖)",
      "Google重新发明了搜索, Facebook重新发明了社交, Apple重新发明了手机, Amazon重新发明了书籍...天朝重新发明了局域网!",
      "几十年来, 朝鲜的领导人只有一个, 叫'金正日'; 几十年来, 天朝的领导人也只有一个, 叫'敏感词'",
      "翻墙和OX的相似之处:	一旦会做就老想做; 做第一次之后觉得天地豁然开朗; 每次做都有快感; 觉得不会做的都是SB!",
      "用人不在于如何减少人的短处, 而在于如何发挥人的长处。	@Peter Ferdinand Drucker (管理学之父)",
      "你想雇用的人必须具备3种品质: 正直诚实、聪明能干和精力充沛。如果缺少第1种, 后2种品质会要你命!	@Warren Edward Buffett",
      "只有偏执狂才能生存!	@Andy Grove (英特尔创始人之一, 前任CEO)",
      "伟大的车工值得给他几倍于普通车工的薪水。但一个伟大的程序员, 其价值相当于普通程序员的1万倍!	@Bill Gates",
      "投资是预测资产收益的活动, 而投机是预测市场心理的活动。	@John Maynard Keynes",
      "投资风险来自于: 你不知道你在做什么 :)	@Warren Edward Buffett",
      "真正坚强并且心态健康的人，被朋友出卖，被亲人误解，被爱人抛弃，也不会对人性失去信心。	@罗永浩",
      "希望你一腔正义或者说充满了正直感，受到恶心的人、身边的人、你相信的人给你打击摧残的时候，你明确这样一点就是：你做正确的事不是为了他们做的，是为了你认为是正确的原则去做的。	@罗永浩",
      "经济学理论并不是一些现成的可以用于政策分析的结论。它不是教条，而是一种方法、一种智力工具、一种思维技巧，有助于拥有它的人得出正确的结论。	@John Maynard Keynes",
      "现代社会的三种毒药：消费主义，性自由和成功学。消费主义以品牌为噱头，以时尚为药效，恋物成瘾。性自由以人性为噱头，以性爱为药效，纵欲成瘾。成功学以速成为噱头，以名利为药效，误导急于走捷径成为人上人的年轻人投身其中，投机成瘾。	@古典 (《拆掉思维里的墙》作者)",
      "1988年1月24日，昆明开往上海的80次特快旅客列车运行到贵昆线且午至邓家村站间，发生颠覆事故，造成88人死亡，62人重伤。	事故发生后，丁关根向国务院请辞了铁道部长一职。"
    ];

    var arrMaxim = arrMaximDefault;
    var str = arrMaxim[Math.floor(Math.random() * arrMaxim.length)];
    str = str.replace(/\t/g, "
");
    str = str.replace(/@/g, "");
    var chLeft = String.fromCharCode(60);
    var chRight = String.fromCharCode(62);
    str = str.replace("http:", chLeft+"a href='http:");
    str = str.replace("html", "html'"+chRight+"相关帖子"+chLeft+"/a"+chRight);
    $("blockquote.pull-right").children("p.maxim").html(str);
  }

  $(document).ready(
    function()
    {
      try
      {
        init();
      }
      catch(err)
      {
      }
    }
  );

});
<commit_msg>Add Brook's law<commit_after>jQuery(function($)
{
  function init()
  {
    var arrMaximDefault = [
      "Adding people to a late software project makes it later. @Fred Brooks",
      "To me, ideas are worth nothing unless executed. They are just a multiplier. Execution is worth millions.	@Derek Sivers",
      "兴趣是最好的老师。	@Albert Einstein",
      "Innovation is not about saying yes to everything. It’s about saying NO to all but the most crucial features.	@Steve Jobs",
      "Stay hungry. Stay foolish.	@Steve Jobs",
      "这辈子没法做太多的事情, 所以每一件都要做到精彩绝伦!	@Steve Jobs",
      "我每天都自问: '如果今天是我生命的最后一天, 我还会做今天打算做的事情吗?'	@Steve Jobs",
      "没有人可以回到过去重新开始, 但谁都可以从现在开始, 书写一个全然不同的结局!",
      "想得到你从未拥有过的东西, 就必须去做你从未做过的事情。",
      "我唯一能确定的就是自己的无知!	@Socrates",
      "不要盲目地崇拜任何权威, 因为你总能找到相反的权威。	@Bertrand Arthur William Russell",
      "许多人宁愿死, 也不愿思考 -- 事实上他们也确实到死都没有思考。	@Bertrand Arthur William Russell",
      "编程的艺术就是处理复杂性的艺术。	@Edsger Dijkstra (图灵奖得主)",
      "简单是可靠的先决条件!	Simplicity is prerequisite for reliability.	@Edsger Dijkstra (图灵奖得主)",
      "设计软件有两种方法: 一种是简单到极致而明显没有缺陷; 另一种是复杂到极致以至于没有明显的缺陷。前者要难得多!	@C.A.R.Hoare",
      "好的程序代码本身就是最好的文档!	@Steve McConnell (《代码大全》作者)",
      "你写下的任何代码, 在六个月以后去看的话, 都像是别人写的。	@Tom Cargill",
      "程序必须首先让人类可以理解, 然后顺便让机器能执行。	@Abelson / Sussman",
      "过早的优化是万恶之源!	Premature optimization is the root of all evil.	@Donald Knuth (算法大牛 图灵奖得主)",
      "在进度落后的项目中增加人手只会导致进度更加落后!	@Fred Brooks (图灵奖得主 《人月神话》作者)",
      "用代码行数测算软件开发进度如同按重量测算飞机的制造进度。	@Bill Gates",
      "如果调试(Debug)是去除Bug的过程, 那么编程就是制造Bug的过程。	@Edsger Dijkstra (图灵奖得主)",
      "软件就像'性'一样, 免费的时候更好!	Software is like sex; it's better when it's free.	@Linus Torvalds (Linux之父)",
      "若批评不自由, 则赞美无意义!	@法国《费加罗报》的宗旨",
      "牺牲基本自由来换取暂时的安全, 最后既得不到安全也得不到自由!	@Benjamin Franklin",
      "在大欺骗的时代, 说出真相就是革命行为!	@George Orwell (《1984》作者)",
      "如果政府不能解决问题, 那它本身就成为问题!	@Ronald Wilson Reagan (美国前总统)",
      "将愚人从他们所敬拜的锁链下解放出来是非常困难的。	@Voltaire (法国启蒙思想家)",
      "解放一个习惯于被奴役的民族比奴役一个习惯于自由的民族更难!	@Charles de Secondat, Baron de Montesquieu (法国启蒙思想家)",
      "你可以暂时地蒙骗所有人, 也可以永久地蒙骗部分人, 但不可能永久地蒙骗所有人。	You can fool all the people some of the time, some of the people all the time, but you cannot fool all the people all the time.	@Abraham Lincoln (美国前总统)",
      "古代愚民政策是不许人民受教育, 现代愚民政策是只许人民受洗脑教育",
      "全中国只有一所学校, 就是党校 -- 其它的学校都是分校!	@陈丹青",
      "小时候一个劲地教你做好人, 长大了一个劲地教你做坏人	这就是中国式教育",
      "以前学英语是为了更好地了解外国, 现在学英语是为了更好地了解中国!",
      "专政与民主是对立的统一, 人民民主是基础, 只有充分民主才能有专政, 离开民主就是法西斯专政!	@胡耀邦",
      "如果人民不欢迎我们, 我们就该下台了!	@胡耀邦",
      "当你试图了解你的祖国, 你已经走上了犯罪道路!	@艾未未 (艺术家 政治异议人士)",
      "既千方百计阻止你知道真相, 又千方百计指责你不明真相 :)",
      "天朝知识分子分三类: 1 沉默的大多数 2 公共知识分子 3 '公公'知识分子",
      "中国人最悲哀的就是: 刚被历史的车轮碾过, 还没来得及爬起来, 发现历史在倒车...",
      "罗马城之所以是这样的罗马城是因为市民就是这样的市民!	This City is what it is because our citizens are what they are.	@Plato",
      "雪崩时, 没有一片雪花觉得自己有责任。	@Voltaire",
      "千万别以为自己可以逃避, 我们的每一步都决定着最后的结局, 我们的脚正在走向自己选定的终点。	@Milan Kundera (作家)",
      "真正的猛士敢于在一个不正常的国家做一个正常的人",
      "每当有事情发生: 懦夫会问: '这么做安全吗?' 患得患失者会问: '这么做明智吗?' 虚荣者会问: '这么做受欢迎吗?' 但是良知只会问: '这么做正确吗?'	@Martin Luther King, Jr. (美国人权领袖)",
      "Google重新发明了搜索, Facebook重新发明了社交, Apple重新发明了手机, Amazon重新发明了书籍...天朝重新发明了局域网!",
      "几十年来, 朝鲜的领导人只有一个, 叫'金正日'; 几十年来, 天朝的领导人也只有一个, 叫'敏感词'",
      "翻墙和OX的相似之处:	一旦会做就老想做; 做第一次之后觉得天地豁然开朗; 每次做都有快感; 觉得不会做的都是SB!",
      "用人不在于如何减少人的短处, 而在于如何发挥人的长处。	@Peter Ferdinand Drucker (管理学之父)",
      "你想雇用的人必须具备3种品质: 正直诚实、聪明能干和精力充沛。如果缺少第1种, 后2种品质会要你命!	@Warren Edward Buffett",
      "只有偏执狂才能生存!	@Andy Grove (英特尔创始人之一, 前任CEO)",
      "伟大的车工值得给他几倍于普通车工的薪水。但一个伟大的程序员, 其价值相当于普通程序员的1万倍!	@Bill Gates",
      "投资是预测资产收益的活动, 而投机是预测市场心理的活动。	@John Maynard Keynes",
      "投资风险来自于: 你不知道你在做什么 :)	@Warren Edward Buffett",
      "真正坚强并且心态健康的人，被朋友出卖，被亲人误解，被爱人抛弃，也不会对人性失去信心。	@罗永浩",
      "希望你一腔正义或者说充满了正直感，受到恶心的人、身边的人、你相信的人给你打击摧残的时候，你明确这样一点就是：你做正确的事不是为了他们做的，是为了你认为是正确的原则去做的。	@罗永浩",
      "经济学理论并不是一些现成的可以用于政策分析的结论。它不是教条，而是一种方法、一种智力工具、一种思维技巧，有助于拥有它的人得出正确的结论。	@John Maynard Keynes",
      "现代社会的三种毒药：消费主义，性自由和成功学。消费主义以品牌为噱头，以时尚为药效，恋物成瘾。性自由以人性为噱头，以性爱为药效，纵欲成瘾。成功学以速成为噱头，以名利为药效，误导急于走捷径成为人上人的年轻人投身其中，投机成瘾。	@古典 (《拆掉思维里的墙》作者)",
      "1988年1月24日，昆明开往上海的80次特快旅客列车运行到贵昆线且午至邓家村站间，发生颠覆事故，造成88人死亡，62人重伤。	事故发生后，丁关根向国务院请辞了铁道部长一职。"
    ];

    var arrMaxim = arrMaximDefault;
    var str = arrMaxim[Math.floor(Math.random() * arrMaxim.length)];
    str = str.replace(/\t/g, "
");
    str = str.replace(/@/g, "");
    var chLeft = String.fromCharCode(60);
    var chRight = String.fromCharCode(62);
    str = str.replace("http:", chLeft+"a href='http:");
    str = str.replace("html", "html'"+chRight+"相关帖子"+chLeft+"/a"+chRight);
    $("blockquote.pull-right").children("p.maxim").html(str);
  }

  $(document).ready(
    function()
    {
      try
      {
        init();
      }
      catch(err)
      {
      }
    }
  );

});
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "aggressive pokerNode",

  bet_request: function(game_state, bet) {

    console.log(
    "round= " + round,
    " bet_index= " + bet_index,
    " small_blind= " + small_blind,
    " orbits= " + orbits,
    " dealer= " + dealer,
    " community_cards= " + community_cards,
    " current_buy_in= " + current_buy_in,
    " pot= " + pot
    );

    bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet);
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Fix error in console.log<commit_after>
module.exports = {

  VERSION: "aggressive pokerNode",

  bet_request: function(game_state, bet) {

    console.log(
    "round= " + round,
    " bet_index= " + game_state.bet_index,
    " small_blind= " + game_state.small_blind,
    " orbits= " + game_state.orbits,
    " dealer= " + game_state.dealer,
    " community_cards= " + game_state.community_cards,
    " current_buy_in= " + game_state.current_buy_in,
    " pot= " + game_state.pot
    );

    bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet);
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>/* autogenerated by the update_version script */
exports.version=1582054566;
<commit_msg>webapp version update<commit_after>/* autogenerated by the update_version script */
exports.version=1582303473;
<|endoftext|>


<commit_before>var vanya = require('./vanya.js');
var cards = require('./cards.js');

function all_in() {
    return 5000;
}

function pass() {
    return 0;
}

function raise() {
    return 2000;
}

function check() {
    return 1000;
}

module.exports = {

  VERSION: "0.1.0",

  bet_request: function(game_state) {
      console.log(JSON.stringify(game_state, null, 2));

      var our_cards = cards.ourCards(game_state);
      var table_cards = game_state.community_cards;
  try {
      switch(vanya(our_cards.concat(table_cards))) {
          case 0:
          case 1:
          case 2:
              return pass();
          break;

          case 3:
          case 4:
          case 5:
              return raise();
          break;

          case 6:
          case 7:
          case 8:
              return all_in();
          break;
      }
  } catch(e) {
      console.log('WTF!!!???')
  }
    return check();
  },

  showdown: function(game_state) {

  },

  getMaxBetFromState: function getMaxBetFromState(game_state) {
      var players = game_state.players;

      var maxBet = players.reduce(function (max, current) {
          return current < max ? max : current;
      }, 0);

      return maxBet;
  }
};
<commit_msg>getMaxBetFromState<commit_after>var vanya = require('./vanya.js');
var cards = require('./cards.js');
var _ = require('lodash');

function all_in() {
    return 5000;
}

function pass() {
    return 0;
}

function raise() {
    return 2000;
}

function check() {
    return 1000;
}

module.exports = {

  VERSION: "0.1.0",

  bet_request: function(game_state) {
      console.log(JSON.stringify(game_state, null, 2));

      var our_cards = cards.ourCards(game_state);
      var table_cards = game_state.community_cards;
  try {
      switch(vanya(our_cards.concat(table_cards))) {
          case 0:
          case 1:
          case 2:
              return pass();
          break;

          case 3:
          case 4:
          case 5:
              return raise();
          break;

          case 6:
          case 7:
          case 8:
              return all_in();
          break;
      }
  } catch(e) {
      console.log('WTF!!!???')
  }
    return check();
  },

  showdown: function(game_state) {

  },

  getMaxBetFromState: function getMaxBetFromState(game_state) {
      var bets = _.pluck(game_state.players, 'bet');

      var maxBet = bets.reduce(function (max, current) {
          return current < max ? max : current;
      }, 0);

      return maxBet;
  }
};
<|endoftext|>


<commit_before>cordova.define("nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage", function (require, exports, module) { /*jslint browser: true, devel: true, node: true, sloppy: true, plusplus: true*/
    /*global require, cordova */
    /*
    The MIT License (MIT)

    Copyright (c) 2015 Dick Verweij, dickydick1969@hotmail.com, AFAS Software  - d.verweij@afas.nl

    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 exec = require('cordova/exec');

    function SecureLocalStorage() { }

    SecureLocalStorage.prototype.getItem = function (key) {
        return exec(resolve, reject, 'SecureLocalStorage', 'getItem', [key]);
    };

    SecureLocalStorage.prototype.setItem = function (key, value) {
        exec(resolve, reject, 'SecureLocalStorage', 'setItem', [key, value]);

    };

    SecureLocalStorage.prototype.removeItem = function (key) {
        exec(resolve, reject, 'SecureLocalStorage', 'removeItem', [key]);
    };

    SecureLocalStorage.prototype.clear = function () {
        exec(resolve, reject, 'SecureLocalStorage', 'clear', []);
    };

    window.SecureLocalStorage = new SecureLocalStorage();

});
<commit_msg>fix js error<commit_after>cordova.define("nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage", function (require, exports, module)
    { /*jslint browser: true, devel: true, node: true, sloppy: true, plusplus: true*/
        /*global require, cordova */
        /*
    The MIT License (MIT)

    Copyright (c) 2015 Dick Verweij, dickydick1969@hotmail.com, AFAS Software  - d.verweij@afas.nl

    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 exec = require('cordova/exec');

        function SecureLocalStorage()
        {
        }

        SecureLocalStorage.prototype.getItem = function (key)
        {
            return exec(null, null, 'SecureLocalStorage', 'getItem', [key]);
        };

        SecureLocalStorage.prototype.setItem = function (key, value)
        {
            exec(null, null, 'SecureLocalStorage', 'setItem', [key, value]);
        };

        SecureLocalStorage.prototype.removeItem = function (key)
        {
            exec(null, null, 'SecureLocalStorage', 'removeItem', [key]);
        };

        SecureLocalStorage.prototype.clear = function ()
        {
            exec(null, null, 'SecureLocalStorage', 'clear', []);
        };

        window.SecureLocalStorage = new SecureLocalStorage();
    });
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, CKSource - Frederico Knabben. All rights reserved.
 * Licensed under the terms of the MIT License (see LICENSE.md).
 */

( function( mocha, bender ) {
	'use strict';

	var duration = 0,
		passed = 0,
		failed = 0,
		errors = 0,
		ignored = 0,
		total = 0,
		config;

	// handle runner's event and pass the results to Bender
	function benderReporter( runner ) {
		// runner events:
		// - start
		// - end
		// - suite
		// - suite end
		// - test
		// - test end
		// - pass
		// - fail

		function buildError( errors ) {
			var pattern = /\n.*mocha.js.*/gi,
				errorMessage = [],
				error,
				i;

			for ( i = 0; i < errors.length; i++ ) {
				error = errors[ i ];

				if ( error.stack.indexOf( error.message ) === -1 ) {
					errorMessage.push( error.message );
				}

				errorMessage.push( error.stack.replace( pattern, '' ) );
			}

			return errorMessage.join( '\n' );
		}

		runner.on( 'test', function( test ) {
			test.errors = [];
		} );

		runner.on( 'fail', function( test, error ) {
			// test is done so we can publish the result
			if ( test.sent ) {
				var result = {};

				result.module = test.parent.title || '';
				result.name = test.title;
				result.fullName = ( test.parent.title || bender.testData.id ) + ' ' + test.title;
				result.success = false;
				result.error = buildError( [ error ] );
				result.errors = 1;

				bender.result( result );
				// an error occured in one of the hooks - throw it immediately
			} else if ( test.type === 'hook' ) {
				throw error;
				// add it to the test's error stack
			} else {
				test.errors.push( error );
			}
			errors++;
		} );

		runner.on( 'test end', function( test ) {
			var result = {};

			duration += test.duration || 0;

			result.module = test.parent.title || '';
			result.name = test.title;
			result.fullName = ( test.parent.title || bender.testData.id ) + ' ' + test.title;
			result.success = true;
			result.duration = test.duration;

			if ( test.state === 'passed' ) {
				passed++;
			} else if ( test.pending ) {
				result.ignored = true;
				ignored++;
			} else {
				result.success = false;
				result.error = buildError( test.errors );
				result.errors = errors;
				failed++;
			}

			bender.result( result );
			test.sent = true;
		} );

		runner.on( 'end', function() {
			bender.next( {
				duration: duration,
				passed: passed,
				failed: failed,
				errors: errors,
				ignored: ignored,
				total: total,
				coverage: window.__coverage__
			} );
		} );
	}

	// checks if the test is a regression
	function isRegression( title ) {
		var condition;

		return bender.regressions &&
			( condition = bender.regressions[ bender.testData.id + '#' + title ] ) &&
			eval( condition );
	}

	// filter tests to run a single one
	function setupFilter() {
		if ( window.location.hash && window.location.hash !== '#child' ) {
			return decodeURIComponent( window.location.hash.substr( 1 ) );
		}
	}

	// build a configuration for Mocha
	function buildConfig() {
		var defaultConfig = {
				reporter: benderReporter,
				ui: 'bdd',
				globals: [ '__cov*' ],
				grep: setupFilter()
			},
			config;

		if ( bender.config && ( config = bender.config.mocha ) ) {
			Object.keys( config ).forEach( function( name ) {
				// don't override the reporter
				if ( name === 'reporter' ) {
					return;
				}

				// extend default globals list
				if ( name === 'globals' ) {
					defaultConfig.globals = defaultConfig.globals.concat( config.globals );
					return;
				}

				defaultConfig[ name ] = config[ name ];
			} );
		}

		return defaultConfig;
	}

	config = buildConfig();

	// setup mocha
	mocha.setup( config );

	// override "it" to allow regression handling
	if ( config.ui === 'bdd' ) {
		var oldIt = window.it;

		window.it = function( title, fn ) {
			oldIt( title, isRegression( title ) ? null : fn );
		};

		window.it.skip = oldIt.skip;
	}

	// override "test" to allow regression handling
	if ( config.ui === 'tdd' || config.ui === 'qunit' ) {
		var oldTest = window.test;

		window.test = function( title, fn ) {
			oldTest( title, isRegression( title ) ? null : fn );
		};

		window.test.skip = oldTest.skip;
	}

	bender.start = function() {
		mocha.run();
	};

	bender.stopRunner = function() {
		// TODO see if this can be implemented?
	};

} )( window.mocha || {}, bender );
<commit_msg>Ignore missing stacks.<commit_after>/**
 * Copyright (c) 2014, CKSource - Frederico Knabben. All rights reserved.
 * Licensed under the terms of the MIT License (see LICENSE.md).
 */

( function( mocha, bender ) {
	'use strict';

	var duration = 0,
		passed = 0,
		failed = 0,
		errors = 0,
		ignored = 0,
		total = 0,
		config;

	// handle runner's event and pass the results to Bender
	function benderReporter( runner ) {
		// runner events:
		// - start
		// - end
		// - suite
		// - suite end
		// - test
		// - test end
		// - pass
		// - fail

		function buildError( errors ) {
			var pattern = /\n.*mocha.js.*/gi,
				errorMessage = [],
				error,
				i;

			for ( i = 0; i < errors.length; i++ ) {
				error = errors[ i ];

				if ( !error.stack ) {
					continue;
				}

				if ( error.stack.indexOf( error.message ) === -1 ) {
					errorMessage.push( error.message );
				}

				errorMessage.push( error.stack.replace( pattern, '' ) );
			}

			return errorMessage.join( '\n' );
		}

		runner.on( 'test', function( test ) {
			test.errors = [];
		} );

		runner.on( 'fail', function( test, error ) {
			// test is done so we can publish the result
			if ( test.sent ) {
				var result = {};

				result.module = test.parent.title || '';
				result.name = test.title;
				result.fullName = ( test.parent.title || bender.testData.id ) + ' ' + test.title;
				result.success = false;
				result.error = buildError( [ error ] );
				result.errors = 1;

				bender.result( result );
				// an error occured in one of the hooks - throw it immediately
			} else if ( test.type === 'hook' ) {
				throw error;
				// add it to the test's error stack
			} else {
				test.errors.push( error );
			}
			errors++;
		} );

		runner.on( 'test end', function( test ) {
			var result = {};

			duration += test.duration || 0;

			result.module = test.parent.title || '';
			result.name = test.title;
			result.fullName = ( test.parent.title || bender.testData.id ) + ' ' + test.title;
			result.success = true;
			result.duration = test.duration;

			if ( test.state === 'passed' ) {
				passed++;
			} else if ( test.pending ) {
				result.ignored = true;
				ignored++;
			} else {
				result.success = false;
				result.error = buildError( test.errors );
				result.errors = errors;
				failed++;
			}

			bender.result( result );
			test.sent = true;
		} );

		runner.on( 'end', function() {
			bender.next( {
				duration: duration,
				passed: passed,
				failed: failed,
				errors: errors,
				ignored: ignored,
				total: total,
				coverage: window.__coverage__
			} );
		} );
	}

	// checks if the test is a regression
	function isRegression( title ) {
		var condition;

		return bender.regressions &&
			( condition = bender.regressions[ bender.testData.id + '#' + title ] ) &&
			eval( condition );
	}

	// filter tests to run a single one
	function setupFilter() {
		if ( window.location.hash && window.location.hash !== '#child' ) {
			return decodeURIComponent( window.location.hash.substr( 1 ) );
		}
	}

	// build a configuration for Mocha
	function buildConfig() {
		var defaultConfig = {
				reporter: benderReporter,
				ui: 'bdd',
				globals: [ '__cov*' ],
				grep: setupFilter()
			},
			config;

		if ( bender.config && ( config = bender.config.mocha ) ) {
			Object.keys( config ).forEach( function( name ) {
				// don't override the reporter
				if ( name === 'reporter' ) {
					return;
				}

				// extend default globals list
				if ( name === 'globals' ) {
					defaultConfig.globals = defaultConfig.globals.concat( config.globals );
					return;
				}

				defaultConfig[ name ] = config[ name ];
			} );
		}

		return defaultConfig;
	}

	config = buildConfig();

	// setup mocha
	mocha.setup( config );

	// override "it" to allow regression handling
	if ( config.ui === 'bdd' ) {
		var oldIt = window.it;

		window.it = function( title, fn ) {
			oldIt( title, isRegression( title ) ? null : fn );
		};

		window.it.skip = oldIt.skip;
	}

	// override "test" to allow regression handling
	if ( config.ui === 'tdd' || config.ui === 'qunit' ) {
		var oldTest = window.test;

		window.test = function( title, fn ) {
			oldTest( title, isRegression( title ) ? null : fn );
		};

		window.test.skip = oldTest.skip;
	}

	bender.start = function() {
		mocha.run();
	};

	bender.stopRunner = function() {
		// TODO see if this can be implemented?
	};

} )( window.mocha || {}, bender );
<|endoftext|>


<commit_before>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var SWAP_BUFFER = 0.5;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;

	this.swapBuffer = SWAP_BUFFER;
	this.swapAllowed = true;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal 	= cellAtTileCoord(LAYER_PORTAL, tx, 		ty);
	var cellKey 	= cellAtTileCoord(LAYER_KEYS, 	   tx, 		ty);
	var cellDoor 	= cellAtTileCoord(LAYER_DOORS,    tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	//reset to idle animation
	else {
		if(this.jumping == false && this.falling == false)
		{
			if(this.sprite.currentAnimation != ANIM_IDLE)
			this.sprite.setAnimation(ANIM_IDLE);
		}
	}

	//set jumping animation
	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	//check for a reality swap
	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellPortal && this.swapAllowed){

		if (CurrentLevel == level1_green){
			CurrentLevel = level1_blue;
			initialize(CurrentLevel);
		}
		else if (CurrentLevel == level1_blue){
			CurrentLevel = level1_green;
			initialize(CurrentLevel);
		}

		this.swapAllowed = false;
	}

	if (!this.swapAllowed){
		this.swapBuffer -= deltaTime;

		if (this.swapBuffer <= 0){
			this.swapBuffer = SWAP_BUFFER;
			this.swapAllowed = true;

		}

	}

	//the player gains the key
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//player has key and is at the door
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor && this.hasKey){
		curGameState = GAMESTATE_ENDGAME
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2) - _cam_x, this.y + (this.height/2) - _cam_y);
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<commit_msg>fixed the jumping animation<commit_after>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var SWAP_BUFFER = 0.5;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;

	this.swapBuffer = SWAP_BUFFER;
	this.swapAllowed = true;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal 	= cellAtTileCoord(LAYER_PORTAL, tx, 		ty);
	var cellKey 	= cellAtTileCoord(LAYER_KEYS, 	   tx, 		ty);
	var cellDoor 	= cellAtTileCoord(LAYER_DOORS,    tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;

		if (this.falling == false && this.jumping == false)
		{
			if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
				this.sprite.setAnimation(ANIM_WALK_LEFT);
		}
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;

		if (this.falling == false && this.jumping == false)
		{
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
		}
	}

	//reset to idle animation
	else {
		if(this.jumping == false && this.falling == false)
		{
			if(this.sprite.currentAnimation != ANIM_IDLE)
			this.sprite.setAnimation(ANIM_IDLE);
		}
	}

	//set jumping animation
	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	//check for a reality swap
	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellPortal && this.swapAllowed){

		if (CurrentLevel == level1_green){
			CurrentLevel = level1_blue;
			initialize(CurrentLevel);
		}
		else if (CurrentLevel == level1_blue){
			CurrentLevel = level1_green;
			initialize(CurrentLevel);
		}

		this.swapAllowed = false;
	}

	if (!this.swapAllowed){
		this.swapBuffer -= deltaTime;

		if (this.swapBuffer <= 0){
			this.swapBuffer = SWAP_BUFFER;
			this.swapAllowed = true;

		}

	}

	//the player gains the key
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//player has key and is at the door
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor && this.hasKey){
		curGameState = GAMESTATE_ENDGAME
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2) - _cam_x, this.y + (this.height/2) - _cam_y);
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<|endoftext|>


<commit_before>/**
 * @file Sagiri thin client for Clara
 * @author Capuccino
 * @author Ovyerus
 */

const FormData = require('form-data');
const fs = require('fs');

/**
 * Query handler for SauceNAO.
 *
 * @prop {String} key API key
 * @prop {Number} numRes Amount of responses returned from the API.
 */
class SauceHandler {
    /**
     * @param {String} key API Key for SauceNAO
     * @param {Number} numRes amount of responses you want returned from the API. Default is 5 Responses.
     * @see {link} https://saucenao.com/user.php?page=search-api
     */
    constructor(key, numRes) {
        if (!key) throw new TypeError('No API key provided!');
        this.key = key,
        this.numRes = numRes || 5;
    }

    /**
     * Gets the source and outputs it in your preferred output type
     *
     * @param {String} file Either a file or URL that you want to find the source of.
     * @returns {Promise<Object>} JSON that contains the closest match.
     * @example client.getSauce(path/link).then(console.log);
     */
    getSauce(file) {
        return new Promise((resolve, reject) => {
            if (typeof file !== 'string') {
                reject(new Error('file is not a string.'));
            } else {
                let form = new FormData();

                form.append('api_key', this.key);
                form.append('output_type', 2);
                form.append('numres', this.numRes);

                if (fs.existsSync(file)) {
                    form.append('file', fs.createReadStream(file));
                } else {
                    form.append('url', file);
                }

                form.submit('https://saucenao.com/search.php', (err, res) => {
                    if (err) {
                        reject(err);
                    } else {
                        let chunked = '';

                        res.setEncoding('utf-8');
                        res.on('data', chunk => chunked += chunk);

                        res.on('end', () => {
                            let allResults = JSON.parse(chunked).results;
                            let result;

                            if (allResults.length > 1) {
                                result = allResults.sort((a, b) => Number(b.header.similarity) - Number(a.header.similarity))[0];
                            } else if (allResults.length === 1) {
                                result = allResults[0];
                            } else {
                                reject(new Error('No results.'));
                            }

                            // TODO: go through the various results and find out how to reliably construct a url
                            if (result) {
                                let returner = {
                                    similarity: Number(result.header.similarity),
                                    original: result
                                };

                                resolve(returner);
                            }
                        });
                    }
                });
            }
        });
    }
}

module.exports = SauceHandler;<commit_msg>Generate some urls automatically<commit_after>/**
 * @file Sagiri thin client for Clara
 * @author Capuccino
 * @author Ovyerus
 */

const FormData = require('form-data');
const fs = require('fs');

/**
 * Query handler for SauceNAO.
 *
 * @prop {String} key API key
 * @prop {Number} numRes Amount of responses returned from the API.
 */
class SauceHandler {
    /**
     * @param {String} key API Key for SauceNAO
     * @param {Number} numRes amount of responses you want returned from the API. Default is 5 Responses.
     * @see {link} https://saucenao.com/user.php?page=search-api
     */
    constructor(key, numRes) {
        if (!key) throw new TypeError('No API key provided!');
        this.key = key,
        this.numRes = numRes || 5;
    }

    /**
     * Gets the source and outputs it in your preferred output type
     *
     * @param {String} file Either a file or URL that you want to find the source of.
     * @returns {Promise<Object>} JSON that contains the closest match.
     * @example client.getSauce(path/link).then(console.log);
     */
    getSauce(file) {
        return new Promise((resolve, reject) => {
            if (typeof file !== 'string') {
                reject(new Error('file is not a string.'));
            } else {
                let form = new FormData();

                form.append('api_key', this.key);
                form.append('output_type', 2);
                form.append('numres', this.numRes);

                if (fs.existsSync(file)) {
                    form.append('file', fs.createReadStream(file));
                } else {
                    form.append('url', file);
                }

                form.submit('https://saucenao.com/search.php', (err, res) => {
                    if (err) {
                        reject(err);
                    } else {
                        let chunked = '';

                        res.setEncoding('utf-8');
                        res.on('data', chunk => chunked += chunk);

                        res.on('end', () => {
                            // TODO: actually check if the error is client or server.
                            if (JSON.parse(chunked).header.status !== 0) {
                                reject(new Error("An error occurred (We don't know because SauceNAO is shit)."));
                            }

                            let allResults = JSON.parse(chunked).results;
                            let result;

                            if (allResults.length > 1) {
                                result = allResults.sort((a, b) => Number(b.header.similarity) - Number(a.header.similarity))[0];
                            } else if (allResults.length === 1) {
                                result = allResults[0];
                            } else {
                                reject(new Error('No results.'));
                            }

                            // TODO: go through the various results and find out how to reliably construct a url
                            if (result) {
                                let returner = {
                                    similarity: Number(result.header.similarity),
                                    url: resolveSauceURL(result),
                                    original: result
                                };

                                resolve(returner);
                            }
                        });
                    }
                });
            }
        });
    }
}

// My god SauceNAO is shit
// I could shorten this to hell and back but it'll do for now.
function resolveSauceURL(data) {
    let url;

    switch (data.header.index_name.match(/^Index #(\d+):? /)[1]) {
        case '5':
            // Pixiv
            url = `https://www.pixiv.net/member_illust.php?mode=medium&illust_id=${data.data.pixiv_id}`;
            break;
        case '8':
            // Nico Nico Seiga
            url = `http://seiga.nicovideo.jp/seiga/im${data.data.seiga_id}`;
            break;
        case '9':
            // Danbooru
            url = `https://danbooru.donmai/us/posts/${data.data.danbooru_id}`;
            break;
        case '10':
            // drawr
            url = `http://drawr.net/show.php?id=${data.data.drawr_id}`;
            break;
        case '11':
            // Nijie
            break;
        case '12':
            // Yande.re
            url = `https://yande.re/post/show/${data.data.yandere_id}`;
            break;
        case '16':
            // FAKKU
            break;
        case '19':
            // 2D-Market
            break;
        case '20':
            // MediBang
            url = data.data.url; // WHY THE FUCK ARE YOU SO BLOODY INCONSISTENT
            break;
        case '21':
            // Anime
            url = `https://anidb.net/perl-bin/animedb.pl?show=anime&aid=${data.data.anidb_aid}`
            break;
        case '25':
            // Gelbooru
            url = `https://gelbooru.com/index.php?page=post&s=view&id=${data.data.gelbooru_id}`;
            break;
        case '26':
            // Konachan
            url = `https://konachan.com/post/show/${data.data.konachan_id}`;
            break;
        case '27':
            // Sankaku Channel
            break;
        case '28':
            // Anime-Pictures
            url = `https://anime-pictures.net/pictures/view_post/${data.data['anime-pictures_id']}`;
            break;
        case '29':
            // e621
            break;
        case '30':
            // Idol Complex
            break;
        case '31':
            // bcy.net Illust
            break;
        case '32':
            // bcy.net Cosplay
            break;
        case '33':
            // PortalGraphics
            break;
        case '35':
            // Pawoo
            break;
        default:
            throw new Error(`Unsupported site index: ${data.header.index_name.match(/^Index #(\d+):? /)[1]}`);
    }

    return url;
}

module.exports = SauceHandler;<|endoftext|>


<commit_before>let message = require('focusjs').message;
let changeBehaviourMixin = {
    /**
     * Display a message when there is a change on a store property resulting from a component action call.
     * @param  {object} changeInfos - An object containing all the event informations, without the data.
     * @return {function} - An override function can be called.
     */
    _displayMessageOnChange: function displayMessageOnChange(changeInfos) {
        if (this.displayMessageOnChange) {
            return this.displayMessageOnChange(changeInfos);
        }
        if (changeInfos && changeInfos.status && changeInfos.status.name) {
            switch (changeInfos.status.name) {
                /* case 'loading':
                 Focus.message.addInformationMessage('detail.loading');
                 break;
                 case 'loaded':
                 Focus.message.addSuccessMessage('detail.loaded');
                 break;
                 case 'saving':
                 Focus.message.addInformationMessage('detail.saving');
                 break;*/
                case 'saved':
                    //Maybe the action result or the event should have a caller notion.
                    message.addSuccessMessage('detail.saved');
                    //Change the page mode as edit
                    this.setState({isEdit: false});
                    break;
                default:
                    break;
            }
        }
    },
    /**
     * After change informations.
     * You can override this method using afterChange function.
     * @param {object} changeInfos - All informations relative to the change.
     * @returns {undefined} -  The return value is the callback.
     */
    _afterChange: function afterChangeForm(changeInfos) {
        if (this.afterChange) {
            return this.afterChange(changeInfos);
        }
        //If there is no callerId in the event, the display message does not have any sens.
        //Other component responding to the store property change does not need to react on it.
        if(changeInfos && changeInfos.informations && changeInfos.informations.callerId && this._identifier === changeInfos.informations.callerId){
            return this._displayMessageOnChange(changeInfos);
        }

    },
    /**
     * Event handler for 'change' events coming from the stores
     * @param {object} changeInfos - The changing informations.
     */
    _onChange: function onFormStoreChangeHandler(changeInfos) {
        let onChange = this.props.onChange || this.onChange;
        if (onChange) {
            onChange.call(this, changeInfos);
        }
        this.setState(this._getStateFromStores(), () => this._afterChange(changeInfos));
    },
    /**
     * Event handler for 'error' events coming from the stores.
     */
    _onError: function onFormErrorHandler() {
        let errorState = this._getErrorStateFromStores();
        for (let key in errorState) {
            if (this.refs[key]) {
                this.refs[key].setError(errorState[key]);
            }
        }
    }
};
module.exports = changeBehaviourMixin;
<commit_msg>[store-change] On error, the state is reread from the stores, fix #303.<commit_after>let message = require('focusjs').message;
let changeBehaviourMixin = {
    /**
     * Display a message when there is a change on a store property resulting from a component action call.
     * @param  {object} changeInfos - An object containing all the event informations, without the data.
     * @return {function} - An override function can be called.
     */
    _displayMessageOnChange: function displayMessageOnChange(changeInfos) {
        if (this.displayMessageOnChange) {
            return this.displayMessageOnChange(changeInfos);
        }
        if (changeInfos && changeInfos.status && changeInfos.status.name) {
            switch (changeInfos.status.name) {
                /* case 'loading':
                 Focus.message.addInformationMessage('detail.loading');
                 break;
                 case 'loaded':
                 Focus.message.addSuccessMessage('detail.loaded');
                 break;
                 case 'saving':
                 Focus.message.addInformationMessage('detail.saving');
                 break;*/
                case 'saved':
                    //Maybe the action result or the event should have a caller notion.
                    message.addSuccessMessage('detail.saved');
                    //Change the page mode as edit
                    this.setState({isEdit: false});
                    break;
                default:
                    break;
            }
        }
    },
    /**
     * After change informations.
     * You can override this method using afterChange function.
     * @param {object} changeInfos - All informations relative to the change.
     * @returns {undefined} -  The return value is the callback.
     */
    _afterChange: function afterChangeForm(changeInfos) {
        if (this.afterChange) {
            return this.afterChange(changeInfos);
        }
        //If there is no callerId in the event, the display message does not have any sens.
        //Other component responding to the store property change does not need to react on it.
        if(changeInfos && changeInfos.informations && changeInfos.informations.callerId && this._identifier === changeInfos.informations.callerId){
            return this._displayMessageOnChange(changeInfos);
        }

    },
    /**
     * Event handler for 'change' events coming from the stores
     * @param {object} changeInfos - The changing informations.
     */
    _onChange: function onFormStoreChangeHandler(changeInfos) {
        let onChange = this.props.onChange || this.onChange;
        if (onChange) {
            onChange.call(this, changeInfos);
        }
        this.setState(this._getStateFromStores(), () => this._afterChange(changeInfos));
    },
    /**
     * Event handler for 'error' events coming from the stores.
     */
    _onError: function onFormErrorHandler(changeInfos) {
        const errorState = this._getErrorStateFromStores();
        for (let key in errorState) {
            if (this.refs[key]) {
                this.refs[key].setError(errorState[key]);
            }
        }
        this.setState(this._getStateFromStores());
    }
};
module.exports = changeBehaviourMixin;
<|endoftext|>


<commit_before>'use strict';

// Make our own plugin main interface an event emitter.
// This can be used to communicate and subscribe to others plugins events.
import { EventEmitter } from 'events';

/**
 * Plugin Interface
 * @class Plugin
 */
export default class extends EventEmitter {

  /**
   * Construct the plugin.
   */
  constructor() {
    super();

    // Will be injected by core
    this.app = null;

    this.plugins = null;
    this.server = null;
    this.players = null;
    this.maps = null;

    /**
     * Will hold the defined models for this plugin!
     *
     * @type {{}}
     */
    this.models = {};
  }

  /**
   * Inject Core App interface into the plugin.
   *
   * @param {App} app
   */
  inject(app) {
    this.app = app;

    this.server = app.server;

    // Expand app into separate parts.
    this.players = app.players;
    this.maps = app.maps;
  }
}
<commit_msg>Inject plugin config from core.<commit_after>'use strict';

// Make our own plugin main interface an event emitter.
// This can be used to communicate and subscribe to others plugins events.
import { EventEmitter } from 'events';

/**
 * Plugin Interface
 * @class Plugin
 */
export default class extends EventEmitter {

  /**
   * Construct the plugin.
   */
  constructor() {
    super();

    // Will be injected by core
    this.app = null;

    this.plugins = null;
    this.server = null;
    this.players = null;
    this.maps = null;

    /**
     * Will hold the defined models for this plugin!
     *
     * @type {{}}
     */
    this.models = {};
  }

  /**
   * Inject Core App interface into the plugin.
   *
   * @param {App} app App context.
   * @param {object} config Plugin config.
   */
  inject(app, config) {
    this.app = app;
    this.config = config;

    this.server = app.server;

    // Expand app into separate parts.
    this.players = app.players;
    this.maps = app.maps;
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, dispatch } from 'redux';
import { Link } from 'react-router';
import { actionFetchSources } from '../../actions/MaintainSourcesAction';
import { actionLoadData, actionLoadDataFile } from '../../actions/LoadDataAction';
import {
    actionLeftMenuClick,
} from '../../actions/LeftMenuAction';
import { Grid, Row, Col, Alert } from 'react-bootstrap';
import SourceCatalogList from './SourceCatalog';
import DisplayLoadData from './DisplayLoadData';

class LoadData extends Component {
    constructor(props) {
        super(props);
        console.log('Props: ', props);

        this.state = {
            selectedItem: null,
            applyRules: false,
            loadInfo: {},
            displayAlertMsg: false,
            alertMsg: "Data File is being transferred. This might take a while. Though you can continue working.",
            alertStyle: "warning"
        };

        this.handleSourceClick = this.handleSourceClick.bind(this);
        this.handleLoadFile = this.handleLoadFile.bind(this);

        //this.viewOnly = _.find(this.props.privileges, { permission: "Load Data" }) ? true : false;
        this.writeOnly = _.find(this.props.privileges, { permission: "Load Data" }) ? true : false;
    }

    componentWillMount() {
        this.props.fetchSources();
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.leftmenu) {
            this.setState({
                selectedItem: null,
                displayAlertMsg: false,
            });
        } else {
            let { alertMsg, alertStyle } = this.state;
            console.log('At the begining of Next Props:', nextProps, nextProps.loadDataProps);
            if (nextProps.loadDataProps.error || nextProps.loadDataProps.message) {
                alertMsg = nextProps.loadDataProps.message;
                alertMsg += nextProps.loadDataProps.error ? " " + nextProps.loadDataProps.error.data.msg : "";
                alertStyle = "danger";
                console.log('Error Loading The Data', this.state);
            }
            if (nextProps.loadDataProps.loadDataFileMsg) {
                if (nextProps.loadDataProps.loadDataFileMsg.msg === 'File Transferred Successfully') {
                    alertMsg = "File Transferred Successfully. Now Loading Data. This might take a while. Though you can continue working.";
                    alertStyle = "info";
                    this.props.loadData({
                        source_id: this.state.loadInfo.source_id,
                        business_date: this.state.loadInfo.business_date,
                        data_file: nextProps.loadDataProps.loadDataFileMsg.filename,
                        file: this.state.loadInfo.file.name
                    });
                    console.log('Now Loading The Data');
                }
                else if (nextProps.loadDataProps.loadDataFileMsg.msg === 'Data Loaded Successfully') {
                    alertMsg = "Data Loaded Successfully.";
                    alertStyle = "success";
                    console.log('Now waiting for Data Load to complete');
                }
            }
            this.setState({ alertMsg: alertMsg, alertStyle: alertStyle }, () => { console.log('End of setState...', this.state); });
            console.log('Next Props:', nextProps, nextProps.loadDataProps);
        }
    }

    componentDidUpdate() {
        console.log("componentDidUpdate LoadData");
        this.props.leftMenuClick(false);
    }

    handleSourceClick(item) {
        console.log('Handle Source Click Item: ', item);
        this.setState({
            selectedItem: item,
            alertMsg: "Data File is being transferred. This might take a while. Though you can continue working.",
            alertStyle: "warning"
        });
    }

    handleLoadFile(option) {
        console.log('Run handleLoadFile', option);
        // data_file: option.selectedFile.name,
        let loadInfo = {
            source_id: option.item.source_id,
            business_date: option.businessDate.format('YYYYMMDD'),
            file: option.selectedFile
        }
        let applyRules = option.applyRules;

        this.setState({ applyRules: applyRules, loadInfo: loadInfo, displayAlertMsg: true });
        window.document.body.scrollTop = 0;
        this.props.loadDataFile(option.selectedFile);
    }

    render() {
        if (typeof this.props.sourceCatalog !== 'undefined') {
            return (

Load Data  Load Data for Available Sources

                                                    {' Sources '}

                                                        <Link to="/dashboard/load-data"
                                                            onClick={() => { this.setState({ selectedItem: null, displayAlertMsg: false, }) }}
                                                        >
                                                             All Sources List
                                                        </Link>

                                                        <SourceCatalogList
                                                            sourceCatalog={this.props.sourceCatalog.country}
                                                            navMenu={true}
                                                            handleSourceClick={this.handleSourceClick}
                                                        />

                                {
                                    this.state.displayAlertMsg &&
                                    <Alert bsStyle={this.state.alertStyle}>
                                        {this.state.alertMsg}
                                    </Alert>
                                }

                                {
                                    this.state.selectedItem ?
                                        <DisplayLoadData
                                            selectedItem={this.state.selectedItem}
                                            handleLoadFile={this.handleLoadFile}
                                        /> :

Please Select a Source to Load Data

                                }
                                {
                                    !this.state.selectedItem &&
                                    <SourceCatalogList
                                        sourceCatalog={this.props.sourceCatalog.country}
                                        navMenu={false}
                                        handleSourceClick={this.handleSourceClick}
                                    />
                                }

            )
        } else {
            return (

 Loading.....

            );
        }
    }
}

function mapStateToProps(state) {
    console.log('State: ', state);
    return {
        sourceCatalog: state.source_feeds.sources,
        loadDataProps: state.loadData,
        login_details: state.login_store,
        leftmenu: state.leftmenu_store.leftmenuclick,
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        fetchSources: (sources, country) => {
            dispatch(actionFetchSources(sources, country));
        },
        loadData: (loadInfo) => {
            dispatch(actionLoadData(loadInfo));
        },
        loadDataFile: (file) => {
            dispatch(actionLoadDataFile(file));
        },
        leftMenuClick: (isLeftMenu) => {
            dispatch(actionLeftMenuClick(isLeftMenu));
        },
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoadData);
<commit_msg>Fix for data file loading status check<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, dispatch } from 'redux';
import { Link } from 'react-router';
import { actionFetchSources } from '../../actions/MaintainSourcesAction';
import { actionLoadData, actionLoadDataFile } from '../../actions/LoadDataAction';
import {
    actionLeftMenuClick,
} from '../../actions/LeftMenuAction';
import { Grid, Row, Col, Alert } from 'react-bootstrap';
import SourceCatalogList from './SourceCatalog';
import DisplayLoadData from './DisplayLoadData';

class LoadData extends Component {
    constructor(props) {
        super(props);
        console.log('Props: ', props);

        this.state = {
            selectedItem: null,
            applyRules: false,
            loadInfo: {},
            displayAlertMsg: false,
            alertMsg: "Data File is being transferred. This might take a while. Though you can continue working.",
            alertStyle: "warning"
        };

        this.handleSourceClick = this.handleSourceClick.bind(this);
        this.handleLoadFile = this.handleLoadFile.bind(this);

        //this.viewOnly = _.find(this.props.privileges, { permission: "Load Data" }) ? true : false;
        this.writeOnly = _.find(this.props.privileges, { permission: "Load Data" }) ? true : false;
    }

    componentWillMount() {
        this.props.fetchSources();
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.leftmenu) {
            this.setState({
                selectedItem: null,
                displayAlertMsg: false,
            });
        } else {
            let { alertMsg, alertStyle } = this.state;
            console.log('At the begining of Next Props:', nextProps, nextProps.loadDataProps);
            if (nextProps.loadDataProps.error || nextProps.loadDataProps.message) {
                alertMsg = nextProps.loadDataProps.message;
                alertMsg += nextProps.loadDataProps.error ? " " + nextProps.loadDataProps.error.data.msg : "";
                alertStyle = "danger";
                console.log('Error Loading The Data', this.state);
            }
            if (nextProps.loadDataProps.loadDataFileMsg) {
                if (nextProps.loadDataProps.loadDataFileMsg.status === 'SUCCESS') {
                    alertMsg = "File Transferred Successfully. Now Loading Data. This might take a while. Though you can continue working.";
                    alertStyle = "info";
                    this.props.loadData({
                        source_id: this.state.loadInfo.source_id,
                        business_date: this.state.loadInfo.business_date,
                        data_file: nextProps.loadDataProps.loadDataFileMsg.filename,
                        file: this.state.loadInfo.file.name
                    });
                    console.log('Now Loading The Data');
                }
                else if (nextProps.loadDataProps.loadDataFileMsg.msg === 'Data Loaded Successfully') {
                    alertMsg = "Data Loaded Successfully.";
                    alertStyle = "success";
                    console.log('Now waiting for Data Load to complete');
                }
            }
            this.setState({ alertMsg: alertMsg, alertStyle: alertStyle }, () => { console.log('End of setState...', this.state); });
            console.log('Next Props:', nextProps, nextProps.loadDataProps);
        }
    }

    componentDidUpdate() {
        console.log("componentDidUpdate LoadData");
        this.props.leftMenuClick(false);
    }

    handleSourceClick(item) {
        console.log('Handle Source Click Item: ', item);
        this.setState({
            selectedItem: item,
            alertMsg: "Data File is being transferred. This might take a while. Though you can continue working.",
            alertStyle: "warning"
        });
    }

    handleLoadFile(option) {
        console.log('Run handleLoadFile', option);
        // data_file: option.selectedFile.name,
        let loadInfo = {
            source_id: option.item.source_id,
            business_date: option.businessDate.format('YYYYMMDD'),
            file: option.selectedFile
        }
        let applyRules = option.applyRules;

        this.setState({ applyRules: applyRules, loadInfo: loadInfo, displayAlertMsg: true });
        window.document.body.scrollTop = 0;
        this.props.loadDataFile(option.selectedFile);
    }

    render() {
        if (typeof this.props.sourceCatalog !== 'undefined') {
            return (

Load Data  Load Data for Available Sources

                                                    {' Sources '}

                                                        <Link to="/dashboard/load-data"
                                                            onClick={() => { this.setState({ selectedItem: null, displayAlertMsg: false, }) }}
                                                        >
                                                             All Sources List
                                                        </Link>

                                                        <SourceCatalogList
                                                            sourceCatalog={this.props.sourceCatalog.country}
                                                            navMenu={true}
                                                            handleSourceClick={this.handleSourceClick}
                                                        />

                                {
                                    this.state.displayAlertMsg &&
                                    <Alert bsStyle={this.state.alertStyle}>
                                        {this.state.alertMsg}
                                    </Alert>
                                }

                                {
                                    this.state.selectedItem ?
                                        <DisplayLoadData
                                            selectedItem={this.state.selectedItem}
                                            handleLoadFile={this.handleLoadFile}
                                        /> :

Please Select a Source to Load Data

                                }
                                {
                                    !this.state.selectedItem &&
                                    <SourceCatalogList
                                        sourceCatalog={this.props.sourceCatalog.country}
                                        navMenu={false}
                                        handleSourceClick={this.handleSourceClick}
                                    />
                                }

            )
        } else {
            return (

 Loading.....

            );
        }
    }
}

function mapStateToProps(state) {
    console.log('State: ', state);
    return {
        sourceCatalog: state.source_feeds.sources,
        loadDataProps: state.loadData,
        login_details: state.login_store,
        leftmenu: state.leftmenu_store.leftmenuclick,
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        fetchSources: (sources, country) => {
            dispatch(actionFetchSources(sources, country));
        },
        loadData: (loadInfo) => {
            dispatch(actionLoadData(loadInfo));
        },
        loadDataFile: (file) => {
            dispatch(actionLoadDataFile(file));
        },
        leftMenuClick: (isLeftMenu) => {
            dispatch(actionLeftMenuClick(isLeftMenu));
        },
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoadData);
<|endoftext|>


<commit_before>/** @jsx React.DOM */

jest.dontMock('../code/views/flagView.jsx');
jest.dontMock('../../../utils/getComponentClasses');

var React = require('react/addons');
var FlagComponent = require('../code/views/flagView.jsx');
var TestUtils = React.addons.TestUtils;

describe('FlagComponent', function() {

  it('should render a Flag', function() {
    var flag = TestUtils.renderIntoDocument(
      <FlagComponent>Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(flag, 'component-flag');
    expect(renderedFlag.getDOMNode().textContent).toEqual('Special Offer');

  });

  it('should render a default flag', function() {
    var defaultFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="default">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(defaultFlag, 'default');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a danger flag', function() {
    var dangerFlag = TestUtils.renderIntoDocument(
      <FlagComponent purpose="danger">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(dangerFlag, 'danger');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a large flag', function() {
    var largeFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="large">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(largeFlag, 'large');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a flag on the right', function() {
    var rightFlag = TestUtils.renderIntoDocument(
      <FlagComponent position="right">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(rightFlag, 'right');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a small secondary right flag', function() {
    var smallSecondaryRightFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="small" purpose="secondary" position="right">Book Now</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(smallSecondaryRightFlag, 'small secondary right');
    expect(renderedFlag).toBeDefined();

  });
});
<commit_msg>adding medium test for flag<commit_after>/** @jsx React.DOM */

jest.dontMock('../code/views/flagView.jsx');
jest.dontMock('../../../utils/getComponentClasses');

var React = require('react/addons');
var FlagComponent = require('../code/views/flagView.jsx');
var TestUtils = React.addons.TestUtils;

describe('FlagComponent', function() {

  it('should render a Flag', function() {
    var flag = TestUtils.renderIntoDocument(
      <FlagComponent>Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(flag, 'component-flag');
    expect(renderedFlag.getDOMNode().textContent).toEqual('Special Offer');

  });

  it('should render a default flag', function() {
    var defaultFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="default">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(defaultFlag, 'default');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a danger flag', function() {
    var dangerFlag = TestUtils.renderIntoDocument(
      <FlagComponent purpose="danger">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(dangerFlag, 'danger');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a medium flag', function() {
    var mediumFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="medium">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(mediumFlag, 'medium');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a large flag', function() {
    var largeFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="large">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(largeFlag, 'large');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a flag on the right', function() {
    var rightFlag = TestUtils.renderIntoDocument(
      <FlagComponent position="right">Special Offer</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(rightFlag, 'right');
    expect(renderedFlag).toBeDefined();

  });

  it('should render a small secondary right flag', function() {
    var smallSecondaryRightFlag = TestUtils.renderIntoDocument(
      <FlagComponent size="small" purpose="secondary" position="right">Book Now</FlagComponent>
    );

    var renderedFlag = TestUtils.findRenderedDOMComponentWithClass(smallSecondaryRightFlag, 'small secondary right');
    expect(renderedFlag).toBeDefined();

  });
});
<|endoftext|>


<commit_before>var fs   = Npm.require('fs');
var less = Npm.require('less');

var LESS_INDEX_FILE_PATH = "client/stylesheets/app.index.less";

var generatedMessage = [
  "// This file is auto generated by the ordered-less package",
  "// New .less files will be automatically '@import'ed  at the bottom",
  "// Existing .less imports will not be touch",
  "// When deleting a .less file you must manually delete it from here",
  "",
  ""
]

generatedMessage = generatedMessage.join("\n");

// Put any files through the Less compiler that end in lessindex
Plugin.registerSourceHandler("index.less", {archMatching: 'web'}, function (compileStep) {
  var source = compileStep.read().toString('utf8');

  var options = {
    syncImport: true,
    // @imports only work relative to the project root
    paths: []
  }

  less.render(source, options, function(error, output) {
    if (error) {
      compileStep.error({
        message: "Less compiler error: " + error.message,
        sourcePath: error.filename || compileStep.inputPath,
        line: error.line,
        column: error.column + 1
      });
    } else {
      compileStep.addStylesheet({
        path: compileStep.inputPath + ".css",
        data: output.css,
        sourceMap: output.map
      });
    }
  });

});

// Trigger when new Less files are created
Plugin.registerSourceHandler("less", {archMatching: 'web'}, function (compileStep) {
  if ( fs.existsSync(LESS_INDEX_FILE_PATH) ) {
    var lessIndex = fs.readFileSync(LESS_INDEX_FILE_PATH, 'utf8');
    if (lessIndex.indexOf(compileStep.inputPath) == -1) {
      fs.appendFileSync(LESS_INDEX_FILE_PATH, '\n@import "' + compileStep.inputPath + '";', 'utf8')
    }
  } else {
    var newFile = generatedMessage + '@import "' + compileStep.inputPath + '";\n';
    fs.writeFileSync(LESS_INDEX_FILE_PATH, newFile, 'utf8')
  }
});<commit_msg>Don't think column needs an increment on error<commit_after>var fs   = Npm.require('fs');
var less = Npm.require('less');

var LESS_INDEX_FILE_PATH = "client/stylesheets/app.index.less";

var generatedMessage = [
  "// This file is auto generated by the ordered-less package",
  "// New .less files will be automatically '@import'ed  at the bottom",
  "// Existing .less imports will not be touch",
  "// When deleting a .less file you must manually delete it from here",
  "",
  ""
]

generatedMessage = generatedMessage.join("\n");

// Put any files through the Less compiler that end in lessindex
Plugin.registerSourceHandler("index.less", {archMatching: 'web'}, function (compileStep) {
  var source = compileStep.read().toString('utf8');

  var options = {
    syncImport: true,
    // @imports only work relative to the project root
    paths: []
  }

  less.render(source, options, function(error, output) {
    if (error) {
      compileStep.error({
        message: "Less compiler error: " + error.message,
        sourcePath: error.filename || compileStep.inputPath,
        line: error.line,
        column: error.column
      });
    } else {
      compileStep.addStylesheet({
        path: compileStep.inputPath + ".css",
        data: output.css,
        sourceMap: output.map
      });
    }
  });

});

// Trigger when new Less files are created
Plugin.registerSourceHandler("less", {archMatching: 'web'}, function (compileStep) {
  if ( fs.existsSync(LESS_INDEX_FILE_PATH) ) {
    var lessIndex = fs.readFileSync(LESS_INDEX_FILE_PATH, 'utf8');
    if (lessIndex.indexOf(compileStep.inputPath) == -1) {
      fs.appendFileSync(LESS_INDEX_FILE_PATH, '\n@import "' + compileStep.inputPath + '";', 'utf8')
    }
  } else {
    var newFile = generatedMessage + '@import "' + compileStep.inputPath + '";\n';
    fs.writeFileSync(LESS_INDEX_FILE_PATH, newFile, 'utf8')
  }
});<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    fs = require('fs'),
    inherits = require('util').inherits;

module.exports = MemSource;

inherits(MemSource, EventEmitter);

function MemSource(docs, info, callback) {
    if (typeof info === 'function') {
        callback = info;
        info = docs;
        docs = null;
    }

    this._shards = {};
    this._grids = {};
    this._info = info || { maxzoom: 6 };
    this._info.geocoder_version = this._info.geocoder_version !== undefined ? this._info.geocoder_version : 1;
    this.open = true;
    this.docs = docs;
    return callback(null, this);
}

// Implements carmen#getGeocoderData method.
MemSource.prototype.getGeocoderData = function(type, shard, callback) {
    return callback(null, this._shards[type] && this._shards[type][shard]);
};

// Implements carmen#putGeocoderData method.
MemSource.prototype.putGeocoderData = function(type, shard, data, callback) {
    if (this._shards[type] === undefined) this._shards[type] = {};
    this._shards[type][shard] = data;
    return callback(null);
};

// Implements carmen#getIndexableDocs method.
MemSource.prototype.getIndexableDocs = function(pointer, callback) {
    pointer = pointer || {};
    if (pointer.done) return callback(null, [], pointer);
    return callback(null, this.docs, {done:true});
};

// Adds carmen schema to startWriting.
MemSource.prototype.startWriting = function(callback) {
    return callback(null);
};

// Shards are stored as binary buffers, so we need to convert them to base64
// strings in order for them to be safe for JSON.stringify
MemSource.prototype.serialize = function(name, callback) {
    function shardify(shards) {
        var o = {};
        for (var i in shards) {
            o[i] = strings(shards[i]);
        }
        return o;
    }

    function strings(shards) {
        var o = {};
        for (var i in shards) {
            o[i] = shards[i].toString('base64');
        }
        return o;
    }

    return {
        shards: shardify(this._shards),
        geocoder: this._geocoder
    };
};

MemSource.prototype.stopWriting = function(callback) {
    return callback(null);
};

MemSource.prototype.getInfo = function(callback) {
    callback(null, this._info);
};

MemSource.prototype.getTile = function(z,x,y,callback) {
    var key = z + '/' + x + '/' + y;
    if (this._grids[key]) return callback(null, this._grids[key]);
    return callback(new Error('Tile does not exist'));
};

MemSource.prototype.putTile= function(z,x,y,grid,callback) {
    var key = z + '/' + x + '/' + y;
    this._grids[key] = grid;
    return callback && callback();
};
<commit_msg>Bump api-mem default to version 2.<commit_after>var EventEmitter = require('events').EventEmitter,
    fs = require('fs'),
    inherits = require('util').inherits;

module.exports = MemSource;

inherits(MemSource, EventEmitter);

function MemSource(docs, info, callback) {
    if (typeof info === 'function') {
        callback = info;
        info = docs;
        docs = null;
    }

    this._shards = {};
    this._grids = {};
    this._info = info || { maxzoom: 6 };
    this._info.geocoder_version = this._info.geocoder_version !== undefined ? this._info.geocoder_version : 2;
    this.open = true;
    this.docs = docs;
    return callback(null, this);
}

// Implements carmen#getGeocoderData method.
MemSource.prototype.getGeocoderData = function(type, shard, callback) {
    return callback(null, this._shards[type] && this._shards[type][shard]);
};

// Implements carmen#putGeocoderData method.
MemSource.prototype.putGeocoderData = function(type, shard, data, callback) {
    if (this._shards[type] === undefined) this._shards[type] = {};
    this._shards[type][shard] = data;
    return callback(null);
};

// Implements carmen#getIndexableDocs method.
MemSource.prototype.getIndexableDocs = function(pointer, callback) {
    pointer = pointer || {};
    if (pointer.done) return callback(null, [], pointer);
    return callback(null, this.docs, {done:true});
};

// Adds carmen schema to startWriting.
MemSource.prototype.startWriting = function(callback) {
    return callback(null);
};

// Shards are stored as binary buffers, so we need to convert them to base64
// strings in order for them to be safe for JSON.stringify
MemSource.prototype.serialize = function(name, callback) {
    function shardify(shards) {
        var o = {};
        for (var i in shards) {
            o[i] = strings(shards[i]);
        }
        return o;
    }

    function strings(shards) {
        var o = {};
        for (var i in shards) {
            o[i] = shards[i].toString('base64');
        }
        return o;
    }

    return {
        shards: shardify(this._shards),
        geocoder: this._geocoder
    };
};

MemSource.prototype.stopWriting = function(callback) {
    return callback(null);
};

MemSource.prototype.getInfo = function(callback) {
    callback(null, this._info);
};

MemSource.prototype.getTile = function(z,x,y,callback) {
    var key = z + '/' + x + '/' + y;
    if (this._grids[key]) return callback(null, this._grids[key]);
    return callback(new Error('Tile does not exist'));
};

MemSource.prototype.putTile= function(z,x,y,grid,callback) {
    var key = z + '/' + x + '/' + y;
    this._grids[key] = grid;
    return callback && callback();
};
<|endoftext|>


<commit_before>module.exports = {
  onPostBuild({ utils: { status: { show } } }) {
    show({ summary: 'Test' })
  }
}
<commit_msg>Debug<commit_after>module.exports = {
  onSuccess({ utils: { status: { show } } }) {
    throw new Error('Arg')
    show({ summary: 'Test' })
  }
}
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import ReactDOM from 'react-dom'
import Icon from 'react-fa'

import SpaceCards from 'gComponents/spaces/cards'
import SpaceList from 'gComponents/spaces/list'
import Container from 'gComponents/utility/container/Container'
import {MembersTab} from './members'

import {httpRequestSelector} from './httpRequestSelector'
import {organizationSpaceSelector} from './organizationSpaceSelector'
import {organizationMemberSelector} from './organizationMemberSelector'

import * as modalActions from 'gModules/modal/actions'
import * as spaceActions from 'gModules/spaces/actions'
import * as organizationActions from 'gModules/organizations/actions'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'

import e from 'gEngine/engine'

import './style.css'

function mapStateToProps(state) {
  return {
    me: state.me,
    organizations: state.organizations,
  }
}

@connect(mapStateToProps)
@connect(organizationSpaceSelector)
@connect(organizationMemberSelector)
@connect(httpRequestSelector)
export default class OrganizationShow extends Component{
  displayName: 'OrganizationShow'

  state = {
    attemptedFetch: false,
    openTab: 'MODELS',
  }

  componentWillMount() {
    this.fetchData()
  }

  componentDidUpdate() {
    this.fetchData()
  }

  fetchData() {
    if (!this.state.attemptedFetch) {
      this.props.dispatch(organizationActions.fetchById(this.props.organizationId))
      this.props.dispatch(spaceActions.fetch({organizationId: this.props.organizationId}))
      this.setState({attemptedFetch: true})
    }
  }

  changeTab(tab) {
    this.setState({
      openTab: tab,
    })
  }

  destroyMembership(membershipId) {
    this.props.dispatch(userOrganizationMembershipActions.destroy(membershipId))
  }

  addUser(email) {
    this.props.dispatch(userOrganizationMembershipActions.createWithEmail(this.props.organizationId, email))
  }

  onRemove(member) {
    this.confirmRemove(member)
  }

  confirmRemove({email, name, membershipId}) {
    const removeCallback = () => {
      this.destroyMembership(membershipId)
      this.props.dispatch(modalActions.close())
    }

    const message = `Are you sure you want to remove ${name} from this organization?`

    this.props.dispatch(modalActions.openConfirmation({onConfirm: removeCallback, message}))
  }

  render () {
    const {organizationId, organizations, members, memberships, invitations} = this.props
    const {openTab} = this.state
    const spaces =  _.orderBy(this.props.organizationSpaces.asMutable(), ['updated_at'], ['desc'])
    const organization = organizations.find(u => u.id.toString() === organizationId.toString())
    const meIsAdmin = !!organization && (organization.admin_id === this.props.me.id)
    const meIsMember = meIsAdmin || !!(members.find(m => m.id === this.props.me.id))

    return (
      <Container>

          <OrganizationHeader organization={organization}/>

          {meIsMember &&
            <OrganizationTabButtons
              tabs={[{name: 'Models', key: 'MODELS'}, {name: 'Members', key: 'MEMBERS'}]}
              openTab={openTab}
              changeTab={this.changeTab.bind(this)}
            />
          }

            {(openTab === 'MODELS' || !meIsMember) && spaces &&
              <SpaceCards
                spaces={spaces}
                showPrivacy={true}
              />
            }

            {(openTab === 'MEMBERS') && meIsMember && members && organization &&
              <MembersTab
                members={members}
                memberships={memberships}
                invitations={invitations}
                admin_id={organization.admin_id}
                onRemove={this.onRemove.bind(this)}
                addUser={this.addUser.bind(this)}
                httpRequests={this.props.httpRequests}
                meIsAdmin={meIsAdmin}
              />
            }

      </Container>
    )
  }
}

const OrganizationHeader = ({organization}) => (

 {organization.name}

)

const OrganizationTabButtons = ({tabs, openTab, changeTab}) => (

        { tabs.map( e => {
          const className = `item ${(openTab === e.key) ? 'active' : ''}`
          return (
             {changeTab(e.key)}}> {e.name}
          )
         })}

)
<commit_msg>The show page should still start on the index tab.<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import ReactDOM from 'react-dom'
import Icon from 'react-fa'

import SpaceCards from 'gComponents/spaces/cards'
import SpaceList from 'gComponents/spaces/list'
import Container from 'gComponents/utility/container/Container'
import {MembersTab} from './members'

import {httpRequestSelector} from './httpRequestSelector'
import {organizationSpaceSelector} from './organizationSpaceSelector'
import {organizationMemberSelector} from './organizationMemberSelector'

import * as modalActions from 'gModules/modal/actions'
import * as spaceActions from 'gModules/spaces/actions'
import * as organizationActions from 'gModules/organizations/actions'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'

import e from 'gEngine/engine'

import './style.css'

function mapStateToProps(state) {
  return {
    me: state.me,
    organizations: state.organizations,
  }
}

@connect(mapStateToProps)
@connect(organizationSpaceSelector)
@connect(organizationMemberSelector)
@connect(httpRequestSelector)
export default class OrganizationShow extends Component{
  displayName: 'OrganizationShow'

  state = {
    attemptedFetch: false,
    openTab: 'MODELS',
  }

  componentWillMount() {
    this.fetchData()
  }

  componentDidUpdate() {
    this.fetchData()
  }

  fetchData() {
    if (!this.state.attemptedFetch) {
      this.props.dispatch(organizationActions.fetchById(this.props.organizationId))
      this.props.dispatch(spaceActions.fetch({organizationId: this.props.organizationId}))
      this.setState({attemptedFetch: true})
    }
  }

  changeTab(tab) {
    this.setState({
      openTab: tab,
    })
  }

  destroyMembership(membershipId) {
    this.props.dispatch(userOrganizationMembershipActions.destroy(membershipId))
  }

  addUser(email) {
    this.props.dispatch(userOrganizationMembershipActions.createWithEmail(this.props.organizationId, email))
  }

  onRemove(member) {
    this.confirmRemove(member)
  }

  confirmRemove({email, name, membershipId}) {
    const removeCallback = () => {
      this.destroyMembership(membershipId)
      this.props.dispatch(modalActions.close())
    }

    const message = `Are you sure you want to remove ${name} from this organization?`

    this.props.dispatch(modalActions.openConfirmation({onConfirm: removeCallback, message}))
  }

  render () {
    const {organizationId, organizations, members, memberships, invitations} = this.props
    const {openTab} = this.state
    const spaces =  _.orderBy(this.props.organizationSpaces.asMutable(), ['updated_at'], ['desc'])
    const organization = organizations.find(u => u.id.toString() === organizationId.toString())
    const meIsAdmin = !!organization && (organization.admin_id === this.props.me.id)
    const meIsMember = meIsAdmin || !!(members.find(m => m.id === this.props.me.id))

    return (
      <Container>

          <OrganizationHeader organization={organization}/>

          {meIsMember &&
            <OrganizationTabButtons
              tabs={[{name: 'Models', key: 'MODELS'}, {name: 'Members', key: 'MEMBERS'}]}
              openTab={openTab}
              changeTab={this.changeTab.bind(this)}
            />
          }

            {(openTab === 'MODELS' || !meIsMember) && spaces &&
              <SpaceCards
                spaces={spaces}
                showPrivacy={true}
              />
            }

            {(openTab === 'MEMBERS') && meIsMember && members && organization &&
              <MembersTab
                startOnIndexTab={true}
                members={members}
                memberships={memberships}
                invitations={invitations}
                admin_id={organization.admin_id}
                onRemove={this.onRemove.bind(this)}
                addUser={this.addUser.bind(this)}
                httpRequests={this.props.httpRequests}
                meIsAdmin={meIsAdmin}
              />
            }

      </Container>
    )
  }
}

const OrganizationHeader = ({organization}) => (

 {organization.name}

)

const OrganizationTabButtons = ({tabs, openTab, changeTab}) => (

        { tabs.map( e => {
          const className = `item ${(openTab === e.key) ? 'active' : ''}`
          return (
             {changeTab(e.key)}}> {e.name}
          )
         })}

)
<|endoftext|>