<commit_before>import React from 'react';

import { mount } from 'enzyme';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';

import Markdown from 'src/components/markdown';

chai.use(chaiEnzyme()); // Note the invocation at the end
const expect = chai.expect;

describe('Enriched Markdown', () => {
  it('should return an empty div', () => {
    const md = '';

    const comp = mount(<Markdown text={md} />);
    expect(comp).to.have.tagName('div');
    expect(comp).to.have.className('Markdown');
  });

  it('should have a heading', () => {
    const md = '# Heading';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > h1')).to.be.present();
  });

  it('should render a simple paragraph', () => {
    const md = 'Some text';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('Some text');
  });

  it('should render emphasized text', () => {
    const md = '*bold* is nice';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('bold is nice');
    expect(comp.find('div > p').find('em')).to.be.present();
    expect(comp.find('div > p').find('em')).to.have.text('bold');
  });

  it('should render emphasized title', () => {
    const md = '## test of *bold* title';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > h2')).to.be.present();
    expect(comp.find('div > h2').find('em')).to.be.present();
  });

  it('should render inline code', () => {
    const md = 'some inline `code`';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('some inline code');
    expect(comp.find('div > p').find('code')).to.be.present();
    expect(comp.find('div > p').find('code')).to.have.text('code');
  });

  it('should render inline math', () => {
    const md = 'some inline `!\delta`';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    // expect(comp.find('div > p')).to.match('some inline');
    expect(comp.find('div > p').find('code')).to.not.be.present();
  });
});
<commit_msg>repair tests<commit_after>import React from 'react';

import { mount } from 'enzyme';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';

import Markdown from 'src/components/markdown';

chai.use(chaiEnzyme()); // Note the invocation at the end
const expect = chai.expect;

describe('Enriched Markdown', () => {
  it('should return an empty div', () => {
    const md = '';

    const comp = mount(<Markdown text={md} />);
    expect(comp).to.have.tagName('div');
    expect(comp).to.have.className('Markdown');
  });

  it('should have a heading', () => {
    const md = '# Heading';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > h1')).to.be.present();
  });

  it('should render a simple paragraph', () => {
    const md = 'Some text';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('Some text');
  });

  it('should render emphasized text', () => {
    const md = '*bold* is nice';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('bold is nice');
    expect(comp.find('div > p').find('em')).to.be.present();
    expect(comp.find('div > p').find('em')).to.have.text('bold');
  });

  it('should render emphasized title', () => {
    const md = '## test of *bold* title';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > h2')).to.be.present();
    expect(comp.find('div > h2').find('em')).to.be.present();
  });

  it('should render inline code', () => {
    const md = 'some inline `code`';

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    expect(comp.find('div > p')).to.have.text('some inline code');
    expect(comp.find('div > p').find('code')).to.be.present();
    expect(comp.find('div > p').find('code')).to.have.text('code');
  });

  it('should render inline math', () => {
    const md = 'some inline $\delta$'; // eslint-disable-line no-useless-escape

    const comp = mount(<Markdown text={md} />);
    expect(comp.find('div > p')).to.be.present();
    // expect(comp.find('div > p')).to.match('some inline');
    expect(comp.find('div > p').find('code')).to.not.be.present();
  });
});
<|endoftext|>


<commit_before>function Editable(el) {
  this.$el = $(el);
  this.$inputContainer = $('<li/>', {'class': 'tag new'});
  this.$input = $('<input/>', {type: 'text'});
  this.$inputContainer.append(this.$input);

  this.$input.keyup(function(e) {
    var text = this.$input.val();
    if(e.keyCode === 13 && text !== '') {
      this.appendNew(text);
      this.$input.val('');
    }
    if(e.keyCode === 8 && text === '') {
      this.removeLast();
    }
  }.bind(this));

  this.$el.click(function() {
    this.$input.focus();
    return false;
  }.bind(this));

  this.$el.append(this.$inputContainer);
}

Editable.prototype = {

  appendNew: function appendNew(text) {
    var old = $('<li/>', {'class': 'tag old'}, text);
    old.html(text);
    old.insertBefore(this.$inputContainer);
  },

  removeLast: function removeLast() {
    this.$inputContainer.prev().remove();
  },

  serialize: function serialize() {
    return [].map.call(this.$el.find('.old'), function(el) {
      return el.innerText.trim();
    });
  }
};

$.fn.editable = function editable() {
  return this.map(function(index, element) {
    new Editable(element);
  });
};<commit_msg>Refactoring<commit_after>function Editable(el, options) {
  this.$el = $(el);
  this.options = options;

  this.$inputContainer = $('<li/>', {'class': 'tag new'});
  this.$input = $('<input/>', {type: 'text'});

  this.$input.keyup(function(e) {
    var text = this.$input.val();
    if(e.keyCode === 13 && text !== '') {
      this.appendNew(text);
      this.$input.val('');
    }
    if(e.keyCode === 8 && text === '') {
      this.removeLast();
    }
  }.bind(this));

  this.$el.click(function() {
    this.$input.focus();
    return false;
  }.bind(this));

  this.$inputContainer.append(this.$input);
  this.$el.append(this.$inputContainer);
}

Editable.prototype = {

  appendNew: function appendNew(text, attributes) {
    var old = $('<li/>', _.extend({'class': 'tag old', text: text}, attributes));
    old.insertBefore(this.$inputContainer);
  },

  removeLast: function removeLast() {
    this.$inputContainer.prev().remove();
  },

  serialize: function serialize() {
    return [].map.call(this.$el.find('.old'), function(el) {
      return el.innerText.trim();
    });
  }
};

$.fn.editable = function editable(options) {
  return new Editable(this, options);
};<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

//import models
var stock = require('../models/stocks');
var article = require('../models/articles');

/* GET article page. */
router.post('/stocks', function(request, response) {
	console.log('render stocks page');
	var userQuery = request.body;
	userQuery.userQueryInput = userQuery.userQueryInput.toUpperCase();
	console.log(userQuery.userQueryInput);
	console.log(userQuery.userQueryInput.charCodeAt(0));

	if ((userQuery.userQueryInput.charCodeAt(0)>=48)&&(userQuery.userQueryInput.charCodeAt(0)<=57)){				//is id search

	//var userInput = localStorage.getItem("stockId");
	var stockQuery = stock.findOne({ id: userQuery.userQueryInput },"name id articles abbr",function (err, result) {
	if (err) // handle this
		console.log("can't find stock in database");

	console.log('inside query');

	var articleQuery = article.find({stock_uid: userQuery.userQueryInput},"author_name title href date likes",function (err, articleResult) {
	if (err) // handle this
		console.log("can't find article in database");

	if (result == null){

	response.render('pages/error',userQuery.userQueryInput);

	}
	else
	{
	var stockVariables = {
		name: result.name,
		id :result.id,
		articles:articleResult
	};

	response.render('pages/stocks',stockVariables);
	}
	});

	});
	}
	else if ((userQuery.userQueryInput.charCodeAt(0)>=65)&&(userQuery.userQueryInput.charCodeAt(0)<=90)){		//is abbr search

	var stockQuery = stock.findOne({ abbr: userQuery.userQueryInput },"name id articles abbr",function (err, result) {
	if (err) // handle this
		console.log("can't find stock in database");

	var articleQuery = article.find({stock_abbr: userQuery.userQueryInput},"author_name title href date likes",function (err, articleResult) {
	if (err) // handle this
		console.log("can't find article in database");

	if (result == null){

	response.render('pages/error',userQuery.userQueryInput);

	}

	else
	{
	var stockVariables = {
		name: result.name,
		id :result.id,
		abbr : result.abbr,
		articles:articleResult
	};

	response.render('pages/stocks',stockVariables);
	}
	});

	});
	}
	else{
		response.render('pages/error',userQuery.userQueryInput);
	}

});

module.exports = router;
<commit_msg>test input<commit_after>var express = require('express');
var router = express.Router();

//import models
var stock = require('../models/stocks');
var article = require('../models/articles');

/* GET article page. */
router.post('/stocks', function(request, response) {
	console.log('render stocks page');
	var userQuery = request.body;
	userQuery.userQueryInput = userQuery.userQueryInput.toUpperCase();
	console.log(userQuery.userQueryInput);
	console.log(userQuery.userQueryInput.charCodeAt(0));
	console.log((userQuery.userQueryInput.charCodeAt(0)>=48)&&(userQuery.userQueryInput.charCodeAt(0)<=57));

	if ((userQuery.userQueryInput.charCodeAt(0)>=48)&&(userQuery.userQueryInput.charCodeAt(0)<=57)){				//is id search

	//var userInput = localStorage.getItem("stockId");
	var stockQuery = stock.findOne({ id: userQuery.userQueryInput },"name id articles abbr",function (err, result) {
	if (err) // handle this
		console.log("can't find stock in database");

	console.log('inside query');

	var articleQuery = article.find({stock_uid: userQuery.userQueryInput},"author_name title href date likes",function (err, articleResult) {
	if (err) // handle this
		console.log("can't find article in database");

	if (result == null){

	response.render('pages/error',userQuery.userQueryInput);

	}
	else
	{
	var stockVariables = {
		name: result.name,
		id :result.id,
		articles:articleResult
	};

	response.render('pages/stocks',stockVariables);
	}
	});

	});
	}
	else if ((userQuery.userQueryInput.charCodeAt(0)>=65)&&(userQuery.userQueryInput.charCodeAt(0)<=90)){		//is abbr search

	var stockQuery = stock.findOne({ abbr: userQuery.userQueryInput },"name id articles abbr",function (err, result) {
	if (err) // handle this
		console.log("can't find stock in database");

	var articleQuery = article.find({stock_abbr: userQuery.userQueryInput},"author_name title href date likes",function (err, articleResult) {
	if (err) // handle this
		console.log("can't find article in database");

	if (result == null){

	response.render('pages/error',userQuery.userQueryInput);

	}

	else
	{
	var stockVariables = {
		name: result.name,
		id :result.id,
		abbr : result.abbr,
		articles:articleResult
	};

	response.render('pages/stocks',stockVariables);
	}
	});

	});
	}
	else{
		response.render('pages/error',userQuery.userQueryInput);
	}

});

