<commit_before>exports.BattleScripts = {
    init: function() {
        for (var i in this.data.FormatsData)
            this.data.FormatsData[i].dreamWorldRelease = true;
    	}
    	this.data.Pokedex.azumarill.types = ["Water","Fairy"];
    	this.data.Learnsets.azumarill.learnset.lunardance = ['5L0'];
    	this.data.Learnsets.azumarill.learnset.mysticcrash = ['5L0'];

    	this.data.Pokedex.gardevoir.types = ["Psychic","Fairy"];
    	this.data.Learnsets.gardevoir.learnset.fairywind = ['5L0'];
        this.data.Learnsets.gardevoir.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gardevoir.learnset.drainingkiss = ['5L0'];

        this.data.Pokedex.clefable.types = ["Normal","Fairy"];
        this.data.Learnsets.clefable.learnset.fairywind = ['5L0'];
        this.data.Learnsets.clefable.learnset.lunardance = ['5L0'];
        this.data.Learnsets.clefable.learnset.topsyturvey = ['5L0'];

        this.data.Pokedex.gallade.types = ["Fighting","Fairy"];
        this.data.Learnsets.gallade.learnset.fairywind = ['5L0'];
        this.data.Learnsets.gallade.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gallade.learnset.drainingkiss = ['5L0'];
        this.data.Learnsets.gallade.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gallade.learnset.mysticcrash = ['5L0'];
    }
};
<commit_msg>Update scripts.js<commit_after>exports.BattleScripts = {
    init: function() {
        for (var i in this.data.FormatsData)
            this.data.FormatsData[i].dreamWorldRelease = true;
    	}
    	this.data.Pokedex.azumarill.types = ["Water","Fairy"];
    	this.data.Learnsets.azumarill.learnset.lunardance = ['5L0'];
    	this.data.Learnsets.azumarill.learnset.mysticcrash = ['5L0'];

    	this.data.Pokedex.gardevoir.types = ["Psychic","Fairy"];
    	this.data.Learnsets.gardevoir.learnset.fairywind = ['5L0'];
        this.data.Learnsets.gardevoir.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gardevoir.learnset.drainingkiss = ['5L0'];

        this.data.Pokedex.clefable.types = ["Normal","Fairy"];
        this.data.Learnsets.clefable.learnset.fairywind = ['5L0'];
        this.data.Learnsets.clefable.learnset.lunardance = ['5L0'];
        this.data.Learnsets.clefable.learnset.topsyturvey = ['5L0'];

        this.data.Pokedex.gallade.types = ["Fighting","Fairy"];
        this.data.Learnsets.gallade.learnset.fairywind = ['5L0'];
        this.data.Learnsets.gallade.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gallade.learnset.drainingkiss = ['5L0'];
        this.data.Learnsets.gallade.learnset.lunardance = ['5L0'];
        this.data.Learnsets.gallade.learnset.mysticcrash = ['5L0'];
	}
};
<|endoftext|>


<commit_before>ScreenTracker = {
  websocket: null,
  wsUri: "ws://localhost:9999",
  init: function() {
            var self = this;
            self.websocket = new WebSocket(self.wsUri);
            self.websocket.onopen = function(evt) {self.onOpen(evt) };
            //self.websocket.onclose = function(evt) { self.onClose(evt) };
            self.websocket.onmessage = function(evt) { self.onMessage(evt) };
            self.websocket.onerror = function(evt) { self.onError(evt) };
  },
  onOpen: function(evt) {
    var self = this;
    self.trackerLog("CONNECTED");
    uuid = self.createUUID();
    window.onmousemove = function(ev){
      self.websocket.send(JSON.stringify({uuid: uuid, date: (new Date()).getTime(), x: ev.clientX,  y:ev.clientY}));
    }
  },
  onClose: function(evt) {
    var self = this;
    self.trackerLog("DISCONNECTED");
  },
  onMessage: function(evt) {
    var self = this;
    self.trackerLog('RESPONSE: ' + evt.data);
    //self.websocket.close();
  },
  onError: function(evt) {
    var self = this;
    alert("Can't connect to server");
    self.trackerLog('ERROR: ' + evt.data);
  },
  doSend: function(message) {
    var self = this;
    self.trackerLog("SENT: " + message);
    self.websocket.send(message);
  },
  trackerLog: function(message) {
    console.log(message);
  },
  createUUID: function() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  }
}
ScreenTracker.init();
<commit_msg>moving url to config. adding custom id<commit_after>ScreenTracker = {
  websocket: null,
  config: {
    wsUri: "ws://localhost:9999",

  },
  init: function(options) {
            var self = this;
            if(options != null){
              for(i in options){
                self.config[i] = options[i];
              }
            }
            self.websocket = new WebSocket(self.config.wsUri);
            self.websocket.onopen = function(evt) {self.onOpen(evt) };
            //self.websocket.onclose = function(evt) { self.onClose(evt) };
            self.websocket.onmessage = function(evt) { self.onMessage(evt) };
            self.websocket.onerror = function(evt) { self.onError(evt) };
  },
  getWindowSize: function() {
  var docEl = document.documentElement,
      IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;

  // Used to feature test Opera returning wrong values
  // for documentElement.clientHeight.
  function isDocumentElementHeightOff () {
      var d = document,
          div = d.createElement('div');
      div.style.height = "2500px";
      d.body.insertBefore(div, d.body.firstChild);
      var r = d.documentElement.clientHeight > 2400;
      d.body.removeChild(div);
      return r;
  }

  if (typeof document.clientWidth == "number") {
     return function () {
       return { width: document.clientWidth, height: document.clientHeight };
     };
  } else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
      var b = document.body;
      return function () {
        return { width: b.clientWidth, height: b.clientHeight };
      };
  } else {
      return function () {
        return { width: docEl.clientWidth, height: docEl.clientHeight };
      };
  }
},
  onOpen: function(evt) {
    var self = this;
    self.trackerLog("CONNECTED");
    if(self.config.id == undefined){
      uuid = self.createUUID();
    } else{
      uuid = self.config.id;
    }

    window.onmousemove = function(ev){
      var size = self.getWindowSize();
      var w = size().width, h= size().height;
      self.websocket.send(JSON.stringify({uuid: uuid, date: (new Date()).getTime(), x: ev.clientX,  y:ev.clientY, width: w, height: h}));
    }
  },
  onClose: function(evt) {
    var self = this;
    self.trackerLog("DISCONNECTED");
  },
  onMessage: function(evt) {
    var self = this;
    self.trackerLog('RESPONSE: ' + evt.data);
    //self.websocket.close();
  },
  onError: function(evt) {
    var self = this;
    alert("Can't connect to server");
    self.trackerLog('ERROR: ' + evt.data);
  },
  doSend: function(message) {
    var self = this;
    self.trackerLog("SENT: " + message);
    self.websocket.send(message);
  },
  trackerLog: function(message) {
    console.log(message);
  },
  createUUID: function() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  }
}

//ScreenTracker.init();<|endoftext|>