module.exports = router;
<|endoftext|>


<commit_before>/**
 * Talisman stats/descriptive
 * ===========================
 *
 * The library's descriptive stats helpers.
 */

/**
 * Function computing the sum of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The sum.
 */
export function sum(sequence) {
  let s = 0;

  for (let i = 0, l = sequence.length; i < l; i++)
    s += sequence[i];

  return s;
}

/**
 * Function computing the mean of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The mean.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function mean(sequence) {
  const length = sequence.length;

  if (!length)
    throw Error('talisman/stats/descriptive#mean: the given list is empty.');

  return sum(sequence) / length;
}

/**
 * Function adding a value to the given mean in constant time.
 *
 * @param  {number}  previousMean - The mean to adjust.
 * @param  {number}  nbValues     - The number of values in the given mean.
 * @param  {number}  value        - The value to add.
 * @return {number}               - The mean.
 */
export function addToMean(previousMean, nbValues, value) {
  return previousMean + ((value - previousMean) / (nbValues + 1));
}

/**
 * Function substracting a value from the given mean in constant time.
 *
 * @param  {number}  previousMean - The mean to adjust.
 * @param  {number}  nbValues     - The number of values in the given mean.
 * @param  {number}  value        - The value to substract.
 * @return {number}               - The mean.
 */
export function substractFromMean(previousMean, nbValues, value) {
  return ((previousMean * nbValues) - value) / (nbValues - 1);
}

/**
 * Function combining two means into one in constant time.
 *
 * @param  {number} ma - The first mean.
 * @param  {number} na - Number of values for a.
 * @param  {number} mb - The second mean.
 * @param  {number} nb - Number of values for b.
 * @return {number}    - The new mean.
 */
export function combineMeans(ma, na, mb, nb) {
  return (ma * na + mb * nb) / (na + nb);
}

/**
 * Function finding the mode of the given sequence.
 *
 * Note: If there are more than one mode, will return the first one seen.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The sequence's mode.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function mode(sequence) {
  if (!sequence.length)
    throw Error('talisman/stats/descriptive#modeSorted: the given list is empty.');

  // Shortcut
  if (sequence.length === 1)
    return sequence[0];

  let currentMode = null,
      max = 0;

  const frequencies = {};

  for (let i = 0, l = sequence.length; i < l; i++) {
    const number = sequence[i];

    frequencies[number] = frequencies[number] || 0;
    const frequency = ++frequencies[number];

    if (frequency > max) {
      max = frequency;
      currentMode = number;
    }
  }

  return currentMode;
}

/**
 * Function computing the variance of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The variance.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function variance(sequence) {
  const length = sequence.length;

  if (!length)
    throw Error('talisman/stats/descriptive#variance: the given list is empty.');

  const m = mean(sequence);

  let s = 0;

  for (let i = 0; i < length; i++)
    s += Math.pow(sequence[i] - m, 2);

  return s / length;
}

/**
 * Function computing the standard deviation of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The standard deviation.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function stdev(sequence) {
  const v = variance(sequence);

  return Math.sqrt(v);
}

/**
 * Function combining two variances into one in constant time.
 *
 * @param  {number} ma - The first mean.
 * @param  {number} va - The first variance.
 * @param  {number} na - Number of values for a.
 * @param  {number} mb - The second mean.
 * @param  {number} vb - The second variance.
 * @param  {number} nb - Number of values for b.
 * @return {number}    - The new mean.
 */
export function combineVariances(ma, va, na, mb, vb, nb) {
  const combinedMean = combineMeans(ma, na, mb, nb);

  return (
    na * (va + Math.pow(ma - combinedMean, 2)) +
    nb * (vb + Math.pow(mb - combinedMean, 2))
  ) / (na + nb);
}
<commit_msg>Improving sum function<commit_after>/**
 * Talisman stats/descriptive
 * ===========================
 *
 * The library's descriptive stats helpers.
 */

/**
 * Function computing the sum of the given sequence, while correcting floating
 * point errors.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The sum.
 */
export function sum(sequence) {
  let compensation = 0,
      s = 0;

  for (let i = 0, l = sequence.length; i < l; i++) {
    const correctedValue = sequence[i] - compensation,
          next = s + correctedValue;

    compensation = next - s - correctedValue;

    s = next;
  }

  return s;
}

/**
 * Function computing the mean of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The mean.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function mean(sequence) {
  const length = sequence.length;

  if (!length)
    throw Error('talisman/stats/descriptive#mean: the given list is empty.');

  return sum(sequence) / length;
}

/**
 * Function adding a value to the given mean in constant time.
 *
 * @param  {number}  previousMean - The mean to adjust.
 * @param  {number}  nbValues     - The number of values in the given mean.
 * @param  {number}  value        - The value to add.
 * @return {number}               - The mean.
 */
export function addToMean(previousMean, nbValues, value) {
  return previousMean + ((value - previousMean) / (nbValues + 1));
}

/**
 * Function substracting a value from the given mean in constant time.
 *
 * @param  {number}  previousMean - The mean to adjust.
 * @param  {number}  nbValues     - The number of values in the given mean.
 * @param  {number}  value        - The value to substract.
 * @return {number}               - The mean.
 */
export function substractFromMean(previousMean, nbValues, value) {
  return ((previousMean * nbValues) - value) / (nbValues - 1);
}

/**
 * Function combining two means into one in constant time.
 *
 * @param  {number} ma - The first mean.
 * @param  {number} na - Number of values for a.
 * @param  {number} mb - The second mean.
 * @param  {number} nb - Number of values for b.
 * @return {number}    - The new mean.
 */
export function combineMeans(ma, na, mb, nb) {
  return (ma * na + mb * nb) / (na + nb);
}

/**
 * Function finding the mode of the given sequence.
 *
 * Note: If there are more than one mode, will return the first one seen.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The sequence's mode.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function mode(sequence) {
  if (!sequence.length)
    throw Error('talisman/stats/descriptive#modeSorted: the given list is empty.');

  // Shortcut
  if (sequence.length === 1)
    return sequence[0];

  let currentMode = null,
      max = 0;

  const frequencies = {};

  for (let i = 0, l = sequence.length; i < l; i++) {
    const number = sequence[i];

    frequencies[number] = frequencies[number] || 0;
    const frequency = ++frequencies[number];

    if (frequency > max) {
      max = frequency;
      currentMode = number;
    }
  }

  return currentMode;
}

/**
 * Function computing the variance of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The variance.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function variance(sequence) {
  const length = sequence.length;

  if (!length)
    throw Error('talisman/stats/descriptive#variance: the given list is empty.');

  const m = mean(sequence);

  let s = 0;

  for (let i = 0; i < length; i++)
    s += Math.pow(sequence[i] - m, 2);

  return s / length;
}

/**
 * Function computing the standard deviation of the given sequence.
 *
 * @param  {array}  sequence - The sequence to process.
 * @return {number}          - The standard deviation.
 *
 * @throws {Error} - The function expects a non-empty list.
 */
export function stdev(sequence) {
  const v = variance(sequence);

  return Math.sqrt(v);
}

/**
 * Function combining two variances into one in constant time.
 *
 * @param  {number} ma - The first mean.
 * @param  {number} va - The first variance.
 * @param  {number} na - Number of values for a.
 * @param  {number} mb - The second mean.
 * @param  {number} vb - The second variance.
 * @param  {number} nb - Number of values for b.
 * @return {number}    - The new mean.
 */
export function combineVariances(ma, va, na, mb, vb, nb) {
  const combinedMean = combineMeans(ma, na, mb, nb);

  return (
    na * (va + Math.pow(ma - combinedMean, 2)) +
    nb * (vb + Math.pow(mb - combinedMean, 2))
  ) / (na + nb);
}
<|endoftext|>


<commit_before>function runTest()
{
    FBTest.setPref("preferJSDSourceLinks", true);
    FBTest.openNewTab(basePath + "console/4658/issue4658.html", function(win)
    {
        FBTest.enablePanels(["console", "script"], function(win)
        {
            var config = {tagName: "div", classes: "logRow logRow-debug"};
            FBTest.waitForDisplayedElement("console", config, function(row)
            {
                var expected = new RegExp("FirebugBug\\s*" + FW.FBL.$STRF("Line",
                    ["clickedFirebugBug.js", 6]).replace(/([\\"'\(\)])/g, "\\$1"));

                FBTest.compare(expected, row.textContent,
                    "The proper message must be displayed.");

                FBTest.testDone(;
            });

            FBTest.clickContentButton(win, "testButton");
        });
    });
}
<commit_msg>Fix FBTest console/4658/issue4658.js (syntax error)<commit_after>function runTest()
{
    FBTest.setPref("preferJSDSourceLinks", true);
    FBTest.openNewTab(basePath + "console/4658/issue4658.html", function(win)
    {
        FBTest.enablePanels(["console", "script"], function(win)
        {
            var config = {tagName: "div", classes: "logRow logRow-debug"};
            FBTest.waitForDisplayedElement("console", config, function(row)
            {
                var expected = new RegExp("FirebugBug\\s*" + FW.FBL.$STRF("Line",
                    ["clickedFirebugBug.js", 6]).replace(/([\\"'\(\)])/g, "\\$1"));

                FBTest.compare(expected, row.textContent,
                    "The proper message must be displayed.");

                FBTest.testDone("issue4658.DONE");
            });

            FBTest.clickContentButton(win, "testButton");
        });
    });
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $("#buttonLoginLayoutFront").fancybox();

    $.chartsVar = new Object();

    if($('#ajaxUrl').val())
    {
        $.post($('#ajaxUrl').val() + 'ajaxPresence')
            .done(function( data ) {
                $.chartsVar.Dez  = data.Dez;
                $.chartsVar.Bank = data.Bank;
                $.chartsVar.spe1 = data.spe1;
                $.chartsVar.spe2 = data.spe2;
                $.chartsVar.spe3 = data.spe3;
                $.chartsVar.spe4 = data.spe4;
            })
            .fail(function() {
                $.chartsVar.Dez  = 0;
                $.chartsVar.Bank = 0;
                $.chartsVar.spe1 = 0;
                $.chartsVar.spe2 = 0;
                $.chartsVar.spe3 = 0;
                $.chartsVar.spe4 = 0;
        });
    }

    // charts
    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['loot', '%'],
          ['Dez',     $.chartsVar.Dez],
          ['Bank',    $.chartsVar.Bank],
          ['Spe 1',   $.chartsVar.spe1],
          ['Spe 2',   $.chartsVar.spe2],
          ['Spe 3',   $.chartsVar.spe3],
          ['Spe 4',   $.chartsVar.spe4],
        ]);

        var options = {
          backgroundColor: { fill:'transparent' },
          chartArea:{left:2,top:2,width:'100%',height:'100%'},
          pieHole: 0.4,
        };

        var chart = new google.visualization.PieChart(document.getElementById('donutpresencechart'));
        chart.draw(data, options);

      }
});

// gestion du loading ajax global
$(document).ajaxStart(function () {
    $("container").addClass("loading");
});
$(document).ajaxStop(function () {
    $("container").removeClass("loading");
});

<commit_msg>debug affichage des stat general<commit_after>$(document).ready(function() {
    $("#buttonLoginLayoutFront").fancybox();

    $.chartsVar = new Object();

    if($('#ajaxUrl').val())
    {
        $.post($('#ajaxUrl').val() + 'ajaxPresence')
            .done(function( data ) {
                $.chartsVar.Dez  = data.Dez;
                $.chartsVar.Bank = data.Bank;
                $.chartsVar.spe1 = data.spe1;
                $.chartsVar.spe2 = data.spe2;
                $.chartsVar.spe3 = data.spe3;
                $.chartsVar.spe4 = data.spe4;
            })
            .fail(function() {
                $.chartsVar.Dez  = 0;
                $.chartsVar.Bank = 0;
                $.chartsVar.spe1 = 0;
                $.chartsVar.spe2 = 0;
                $.chartsVar.spe3 = 0;
                $.chartsVar.spe4 = 0;
        });

    // charts
    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['loot', '%'],
          ['Dez',     $.chartsVar.Dez],
          ['Bank',    $.chartsVar.Bank],
          ['Spe 1',   $.chartsVar.spe1],
          ['Spe 2',   $.chartsVar.spe2],
          ['Spe 3',   $.chartsVar.spe3],
          ['Spe 4',   $.chartsVar.spe4],
        ]);

        var options = {
          backgroundColor: { fill:'transparent' },
          chartArea:{left:2,top:2,width:'100%',height:'100%'},
          pieHole: 0.4,
        };

        var chart = new google.visualization.PieChart(document.getElementById('donutpresencechart'));
        chart.draw(data, options);

      }
    }
});

// gestion du loading ajax global
$(document).ajaxStart(function () {
    $("container").addClass("loading");
});
$(document).ajaxStop(function () {
    $("container").removeClass("loading");
});

<|endoftext|>


<commit_before>/**
 * routes/search.js - Defines route to /search URL
 *
 * Authors: Ian McGaunn; Dave Zimmelman
 * Modified: 22 Apr 15
 */

var express = require('express');
var router = express.Router();

// Preload search results
router.get('/:term?', function (req, res, next) {
    // Check that param exists
    if (!req.params.hasOwnProperty('term')) {
        // If not, reroute to landing page.
        res.redirect('/');
    }
    else {
        res.render('index', {user: req.session.user,
                             GLOBALS: {'preload_search': req.params.term},
                             title: 'Podplay.me'});
    }
});

// Expose route
module.exports = router;
<commit_msg>[Doc] routes/search<commit_after>/**
 * routes/search.js - Defines route to /search URL
 *
 * Authors: Ian McGaunn; Dave Zimmelman
 * Modified: 30 Apr 15
 */

var express = require('express');
var router = express.Router();

/**
 * @expressRoute /search/<search_term> - Load website with preloaded search
        view request and data.
 * @render
 *  @always `index.jade`
 */
router.get('/:term?', function (req, res, next) {
    // Check that param exists
    if (!req.params.hasOwnProperty('term')) {
        // If not, reroute to landing page.
        res.redirect('/');
    }
    else {
        res.render('index', {user: req.session.user,
                             GLOBALS: {'preload_search': req.params.term},
                             title: 'Podplay.me'});
    }
});

// Expose route
module.exports = router;
<|endoftext|>


<commit_before>class TopPage {
    constructor (game) {
        this.game = game;
        this.scene = new Scene();
        this.enabled = false;

        // background image
        this.bg = new Sprite(1920, 1080);
        this.bg.image = this.game.assets[bgImg];
        this.scene.addChild(this.bg);

        // username label
        this.usernameLabel = new Label('Username :');
        this.usernameLabel.font = `12px ${normalFont}`;
        this.usernameLabel.scale(3);
        this.usernameLabel.moveTo(800, 340);

        // input text for username
        this.usernameInputBox = new InputTextBox();
        this.usernameInputBox.scale(3);
        this.usernameInputBox.moveTo(1075, 340);
        this.usernameInputBox.width = 330;
        this.usernameInputBox.height = 24;
        this.usernameInputBox.placeholder = 'Input your name';

        // joined user list label
        this.userList = new Label();
        this.userList.font = `50px ${normalFont}`;
        this.userList.moveTo(1580,400);

        // enter button
        this.enterButton = new Button();
        this.enterButton.initialize = (((_initialize) => () => {
            _initialize.call(this.enterButton);
            this.enterButton.font = `100px ${normalFont}`;
            this.enterButton.text = 'Enter';
            this.enterButton.moveTo(580, 440);
            this.enterButton.width = 630;
            this.enterButton.height = 190;
            this.enterButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                const username = this.usernameInputBox.value;
                socket.join(username);
            });
        })(this.enterButton.initialize));

        // start button
        this.startButton = new Button();
        this.startButton.initialize = (((_initialize) => () => {
            _initialize.call(this.startButton);
            this.startButton.font = `100px ${normalFont}`;
            this.startButton.text = 'Start';
            this.startButton.moveTo(410, 380);
            this.startButton.width = 630;
            this.startButton.height = 190;
            this.startButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                socket.initGame();
            });
        })(this.startButton.initialize));

        // back button
        this.backButton = new Button();
        this.backButton.initialize = (((_initialize) => () => {
            _initialize.call(this.backButton);
            this.backButton.font = `30px ${normalFont}`;
            this.backButton.text = 'Back';
            this.backButton.moveTo(1110, 470);
            this.backButton.width = 240;
            this.backButton.height = 95;
            this.backButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                socket.leave();
                this.changeScreenToTop1();
            });
        })(this.backButton.initialize));

        // set socket events
        socket.on('joinRoom', (req) => {
            if (!this.enabled) { return; }
            this.updateUserList(req.game.players);
        });

        socket.on('leaveRoom', (req) => {
            if (!this.enabled) { return; }
            this.updateUserList(req.game.players);
        });

        socket.on('yourInfo', (req) => {
            if (!this.enabled) { return; }
            myId = req.id;
            this.changeScreenToTop2();
        });

        socket.on('initGame', (req) => {
            // initPlayScene(this.game, req.game);
            playPage.init(req.game);
            this.enabled = false;
        });
    }

    init ({entered = false} = {}) {
        // bgm
        bgmController.stop();
        bgmController.play(topPageBgm);

        this.enabled = true;
        this.game.replaceScene(this.scene);

        if (entered) {
            this.changeScreenToTop2();
        } else {
            this.changeScreenToTop1();
        }
    }

    changeScreenToTop1 () {
        // remove nodes
        this.scene.removeChild(this.startButton);
        this.scene.removeChild(this.backButton);
        this.scene.removeChild(this.userList);

        // add nodes
        this.enterButton.initialize();
        this.scene.addChild(this.usernameLabel);
        this.scene.addChild(this.usernameInputBox);
        this.scene.addChild(this.enterButton);
    }

    changeScreenToTop2 () {
        // remove nodes
        this.scene.removeChild(this.usernameLabel);
        this.scene.removeChild(this.usernameInputBox);
        this.scene.removeChild(this.enterButton);

        // add nodes
        this.startButton.initialize();
        this.backButton.initialize();
        this.scene.addChild(this.startButton);
        this.scene.addChild(this.backButton);
        this.scene.addChild(this.userList);
    }

    updateUserList (players) {
        this.userList.text = players.filter(player => player.user).map(player => player.user.username).join('
');
    }
}
<commit_msg>fix 2 times title error<commit_after>class TopPage {
    constructor (game) {
        this.game = game;
        this.scene = new Scene();
        this.enabled = false;

        // background image
        this.bg = new Sprite(1920, 1080);
        this.bg.image = this.game.assets[bgImg];
        this.scene.addChild(this.bg);

        // username label
        this.usernameLabel = new Label('Username :');
        this.usernameLabel.font = `12px ${normalFont}`;
        this.usernameLabel.scale(3);
        this.usernameLabel.moveTo(800, 340);

        // input text for username
        this.usernameInputBox = new InputTextBox();
        this.usernameInputBox.scale(3);
        this.usernameInputBox.moveTo(1075, 340);
        this.usernameInputBox.width = 330;
        this.usernameInputBox.height = 24;
        this.usernameInputBox.placeholder = 'Input your name';

        // joined user list label
        this.userList = new Label();
        this.userList.font = `50px ${normalFont}`;
        this.userList.moveTo(1580,400);

        // enter button
        this.enterButton = new Button();
        this.enterButton.initialize = (((_initialize) => () => {
            _initialize.call(this.enterButton);
            this.enterButton.font = `100px ${normalFont}`;
            this.enterButton.text = 'Enter';
            this.enterButton.moveTo(580, 440);
            this.enterButton.width = 630;
            this.enterButton.height = 190;
            this.enterButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                const username = this.usernameInputBox.value;
                socket.join(username);
            });
        })(this.enterButton.initialize));

        // start button
        this.startButton = new Button();
        this.startButton.initialize = (((_initialize) => () => {
            _initialize.call(this.startButton);
            this.startButton.font = `100px ${normalFont}`;
            this.startButton.text = 'Start';
            this.startButton.moveTo(410, 380);
            this.startButton.width = 630;
            this.startButton.height = 190;
            this.startButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                socket.initGame();
            });
        })(this.startButton.initialize));

        // back button
        this.backButton = new Button();
        this.backButton.initialize = (((_initialize) => () => {
            _initialize.call(this.backButton);
            this.backButton.font = `30px ${normalFont}`;
            this.backButton.text = 'Back';
            this.backButton.moveTo(1110, 470);
            this.backButton.width = 240;
            this.backButton.height = 95;
            this.backButton.on(Event.TOUCH_START, () => {
                this.game.assets[decisionSe].play();
                socket.leave();
                this.changeScreenToTop1();
            });
        })(this.backButton.initialize));

        // set socket events
        socket.on('joinRoom', (req) => {
            if (!this.enabled) { return; }
            this.updateUserList(req.game.players);
        });

        socket.on('leaveRoom', (req) => {
            if (!this.enabled) { return; }
            this.updateUserList(req.game.players);
        });

        socket.on('yourInfo', (req) => {
            if (!this.enabled) { return; }
            myId = req.id;
            this.changeScreenToTop2();
        });

        socket.on('initGame', (req) => {
            playPage.init(req.game);
            this.enabled = false;
        });
    }

    init ({entered = false} = {}) {
        // bgm
        bgmController.stop();
        bgmController.play(topPageBgm);

        this.enabled = true;
        this.game.replaceScene(this.scene);

        if (entered) {
            this.changeScreenToTop1();
            const username = this.usernameInputBox.value;
            socket.join(username);
            this.changeScreenToTop2();
        } else {
            this.changeScreenToTop1();
        }
    }

    changeScreenToTop1 () {
        // remove nodes
        this.scene.removeChild(this.startButton);
        this.scene.removeChild(this.backButton);
        this.scene.removeChild(this.userList);

        // add nodes
        this.enterButton.initialize();
        this.scene.addChild(this.usernameLabel);
        this.scene.addChild(this.usernameInputBox);
        this.scene.addChild(this.enterButton);
    }

    changeScreenToTop2 () {
        // remove nodes
        this.scene.removeChild(this.usernameLabel);
        this.scene.removeChild(this.usernameInputBox);
        this.scene.removeChild(this.enterButton);

        // add nodes
        this.startButton.initialize();
        this.backButton.initialize();
        this.scene.addChild(this.startButton);
        this.scene.addChild(this.backButton);
        this.scene.addChild(this.userList);
    }

    updateUserList (players) {
        this.userList.text = players.filter(player => player.user).map(player => player.user.username).join('
');
    }
}
<|endoftext|>