<commit_before>var MainScene = cc.Scene.extend({
    ctor: function () {
        this._super();
        var background = new cc.Sprite(res.MainSceneBG_png);
        background.attr({
            scale: Math.max(size.width / background.width, size.height / background.width),
            anchorX: 0.5,
            anchorY: 1,
            x: size.width / 2,
            y: size.height
        });
        this.addChild(background);

        scrollableLayer = new cc.Layer();
        this.addChild(scrollableLayer);

        //登录界面
        var loginUI = new ccui.Widget();
        scrollableLayer.addChild(loginUI);
        var titleLabel = creator.createLabel(txt.mainScene.loginTitle, 40);
        titleLabel.setPosition(size.width / 2, size.height / 2 + 100);
        loginUI.addChild(titleLabel);

        var nameBox = creator.createEditBox(txt.mainScene.enterName);
        nameBox.setPosition(size.width / 2, size.height / 2 + 20);
        loginUI.addChild(nameBox);

        function moveToMainUI() {
            loginUI.enabled = false;
            mainUI.enabled = true;
            playOnlineButton.enabled = !player.guest;
            var moveAction = cc.moveTo(1, cc.p(-size.width, 0)).easing(cc.easeExponentialInOut());
            scrollableLayer.runAction(moveAction);
            updatePlayerLabel();
        }

        var loginButton = creator.createButton(txt.mainScene.login, cc.size(200, 40), function () {
            var name = nameBox.getString();
            if (name.length == 0) {
                showMessage(txt.mainScene.emptyName);
            } else if (name.length > 15) {
                showMessage(txt.mainScene.nameTooLong);
            } else {
                player.login(nameBox.getString(), function () {
                    moveToMainUI();
                }, function (error) {
                    showMessage(error);
                })
            }
        });

        loginButton.setPosition(size.width / 2, size.height / 2 - 80);
        loginUI.addChild(loginButton);

        guestButton = creator.createButton(txt.mainScene.loginAsGuest, cc.size(200, 40), function () {
            player.loginAsGuest();
            moveToMainUI();
        });
        guestButton.setPosition(size.width / 2, size.height / 2 - 140);
        loginUI.addChild(guestButton);

        var messageLabel = creator.createLabel("", 30, cc.color(255, 20, 20));
        messageLabel.setPosition(size.width / 2, size.height / 2 - 200);
        messageLabel.opacity = 0;
        this.addChild(messageLabel);

        var showMessageTID;
        function showMessage(text) {
            messageLabel.string = text;
            messageLabel.opacity = 255;
            clearTimeout(showMessageTID);
            messageLabel.stopAllActions();
            showMessageTID=setTimeout(function () {
                messageLabel.runAction(cc.fadeOut(1));
            }, 2000);
        }

        //主界面层
        var mainUI = new ccui.Widget();
        mainUI.x = size.width;
        scrollableLayer.addChild(mainUI);

        var playOnlineButton = new ccui.Button(res.PlayOnlineButton_png);
        playOnlineButton.setPosition(size.width / 2, size.height / 2 + 60);
        playOnlineButton.addClickEventListener(function () {
            cc.director.runScene(new OnlineGameScene());
        });
        mainUI.addChild(playOnlineButton);

        var playWithAIButton = creator.createButton(txt.mainScene.playWithAI, cc.size(250, 40), function () {
            cc.director.runScene(new AIGameScene());
        });
        playWithAIButton.setPosition(size.width / 2, size.height / 2 - 40);
        mainUI.addChild(playWithAIButton);

        var playDoubleButton = creator.createButton(txt.mainScene.playDouble, cc.size(250, 40), function () {
            cc.director.runScene(new DoubleGameScene());
        });
        playDoubleButton.setPosition(size.width / 2, size.height / 2 - 100);
        mainUI.addChild(playDoubleButton);

        var logoutButton = creator.createButton(txt.mainScene.logout, cc.size(100, 40), function () {
            player.logout();
            loginUI.enabled = true;
            loginUI.visible = true;
            mainUI.enabled = false;
            var moveAction = cc.moveTo(1, cc.p(0, 0)).easing(cc.easeExponentialInOut());
            scrollableLayer.runAction(moveAction);
        });
        logoutButton.setPosition(size.width / 2, size.height / 2 - 200);
        mainUI.addChild(logoutButton);

        var playerLabel = creator.createLabel("", 25);
        mainUI.addChild(playerLabel);
        function updatePlayerLabel() {
            var str = player.name;
            if (!player.guest) {
                str += "   " + txt.mainScene.serverName + player.serverName;
            }
            playerLabel.string = str;
            playerLabel.setPosition(playerLabel.width / 2 + 20, size.height - playerLabel.height / 2 - 20);
        }

        if (player.logged) {
            loginUI.enabled = false;
            loginUI.visible = false;
            updatePlayerLabel();
            scrollableLayer.x = -size.width;
            playOnlineButton.enabled = !player.guest;
        } else {
            mainUI.enabled = false;
        }

        //固定界面
        var optionButton = new ccui.Button(res.OptionButtonN_png, res.OptionButtonS_png);
        optionButton.setPosition(optionButton.width / 2 + 10, optionButton.height / 2 + 10);
        optionButton.addClickEventListener(function () {
            cc.director.runScene(new OptionScene());
        });
        this.addChild(optionButton);
        return true;
    }
});
<commit_msg>登录层的错误提示不再被延续到主界面层<commit_after>var MainScene = cc.Scene.extend({
    ctor: function () {
        this._super();
        var background = new cc.Sprite(res.MainSceneBG_png);
        background.attr({
            scale: Math.max(size.width / background.width, size.height / background.width),
            anchorX: 0.5,
            anchorY: 1,
            x: size.width / 2,
            y: size.height
        });
        this.addChild(background);

        scrollableLayer = new cc.Layer();
        this.addChild(scrollableLayer);

        //登录界面
        var loginUI = new ccui.Widget();
        scrollableLayer.addChild(loginUI);
        var titleLabel = creator.createLabel(txt.mainScene.loginTitle, 40);
        titleLabel.setPosition(size.width / 2, size.height / 2 + 100);
        loginUI.addChild(titleLabel);

        var nameBox = creator.createEditBox(txt.mainScene.enterName);
        nameBox.setPosition(size.width / 2, size.height / 2 + 20);
        loginUI.addChild(nameBox);

        function moveToMainUI() {
            messageLabel.opacity = 0;
            clearTimeout(showMessageTID);
            messageLabel.stopAllActions();
            loginUI.enabled = false;
            mainUI.enabled = true;
            playOnlineButton.enabled = !player.guest;
            var moveAction = cc.moveTo(1, cc.p(-size.width, 0)).easing(cc.easeExponentialInOut());
            scrollableLayer.runAction(moveAction);
            updatePlayerLabel();
        }

        var loginButton = creator.createButton(txt.mainScene.login, cc.size(200, 40), function () {
            var name = nameBox.getString();
            if (name.length == 0) {
                showMessage(txt.mainScene.emptyName);
            } else if (name.length > 15) {
                showMessage(txt.mainScene.nameTooLong);
            } else {
                player.login(nameBox.getString(), function () {
                    moveToMainUI();
                }, function (error) {
                    showMessage(error);
                })
            }
        });

        loginButton.setPosition(size.width / 2, size.height / 2 - 80);
        loginUI.addChild(loginButton);

        guestButton = creator.createButton(txt.mainScene.loginAsGuest, cc.size(200, 40), function () {
            player.loginAsGuest();
            moveToMainUI();
        });
        guestButton.setPosition(size.width / 2, size.height / 2 - 140);
        loginUI.addChild(guestButton);

        var messageLabel = creator.createLabel("", 30, cc.color(255, 20, 20));
        messageLabel.setPosition(size.width / 2, size.height / 2 - 200);
        messageLabel.opacity = 0;
        this.addChild(messageLabel);

        var showMessageTID;
        function showMessage(text) {
            messageLabel.string = text;
            messageLabel.opacity = 255;
            clearTimeout(showMessageTID);
            messageLabel.stopAllActions();
            showMessageTID=setTimeout(function () {
                messageLabel.runAction(cc.fadeOut(1));
            }, 2000);
        }

        //主界面层
        var mainUI = new ccui.Widget();
        mainUI.x = size.width;
        scrollableLayer.addChild(mainUI);

        var playOnlineButton = new ccui.Button(res.PlayOnlineButton_png);
        playOnlineButton.setPosition(size.width / 2, size.height / 2 + 60);
        playOnlineButton.addClickEventListener(function () {
            cc.director.runScene(new OnlineGameScene());
        });
        mainUI.addChild(playOnlineButton);

        var playWithAIButton = creator.createButton(txt.mainScene.playWithAI, cc.size(250, 40), function () {
            cc.director.runScene(new AIGameScene());
        });
        playWithAIButton.setPosition(size.width / 2, size.height / 2 - 40);
        mainUI.addChild(playWithAIButton);

        var playDoubleButton = creator.createButton(txt.mainScene.playDouble, cc.size(250, 40), function () {
            cc.director.runScene(new DoubleGameScene());
        });
        playDoubleButton.setPosition(size.width / 2, size.height / 2 - 100);
        mainUI.addChild(playDoubleButton);

        var logoutButton = creator.createButton(txt.mainScene.logout, cc.size(100, 40), function () {
            player.logout();
            loginUI.enabled = true;
            loginUI.visible = true;
            mainUI.enabled = false;
            var moveAction = cc.moveTo(1, cc.p(0, 0)).easing(cc.easeExponentialInOut());
            scrollableLayer.runAction(moveAction);
        });
        logoutButton.setPosition(size.width / 2, size.height / 2 - 200);
        mainUI.addChild(logoutButton);

        var playerLabel = creator.createLabel("", 25);
        mainUI.addChild(playerLabel);
        function updatePlayerLabel() {
            var str = player.name;
            if (!player.guest) {
                str += "   " + txt.mainScene.serverName + player.serverName;
            }
            playerLabel.string = str;
            playerLabel.setPosition(playerLabel.width / 2 + 20, size.height - playerLabel.height / 2 - 20);
        }

        if (player.logged) {
            loginUI.enabled = false;
            loginUI.visible = false;
            updatePlayerLabel();
            scrollableLayer.x = -size.width;
            playOnlineButton.enabled = !player.guest;
        } else {
            mainUI.enabled = false;
        }

        //固定界面
        var optionButton = new ccui.Button(res.OptionButtonN_png, res.OptionButtonS_png);
        optionButton.setPosition(optionButton.width / 2 + 10, optionButton.height / 2 + 10);
        optionButton.addClickEventListener(function () {
            cc.director.runScene(new OptionScene());
        });
        this.addChild(optionButton);
        return true;
    }
});
<|endoftext|>


<commit_before>import React from 'react';

import CampaignTable from '../CampaignTable';

class CampaignOverview extends React.Component {
  render() {
    const { pending, etc } = this.props;

    return (

        <CampaignTable cause="Pending Review" campaigns={pending} />
        <CampaignTable cause="etc." campaigns={etc} />

    );
  }
}

export default CampaignOverview;
<commit_msg>Add simple filtering to overview page.<commit_after>import React from 'react';

import CampaignTable from '../CampaignTable';

class CampaignOverview extends React.Component {
  constructor(props) {
    super(props);

    this.state = { search: '' };

    this.onChange = this.onChange.bind(this);
  }

  /**
   * Update state when search term changes.
   *
   * @param {*} event
   */
  onChange(event) {
    this.setState({ search: event.target.value });
  }

  /**
   * Filter the given campaigns by current search term.
   *
   * @return {Array}
   */
  filterCampaigns(campaigns) {
    const search = this.state.search.toLowerCase();

    return campaigns.filter(campaign => {
      if (this.state.search === '') {
        return true;
      }

      const matchesId = campaign.id.toString().includes(search);

      const matchesTitle = campaign.internal_title
        .toLowerCase()
        .includes(search);

      const matchesCause = campaign.cause.some(cause =>
        cause.toLowerCase().includes(search),
      );

      return matchesId || matchesTitle || matchesCause;
    });
  }

  /**
   * Render the campaign overview!
   *
   * @return {React.Element}
   */
  render() {
    const pending = this.filterCampaigns(this.props.pending);
    const etc = this.filterCampaigns(this.props.etc);

    return (

          <input
            type="text"
            className="text-field -search"
            placeholder="Filter by campaign ID, name, cause..."
            onChange={this.onChange}
          />

        <CampaignTable cause="Pending Review" campaigns={pending} />
        <CampaignTable cause="etc." campaigns={etc} />

    );
  }
}

export default CampaignOverview;
<|endoftext|>


<commit_before>// Start enchant.js
enchant();

var browserWidth = window.innerWidth || document.body.clientWidth;
var browserHeight = window.innerHeight || document.body.clientHeight;
window.onload = function() {

    // Starting point
    //var game = new Game(320, 440);
	//var game = new Game(440, 320);
	var game = new Game(browserWidth, browserHeight);
    game.preload(
                 'res/unicornSheetV1.png',
                 'res/drive.png',
                 'res/Hit.mp3',
                 'res/bgm.mp3',
				 'res/deadUnicornV001.jpg');
    game.fps = 30;
    game.scale = 1;
    game.onload = function() {
        // Once Game finish loading
        console.log("Hi, Boxer!");
        var scene = new SceneGame();
        game.pushScene(scene);
    }
    window.scrollTo(0,0);
    game.start();
};

/**
 * SceneGame
 */
var SceneGame = Class.create(Scene, {
    /**
     * The main gameplay scene.
     */
    initialize: function() {
        var game, label, bg, unicorn, driveGroup;

        // Call superclass constructor
        Scene.apply(this);

        // Access to the game singleton instance
        game = Game.instance;
        label = new Label('SCORE:   0');
        label.x = game.width/2-150;
        label.y = 50;
        label.color = 'black';
        label.font = '25px Impact';
        label.textAlign = 'center';
        label._style.textShadow ="-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black";
        this.scoreLabel = label;

        bg = new Sprite(browserWidth, browserHeight);

        unicorn = new Unicorn();
        unicorn.y = game.height/2 - unicorn.height/2;
        unicorn.x = 10;
        this.unicorn = unicorn;

        driveGroup = new Group();
        this.driveGroup = driveGroup;

        this.addChild(bg);
        this.addChild(driveGroup);
        this.addChild(unicorn);
        this.addChild(label);

        this.addEventListener(Event.TOUCH_START,this.handleTouchControl);
        this.addEventListener(Event.ENTER_FRAME,this.update);

        // Instance variables
        this.generatedriveTimer = 0;
        this.scoreTimer = 0;
        this.score = 0;

        this.bgm = game.assets['res/bgm.mp3']; // Add this line

        // Start BGM
        this.bgm.play();
    },

    handleTouchControl: function (evt) {
        var laneHeight, lane;
        laneHeight = 600/3;
        lane = Math.floor(evt.y/laneHeight);
        lane = Math.max(Math.min(2,lane),0);
        this.unicorn.switchToLaneNumber(lane);
    },

    update: function(evt) {
        // Score increase as time pass
        this.scoreTimer += evt.elapsed * 0.001;
        if(this.scoreTimer >= 0.5)
        {
            this.setScore(this.score + 1);
            this.scoreTimer -= 0.5;
        }

        // Check if it's time to create a new set of obstacles
        this.generatedriveTimer += evt.elapsed * 0.001;
        if(this.generatedriveTimer >= 0.5)
        {
            var drive;
            this.generatedriveTimer -= 0.5;
            drive = new Drive(Math.floor(Math.random()*3));
            this.driveGroup.addChild(drive);
        }

        // Check collision
        for (var i = this.driveGroup.childNodes.length - 1; i >= 0; i--) {
            var drive;
            drive = this.driveGroup.childNodes[i];
            if(drive.intersect(this.unicorn)){
                var game;
                game = Game.instance;
                game.assets['res/Hit.mp3'].play();
                this.driveGroup.removeChild(drive);
                this.bgm.stop();
                game.replaceScene(new SceneGameOver(this.score));
                break;
            }
        }

        // Loop BGM
        if( this.bgm.currentTime >= this.bgm.duration ){
            this.bgm.play();
        }
    },

    setScore: function (value) {
        this.score = value;
        this.scoreLabel.text = 'SCORE:   ' + this.score;
    }
});

/**
 * unicorn
 */
 var Unicorn = Class.create(Sprite, {
    /**
     * The player character.
     */
    initialize: function() {
        // Call superclass constructor
        Sprite.apply(this,[100, 60]);
        this.image = Game.instance.assets['res/unicornSheetV1.png'];
        this.animationDuration = 0;
        this.addEventListener(Event.ENTER_FRAME, this.updateAnimation);
    },

    updateAnimation: function (evt) {
        this.animationDuration += evt.elapsed * 0.001;
        if(this.animationDuration >= 0.25)
        {
            this.frame = (this.frame + 1) % 2;
            this.animationDuration -= 0.25;
        }
    },

    switchToLaneNumber: function(lane){
        var targetY = 300 - this.height/2 + (lane-1)*150;
        this.y = targetY;
    }
});

var UnicornGameOver = Class.create (Sprite, {
	initialize: function() {
		Sprite.apply(this,[browserWidth,browserHeight]);
		// this.image = Game.instance.assets['res/deadUnicornV001.jpg'];
	}
});

var Drive = Class.create(Sprite, {
    /**
     * The obstacle that the unicorn must avoid
     */
    initialize: function(lane) {
        // Call superclass constructor
        Sprite.apply(this,[48, 49]);
        this.image  = Game.instance.assets['res/drive.png'];
        this.rotationSpeed = 0;
        this.setLane(lane);
        this.addEventListener(Event.ENTER_FRAME, this.update);
    },

    setLane: function(lane) {
        var game, distance;
        game = Game.instance;
        distance = 170;

        this.rotationSpeed = Math.random() * 100 - 50;

        this.y = game.height/2 - this.height/2 + (lane - 1) * distance;
        this.x = game.width;
        this.rotation = Math.floor( Math.random() * 360 );
    },

    update: function(evt) {
        var ySpeed, game;

        game = Game.instance;
        ySpeed = 300;

        this.x -= ySpeed * evt.elapsed * 0.001;
        this.rotation += this.rotationSpeed * evt.elapsed * 0.001;
        if(this.x < 0)
        {
            this.parentNode.removeChild(this);
        }
    }
});

/**
 * SceneGameOver
 */
var SceneGameOver = Class.create(Scene, {
    initialize: function(score) {
        var gameOverLabel, scoreLabel, unicornGameOver, game;
		game = Game.instance;
        Scene.apply(this);
		// this.image = Game.instance.assets['res/deadUnicornV001.jpg'];

        gameOverLabel = new Label("Tap to Restart!");
        gameOverLabel.x = (browserWidth/2)-150;
        gameOverLabel.y = (game.height/2)-120;
        gameOverLabel.color = 'black';
        gameOverLabel.font = '32px Impact';
        gameOverLabel.textAlign = 'center';

        scoreLabel = new Label('SCORE:   ' + score);
        scoreLabel.x = (game.width/2)-150;
        scoreLabel.y = 100;
        scoreLabel.color = 'black';
        scoreLabel.font = '25px Impact';
        scoreLabel.textAlign = 'center';

		unicornGameOver = new UnicornGameOver();

		this.addChild(unicornGameOver);
        this.addChild(gameOverLabel);
        this.addChild(scoreLabel);

        this.addEventListener(Event.TOUCH_START, this.touchToRestart);

    },

    touchToRestart: function(evt) {
        var game = Game.instance;
        game.replaceScene(new SceneGame());
    }
});<commit_msg>;lkajsdf<commit_after>// Start enchant.js
enchant();

var browserWidth = window.innerWidth || document.body.clientWidth;
var browserHeight = window.innerHeight || document.body.clientHeight;
window.onload = function() {

    // Starting point
    //var game = new Game(320, 440);
	//var game = new Game(440, 320);
	var game = new Game(browserWidth, browserHeight);
    game.preload(
                 'res/unicornSheetV1.png',
                 'res/drive.png',
                 'res/Hit.mp3',
                 'res/bgm.mp3',
				 'res/deadUnicornV001.jpg');
    game.fps = 30;
    game.scale = 1;
    game.onload = function() {
        // Once Game finish loading
        console.log("Hi, Boxer!");
        var scene = new SceneGame();
        game.pushScene(scene);
    }
    window.scrollTo(0,0);
    game.start();
};

/**
 * SceneGame
 */