<commit_before>/*
Copyright 2017 New Vector Ltd

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.
*/

import EventEmitter from 'events';
import Promise from 'bluebird';

const BULK_REQUEST_DEBOUNCE_MS = 200;

// Does the server support groups? Assume yes until we receive M_UNRECOGNIZED.
// If true, flair can function and we should keep sending requests for groups and avatars.
let groupSupport = true;

const USER_GROUPS_CACHE_BUST_MS = 1800000; // 30 mins
const GROUP_PROFILES_CACHE_BUST_MS = 1800000; // 30 mins

/**
 * Stores data used by <Flair/>
 */
class FlairStore extends EventEmitter {
    constructor(matrixClient) {
        super();
        this._matrixClient = matrixClient;
        this._userGroups = {
            // $userId: ['+group1:domain', '+group2:domain', ...]
        };
        this._groupProfiles = {
            //  $groupId: {
            //      avatar_url: 'mxc://...'
            //  }
        };
        this._groupProfilesPromise = {
            //  $groupId: Promise
        };
        this._usersPending = {
            //  $userId: {
            //      prom: Promise
            //      resolve: () => {}
            //      reject: () => {}
            //  }
        };
        this._usersInFlight = {
            // This has the same schema as _usersPending
        };

        this._debounceTimeoutID = null;
    }

    groupSupport() {
        return groupSupport;
    }

    invalidatePublicisedGroups(userId) {
        delete this._userGroups[userId];
    }

    getPublicisedGroupsCached(matrixClient, userId) {
        if (this._userGroups[userId]) {
            return Promise.resolve(this._userGroups[userId]);
        }

        // Bulk lookup ongoing, return promise to resolve/reject
        if (this._usersPending[userId]) {
            return this._usersPending[userId].prom;
        }
        // User has been moved from pending to in-flight
        if (this._usersInFlight[userId]) {
            return this._usersInFlight[userId].prom;
        }

        this._usersPending[userId] = {};
        this._usersPending[userId].prom = new Promise((resolve, reject) => {
            this._usersPending[userId].resolve = resolve;
            this._usersPending[userId].reject = reject;
        }).then((groups) => {
            this._userGroups[userId] = groups;
            setTimeout(() => {
                delete this._userGroups[userId];
            }, USER_GROUPS_CACHE_BUST_MS);
            return this._userGroups[userId];
        }).catch((err) => {
            // Indicate whether the homeserver supports groups
            if (err.errcode === 'M_UNRECOGNIZED') {
                console.warn('Cannot display flair, server does not support groups');
                groupSupport = false;
                // Return silently to avoid spamming for non-supporting servers
                return;
            }
            console.error('Could not get groups for user', userId, err);
            throw err;
        }).finally(() => {
            delete this._usersInFlight[userId];
        });

        // This debounce will allow consecutive requests for the public groups of users that
        // are sent in intervals of < BULK_REQUEST_DEBOUNCE_MS to be batched and only requested
        // when no more requests are received within the next BULK_REQUEST_DEBOUNCE_MS. The naive
        // implementation would do a request that only requested the groups for `userId`, leading
        // to a worst and best case of 1 user per request. This implementation's worst is still
        // 1 user per request but only if the requests are > BULK_REQUEST_DEBOUNCE_MS apart and the
        // best case is N users per request.
        //
        // This is to reduce the number of requests made whilst trading off latency when viewing
        // a Flair component.
        if (this._debounceTimeoutID) clearTimeout(this._debounceTimeoutID);
        this._debounceTimeoutID = setTimeout(() => {
            this._batchedGetPublicGroups(matrixClient);
        }, BULK_REQUEST_DEBOUNCE_MS);

        return this._usersPending[userId].prom;
    }

    async _batchedGetPublicGroups(matrixClient) {
        // Move users pending to users in flight
        this._usersInFlight = this._usersPending;
        this._usersPending = {};

        let resp = {
            users: [],
        };
        try {
            resp = await matrixClient.getPublicisedGroups(Object.keys(this._usersInFlight));
        } catch (err) {
            // Propagate the same error to all usersInFlight
            Object.keys(this._usersInFlight).forEach((userId) => {
                // The promise should always exist for userId, but do a null-check anyway
                if (!this._usersInFlight[userId]) return;
                this._usersInFlight[userId].reject(err);
            });
            return;
        }
        const updatedUserGroups = resp.users;
        Object.keys(this._usersInFlight).forEach((userId) => {
            // The promise should always exist for userId, but do a null-check anyway
            if (!this._usersInFlight[userId]) return;
            this._usersInFlight[userId].resolve(updatedUserGroups[userId] || []);
        });
    }

    async getGroupProfileCached(matrixClient, groupId) {
        if (this._groupProfiles[groupId]) {
            return this._groupProfiles[groupId];
        }

        // No request yet, start one
        if (!this._groupProfilesPromise[groupId]) {
            this._groupProfilesPromise[groupId] = matrixClient.getGroupProfile(groupId);
        }

        let profile;
        try {
            profile = await this._groupProfilesPromise[groupId];
        } catch (e) {
            console.log('Failed to get group profile for ' + groupId, e);
            // Don't retry, but allow a retry when the profile is next requested
            delete this._groupProfilesPromise[groupId];
            return;
        }

        this._groupProfiles[groupId] = {
            groupId,
            avatarUrl: profile.avatar_url,
            name: profile.name,
            shortDescription: profile.short_description,
        };
        delete this._groupProfilesPromise[groupId];

        /// XXX: This is verging on recreating a third "Flux"-looking Store. We really
        /// should replace FlairStore with a Flux store and some async actions.
        this.emit('updateGroupProfile');

        setTimeout(() => {
            this.refreshGroupProfile(groupId);
        }, GROUP_PROFILES_CACHE_BUST_MS);

        return this._groupProfiles[groupId];
    }

    refreshGroupProfile(matrixClient, groupId) {
        // Invalidate the cache
        delete this._groupProfiles[groupId];
        // Fetch new profile data, and cache it
        return this.getGroupProfileCached(matrixClient, groupId);
    }
}

if (global.singletonFlairStore === undefined) {
    global.singletonFlairStore = new FlairStore();
}
export default global.singletonFlairStore;
<commit_msg>Fix FlairStore cache busting<commit_after>/*
Copyright 2017 New Vector Ltd

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.
*/

import EventEmitter from 'events';
import Promise from 'bluebird';

const BULK_REQUEST_DEBOUNCE_MS = 200;

// Does the server support groups? Assume yes until we receive M_UNRECOGNIZED.
// If true, flair can function and we should keep sending requests for groups and avatars.
let groupSupport = true;

const USER_GROUPS_CACHE_BUST_MS = 1800000; // 30 mins
const GROUP_PROFILES_CACHE_BUST_MS = 1800000; // 30 mins

/**
 * Stores data used by <Flair/>
 */
class FlairStore extends EventEmitter {
    constructor(matrixClient) {
        super();
        this._matrixClient = matrixClient;
        this._userGroups = {
            // $userId: ['+group1:domain', '+group2:domain', ...]
        };
        this._groupProfiles = {
            //  $groupId: {
            //      avatar_url: 'mxc://...'
            //  }
        };
        this._groupProfilesPromise = {
            //  $groupId: Promise
        };
        this._usersPending = {
            //  $userId: {
            //      prom: Promise
            //      resolve: () => {}
            //      reject: () => {}
            //  }
        };
        this._usersInFlight = {
            // This has the same schema as _usersPending
        };

        this._debounceTimeoutID = null;
    }

    groupSupport() {
        return groupSupport;
    }

    invalidatePublicisedGroups(userId) {
        delete this._userGroups[userId];
    }

    getPublicisedGroupsCached(matrixClient, userId) {
        if (this._userGroups[userId]) {
            return Promise.resolve(this._userGroups[userId]);
        }

        // Bulk lookup ongoing, return promise to resolve/reject
        if (this._usersPending[userId]) {
            return this._usersPending[userId].prom;
        }
        // User has been moved from pending to in-flight
        if (this._usersInFlight[userId]) {
            return this._usersInFlight[userId].prom;
        }

        this._usersPending[userId] = {};
        this._usersPending[userId].prom = new Promise((resolve, reject) => {
            this._usersPending[userId].resolve = resolve;
            this._usersPending[userId].reject = reject;
        }).then((groups) => {
            this._userGroups[userId] = groups;
            setTimeout(() => {
                delete this._userGroups[userId];
            }, USER_GROUPS_CACHE_BUST_MS);
            return this._userGroups[userId];
        }).catch((err) => {
            // Indicate whether the homeserver supports groups
            if (err.errcode === 'M_UNRECOGNIZED') {
                console.warn('Cannot display flair, server does not support groups');
                groupSupport = false;
                // Return silently to avoid spamming for non-supporting servers
                return;
            }
            console.error('Could not get groups for user', userId, err);
            throw err;
        }).finally(() => {
            delete this._usersInFlight[userId];
        });

        // This debounce will allow consecutive requests for the public groups of users that
        // are sent in intervals of < BULK_REQUEST_DEBOUNCE_MS to be batched and only requested
        // when no more requests are received within the next BULK_REQUEST_DEBOUNCE_MS. The naive
        // implementation would do a request that only requested the groups for `userId`, leading
        // to a worst and best case of 1 user per request. This implementation's worst is still
        // 1 user per request but only if the requests are > BULK_REQUEST_DEBOUNCE_MS apart and the
        // best case is N users per request.
        //
        // This is to reduce the number of requests made whilst trading off latency when viewing
        // a Flair component.
        if (this._debounceTimeoutID) clearTimeout(this._debounceTimeoutID);
        this._debounceTimeoutID = setTimeout(() => {
            this._batchedGetPublicGroups(matrixClient);
        }, BULK_REQUEST_DEBOUNCE_MS);

        return this._usersPending[userId].prom;
    }

    async _batchedGetPublicGroups(matrixClient) {
        // Move users pending to users in flight
        this._usersInFlight = this._usersPending;
        this._usersPending = {};

        let resp = {
            users: [],
        };
        try {
            resp = await matrixClient.getPublicisedGroups(Object.keys(this._usersInFlight));
        } catch (err) {
            // Propagate the same error to all usersInFlight
            Object.keys(this._usersInFlight).forEach((userId) => {
                // The promise should always exist for userId, but do a null-check anyway
                if (!this._usersInFlight[userId]) return;
                this._usersInFlight[userId].reject(err);
            });
            return;
        }
        const updatedUserGroups = resp.users;
        Object.keys(this._usersInFlight).forEach((userId) => {
            // The promise should always exist for userId, but do a null-check anyway
            if (!this._usersInFlight[userId]) return;
            this._usersInFlight[userId].resolve(updatedUserGroups[userId] || []);
        });
    }

    async getGroupProfileCached(matrixClient, groupId) {
        if (this._groupProfiles[groupId]) {
            return this._groupProfiles[groupId];
        }

        // No request yet, start one
        if (!this._groupProfilesPromise[groupId]) {
            this._groupProfilesPromise[groupId] = matrixClient.getGroupProfile(groupId);
        }

        let profile;
        try {
            profile = await this._groupProfilesPromise[groupId];
        } catch (e) {
            console.log('Failed to get group profile for ' + groupId, e);
            // Don't retry, but allow a retry when the profile is next requested
            delete this._groupProfilesPromise[groupId];
            return;
        }

        this._groupProfiles[groupId] = {
            groupId,
            avatarUrl: profile.avatar_url,
            name: profile.name,
            shortDescription: profile.short_description,
        };
        delete this._groupProfilesPromise[groupId];

        /// XXX: This is verging on recreating a third "Flux"-looking Store. We really
        /// should replace FlairStore with a Flux store and some async actions.
        this.emit('updateGroupProfile');

        setTimeout(() => {
            this.refreshGroupProfile(matrixClient, groupId);
        }, GROUP_PROFILES_CACHE_BUST_MS);

        return this._groupProfiles[groupId];
    }

    refreshGroupProfile(matrixClient, groupId) {
        // Invalidate the cache
        delete this._groupProfiles[groupId];
        // Fetch new profile data, and cache it
        return this.getGroupProfileCached(matrixClient, groupId);
    }
}

if (global.singletonFlairStore === undefined) {
    global.singletonFlairStore = new FlairStore();
}
export default global.singletonFlairStore;
<|endoftext|>