var SceneGame = Class.create(Scene, {
    /**
     * The main gameplay scene.
     */
    initialize: function() {
        var game, label, bg, unicorn, driveGroup;

        // Call superclass constructor
        Scene.apply(this);

        // Access to the game singleton instance
        game = Game.instance;
        label = new Label('SCORE:   0');
        label.x = game.width/2-150;
        label.y = 50;
        label.color = 'black';
        label.font = '25px Impact';
        label.textAlign = 'center';
        label._style.textShadow ="-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black";
        this.scoreLabel = label;

        bg = new Sprite(browserWidth, browserHeight);

        unicorn = new Unicorn();
        unicorn.y = game.height/2 - unicorn.height/2;
        unicorn.x = 10;
        this.unicorn = unicorn;

        driveGroup = new Group();
        this.driveGroup = driveGroup;

        this.addChild(bg);
        this.addChild(driveGroup);
        this.addChild(unicorn);
        this.addChild(label);

        this.addEventListener(Event.TOUCH_START,this.handleTouchControl);
        this.addEventListener(Event.ENTER_FRAME,this.update);

        // Instance variables
        this.generatedriveTimer = 0;
        this.scoreTimer = 0;
        this.score = 0;

        this.bgm = game.assets['res/bgm.mp3']; // Add this line

        // Start BGM
        this.bgm.play();
    },

    handleTouchControl: function (evt) {
        var laneHeight, lane;
        laneHeight = 600/3;
        lane = Math.floor(evt.y/laneHeight);
        lane = Math.max(Math.min(2,lane),0);
        this.unicorn.switchToLaneNumber(lane);
    },

    update: function(evt) {
        // Score increase as time pass
        this.scoreTimer += evt.elapsed * 0.001;
        if(this.scoreTimer >= 0.5)
        {
            this.setScore(this.score + 1);
            this.scoreTimer -= 0.5;
        }

        // Check if it's time to create a new set of obstacles
        this.generatedriveTimer += evt.elapsed * 0.001;
        if(this.generatedriveTimer >= 0.5)
        {
            var drive;
            this.generatedriveTimer -= 0.5;
            drive = new Drive(Math.floor(Math.random()*3));
            this.driveGroup.addChild(drive);
        }

        // Check collision
        for (var i = this.driveGroup.childNodes.length - 1; i >= 0; i--) {
            var drive;
            drive = this.driveGroup.childNodes[i];
            if(drive.intersect(this.unicorn)){
                var game;
                game = Game.instance;
                game.assets['res/Hit.mp3'].play();
                this.driveGroup.removeChild(drive);
                this.bgm.stop();
                game.replaceScene(new SceneGameOver(this.score));
                break;
            }
        }

        // Loop BGM
        if( this.bgm.currentTime >= this.bgm.duration ){
            this.bgm.play();
        }
    },

    setScore: function (value) {
        this.score = value;
        this.scoreLabel.text = 'SCORE:   ' + this.score;
    }
});

/**
 * unicorn
 */
 var Unicorn = Class.create(Sprite, {
    /**
     * The player character.
     */
    initialize: function() {
        // Call superclass constructor
        Sprite.apply(this,[100, 60]);
        this.image = Game.instance.assets['res/unicornSheetV1.png'];
        this.animationDuration = 0;
        this.addEventListener(Event.ENTER_FRAME, this.updateAnimation);
    },

    updateAnimation: function (evt) {
        this.animationDuration += evt.elapsed * 0.001;
        if(this.animationDuration >= 0.25)
        {
            this.frame = (this.frame + 1) % 2;
            this.animationDuration -= 0.25;
        }
    },

    switchToLaneNumber: function(lane){
        var targetY = 300 - this.height/2 + (lane-1)*150;
        this.y = targetY;
    }
});

var UnicornGameOver = Class.create (Sprite, {
	initialize: function() {
		Sprite.apply(this,[browserWidth,browserHeight]);
		// this.image = Game.instance.assets['res/deadUnicornV001.jpg'];
	}
});

var Drive = Class.create(Sprite, {
    /**
     * The obstacle that the unicorn must avoid
     */
    initialize: function(lane) {
        // Call superclass constructor
        Sprite.apply(this,[48, 49]);
        this.image  = Game.instance.assets['res/drive.png'];
        this.rotationSpeed = 0;
        this.setLane(lane);
        this.addEventListener(Event.ENTER_FRAME, this.update);
    },

    setLane: function(lane) {
        var game, distance;
        game = Game.instance;
        distance = 170;

        this.rotationSpeed = Math.random() * 100 - 50;

        this.y = game.height/2 - this.height/2 + (lane - 1) * distance;
        this.x = game.width;
        this.rotation = Math.floor( Math.random() * 360 );
    },

    update: function(evt) {
        var ySpeed, game;

        game = Game.instance;
        ySpeed = 300;

        this.x -= ySpeed * evt.elapsed * 0.001;
        this.rotation += this.rotationSpeed * evt.elapsed * 0.001;
        if(this.x < 0)
        {
            this.parentNode.removeChild(this);
        }
    }
});

/**
 * SceneGameOver
 */
var SceneGameOver = Class.create(Scene, {
    initialize: function(score) {
        var gameOverLabel, scoreLabel, unicornGameOver, game;
		game = Game.instance;
        Scene.apply(this);
		// this.image = Game.instance.assets['res/deadUnicornV001.jpg'];

        gameOverLabel = new Label("Tap to Restart!");
        gameOverLabel.x = (browserWidth/2)-150;
        gameOverLabel.y = (browserHeight/2)-120;
        gameOverLabel.color = 'black';
        gameOverLabel.font = '32px Impact';
        gameOverLabel.textAlign = 'center';

        scoreLabel = new Label('SCORE:   ' + score);
        scoreLabel.x = (game.width/2)-150;
        scoreLabel.y = 100;
        scoreLabel.color = 'black';
        scoreLabel.font = '25px Impact';
        scoreLabel.textAlign = 'center';

		unicornGameOver = new UnicornGameOver();

		this.addChild(unicornGameOver);
        this.addChild(gameOverLabel);
        this.addChild(scoreLabel);

        this.addEventListener(Event.TOUCH_START, this.touchToRestart);

    },

    touchToRestart: function(evt) {
        var game = Game.instance;
        game.replaceScene(new SceneGame());
    }
});<|endoftext|>


<commit_before>{% load djblets_js djblets_utils features reviewtags %}
        el: document.body,
        reviewRequestData: {
            bugTrackerURL: "{% if review_request.repository.bug_tracker %}{% url 'bug_url' review_request.display_id '--bug_id--' %}{% endif %}",
            id: {{review_request.display_id}},
            submitter: {
{% with submitter=draft.submitter %}
                title: '{{submitter.username|escapejs}}',
                url: '{{submitter.get_absolute_url|escapejs}}'
{% endwith %}
            },
            localSitePrefix: "{% if review_request.local_site %}s/{{review_request.local_site.name}}/{% endif %}",
            branch: "{{review_request_details.branch|escapejs}}",
            bugsClosed: {{review_request_details.get_bug_list|json_dumps}},
            closeDescription: "{% normalize_text_for_edit close_description close_description_rich_text True %}",
            closeDescriptionRichText: {{close_description_rich_text|yesno:'true,false'}},
            description: "{% normalize_text_for_edit review_request_details.description review_request_details.description_rich_text True %}",
            descriptionRichText: {{review_request_details.description_rich_text|yesno:'true,false'}},
            generalCommentsEnabled: {% if_feature_enabled 'reviews.general_comments' %}'true'{% else %}'false'{% endif_feature_enabled %},
            hasDraft: {{draft|yesno:'true,false'}},
            lastUpdatedTimestamp: {{review_request.last_updated|json_dumps}},
            public: {{review_request.public|yesno:'true,false'}},
{% if review_request.repository %}
            repository: new RB.Repository({
{%  with repo=review_request.repository %}
{%   with scmtool=repo.get_scmtool %}
                id: {{repo.id}},
                localSitePrefix: '{% if review_request.local_site %}s/{{review_request.local_site.name}}/{% endif %}',
                name: '{{repo.name|escapejs}}',
                requiresBasedir: {{scmtool.diffs_use_absolute_paths|yesno:'false,true'}},
                requiresChangeNumber: {{scmtool.supports_pending_changesets|yesno:'true,false'}},
                scmtoolName: '{{scmtool.name|escapejs}}',
                supportsPostCommit: {{repo.supports_post_commit|yesno:'true,false'}}
{%   endwith %}
{%  endwith %}
            }),
{% endif %}
            reviewURL: "{{review_request.get_absolute_url|escapejs}}",
            state: RB.ReviewRequest.{% if review_request.status == 'P' %}PENDING{% elif review_request.status == 'D' %}CLOSE_DISCARDED{% elif review_request.status == 'S' %}CLOSE_SUBMITTED{% endif %},
            summary: "{{review_request_details.summary|escapejs}}",
            targetGroups: [{% spaceless %}
{% for group in review_request_details.target_groups.all %}
                {
                    name: "{{group.name|escapejs}}",
                    url: "{{group.get_absolute_url}}"
                }{% if not forloop.last %},{% endif %}
{% endfor %}{% endspaceless %}],
            targetPeople: [{% spaceless %}
{% for user in review_request_details.target_people.all %}
                {
                    username: "{{user.username|escapejs}}",
                    url: "{% url 'user' user %}"
                }{% if not forloop.last %},{% endif %}
{% endfor %}{% endspaceless %}],
            testingDone: "{% normalize_text_for_edit review_request_details.testing_done review_request_details.testing_done_rich_text True %}",
            testingDoneRichText: {{review_request_details.testing_done_rich_text|yesno:'true,false'}},
{% if review_request_visit.visibility == 'V' %}
            visibility: RB.ReviewRequest.VISIBILITY_VISIBLE
{% elif review_request_visit.visibility == 'A' %}
            visibility: RB.ReviewRequest.VISIBILITY_ARCHIVED
{% elif review_request_visit.visibility == 'M' %}
            visibility: RB.ReviewRequest.VISIBILITY_MUTED
{% endif %}
        },
        extraReviewRequestDraftData: {
{% if draft.changedesc %}
{%  if draft.diffset %}
{%   url "view-interdiff" review_request.display_id draft.diffset.revision|add:"-1" draft.diffset.revision as interdiffLink %}
            interdiffLink: '{{interdiffLink|escapejs}}',
{%  endif %}
            changeDescription: "{% normalize_text_for_edit draft.changedesc.text draft.changedesc.rich_text True %}",
            changeDescriptionRichText: {{draft.changedesc.rich_text|yesno:'true,false'}}
{% endif %}
        },
        editorData: {
{% if draft.changedesc %}
            changeDescriptionRenderedText: '{{draft.changedesc.text|render_markdown:draft.changedesc.rich_text|escapejs}}',
{% endif %}
            closeDescriptionRenderedText: '{{close_description|render_markdown:close_description_rich_text|escapejs}}',
            hasDraft: {{draft|yesno:'true,false'}},
            mutableByUser: {{mutable_by_user|yesno:'true,false'}},
            statusMutableByUser: {{status_mutable_by_user|yesno:'true,false'}},
            fileAttachments: [
{% for file in file_attachments %}
{%  has_usable_review_ui request.user review_request file as use_review_ui %}
{%  definevar "caption" %}{% if draft %}{{file.draft_caption}}{% else %}{{file.caption}}{% endif %}{% enddefinevar %}
{%  definevar "file_attachment_url" %}{% if use_review_ui %}{% url "file-attachment" review_request.display_id file.pk %}{% endif %}{% enddefinevar %}
                {
                    id: {{file.pk}},
                    loaded: true,
{%  if file.attachment_history_id %}
                    attachmentHistoryID: {{file.attachment_history_id}},
{%  endif %}
                    caption: _.unescape('{{caption|escapejs}}'),
                    downloadURL: '{{file.get_absolute_url|escapejs}}',
                    filename: '{{file.filename|escapejs}}',
                    reviewURL: '{{file_attachment_url|escapejs}}',
                    revision: {{file.attachment_revision}},
                    thumbnailHTML: '{{file.thumbnail|escapejs}}'
                }{% if not forloop.last %},{% endif %}
{% endfor %}
            ],
            fileAttachmentComments: {
{% if all_file_attachments %}
{%  for file_attachment in all_file_attachments %}
                {{file_attachment.id}}: {% file_attachment_comments file_attachment %}{% if not forloop.last %},{% endif %}
{%  endfor %}
{% endif %}
            }
        }