<commit_before>define(function() {
	var Utils, Config, userCheck;

	var Base = {
		init: function(callback) {
			//todo I hate this
			require([
				'plugins/nodebb-plugin-shoutbox/public/js/lib/utils.js',
				'plugins/nodebb-plugin-shoutbox/public/js/lib/config.js'], function(u, c) {
				Config = c;
				u.init(Base, c, function() {
					Utils = u;
					callback();
				});
			});
		},
		load: function(callback) {
			Utils.checkAnon(function(isAnon) {
				if(!isAnon) {
					Utils.prepareShoutbox(Base, callback);
				}
			});
		},
		addShout: function(shoutBox, shout) {
			if (shout && shout.sid) {
				var shoutContent = shoutBox.find('#shoutbox-content');
				if (shoutContent.find('div[class="shoutbox-shout-container"]').length === 0) {
					shoutContent.html('');
				}
				if (shout.fromuid === shoutContent.find('[data-uid]:last').data('uid')) {
					$('[data-sid]:last').after(Utils.parseShout(shout, true));
				} else {
					shoutContent.append(Utils.parseShout(shout));
				}
				Base.scrollToBottom(shoutContent);
//				Config.vars.lastSid = shout.sid;
//				Config.vars.lastUid = shout.fromuid;
//				if (shout.fromuid === app.uid) {
//					Config.vars.lastSidByUser = shout.sid;
//				}
			}
		},
		getShouts: function(shoutBox) {
			socket.emit(Config.sockets.get, function(err, shouts) {
				if (shouts.length === 0) {
					Utils.showEmptyMessage(shoutBox);
				} else {
					for(var i = 0; i < shouts.length; i++) {
						Base.addShout(shoutBox, shouts[i]);
					}
					Base.updateUserStatus(shoutBox);
				}
			});
		},
		scrollToBottom: function(shoutContent) {
			if(shoutContent[0]) {
				shoutContent.scrollTop(
					shoutContent[0].scrollHeight - shoutContent.height()
				);
			}
		},
		updateUserStatus: function(shoutBox, uid, status) {
			var getStatus = function(uid) {
				socket.emit(Config.sockets.getUserStatus, uid, function(err, data) {
					console.log(data);
					setStatus(uid, data.status);
				});
			}
			var setStatus = function(uid, status) {
				shoutBox.find('[data-uid="' + uid + '"] > img').removeClass().addClass('shoutbox-shout-avatar ' + status);
			}

			if (!uid) {
				uid = [];
				shoutBox.find('[data-uid]').each(function(index, el){
					uid.push($(el).data('uid'))
				});
				uid = uid.filter(function(el, index) {
					return uid.indexOf(el) === index;
				});
			}

			if (!status) {
				if (typeof(uid) === 'number') {
					getStatus(uid);
				} else if (Array.isArray(uid)) {
					for(var i = 0, l = uid.length; i < l; i++) {
						getStatus(uid[i]);
					}
				}
			} else {
				if (typeof(uid) === 'number') {
					setStatus(uid, status);
				} else if (Array.isArray(uid)) {
					for(var i = 0, l = uid.length; i < l; i++) {
						setStatus(uid[i], status);
					}
				}
			}
		},
		updateUsers: function() {
			socket.emit(Config.sockets.getUsers, {}, function(err, data) {
				var userCount = data.length;
				var usernames = data.map(function(i) {
					return (i.username === null ? 'Anonymous' : i.username);
				});
				var userString = usernames.join('; ');
				Base.getUsersPanel().find('.panel-body').text(userString);
				Base.getUsersPanel().find('.panel-title').text('Users (' + userCount + ')');
			});
			if(userCheck === 0) {
				userCheck = setInterval(function() {
					Base.updateUsers();
				}, 10000);
			}
		},
		getShoutPanel: function() {
			return $('#shoutbox');
		},
		getUsersPanel: function() {
			return $('#shoutbox-users');
		}
	};

	return Base;
});<commit_msg>console.log + remove comment<commit_after>define(function() {
	var Utils, Config, userCheck;

	var Base = {
		init: function(callback) {
			//todo I hate this
			require([
				'plugins/nodebb-plugin-shoutbox/public/js/lib/utils.js',
				'plugins/nodebb-plugin-shoutbox/public/js/lib/config.js'], function(u, c) {
				Config = c;
				u.init(Base, c, function() {
					Utils = u;
					callback();
				});
			});
		},
		load: function(callback) {
			Utils.checkAnon(function(isAnon) {
				if(!isAnon) {
					Utils.prepareShoutbox(Base, callback);
				}
			});
		},
		addShout: function(shoutBox, shout) {
			if (shout && shout.sid) {
				var shoutContent = shoutBox.find('#shoutbox-content');
				if (shoutContent.find('div[class="shoutbox-shout-container"]').length === 0) {
					shoutContent.html('');
				}
				if (shout.fromuid === shoutContent.find('[data-uid]:last').data('uid')) {
					$('[data-sid]:last').after(Utils.parseShout(shout, true));
				} else {
					shoutContent.append(Utils.parseShout(shout));
				}
				Base.scrollToBottom(shoutContent);
			}
		},
		getShouts: function(shoutBox) {
			socket.emit(Config.sockets.get, function(err, shouts) {
				if (shouts.length === 0) {
					Utils.showEmptyMessage(shoutBox);
				} else {
					for(var i = 0; i < shouts.length; i++) {
						Base.addShout(shoutBox, shouts[i]);
					}
					Base.updateUserStatus(shoutBox);
				}
			});
		},
		scrollToBottom: function(shoutContent) {
			if(shoutContent[0]) {
				shoutContent.scrollTop(
					shoutContent[0].scrollHeight - shoutContent.height()
				);
			}
		},
		updateUserStatus: function(shoutBox, uid, status) {
			var getStatus = function(uid) {
				socket.emit(Config.sockets.getUserStatus, uid, function(err, data) {
					setStatus(uid, data.status);
				});
			}
			var setStatus = function(uid, status) {
				shoutBox.find('[data-uid="' + uid + '"] > img').removeClass().addClass('shoutbox-shout-avatar ' + status);
			}

			if (!uid) {
				uid = [];
				shoutBox.find('[data-uid]').each(function(index, el){
					uid.push($(el).data('uid'))
				});
				uid = uid.filter(function(el, index) {
					return uid.indexOf(el) === index;
				});
			}

			if (!status) {
				if (typeof(uid) === 'number') {
					getStatus(uid);
				} else if (Array.isArray(uid)) {
					for(var i = 0, l = uid.length; i < l; i++) {
						getStatus(uid[i]);
					}
				}
			} else {
				if (typeof(uid) === 'number') {
					setStatus(uid, status);
				} else if (Array.isArray(uid)) {
					for(var i = 0, l = uid.length; i < l; i++) {
						setStatus(uid[i], status);
					}
				}
			}
		},
		updateUsers: function() {
			socket.emit(Config.sockets.getUsers, {}, function(err, data) {
				var userCount = data.length;
				var usernames = data.map(function(i) {
					return (i.username === null ? 'Anonymous' : i.username);
				});
				var userString = usernames.join('; ');
				Base.getUsersPanel().find('.panel-body').text(userString);
				Base.getUsersPanel().find('.panel-title').text('Users (' + userCount + ')');
			});
			if(userCheck === 0) {
				userCheck = setInterval(function() {
					Base.updateUsers();
				}, 10000);
			}
		},
		getShoutPanel: function() {
			return $('#shoutbox');
		},
		getUsersPanel: function() {
			return $('#shoutbox-users');
		}
	};

	return Base;
});<|endoftext|>


<commit_before>var app = angular.module("mainApp", ["ngRoute", "firebase", "ngCookies"]);

initalizeFirebase();

app.config(function($routeProvider){
     $routeProvider.when("/",{templateUrl:"MyProfile.html"})

     .when("/MyNotifications",{templateUrl:"MyNotifications.html"})

     .when("/MyEvents/:p",{templateUrl:"MyEvents.html", controller:"paramCtrl"})
     .when("/MyConversation/:p",{templateUrl:"MyConversations.html", controller:"paramCtrl"});

});

app.controller("searchController",function($scope){
 $scope.searchType = "Search Team";
 $scope.setSearchT = function(){
   $scope.searchType = "Search Team";
 };
 $scope.setSearchP = function(){
   $scope.searchType = "Search Person";
 };
 $scope.setSearchE = function(){
   $scope.searchType = "Search Event";
 };
});

app.controller("EventController",function($scope,$routeParams){
        //   $scope.param = $routeParams.p;
            $scope.IsVisibleCOMP3111 = false;
            $scope.IsVisibleCOMP3511 = false;
            $scope.IsVisibleCOMP2012 = false;
  //          $scope.show=function(a){
        //       $scope.IsVisibleCOMP3111 = angular.equals($scope.param, a);
      //      }
          $scope.IsVisibleCOMP3111 = angular.equals($routeParams.p, 'COMP3111');
          $scope.IsVisibleCOMP3511 = angular.equals($routeParams.p, 'COMP3511');
          $scope.IsVisibleCOMP2012 = angular.equals($routeParams.p, 'COMP2012');

});
app.controller("ConversationController",function($scope,$routeParams){
        //   $scope.param = $routeParams.p;
            $scope.IsVisiblePeter = false;
            $scope.IsVisibleJason = false;
            $scope.IsVisibleKevin = false;
  //          $scope.show=function(a){
        //       $scope.IsVisibleCOMP3111 = angular.equals($scope.param, a);
      //      }
         $scope.IsVisiblePeter = angular.equals($routeParams.p, 'Peter');
          $scope.IsVisibleJason = angular.equals($routeParams.p, 'Jason');
          $scope.IsVisibleKevin = angular.equals($routeParams.p, 'Kevin');

});

app.controller("NotificationController", function($scope){
			$scope.userList=[
      				{ Name: "O(n^3) is not that slow", type: "Invitation", Info: ""},
      				{ Name: "Andy", type: "Application", Info: ""},
      				{ Name: "Your team", type: "Information", Info: ""}
       ];
      var i;
      for(i=0; i<$scope.userList.length; ++i){
      	if($scope.userList[i].type=="Invitation"){
      		$scope.userList[i].Info="He invites you into the team.";
      	}
      	else if($scope.userList[i].type=="Application"){
      		$scope.userList[i].Info="He wants to join your team.";
      	}
      	else if($scope.userList[i].type=="Information"){
      		$scope.userList[i].Info="He left the team.";
      	}
      }

      $scope.removeuser=function(user){
       			$scope.userList.splice(user,1);
      }
  });
<commit_msg>Error Correction<commit_after>var app = angular.module("mainApp", ["ngRoute", "firebase", "ngCookies"]);

initalizeFirebase();

app.config(function($routeProvider){
     $routeProvider.when("/",{templateUrl:"MyProfile.html"})

     .when("/MyNotifications",{templateUrl:"MyNotifications.html"})

     .when("/MyEvents/:p",{templateUrl:"MyEvents.html", controller:"EventController"})
     .when("/MyConversation/:p",{templateUrl:"MyConversations.html", controller:"ConversationController"});

});

app.controller("searchController",function($scope){
 $scope.searchType = "Search Team";
 $scope.setSearchT = function(){
   $scope.searchType = "Search Team";
 };
 $scope.setSearchP = function(){
   $scope.searchType = "Search Person";
 };
 $scope.setSearchE = function(){
   $scope.searchType = "Search Event";
 };
});

app.controller("EventController",function($scope,$routeParams){
        //   $scope.param = $routeParams.p;
            $scope.IsVisibleCOMP3111 = false;
            $scope.IsVisibleCOMP3511 = false;
            $scope.IsVisibleCOMP2012 = false;
  //          $scope.show=function(a){
        //       $scope.IsVisibleCOMP3111 = angular.equals($scope.param, a);
      //      }
          $scope.IsVisibleCOMP3111 = angular.equals($routeParams.p, 'COMP3111');
          $scope.IsVisibleCOMP3511 = angular.equals($routeParams.p, 'COMP3511');
          $scope.IsVisibleCOMP2012 = angular.equals($routeParams.p, 'COMP2012');

});
app.controller("ConversationController",function($scope,$routeParams){
        //   $scope.param = $routeParams.p;
            $scope.IsVisiblePeter = false;
            $scope.IsVisibleJason = false;
            $scope.IsVisibleKevin = false;
  //          $scope.show=function(a){
        //       $scope.IsVisibleCOMP3111 = angular.equals($scope.param, a);
      //      }
         $scope.IsVisiblePeter = angular.equals($routeParams.p, 'Peter');
          $scope.IsVisibleJason = angular.equals($routeParams.p, 'Jason');
          $scope.IsVisibleKevin = angular.equals($routeParams.p, 'Kevin');

});