<commit_msg>Fix display of the "Send E-mail" checkbox in the review request draft banner.<commit_after>{% load djblets_js djblets_utils features reviewtags %}
        el: document.body,
        reviewRequestData: {
            bugTrackerURL: "{% if review_request.repository.bug_tracker %}{% url 'bug_url' review_request.display_id '--bug_id--' %}{% endif %}",
            id: {{review_request.display_id}},
            submitter: {
{% with submitter=draft.submitter %}
                title: '{{submitter.username|escapejs}}',
                url: '{{submitter.get_absolute_url|escapejs}}'
{% endwith %}
            },
            localSitePrefix: "{% if review_request.local_site %}s/{{review_request.local_site.name}}/{% endif %}",
            branch: "{{review_request_details.branch|escapejs}}",
            bugsClosed: {{review_request_details.get_bug_list|json_dumps}},
            closeDescription: "{% normalize_text_for_edit close_description close_description_rich_text True %}",
            closeDescriptionRichText: {{close_description_rich_text|yesno:'true,false'}},
            description: "{% normalize_text_for_edit review_request_details.description review_request_details.description_rich_text True %}",
            descriptionRichText: {{review_request_details.description_rich_text|yesno:'true,false'}},
            generalCommentsEnabled: {% if_feature_enabled 'reviews.general_comments' %}'true'{% else %}'false'{% endif_feature_enabled %},
            hasDraft: {{draft|yesno:'true,false'}},
            lastUpdatedTimestamp: {{review_request.last_updated|json_dumps}},
            public: {{review_request.public|yesno:'true,false'}},
{% if review_request.repository %}
            repository: new RB.Repository({
{%  with repo=review_request.repository %}
{%   with scmtool=repo.get_scmtool %}
                id: {{repo.id}},
                localSitePrefix: '{% if review_request.local_site %}s/{{review_request.local_site.name}}/{% endif %}',
                name: '{{repo.name|escapejs}}',
                requiresBasedir: {{scmtool.diffs_use_absolute_paths|yesno:'false,true'}},
                requiresChangeNumber: {{scmtool.supports_pending_changesets|yesno:'true,false'}},
                scmtoolName: '{{scmtool.name|escapejs}}',
                supportsPostCommit: {{repo.supports_post_commit|yesno:'true,false'}}
{%   endwith %}
{%  endwith %}
            }),
{% endif %}
            reviewURL: "{{review_request.get_absolute_url|escapejs}}",
            state: RB.ReviewRequest.{% if review_request.status == 'P' %}PENDING{% elif review_request.status == 'D' %}CLOSE_DISCARDED{% elif review_request.status == 'S' %}CLOSE_SUBMITTED{% endif %},
            summary: "{{review_request_details.summary|escapejs}}",
            targetGroups: [{% spaceless %}
{% for group in review_request_details.target_groups.all %}
                {
                    name: "{{group.name|escapejs}}",
                    url: "{{group.get_absolute_url}}"
                }{% if not forloop.last %},{% endif %}
{% endfor %}{% endspaceless %}],
            targetPeople: [{% spaceless %}
{% for user in review_request_details.target_people.all %}
                {
                    username: "{{user.username|escapejs}}",
                    url: "{% url 'user' user %}"
                }{% if not forloop.last %},{% endif %}
{% endfor %}{% endspaceless %}],
            testingDone: "{% normalize_text_for_edit review_request_details.testing_done review_request_details.testing_done_rich_text True %}",
            testingDoneRichText: {{review_request_details.testing_done_rich_text|yesno:'true,false'}},
{% if review_request_visit.visibility == 'V' %}
            visibility: RB.ReviewRequest.VISIBILITY_VISIBLE
{% elif review_request_visit.visibility == 'A' %}
            visibility: RB.ReviewRequest.VISIBILITY_ARCHIVED
{% elif review_request_visit.visibility == 'M' %}
            visibility: RB.ReviewRequest.VISIBILITY_MUTED
{% endif %}
        },
        extraReviewRequestDraftData: {
{% if draft.changedesc %}
{%  if draft.diffset %}
{%   url "view-interdiff" review_request.display_id draft.diffset.revision|add:"-1" draft.diffset.revision as interdiffLink %}
            interdiffLink: '{{interdiffLink|escapejs}}',
{%  endif %}
            changeDescription: "{% normalize_text_for_edit draft.changedesc.text draft.changedesc.rich_text True %}",
            changeDescriptionRichText: {{draft.changedesc.rich_text|yesno:'true,false'}}
{% endif %}
        },
        editorData: {
{% if draft.changedesc %}
            changeDescriptionRenderedText: '{{draft.changedesc.text|render_markdown:draft.changedesc.rich_text|escapejs}}',
{% endif %}
            closeDescriptionRenderedText: '{{close_description|render_markdown:close_description_rich_text|escapejs}}',
            hasDraft: {{draft|yesno:'true,false'}},
            mutableByUser: {{mutable_by_user|yesno:'true,false'}},
            showSendEmail: {{send_email|yesno:'true,false'}},
            statusMutableByUser: {{status_mutable_by_user|yesno:'true,false'}},
            fileAttachments: [
{% for file in file_attachments %}
{%  has_usable_review_ui request.user review_request file as use_review_ui %}
{%  definevar "caption" %}{% if draft %}{{file.draft_caption}}{% else %}{{file.caption}}{% endif %}{% enddefinevar %}
{%  definevar "file_attachment_url" %}{% if use_review_ui %}{% url "file-attachment" review_request.display_id file.pk %}{% endif %}{% enddefinevar %}
                {
                    id: {{file.pk}},
                    loaded: true,
{%  if file.attachment_history_id %}
                    attachmentHistoryID: {{file.attachment_history_id}},
{%  endif %}
                    caption: _.unescape('{{caption|escapejs}}'),
                    downloadURL: '{{file.get_absolute_url|escapejs}}',
                    filename: '{{file.filename|escapejs}}',
                    reviewURL: '{{file_attachment_url|escapejs}}',
                    revision: {{file.attachment_revision}},
                    thumbnailHTML: '{{file.thumbnail|escapejs}}'
                }{% if not forloop.last %},{% endif %}
{% endfor %}
            ],
            fileAttachmentComments: {
{% if all_file_attachments %}
{%  for file_attachment in all_file_attachments %}
                {{file_attachment.id}}: {% file_attachment_comments file_attachment %}{% if not forloop.last %},{% endif %}
{%  endfor %}
{% endif %}
            }
        }
<|endoftext|>


<commit_before>/*
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * RNAcentral metadata search Angular.js app.
 */

; // concatenation safeguard

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function() {
    return window._;
});

/**
 * Create RNAcentral app.
 */
var rnaMetasearch = angular.module('rnacentralApp', ['chieffancypants.loadingBar', 'underscore', 'ngAnimate']);

// hide spinning wheel
rnaMetasearch.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeSpinner = false;
}]);

/**
 * html5mode removes hashtags from urls.
 */
rnaMetasearch.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

/**
 * Service for launching a metadata search.
 */
rnaMetasearch.service('search', ['$location', function($location) {

    /**
     * To launch a new search, change browser url,
     * which will automatically trigger a new search
     * since the url changes are watched in the query controller.
     */
    this.meta_search = function(query) {
        $location.url('/search' + '?q=' + query);
    };

}]);

/**
 * Service for passing data between controllers.
 */