app.controller("NotificationController", function($scope){
			$scope.userList=[
      				{ Name: "O(n^3) is not that slow", type: "Invitation", Info: ""},
      				{ Name: "Andy", type: "Application", Info: ""},
      				{ Name: "Your team", type: "Information", Info: ""}
       ];
      var i;
      for(i=0; i<$scope.userList.length; ++i){
      	if($scope.userList[i].type=="Invitation"){
      		$scope.userList[i].Info="He invites you into the team.";
      	}
      	else if($scope.userList[i].type=="Application"){
      		$scope.userList[i].Info="He wants to join your team.";
      	}
      	else if($scope.userList[i].type=="Information"){
      		$scope.userList[i].Info="He left the team.";
      	}
      }

      $scope.removeuser=function(user){
       			$scope.userList.splice(user,1);
      }
  });
<|endoftext|>


<commit_before>var url = require('url');

exports.state = function(request, response) {
  var parsedUrl = url.parse(request.url, true);
  var _queryObj = parsedUrl.query;

  console.log(JSON.stringify(_queryObj));

  var result = {};
  result.success = true;
  response.send(result);
};<commit_msg>- added more info about the request & server in the response<commit_after>var url = require('url'),
	os = require('os');

exports.state = function(request, response) {
  var parsedUrl = url.parse(request.url, true);
  var _queryObj = parsedUrl.query;

  var os		= {};
  os.hostname	= os.hostname();
  os.type		= os.type();
  os.platform	= os.platform();
  os.release	= os.release();
  os.uptime		= os.uptime();
  os.loadavg	= os.loadavg();
  os.totalmem	= os.totalmem();
  os.freemem	= os.freemem();
  os.cpus		= os.cpus();

  var result	= {};
  result.success= true;
  result.query	= JSON.stringify(_queryObj);
  result.request= JSON.stringify(request);

  response.send(result);
};<|endoftext|>


<commit_before>const { Collection, MessageEmbed, Permissions } = require('discord.js');

class ClientUtil {
    /**
     * Client utilities to help with common tasks.
     * @param {AkairoClient} client - The client.
     */
    constructor(client) {
        /**
         * The Akairo client.
         * @readonly
         * @name ClientUtil#client
         * @type {AkairoClient}
         */
        Object.defineProperty(this, 'client', {
            value: client
        });
    }