rnaMetasearch.service('results', ['_', '$http', '$location', '$window', function(_, $http, $location, $window) {

    /**
     * Service initialization.
     */
    var result = {
        hitCount: null,
        entries: [],
        facets: [],
    };

    var status = {
        display_search_interface: false, // hide results section at first
        search_in_progress: false, // display spinning wheel while searching
        show_error: false, // display error message
    };

    var search_config = {
        ebeye_base_url: 'http://wwwdev.ebi.ac.uk/ebisearch/ws/rest/rnacentral',
        rnacentral_base_url: get_base_url(),
        fields: ['description', 'active', 'length'],
        facetfields: ['expert_db', 'rna_type', 'TAXONOMY'], // will be displayed in this order
        facetcount: 30,
        pagesize: 15,
    };

    var query_urls = {
        'ebeye_search': search_config.ebeye_base_url +
                        '?query={QUERY}' +
                        '&format=json' +
                        '&fields=' + search_config.fields.join() +
                        '&facetcount=' + search_config.facetcount +
                        '&facetfields=' + search_config.facetfields.join() +
                        '&size=' + search_config.pagesize +
                        '&start={START}',
        'proxy': search_config.rnacentral_base_url +
                 '/api/internal/ebeye?url={EBEYE_URL}',
    };

    /**
     * Calculate base url for production and development environments.
     */
    function get_base_url() {
        var base_url = $location.protocol() + '://' + $location.host();
        var port = $location.port();
        if (port !== '') {
            base_url += ':' + port
        }
        return base_url;
    }

    /**
     * Launch EBeye search.
     * `start` determines the range of the results to be returned.
     */
    this.search = function(query, start) {
        start = start || 0;

        display_search_interface();
        display_spinner();
        update_page_title();

        query = preprocess_query(query);
        query_url = get_query_url(query, start);
        execute_ebeye_search(query_url, start === 0);

        /**
         * Display search spinner if not a "load more" request.
         */
        function display_spinner() {
            if (start === 0) {
                result.hitCount = null; // display spinner
            }
        }

        /**
         * Change page title, which is also used in browser tabs.
         */
        function update_page_title() {
            $window.document.title = 'Search: ' + query;
        }

        /**
         * Setting `display_search_interface` value to true hides all non-search page content
         * and begins displaying search results interface.
         */
        function display_search_interface() {
            status.display_search_interface = true;
        }

        /**
         * Create an RNAcentral proxy query url which includes EBeye query url.
         */
        function get_query_url() {
            var ebeye_url = query_urls.ebeye_search.replace('{QUERY}', query).replace('{START}', start);
            var url = query_urls.proxy.replace('{EBEYE_URL}', encodeURIComponent(ebeye_url));
            return url;
        }

        /**
         * Split query into words and then:
         *  - append wildcards to all terms without double quotes and not ending with wildcards
         *  - escape special symbols
         *  - capitalize logical operators
         *
         *  Splitting into words is based on this SO question:
         *  http://stackoverflow.com/questions/366202/regex-for-splitting-a-string-using-space-when-not-surrounded-by-single-or-double
         * Each "word" is a sequence of characters that aren't spaces or quotes,
         * or a sequence of characters that begin and end with a quote, with no quotes in between.
         */
        function preprocess_query(query) {
            var words = query.match(/[^\s"]+|"[^"]*"/g);
            var array_length = words.length;
            for (var i = 0; i < array_length; i++) {
                if ( words[i].match(/and|or|not/gi) ) {
                    // capitalize logical operators
                    words[i] = words[i].toUpperCase();
                } else if ( words[i].match(/\:$/gi) ) {
                    // faceted search term, do nothing
                } else if ( words[i].match(/^".+?"$/) ) {
                    // double quotes, do nothing
                } else if ( words[i].match(/\*$/) ) {
                    // wildcard, escape term
                    words[i] = escape_search_term(words[i]);
                } else {
                    // all other words
                    // escape term, add wildcard
                    words[i] = escape_search_term(words[i]) + '*';
                };
            }
            query = words.join(' ');
            return query;

            /**
             * Escape special symbols used by Lucene
             * Escaped: + - && || ! { } [ ] ^ ~ ? : \
             * Not escaped: * " ( ) because they may be used deliberately by the user
             */
            function escape_search_term(search_term) {
                return search_term.replace(/[\+\-&|!\{\}\[\]\^~\?\:\\]/g, "\\$&");
            }
        }

        /**
         * Execute remote request.
         */
        function execute_ebeye_search(url, overwrite_results) {
            status.search_in_progress = true;
            status.show_error = false;
            $http({
                url: url,
                method: 'GET'
            }).success(function(data) {
                data = preprocess_results(data);
                overwrite_results = overwrite_results || false;
                if (overwrite_results) {
                    result = data; // replace
                } else {
                    // append only entries
                    result.entries = result.entries.concat(data.entries);
                }
                status.search_in_progress = false;
            }).error(function(){
                status.search_in_progress = false;
                status.show_error = true;
            });

            /**
             * Preprocess data received from the server.
             */
            function preprocess_results(data) {
                // sort facets the same way as in config
                _.sortBy(data.facets, function(facet){
                    return _.indexOf(search_config.facetfields, facet.id);
                });
                return data;
            }
        }

    }

    /**
     * Load more results starting from the last loaded index.
     */
    this.load_more_results = function() {
        query = $location.search().q;
        this.search(query, result.entries.length);
    };

    /**
     * Broadcast whether search interface should be displayed.
     */
    this.get_status = function() {
        return status.display_search_interface;
    };

    /**
     * Broadcast search results changes.
     */
    this.get_result = function() {
        return result;
    };

    /**
     * Broadcast whether search is in progress.
     */
    this.get_search_in_progress = function() {
        return status.search_in_progress;
    };

    /**
     * Broadcast whether an error has occurred.
     */
    this.get_show_error = function() {
        return status.show_error;
    };

}]);

rnaMetasearch.controller('MainContent', ['$scope', '$anchorScroll', '$location', 'results', 'search', function($scope, $anchorScroll, $location, results, search) {
    /**
     * Enables scrolling to anchor tags.
     * Title
     */
    $scope.scrollTo = function(id) {
        $location.hash(id);
        $anchorScroll();
    };

    /**
     * Watch `display_search_interface` in order to hide non-search-related content
     * when a search is initiated.
     */
    $scope.$watch(function () { return results.get_status(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.display_search_interface = newValue;
        }
    });

    /**
     * Launch a metadata search from a web page.
     */
    $scope.meta_search = function(query) {
        search.meta_search(query);
    };

}]);

/**
 * Results display controller
 * Responsible for visualising search results.
 */
rnaMetasearch.controller('ResultsListCtrl', ['$scope', '$location', 'results', function($scope, $location, results) {

    $scope.result = {
        entries: [],
    };

    $scope.search_in_progress = results.get_search_in_progress();
    $scope.show_error = results.get_show_error();

    /**
     * Watch `result` changes.
     */
    $scope.$watch(function () { return results.get_result(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.result = newValue;
        }
    });

    /**
     * Watch `display_search_interface` changes.
     */
    $scope.$watch(function () { return results.get_status(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.display_search_interface = newValue;
        }
    });

    /**
     * Watch `search_in_progress` changes.
     */
    $scope.$watch(function () { return results.get_search_in_progress(); }, function (newValue, oldValue) {
        if (newValue != oldValue) {
            $scope.search_in_progress = newValue;
        }
    });

    /**
     * Watch `show_error` changes.
     */
    $scope.$watch(function () { return results.get_show_error(); }, function (newValue, oldValue) {
        if (newValue != oldValue) {
            $scope.show_error = newValue;
        }
    });

    /**
     * Fired when "Load more" button is clicked.
     */
    $scope.load_more_results = function() {
        results.load_more_results();
    };

    /**
     * Determine if the facet has already been applied.
     */
    $scope.is_facet_applied = function(facet_id, facet_value) {
        var query = $location.search().q || '';
        var facet_query = facet_id + ':"' + facet_value + '"';
        if (query.indexOf(facet_query) == -1) {
            return false;
        } else {
            return true;
        }
    };

    /**
     * Run a search with a facet enabled.
     * The facet will be toggled on and off in the repeated calls with the same
     * parameters.
     */
    $scope.facet_search = function(facet_id, facet_value) {
        var query = $location.search().q || '';
        var facet_query = ' AND ' + facet_id + ':"' + facet_value + '"';
        if ($scope.is_facet_applied(facet_id, facet_value)) {
            new_query = query.replace(facet_query, ''); // remove facet
        } else {
            new_query = query + facet_query; // add new facet
        }
        $location.search('q', new_query);
    };

    /**
     * Show/hide search facets to save screen space.
     * Uses jQuery for simplicity.
     * Activated only on mobile devices.
     */
    $scope.toggle_facets = function() {
        var facets = $('.metasearch-facets');
        facets.toggleClass('hidden-xs', !facets.hasClass('hidden-xs'));
        $('#toggle-facets').text(function(i, text){
          return text === "Show facets" ? "Hide facets" : "Show facets";
        });
    };

}]);

/**
 * Query controller
 * Responsible for the search box in the header.
 */
rnaMetasearch.controller('QueryCtrl', ['$scope', '$location', '$window', '$timeout', 'results', 'search', function($scope, $location, $window, $timeout, results, search) {

    $scope.query = {
        text: '',
        submitted: false
    };

    /**
     * Launch a metadata search using the service.
     */
    $scope.meta_search = function(query) {
        search.meta_search(query);
    };

    /**
     * Control browser navigation buttons.
     */
    $scope.$watch(function () { return $location.url(); }, function (newUrl, oldUrl) {
        // ignore url hash
        newUrl = newUrl.replace(/#.+$/, '');
        oldUrl = oldUrl.replace(/#.+$/, '');
        // url has changed
        if (newUrl !== oldUrl) {
            if (newUrl.indexOf('/search') == -1) {
                // a non-search url, load that page
                $timeout(function() {
                    // wrapping in $timeout to avoid "digest in progress" errors
                    $window.location = newUrl;
                });
            } else {
                // the new url is a search result page, launch that search
                $scope.query.text = $location.search().q;
                results.search($location.search().q);
                $scope.query.submitted = false;
            }
        }
    });

    /**
     * Called when the form is submitted.
     */
    $scope.submit_query = function() {
        $scope.query.submitted = true;
        if ($scope.queryForm.text.$invalid) {
            return;
        }
        $scope.meta_search($scope.query.text);
    };

    /**
     * Check if the url contains a query when the controller is first created
     * and initiate a search if necessary.
     */
    (function () {
        if ($location.url().indexOf("/search?q=") > -1) {
            // a search result page, launch a new search
            $scope.query.text = $location.search().q;
            results.search($location.search().q);
        }
    })();

}]);
<commit_msg>Do not add wildcards to grouping parentheses in metasearch<commit_after>/*
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * RNAcentral metadata search Angular.js app.
 */

; // concatenation safeguard

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function() {
    return window._;
});

/**
 * Create RNAcentral app.
 */
var rnaMetasearch = angular.module('rnacentralApp', ['chieffancypants.loadingBar', 'underscore', 'ngAnimate']);

// hide spinning wheel
rnaMetasearch.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeSpinner = false;
}]);

/**
 * html5mode removes hashtags from urls.
 */
rnaMetasearch.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

/**
 * Service for launching a metadata search.
 */
rnaMetasearch.service('search', ['$location', function($location) {

    /**
     * To launch a new search, change browser url,
     * which will automatically trigger a new search
     * since the url changes are watched in the query controller.
     */
    this.meta_search = function(query) {
        $location.url('/search' + '?q=' + query);
    };

}]);

/**
 * Service for passing data between controllers.
 */
rnaMetasearch.service('results', ['_', '$http', '$location', '$window', function(_, $http, $location, $window) {

    /**
     * Service initialization.
     */
    var result = {
        hitCount: null,
        entries: [],
        facets: [],
    };

    var status = {
        display_search_interface: false, // hide results section at first
        search_in_progress: false, // display spinning wheel while searching
        show_error: false, // display error message
    };

    var search_config = {
        ebeye_base_url: 'http://wwwdev.ebi.ac.uk/ebisearch/ws/rest/rnacentral',
        rnacentral_base_url: get_base_url(),
        fields: ['description', 'active', 'length'],
        facetfields: ['expert_db', 'rna_type', 'TAXONOMY'], // will be displayed in this order
        facetcount: 30,
        pagesize: 15,
    };

    var query_urls = {
        'ebeye_search': search_config.ebeye_base_url +
                        '?query={QUERY}' +
                        '&format=json' +
                        '&fields=' + search_config.fields.join() +
                        '&facetcount=' + search_config.facetcount +
                        '&facetfields=' + search_config.facetfields.join() +
                        '&size=' + search_config.pagesize +
                        '&start={START}',
        'proxy': search_config.rnacentral_base_url +
                 '/api/internal/ebeye?url={EBEYE_URL}',
    };

    /**
     * Calculate base url for production and development environments.
     */
    function get_base_url() {
        var base_url = $location.protocol() + '://' + $location.host();
        var port = $location.port();
        if (port !== '') {
            base_url += ':' + port
        }
        return base_url;
    }

    /**
     * Launch EBeye search.
     * `start` determines the range of the results to be returned.
     */
    this.search = function(query, start) {
        start = start || 0;

        display_search_interface();
        display_spinner();
        update_page_title();

        query = preprocess_query(query);
        query_url = get_query_url(query, start);
        execute_ebeye_search(query_url, start === 0);

        /**
         * Display search spinner if not a "load more" request.
         */
        function display_spinner() {
            if (start === 0) {
                result.hitCount = null; // display spinner
            }
        }

        /**
         * Change page title, which is also used in browser tabs.
         */
        function update_page_title() {
            $window.document.title = 'Search: ' + query;
        }

        /**
         * Setting `display_search_interface` value to true hides all non-search page content
         * and begins displaying search results interface.
         */
        function display_search_interface() {
            status.display_search_interface = true;
        }

        /**
         * Create an RNAcentral proxy query url which includes EBeye query url.
         */
        function get_query_url() {
            var ebeye_url = query_urls.ebeye_search.replace('{QUERY}', query).replace('{START}', start);
            var url = query_urls.proxy.replace('{EBEYE_URL}', encodeURIComponent(ebeye_url));
            return url;
        }

        /**
         * Split query into words and then:
         *  - append wildcards to all terms without double quotes and not ending with wildcards
         *  - escape special symbols
         *  - capitalize logical operators
         *
         *  Splitting into words is based on this SO question:
         *  http://stackoverflow.com/questions/366202/regex-for-splitting-a-string-using-space-when-not-surrounded-by-single-or-double
         * Each "word" is a sequence of characters that aren't spaces or quotes,
         * or a sequence of characters that begin and end with a quote, with no quotes in between.
         */
        function preprocess_query(query) {
            var words = query.match(/[^\s"]+|"[^"]*"/g);
            var array_length = words.length;
            for (var i = 0; i < array_length; i++) {
                if ( words[i].match(/and|or|not/gi) ) {
                    // capitalize logical operators
                    words[i] = words[i].toUpperCase();
                } else if ( words[i].match(/\:$/gi) ) {
                    // faceted search term, do nothing
                } else if ( words[i].match(/^".+?"$/) ) {
                    // double quotes, do nothing
                } else if ( words[i].match(/\*$/) ) {
                    // wildcard, escape term
                    words[i] = escape_search_term(words[i]);
                } else if ( words[i].match(/\)$/) ) {
                    // right closing grouping parenthesis, don't add a wildcard
                } else {
                    // all other words
                    // escape term, add wildcard
                    words[i] = escape_search_term(words[i]) + '*';
                };
            }
            query = words.join(' ');
            return query;

            /**
             * Escape special symbols used by Lucene
             * Escaped: + - && || ! { } [ ] ^ ~ ? : \
             * Not escaped: * " ( ) because they may be used deliberately by the user
             */
            function escape_search_term(search_term) {
                return search_term.replace(/[\+\-&|!\{\}\[\]\^~\?\:\\]/g, "\\$&");
            }
        }

        /**
         * Execute remote request.
         */
        function execute_ebeye_search(url, overwrite_results) {
            status.search_in_progress = true;
            status.show_error = false;
            $http({
                url: url,
                method: 'GET'
            }).success(function(data) {
                data = preprocess_results(data);
                overwrite_results = overwrite_results || false;
                if (overwrite_results) {
                    result = data; // replace
                } else {
                    // append only entries
                    result.entries = result.entries.concat(data.entries);
                }
                status.search_in_progress = false;
            }).error(function(){
                status.search_in_progress = false;
                status.show_error = true;
            });

            /**
             * Preprocess data received from the server.
             */
            function preprocess_results(data) {
                // sort facets the same way as in config
                _.sortBy(data.facets, function(facet){
                    return _.indexOf(search_config.facetfields, facet.id);
                });
                return data;
            }
        }

    }

    /**
     * Load more results starting from the last loaded index.
     */
    this.load_more_results = function() {
        query = $location.search().q;
        this.search(query, result.entries.length);
    };

    /**
     * Broadcast whether search interface should be displayed.
     */
    this.get_status = function() {
        return status.display_search_interface;
    };

    /**
     * Broadcast search results changes.
     */
    this.get_result = function() {
        return result;
    };

    /**
     * Broadcast whether search is in progress.
     */
    this.get_search_in_progress = function() {
        return status.search_in_progress;
    };

    /**
     * Broadcast whether an error has occurred.
     */
    this.get_show_error = function() {
        return status.show_error;
    };

}]);

rnaMetasearch.controller('MainContent', ['$scope', '$anchorScroll', '$location', 'results', 'search', function($scope, $anchorScroll, $location, results, search) {
    /**
     * Enables scrolling to anchor tags.
     * Title
     */
    $scope.scrollTo = function(id) {
        $location.hash(id);
        $anchorScroll();
    };

    /**
     * Watch `display_search_interface` in order to hide non-search-related content
     * when a search is initiated.
     */
    $scope.$watch(function () { return results.get_status(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.display_search_interface = newValue;
        }
    });

    /**
     * Launch a metadata search from a web page.
     */
    $scope.meta_search = function(query) {
        search.meta_search(query);
    };

}]);

/**
 * Results display controller
 * Responsible for visualising search results.
 */
rnaMetasearch.controller('ResultsListCtrl', ['$scope', '$location', 'results', function($scope, $location, results) {

    $scope.result = {
        entries: [],
    };

    $scope.search_in_progress = results.get_search_in_progress();
    $scope.show_error = results.get_show_error();

    /**
     * Watch `result` changes.
     */
    $scope.$watch(function () { return results.get_result(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.result = newValue;
        }
    });

    /**
     * Watch `display_search_interface` changes.
     */
    $scope.$watch(function () { return results.get_status(); }, function (newValue, oldValue) {
        if (newValue != null) {
            $scope.display_search_interface = newValue;
        }
    });

    /**
     * Watch `search_in_progress` changes.
     */
    $scope.$watch(function () { return results.get_search_in_progress(); }, function (newValue, oldValue) {
        if (newValue != oldValue) {
            $scope.search_in_progress = newValue;
        }
    });

    /**
     * Watch `show_error` changes.
     */
    $scope.$watch(function () { return results.get_show_error(); }, function (newValue, oldValue) {
        if (newValue != oldValue) {
            $scope.show_error = newValue;
        }
    });

    /**
     * Fired when "Load more" button is clicked.
     */
    $scope.load_more_results = function() {
        results.load_more_results();
    };

    /**
     * Determine if the facet has already been applied.
     */
    $scope.is_facet_applied = function(facet_id, facet_value) {
        var query = $location.search().q || '';
        var facet_query = facet_id + ':"' + facet_value + '"';
        if (query.indexOf(facet_query) == -1) {
            return false;
        } else {
            return true;
        }
    };

    /**
     * Run a search with a facet enabled.
     * The facet will be toggled on and off in the repeated calls with the same
     * parameters.
     */
    $scope.facet_search = function(facet_id, facet_value) {
        var query = $location.search().q || '';
        var facet_query = ' AND ' + facet_id + ':"' + facet_value + '"';
        if ($scope.is_facet_applied(facet_id, facet_value)) {
            new_query = query.replace(facet_query, ''); // remove facet
        } else {
            new_query = query + facet_query; // add new facet
        }
        $location.search('q', new_query);
    };

    /**
     * Show/hide search facets to save screen space.
     * Uses jQuery for simplicity.
     * Activated only on mobile devices.
     */
    $scope.toggle_facets = function() {
        var facets = $('.metasearch-facets');
        facets.toggleClass('hidden-xs', !facets.hasClass('hidden-xs'));
        $('#toggle-facets').text(function(i, text){
          return text === "Show facets" ? "Hide facets" : "Show facets";
        });
    };

}]);

/**
 * Query controller
 * Responsible for the search box in the header.
 */
rnaMetasearch.controller('QueryCtrl', ['$scope', '$location', '$window', '$timeout', 'results', 'search', function($scope, $location, $window, $timeout, results, search) {

    $scope.query = {
        text: '',
        submitted: false
    };

    /**
     * Launch a metadata search using the service.
     */
    $scope.meta_search = function(query) {
        search.meta_search(query);
    };

    /**
     * Control browser navigation buttons.
     */
    $scope.$watch(function () { return $location.url(); }, function (newUrl, oldUrl) {
        // ignore url hash
        newUrl = newUrl.replace(/#.+$/, '');
        oldUrl = oldUrl.replace(/#.+$/, '');
        // url has changed
        if (newUrl !== oldUrl) {
            if (newUrl.indexOf('/search') == -1) {
                // a non-search url, load that page
                $timeout(function() {
                    // wrapping in $timeout to avoid "digest in progress" errors
                    $window.location = newUrl;
                });
            } else {
                // the new url is a search result page, launch that search
                $scope.query.text = $location.search().q;
                results.search($location.search().q);
                $scope.query.submitted = false;
            }
        }
    });

    /**
     * Called when the form is submitted.
     */
    $scope.submit_query = function() {
        $scope.query.submitted = true;
        if ($scope.queryForm.text.$invalid) {
            return;
        }
        $scope.meta_search($scope.query.text);
    };

    /**
     * Check if the url contains a query when the controller is first created
     * and initiate a search if necessary.
     */
    (function () {
        if ($location.url().indexOf("/search?q=") > -1) {
            // a search result page, launch a new search
            $scope.query.text = $location.search().q;
            results.search($location.search().q);
        }
    })();

}]);
<|endoftext|>


<commit_before>var app = require('../app');
var chai = require('chai');
var request = require('supertest');
var HttpStatus = require('http-status-codes');
var expect = chai.expect;

const common = require('../common/config');
const config = common.config();

const superagent = require('superagent');

describe('Secured Public API Tests', function () {

  let bearerToken;
  const ratingTestUserId = config.integration_tests.test_user_id;
  const baseApiUrl = '/api/secured/public/codingmarks/';

  before(function(done) {
    superagent
      .post(config.integration_tests.token_endpoint)
      .send('client_id=' + config.integration_tests.client_id)
      .send('client_secret=' + config.integration_tests.client_secret)
      .send('grant_type=client_credentials')
      .set('Accept', 'application/json')
      .then(res => {
        bearerToken = 'Bearer ' + res.body.access_token;
        done();
      });

  });

  describe('patch codingmark tests', function () {
    let codingmarkUnderTest;

    before(function(done) {
      superagent
        .get('http://localhost:3000/api/public/codingmarks')
        .query({location: 'https://www.codingmarks.org'})
        .set('Accept', 'application/json')
        .then(res => {
            codingmarkUnderTest = res.body;
            done();
        });

    });

    it('should fail trying to rate with invalid userId', function (done) {

      request(app)
        .patch(baseApiUrl + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: 'blablabla'})
        .end(function (err, res) {
          console.log(res.statusCode);
          expect(res.statusCode).to.equal(HttpStatus.UNAUTHORIZED);
          done();
        });
    });

    it('should fail trying to rate with invalid patching action', function (done) {
      request(app)
        .patch(baseApiUrl + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'STARR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.BAD_REQUEST);
          done();
        });
    });

    it('should fail trying to rate (STAR) a non-existing codingmark', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrl + inexistentCodingmarkId)
        .set('Authorization', bearerToken)
        .send({action: 'STAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.NOT_FOUND);
          done();
        });
    });

    it('should fail trying to rate (UNSTAR) a non-existing codingmark', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrl + inexistentCodingmarkId)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.NOT_FOUND);
          done();
        });
    });

    it('should fail trying to rate with incomplete request attributes - action', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrl + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.BAD_REQUEST);
          done();
        });
    });

    it('should star codingmark ', function (done) {
      request(app)
        .patch(baseApiUrl + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'STAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.OK);
          request(app)
            .get('/api/public/codingmarks/' + codingmarkUnderTest._id)
            .end(function (err, res) {
              expect(res.statusCode).to.equal(HttpStatus.OK);
              expect(res.body.starredBy).to.be.an('array').that.does.include(ratingTestUserId);
              done();
            });
        });
    });

    it('should unstar codingmark ', function (done) {
      request(app)
        .patch(baseApiUrl + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.OK);
          request(app)
            .get('/api/public/codingmarks/' + codingmarkUnderTest._id)
            .end(function (err, res) {
              expect(res.statusCode).to.equal(HttpStatus.OK);
              expect(res.body.starredBy).to.be.an('array').that.does.not.include(ratingTestUserId);
              done();
            });
        });
    });

  });

});
<commit_msg>rename some variables to make the testing even clearer<commit_after>var app = require('../app');
var chai = require('chai');
var request = require('supertest');
var HttpStatus = require('http-status-codes');
var expect = chai.expect;