    /**
     * Resolves a user from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} users - Collection of users to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {User}
     */
    resolveUser(text, users, caseSensitive = false, wholeWord = false) {
        return users.find(user => this.checkUser(text, user, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple users from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} users - Collection of users to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, User>}
     */
    resolveUsers(text, users, caseSensitive = false, wholeWord = false) {
        return users.filter(user => this.checkUser(text, user, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a user.
     * @param {string} text - Text to check.
     * @param {User} user - User to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkUser(text, user, caseSensitive = false, wholeWord = false) {
        if (user.id !== '1' && user.id === text) return true;

        const reg = /<@!?(\d{17,19})>/;
        const match = text.match(reg);

        if (match && user.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const username = caseSensitive ? user.username : user.username.toLowerCase();
        const discrim = user.discriminator;

        if (!wholeWord) {
            return username.includes(text)
            || (username.includes(text.split('#')[0]) && discrim.includes(text.split('#')[1]));
        }

        return username === text
        || (username === text.split('#')[0] && discrim === text.split('#')[1]);
    }

    /**
     * Resolves a member from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} members - Collection of members to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {GuildMember}
     */
    resolveMember(text, members, caseSensitive = false, wholeWord = false) {
        return members.find(member => this.checkMember(text, member, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple members from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} members - Collection of members to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, GuildMember>}
     */
    resolveMembers(text, members, caseSensitive = false, wholeWord = false) {
        return members.filter(member => this.checkMember(text, member, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a member.
     * @param {string} text - Text to check.
     * @param {GuildMember} member - Member to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkMember(text, member, caseSensitive = false, wholeWord = false) {
        if (member.id !== '1' && member.id === text) return true;

        const reg = /<@!?(\d{17,19})>/;
        const match = text.match(reg);

        if (match && member.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const username = caseSensitive ? member.user.username : member.user.username.toLowerCase();
        const displayName = caseSensitive ? member.displayName : member.displayName.toLowerCase();
        const discrim = member.user.discriminator;

        if (!wholeWord) {
            return displayName.includes(text)
            || username.includes(text)
            || ((username.includes(text.split('#')[0]) || displayName.includes(text.split('#')[0])) && discrim.includes(text.split('#')[1]));
        }

        return displayName === text
        || username === text
        || ((username === text.split('#')[0] || displayName === text.split('#')[0]) && discrim === text.split('#')[1]);
    }

    /**
     * Resolves a guild channel from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} channels - Collection of channels to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {GuildChannel}
     */
    resolveChannel(text, channels, caseSensitive = false, wholeWord = false) {
        return channels.find(channel => this.checkChannel(text, channel, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple guild channels from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} channels - Collection of channels to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, GuildChannel>}
     */
    resolveChannels(text, channels, caseSensitive = false, wholeWord = false) {
        return channels.filter(channel => this.checkChannel(text, channel, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a channel.
     * @param {string} text - Text to check.
     * @param {Channel} channel - Channel to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkChannel(text, channel, caseSensitive = false, wholeWord = false) {
        if (channel.id === text) return true;

        const reg = /<#(\d{17,19})>/;
        const match = text.match(reg);

        if (match && channel.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? channel.name : channel.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/^#/, ''));
        }

        return name === text
        || name === text.replace(/^#/, '');
    }

    /**
     * Resolves a role from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} roles - Collection of roles to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Role}
     */
    resolveRole(text, roles, caseSensitive = false, wholeWord = false) {
        return roles.find(role => this.checkRole(text, role, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple roles from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} roles - Collection of roles to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Role>}
     */
    resolveRoles(text, roles, caseSensitive = false, wholeWord = false) {
        return roles.filter(role => this.checkRole(text, role, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a role.
     * @param {string} text - Text to check.
     * @param {Role} role - Role to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkRole(text, role, caseSensitive = false, wholeWord = false) {
        if (role.id === text) return true;

        const reg = /<@&(\d{17,19})>/;
        const match = text.match(reg);

        if (match && role.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? role.name : role.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/^@/, ''));
        }

        return name === text
        || name === text.replace(/^@/, '');
    }

    /**
     * Resolves a custom emoji from a string, such as a name or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} emojis - Collection of emojis to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Emoji}
     */
    resolveEmoji(text, emojis, caseSensitive = false, wholeWord = false) {
        return emojis.find(emoji => this.checkEmoji(text, emoji, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple custom emojis from a string, such as a name or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} emojis - Collection of emojis to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Emoji>}
     */
    resolveEmojis(text, emojis, caseSensitive = false, wholeWord = false) {
        return emojis.filter(emoji => this.checkEmoji(text, emoji, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a emoji.
     * @param {string} text - Text to check.
     * @param {Emoji} emoji - Emoji to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkEmoji(text, emoji, caseSensitive = false, wholeWord = false) {
        if (emoji.id === text) return true;

        const reg = /<:[a-zA-Z0-9_]+:(\d{17,19})>/;
        const match = text.match(reg);

        if (match && emoji.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? emoji.name : emoji.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/:/, ''));
        }

        return name === text
        || name === text.replace(/:/, '');
    }

    /**
     * Resolves a guild from a string, such as an ID or a name.
     * @param {string} text - Text to resolve.
     * @param {Collection} guilds - Collection of guilds to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Guild}
     */
    resolveGuild(text, guilds, caseSensitive = false, wholeWord = false) {
        return guilds.find(guild => this.checkGuild(text, guild, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple guilds from a string, such as an ID or a name.
     * @param {string} text - Text to resolve.
     * @param {Collection} guilds - Collection of guilds to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Guild>}
     */
    resolveGuilds(text, guilds, caseSensitive = false, wholeWord = false) {
        return guilds.filter(guild => this.checkGuild(text, guild, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a guild.
     * @param {string} text - Text to check.
     * @param {Guild} guild - Guild to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkGuild(text, guild, caseSensitive, wholeWord) {
        if (guild.id === text) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? guild.name : guild.name.toLowerCase();

        if (!wholeWord) return name.includes(text);
        return name === text;
    }

    /**
     * Array of permission names.
     * @returns {string[]}
     */
    permissionNames() {
        return Object.keys(Permissions.FLAGS);
    }

    /**
     * Resolves a permission number and returns an array of permission names.
     * @param {number} number - The permissions number.
     * @returns {string[]}
     */
    resolvePermissionNumber(number) {
        const resolved = [];

        for (const key of Object.keys(Permissions.FLAGS)) {
            if (number & Permissions.FLAGS[key]) resolved.push(key);
        }

        return resolved;
    }

    /**
     * Compares two member objects presences and checks if they stopped or started a stream or not.
     * Returns `0`, `1`, or `2` for no change, stopped, or started.
     * @param {GuildMember} oldMember - The old member.
     * @param {GuildMember} newMember - The new member.
     * @returns {number}
     */
    compareStreaming(oldMember, newMember) {
        const s1 = oldMember.presence.game && oldMember.presence.game.streaming;
        const s2 = newMember.presence.game && newMember.presence.game.streaming;

        if (s1 === s2) return 0;
        if (s1) return 1;
        if (s2) return 2;
        return 0;
    }

    /**
     * Combination of `<Client>.fetchUser()` and `<Guild>.fetchMember()`.
     * @param {Guild} guild - Guild to fetch in.
     * @param {string} id - ID of the user.
     * @param {boolean} cache - Whether or not to add to cache.
     * @returns {Promise<GuildMember>}
     */
    async fetchMember(guild, id, cache) {
        const user = await this.client.users.fetch(id, cache);
        return guild.members.fetch(user, cache);
    }

    /**
     * Makes a MessageEmbed.
     * @param {Object} [data] - Embed data.
     * @returns {MessageEmbed}
     */
    embed(data) {
        return new MessageEmbed(data);
    }

    /**
     * Makes a Collection.
     * @param {Iterable} [iterable] - Entries to fill with.
     * @returns {Collection}
     */
    collection(iterable) {
        return new Collection(iterable);
    }
}

module.exports = ClientUtil;
<commit_msg>Change docs type for GuildChannel to Channel<commit_after>const { Collection, MessageEmbed, Permissions } = require('discord.js');

class ClientUtil {
    /**
     * Client utilities to help with common tasks.
     * @param {AkairoClient} client - The client.
     */
    constructor(client) {
        /**
         * The Akairo client.
         * @readonly
         * @name ClientUtil#client
         * @type {AkairoClient}
         */
        Object.defineProperty(this, 'client', {
            value: client
        });
    }

    /**
     * Resolves a user from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} users - Collection of users to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {User}
     */
    resolveUser(text, users, caseSensitive = false, wholeWord = false) {
        return users.find(user => this.checkUser(text, user, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple users from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} users - Collection of users to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, User>}
     */
    resolveUsers(text, users, caseSensitive = false, wholeWord = false) {
        return users.filter(user => this.checkUser(text, user, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a user.
     * @param {string} text - Text to check.
     * @param {User} user - User to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkUser(text, user, caseSensitive = false, wholeWord = false) {
        if (user.id !== '1' && user.id === text) return true;

        const reg = /<@!?(\d{17,19})>/;
        const match = text.match(reg);

        if (match && user.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const username = caseSensitive ? user.username : user.username.toLowerCase();
        const discrim = user.discriminator;

        if (!wholeWord) {
            return username.includes(text)
            || (username.includes(text.split('#')[0]) && discrim.includes(text.split('#')[1]));
        }

        return username === text
        || (username === text.split('#')[0] && discrim === text.split('#')[1]);
    }

    /**
     * Resolves a member from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} members - Collection of members to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {GuildMember}
     */
    resolveMember(text, members, caseSensitive = false, wholeWord = false) {
        return members.find(member => this.checkMember(text, member, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple members from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} members - Collection of members to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, GuildMember>}
     */
    resolveMembers(text, members, caseSensitive = false, wholeWord = false) {
        return members.filter(member => this.checkMember(text, member, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a member.
     * @param {string} text - Text to check.
     * @param {GuildMember} member - Member to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkMember(text, member, caseSensitive = false, wholeWord = false) {
        if (member.id !== '1' && member.id === text) return true;

        const reg = /<@!?(\d{17,19})>/;
        const match = text.match(reg);

        if (match && member.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const username = caseSensitive ? member.user.username : member.user.username.toLowerCase();
        const displayName = caseSensitive ? member.displayName : member.displayName.toLowerCase();
        const discrim = member.user.discriminator;

        if (!wholeWord) {
            return displayName.includes(text)
            || username.includes(text)
            || ((username.includes(text.split('#')[0]) || displayName.includes(text.split('#')[0])) && discrim.includes(text.split('#')[1]));
        }

        return displayName === text
        || username === text
        || ((username === text.split('#')[0] || displayName === text.split('#')[0]) && discrim === text.split('#')[1]);
    }

    /**
     * Resolves a channel from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} channels - Collection of channels to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Channel}
     */
    resolveChannel(text, channels, caseSensitive = false, wholeWord = false) {
        return channels.find(channel => this.checkChannel(text, channel, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple channels from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} channels - Collection of channels to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Channel>}
     */
    resolveChannels(text, channels, caseSensitive = false, wholeWord = false) {
        return channels.filter(channel => this.checkChannel(text, channel, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a channel.
     * @param {string} text - Text to check.
     * @param {Channel} channel - Channel to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkChannel(text, channel, caseSensitive = false, wholeWord = false) {
        if (channel.id === text) return true;

        const reg = /<#(\d{17,19})>/;
        const match = text.match(reg);

        if (match && channel.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? channel.name : channel.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/^#/, ''));
        }

        return name === text
        || name === text.replace(/^#/, '');
    }

    /**
     * Resolves a role from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} roles - Collection of roles to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Role}
     */
    resolveRole(text, roles, caseSensitive = false, wholeWord = false) {
        return roles.find(role => this.checkRole(text, role, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple roles from a string, such as an ID, a name, or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} roles - Collection of roles to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Role>}
     */
    resolveRoles(text, roles, caseSensitive = false, wholeWord = false) {
        return roles.filter(role => this.checkRole(text, role, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a role.
     * @param {string} text - Text to check.
     * @param {Role} role - Role to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkRole(text, role, caseSensitive = false, wholeWord = false) {
        if (role.id === text) return true;

        const reg = /<@&(\d{17,19})>/;
        const match = text.match(reg);

        if (match && role.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? role.name : role.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/^@/, ''));
        }

        return name === text
        || name === text.replace(/^@/, '');
    }

    /**
     * Resolves a custom emoji from a string, such as a name or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} emojis - Collection of emojis to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Emoji}
     */
    resolveEmoji(text, emojis, caseSensitive = false, wholeWord = false) {
        return emojis.find(emoji => this.checkEmoji(text, emoji, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple custom emojis from a string, such as a name or a mention.
     * @param {string} text - Text to resolve.
     * @param {Collection} emojis - Collection of emojis to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Emoji>}
     */
    resolveEmojis(text, emojis, caseSensitive = false, wholeWord = false) {
        return emojis.filter(emoji => this.checkEmoji(text, emoji, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a emoji.
     * @param {string} text - Text to check.
     * @param {Emoji} emoji - Emoji to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkEmoji(text, emoji, caseSensitive = false, wholeWord = false) {
        if (emoji.id === text) return true;

        const reg = /<:[a-zA-Z0-9_]+:(\d{17,19})>/;
        const match = text.match(reg);

        if (match && emoji.id === match[1]) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? emoji.name : emoji.name.toLowerCase();

        if (!wholeWord) {
            return name.includes(text)
            || name.includes(text.replace(/:/, ''));
        }

        return name === text
        || name === text.replace(/:/, '');
    }

    /**
     * Resolves a guild from a string, such as an ID or a name.
     * @param {string} text - Text to resolve.
     * @param {Collection} guilds - Collection of guilds to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Guild}
     */
    resolveGuild(text, guilds, caseSensitive = false, wholeWord = false) {
        return guilds.find(guild => this.checkGuild(text, guild, caseSensitive, wholeWord));
    }

    /**
     * Resolves multiple guilds from a string, such as an ID or a name.
     * @param {string} text - Text to resolve.
     * @param {Collection} guilds - Collection of guilds to find in.
     * @param {boolean} [caseSensitive=false] - Makes finding by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes finding by name match full word only.
     * @returns {Collection<string, Guild>}
     */
    resolveGuilds(text, guilds, caseSensitive = false, wholeWord = false) {
        return guilds.filter(guild => this.checkGuild(text, guild, caseSensitive, wholeWord));
    }

    /**
     * Checks if a string could be referring to a guild.
     * @param {string} text - Text to check.
     * @param {Guild} guild - Guild to check.
     * @param {boolean} [caseSensitive=false] - Makes checking by name case sensitive.
     * @param {boolean} [wholeWord=false] - Makes checking by name match full word only.
     * @returns {boolean}
     */
    checkGuild(text, guild, caseSensitive, wholeWord) {
        if (guild.id === text) return true;

        text = caseSensitive ? text : text.toLowerCase();
        const name = caseSensitive ? guild.name : guild.name.toLowerCase();

        if (!wholeWord) return name.includes(text);
        return name === text;
    }

    /**
     * Array of permission names.
     * @returns {string[]}
     */
    permissionNames() {
        return Object.keys(Permissions.FLAGS);
    }

    /**
     * Resolves a permission number and returns an array of permission names.
     * @param {number} number - The permissions number.
     * @returns {string[]}
     */
    resolvePermissionNumber(number) {
        const resolved = [];

        for (const key of Object.keys(Permissions.FLAGS)) {
            if (number & Permissions.FLAGS[key]) resolved.push(key);
        }

        return resolved;
    }

    /**
     * Compares two member objects presences and checks if they stopped or started a stream or not.
     * Returns `0`, `1`, or `2` for no change, stopped, or started.
     * @param {GuildMember} oldMember - The old member.
     * @param {GuildMember} newMember - The new member.
     * @returns {number}
     */
    compareStreaming(oldMember, newMember) {
        const s1 = oldMember.presence.game && oldMember.presence.game.streaming;
        const s2 = newMember.presence.game && newMember.presence.game.streaming;

        if (s1 === s2) return 0;
        if (s1) return 1;
        if (s2) return 2;
        return 0;
    }

    /**
     * Combination of `<Client>.fetchUser()` and `<Guild>.fetchMember()`.
     * @param {Guild} guild - Guild to fetch in.
     * @param {string} id - ID of the user.
     * @param {boolean} cache - Whether or not to add to cache.
     * @returns {Promise<GuildMember>}
     */
    async fetchMember(guild, id, cache) {
        const user = await this.client.users.fetch(id, cache);
        return guild.members.fetch(user, cache);
    }

    /**
     * Makes a MessageEmbed.
     * @param {Object} [data] - Embed data.
     * @returns {MessageEmbed}
     */
    embed(data) {
        return new MessageEmbed(data);
    }

    /**
     * Makes a Collection.
     * @param {Iterable} [iterable] - Entries to fill with.
     * @returns {Collection}
     */
    collection(iterable) {
        return new Collection(iterable);
    }
}

module.exports = ClientUtil;
<|endoftext|>