const common = require('../common/config');
const config = common.config();

const superagent = require('superagent');

describe('Secured Public API Tests', function () {

  let bearerToken;
  const ratingTestUserId = config.integration_tests.test_user_id;
  const baseApiUrlUnderTest = '/api/secured/public/codingmarks/';

  before(function(done) {
    superagent
      .post(config.integration_tests.token_endpoint)
      .send('client_id=' + config.integration_tests.client_id)
      .send('client_secret=' + config.integration_tests.client_secret)
      .send('grant_type=client_credentials')
      .set('Accept', 'application/json')
      .then(res => {
        bearerToken = 'Bearer ' + res.body.access_token;
        done();
      });

  });

  describe('patch codingmark tests', function () {
    let codingmarkUnderTest;

    before(function(done) {
      superagent
        .get(config.basicApiUrl + 'public/codingmarks')
        .query({location: 'https://www.codingmarks.org'})
        .set('Accept', 'application/json')
        .then(res => {
            codingmarkUnderTest = res.body;
            done();
        });

    });

    it('should fail trying to rate with invalid userId', function (done) {

      request(app)
        .patch(baseApiUrlUnderTest + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: 'blablabla'})
        .end(function (err, res) {
          console.log(res.statusCode);
          expect(res.statusCode).to.equal(HttpStatus.UNAUTHORIZED);
          done();
        });
    });

    it('should fail trying to rate with invalid patching action', function (done) {
      request(app)
        .patch(baseApiUrlUnderTest + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'STARR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.BAD_REQUEST);
          done();
        });
    });

    it('should fail trying to rate (STAR) a non-existing codingmark', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrlUnderTest + inexistentCodingmarkId)
        .set('Authorization', bearerToken)
        .send({action: 'STAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.NOT_FOUND);
          done();
        });
    });

    it('should fail trying to rate (UNSTAR) a non-existing codingmark', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrlUnderTest + inexistentCodingmarkId)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.NOT_FOUND);
          done();
        });
    });

    it('should fail trying to rate with incomplete request attributes - action', function (done) {
      const inexistentCodingmarkId = '507f191e810c19729de860aa';
      request(app)
        .patch(baseApiUrlUnderTest + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.BAD_REQUEST);
          done();
        });
    });

    it('should star codingmark ', function (done) {
      request(app)
        .patch(baseApiUrlUnderTest + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'STAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.OK);
          request(app)
            .get('/api/public/codingmarks/' + codingmarkUnderTest._id)
            .end(function (err, res) {
              expect(res.statusCode).to.equal(HttpStatus.OK);
              expect(res.body.starredBy).to.be.an('array').that.does.include(ratingTestUserId);
              done();
            });
        });
    });

    it('should unstar codingmark ', function (done) {
      request(app)
        .patch(baseApiUrlUnderTest + codingmarkUnderTest._id)
        .set('Authorization', bearerToken)
        .send({action: 'UNSTAR'})
        .send({ratingUserId: ratingTestUserId})
        .end(function (err, res) {
          expect(res.statusCode).to.equal(HttpStatus.OK);
          request(app)
            .get('/api/public/codingmarks/' + codingmarkUnderTest._id)
            .end(function (err, res) {
              expect(res.statusCode).to.equal(HttpStatus.OK);
              expect(res.body.starredBy).to.be.an('array').that.does.not.include(ratingTestUserId);
              done();
            });
        });
    });

  });

});
<|endoftext|>