<commit_before>var e = Math.E;
var pi = Math.PI;
var np = {};
var MU = "\u03BC";

float = function(val) {
	return val*1.0;
};

int = function(val) {
	return parseInt(val, 10);
};

pow = function(val,points) {
	return Math.pow(val, points);
};

round = function(val, digits) {
	var digits = digits || 0;
	return val.toFixed(digits);

};

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var log = function(e) {
	if(window.console){
		console.log(e);
	}
}

var toast = function(msg) {
	var el = document.createElement("div");
	el.className = "toast alert alert-info";
	el.innerHTML = msg;
	el.style.position = "absolute";
	el.style.display = "block";
	el.style.width = "30%";
	el.style.left = "50%";
	el.style.top = "50%";
	el.style["margin-left"] = "-15%";
	el.style["margin-top"] = "0px";
	document.getElementsByTagName("body")[0].appendChild(el);
	$(".toast").fadeOut(0);
	$(".toast").fadeIn(500);
	setTimeout(function() {$(".toast").fadeOut(500);}, 3000);

};

Math.trunc = function(num, digits) {
	return num.toFixed(digits);
};

function testBit(data, offset) {
	var mask = 1 << offset;
	    return(data & mask)
}

function truncate(number, points) {
	var points = points || 0;
	return Math.trunc(number*pow(10, points))/float(pow(10, points), points);

}

function unpackStruct(bytes) {
	var struct = [];
	for(var n=0; n < bytes.length; n+=2){
		var msb = bytes.charCodeAt(n);
		var lsb = bytes.charCodeAt(n+1);
		var combo = msb*256 + lsb;
		struct.push(combo);
	}
	return struct;

};

function unpackSigned(data) {
	var isNegative = ( testBit(data, 15) > 0 );
	var dotOffset =  (data >> 13) & 3; //Rotate and mask w/ 0x0003
	var value = float(data & 1023)/1000.0;
	if( isNegative )
	    return truncate(round((-1.0) * value * (pow(10, dotOffset)), 3 - dotOffset), 3 - dotOffset)
	else
	    return truncate(round(value * (pow(10, dotOffset)), 3 - dotOffset), 3 - dotOffset)

}

function unpackUnsigned(data) {
	var dotOffset =  (data >> 14) & 3; //Rotate and mask w/ 0x0003
	var value = float(data & 1023)/10000.0;
	return truncate(round(value * (pow(10, dotOffset)), 4 - dotOffset), 4 - dotOffset);
	/*
	dotOffset =  (data >> 14) & 3 #Rotate and mask w/ 0x0003
	value = (data & int("0x3FFF", 16))/10000.0
	return truncate(round(value * pow(10, dotOffset), 4 - dotOffset), 4 - dotOffset)
	*/
}

Number.prototype.pad = function(padding) {
	var s = "" + this;
	var padding_needed = (s.length - padding);
	for (var i = 0; i < padding_needed; i++) {
		s = '0' + s;
	}
	return s;
};

Date.prototype.toQFormat = function() {
	var output = "";
	output += this.getFullYear() + "-" + (this.getMonth()+1) + "-" + this.getDate();
	output += " ";
	output += this.getHours().pad(2) + ":" + this.getMinutes().pad(2) + ":" + this.getSeconds().pad(2);
	output += " ";
	output += "Offset:" + ( (this.getTimezoneOffset() > 0) ? "+" + this.getTimezoneOffset() : this.getTimezoneOffset() );
	return output;
};

parseDate = function(val) {
	//2011-04-27 18:55:39 Offset:-04
	var dateString = val.split(" ")[0];
	var time = val.split(" ")[1];
	var tz = float(val.split(" ")[2].split(":")[1]);

	var year = int( dateString.split("-")[0] );
	var month = int(  dateString.split("-")[1] - 1 );
	var day = int(  dateString.split("-")[2] );

	var hours = int( time.split(":")[0] );
	var minutes = int( time.split(":")[1] );
	var seconds = int( time.split(":")[2] );

	return (new Date(year, month, day, hours, minutes, seconds, 0));

};

var TimeDelta = function(delta) {
	var that = {};
	if(!delta.isPrototypeOf(Object)) {
		that.days = Math.floor(delta/(1000*60*60*24));
		that.hours = Math.floor( (delta % (1000*60*60*24))/(1000*60*60) );
		that.minutes = Math.floor( (delta % (1000*60*60))/(1000*60) );
		that.seconds = Math.floor( (delta % (1000*60))/(1000) );
		that.milliseconds = Math.floor( (delta % (1000)) );
	}
	else {
		that.days = delta.days || 0;
		that.hours = delta.hours || 0;
		that.minutes = delta.minutes || 0;
		that.seconds = delta.seconds || 0;
		that.milliseconds = delta.milliseconds || 0;
	}

	that.toString = function() {
		return this.days + " days " + this.hours + ":" + this.minutes + ":" +this.seconds + "." + this.milliseconds.toFixed(3);

	};

	that.valueOf = function() {
		var value = 0;
		value += 1000*60*60*24*this.days;
		value += 1000*60*60*this.hours;
		value += 1000*60*this.minutes;
		value += 1000*this.seconds;
		value += this.milliseconds;
		return value;
	};

	return that;

};

Date.prototype.sub = function(date) {
	var diff = this.valueOf() - date.valueOf();
	return TimeDelta(diff);
};

Date.prototype.add = function(delta) {
	return new Date(this.valueOf() + TimeDelta(delta).valueOf());
};

Date.prototype.addMilliseconds = function(ms) {
	var newDate = new Date(this.valueOf() + ms);
	return newDate;

};

Date.prototype.addSeconds = function(seconds) {
	return this.addMilliseconds(seconds*1000);

};

Date.prototype.addMinutes = function(mins) {
	return this.addSeconds(60*mins);
};

Date.prototype.addHours = function(hours) {
	return this.addMinutes(60*hours);
}

Date.prototype.addDays = function(days) {
	return this.addHours(24*days);
}

Date.prototype.getMinutesSinceMidnight = function() {
	var midnight = new Date(this.toString());
	midnight.setHours(0);
	midnight.setMinutes(0);
	midnight.setSeconds(0);
	midnight.setMilliseconds(0);

	var timeInMinutes = (midnight.valueOf() - this.valueOf())/(60*1000);
	return timeInMinutes;

};

Date.prototype.shortString = function() {
	return this.toLocaleTimeString();
};

String.prototype.contains = function(substr) {

	return (this.indexOf(substr) > -1);

}

String.prototype.isnum = function() {
	try {
		var f = parseFloat(this.toString());
		return true;
	}
	catch (error) {
		return false;
	}

};

String.prototype.isdate = function() {
	try {
		var d = new Date(this.toString());
		if(d.valueOf() != NaN){
			return true;
		}
		else {
			return false;
		}
	}
	catch (error) {
		return false;
	}

};

String.prototype.autoconvert = function() {
{
		try {
			return parseDate(this.toString());
		}
		catch (error) {

		}
		try {
			var n =  parseFloat(this.toString());
			if(n != NaN) {
				return n;
			}
			else {
				return this.toString();
			}
		}
		catch (error) {
			return this.toString();
		}
	}

};

guess = function(x) {
	if (typeof(x) != "string") {
		return typeof(x);
	}
	else if (x.isdate()) {
		return "date";
	}
	else if (x.isnum()) {
		if(x.toString().contains(".") || x.toString().contains(",")) {
			return "float";
		}
		else {
			return "int";
		}
	}
	else {
		return "unknown";
	}

}

autoformat = function(x) {
	var format = guess(x);
	switch (format) {
		case "float":
			return float(x);
			break;
		case "int":
			return int(x);
			break;
		case "date":
			return new Date(x);
			break;
		default:
			return x;
			break;

	}
}

// a = 1/(σ√(2π)), b = μ, c = σ
gaussian = function(x, width) {
	var c = Math.sqrt(width);
	var a = 1/(c*Math.sqrt(2*pi));
	var b = 0;

	var exp = -1*(Math.pow((x-b),2)/(2*c*c));
	var fx = a*Math.pow(e,exp);
	return fx;
}

gaussianKernel = function(width,resolution) {
	var kernel = new Array();
	for(var n=-1*resolution/2; n < resolution/2; n++) {
		kernel.push(gaussian(n, width));
	}
	return kernel;
}

gaussianFilter = function(values, width, resolution){
	var result = new Array();
	if(resolution == undefined){
		resolution = 100;
	}
	for(var n=0; n < values.length; n++){
		var start = (n-resolution/2) < 0? 0 : n - resolution/2;
		var end = (n+resolution/2)>=values.length? values.length-1 : n + resolution/2;

		var kernel = gaussianKernel(width, end-start);
		result.push(np.sum(convolve(kernel,values.slice(start,end))));
	}
	return result;

}

np.arange = function(start,end,step) {
	if(step == undefined){
		step = 1;
	}
	var range = new Array();
	for(var n=start; n < end; n+=step){
		range.push(n);
	}
	return range;
}

np.round = function(val, step){
	var remainder = val%step;
	if(remainder > step/2){
		val = (Math.round(val/step)+1)*step;
	}
	else {
		val = (Math.round(val/step))*step;
	}
	return val;
}

np.map = function(func, arr) {
	var result = new Array();
	for(var n=0; n < arr.length; n++){
		result.push(func(arr[n]));
	}
	return result;
}

np.max = function(arr){
	var max = -Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] > max){
			max = arr[n];
		}
	}
	return max;
}

np.min = function(arr){
	var min = Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] < min){
			min = arr[n];
		}
	}
	return min;
}

convolve = function(mat1,mat2) {
	var result = new Array();
	if(mat1.length != mat2.length){
		return false;
	}
	else {
		for(var n=0; n < mat1.length; n++){
			result.push(mat1[n]*mat2[n]);
		}
		return result;
	}
}

np.sum = function(values) {
	var result = 0;
	for(var n=0;n<values.length;n++) {
		if(!values[n].isNaN){
			result += values[n];
		}
	}
	return result;
}

Array.prototype.max = function(){
	var arr = this;
	var max = -Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] > max){
			max = arr[n];
		}
	}
	return max;
}

Array.prototype.min = function(){
	var arr = this;
	var min = Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] < min){
			min = arr[n];
		}
	}
	return min;
}

Array.prototype.find = function(val){
	var arr = this;
	var results = new Array();
	for(var n=0; n < arr.length; n++){
		if(arr[n] == val){
			results.push(n);
		}
	}

	return results;
}

Array.prototype.map = function(func) {
	var arr = this;
	var result = new Array();
	for(var n=0; n < arr.length; n++){
		result.push(func(arr[n]));
	}
	return result;
}
<commit_msg>fix nan compare<commit_after>var e = Math.E;
var pi = Math.PI;
var np = {};
var MU = "\u03BC";

float = function(val) {
	return val*1.0;
};

int = function(val) {
	return parseInt(val, 10);
};

pow = function(val,points) {
	return Math.pow(val, points);
};

round = function(val, digits) {
	var digits = digits || 0;
	return val.toFixed(digits);

};

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var log = function(e) {
	if(window.console){
		console.log(e);
	}
}

var toast = function(msg) {
	var el = document.createElement("div");
	el.className = "toast alert alert-info";
	el.innerHTML = msg;
	el.style.position = "absolute";
	el.style.display = "block";
	el.style.width = "30%";
	el.style.left = "50%";
	el.style.top = "50%";
	el.style["margin-left"] = "-15%";
	el.style["margin-top"] = "0px";
	document.getElementsByTagName("body")[0].appendChild(el);
	$(".toast").fadeOut(0);
	$(".toast").fadeIn(500);
	setTimeout(function() {$(".toast").fadeOut(500);}, 3000);

};

Math.trunc = function(num, digits) {
	return num.toFixed(digits);
};

function testBit(data, offset) {
	var mask = 1 << offset;
	    return(data & mask)
}

function truncate(number, points) {
	var points = points || 0;
	return Math.trunc(number*pow(10, points))/float(pow(10, points), points);

}

function unpackStruct(bytes) {
	var struct = [];
	for(var n=0; n < bytes.length; n+=2){
		var msb = bytes.charCodeAt(n);
		var lsb = bytes.charCodeAt(n+1);
		var combo = msb*256 + lsb;
		struct.push(combo);
	}
	return struct;

};

function unpackSigned(data) {
	var isNegative = ( testBit(data, 15) > 0 );
	var dotOffset =  (data >> 13) & 3; //Rotate and mask w/ 0x0003
	var value = float(data & 1023)/1000.0;
	if( isNegative )
	    return truncate(round((-1.0) * value * (pow(10, dotOffset)), 3 - dotOffset), 3 - dotOffset)
	else
	    return truncate(round(value * (pow(10, dotOffset)), 3 - dotOffset), 3 - dotOffset)

}

function unpackUnsigned(data) {
	var dotOffset =  (data >> 14) & 3; //Rotate and mask w/ 0x0003
	var value = float(data & 1023)/10000.0;
	return truncate(round(value * (pow(10, dotOffset)), 4 - dotOffset), 4 - dotOffset);
	/*
	dotOffset =  (data >> 14) & 3 #Rotate and mask w/ 0x0003
	value = (data & int("0x3FFF", 16))/10000.0
	return truncate(round(value * pow(10, dotOffset), 4 - dotOffset), 4 - dotOffset)
	*/
}

Number.prototype.pad = function(padding) {
	var s = "" + this;
	var padding_needed = (s.length - padding);
	for (var i = 0; i < padding_needed; i++) {
		s = '0' + s;
	}
	return s;
};

Number.prototype.isNaN = function() {

	return isNaN(this);
}

Date.prototype.toQFormat = function() {
	var output = "";
	output += this.getFullYear() + "-" + (this.getMonth()+1) + "-" + this.getDate();
	output += " ";
	output += this.getHours().pad(2) + ":" + this.getMinutes().pad(2) + ":" + this.getSeconds().pad(2);
	output += " ";
	output += "Offset:" + ( (this.getTimezoneOffset() > 0) ? "+" + this.getTimezoneOffset() : this.getTimezoneOffset() );
	return output;
};

parseDate = function(val) {
	//2011-04-27 18:55:39 Offset:-04
	var dateString = val.split(" ")[0];
	var time = val.split(" ")[1];
	var tz = float(val.split(" ")[2].split(":")[1]);

	var year = int( dateString.split("-")[0] );
	var month = int(  dateString.split("-")[1] - 1 );
	var day = int(  dateString.split("-")[2] );

	var hours = int( time.split(":")[0] );
	var minutes = int( time.split(":")[1] );
	var seconds = int( time.split(":")[2] );

	return (new Date(year, month, day, hours, minutes, seconds, 0));

};

var TimeDelta = function(delta) {
	var that = {};
	if(!delta.isPrototypeOf(Object)) {
		that.days = Math.floor(delta/(1000*60*60*24));
		that.hours = Math.floor( (delta % (1000*60*60*24))/(1000*60*60) );
		that.minutes = Math.floor( (delta % (1000*60*60))/(1000*60) );
		that.seconds = Math.floor( (delta % (1000*60))/(1000) );
		that.milliseconds = Math.floor( (delta % (1000)) );
	}
	else {
		that.days = delta.days || 0;
		that.hours = delta.hours || 0;
		that.minutes = delta.minutes || 0;
		that.seconds = delta.seconds || 0;
		that.milliseconds = delta.milliseconds || 0;
	}

	that.toString = function() {
		return this.days + " days " + this.hours + ":" + this.minutes + ":" +this.seconds + "." + this.milliseconds.toFixed(3);

	};

	that.valueOf = function() {
		var value = 0;
		value += 1000*60*60*24*this.days;
		value += 1000*60*60*this.hours;
		value += 1000*60*this.minutes;
		value += 1000*this.seconds;
		value += this.milliseconds;
		return value;
	};

	return that;

};

Date.prototype.sub = function(date) {
	var diff = this.valueOf() - date.valueOf();
	return TimeDelta(diff);
};

Date.prototype.add = function(delta) {
	return new Date(this.valueOf() + TimeDelta(delta).valueOf());
};

Date.prototype.addMilliseconds = function(ms) {
	var newDate = new Date(this.valueOf() + ms);
	return newDate;

};

Date.prototype.addSeconds = function(seconds) {
	return this.addMilliseconds(seconds*1000);

};

Date.prototype.addMinutes = function(mins) {
	return this.addSeconds(60*mins);
};

Date.prototype.addHours = function(hours) {
	return this.addMinutes(60*hours);
}

Date.prototype.addDays = function(days) {
	return this.addHours(24*days);
}

Date.prototype.getMinutesSinceMidnight = function() {
	var midnight = new Date(this.toString());
	midnight.setHours(0);
	midnight.setMinutes(0);
	midnight.setSeconds(0);
	midnight.setMilliseconds(0);

	var timeInMinutes = (midnight.valueOf() - this.valueOf())/(60*1000);
	return timeInMinutes;

};

Date.prototype.shortString = function() {
	return this.toLocaleTimeString();
};

String.prototype.contains = function(substr) {

	return (this.indexOf(substr) > -1);

}

String.prototype.isnum = function() {
	try {
		var f = parseFloat(this.toString());
		return true;
	}
	catch (error) {
		return false;
	}

};

String.prototype.isdate = function() {
	try {
		var d = new Date(this.toString());
		if(!d.valueOf().isNaN()){
			return true;
		}
		else {
			return false;
		}
	}
	catch (error) {
		return false;
	}

};

String.prototype.autoconvert = function() {
{
		try {
			return parseDate(this.toString());
		}
		catch (error) {

		}
		try {
			var n =  parseFloat(this.toString());
			if(n != NaN) {
				return n;
			}
			else {
				return this.toString();
			}
		}
		catch (error) {
			return this.toString();
		}
	}

};

guess = function(x) {
	if (typeof(x) != "string") {
		return typeof(x);
	}
	else if (x.isdate()) {
		return "date";
	}
	else if (x.isnum()) {
		if(x.toString().contains(".") || x.toString().contains(",")) {
			return "float";
		}
		else {
			return "int";
		}
	}
	else {
		return "unknown";
	}

}

autoformat = function(x) {
	var format = guess(x);
	switch (format) {
		case "float":
			return float(x);
			break;
		case "int":
			return int(x);
			break;
		case "date":
			return new Date(x);
			break;
		default:
			return x;
			break;

	}
}

// a = 1/(σ√(2π)), b = μ, c = σ
gaussian = function(x, width) {
	var c = Math.sqrt(width);
	var a = 1/(c*Math.sqrt(2*pi));
	var b = 0;

	var exp = -1*(Math.pow((x-b),2)/(2*c*c));
	var fx = a*Math.pow(e,exp);
	return fx;
}

gaussianKernel = function(width,resolution) {
	var kernel = new Array();
	for(var n=-1*resolution/2; n < resolution/2; n++) {
		kernel.push(gaussian(n, width));
	}
	return kernel;
}

gaussianFilter = function(values, width, resolution){
	var result = new Array();
	if(resolution == undefined){
		resolution = 100;
	}
	for(var n=0; n < values.length; n++){
		var start = (n-resolution/2) < 0? 0 : n - resolution/2;
		var end = (n+resolution/2)>=values.length? values.length-1 : n + resolution/2;

		var kernel = gaussianKernel(width, end-start);
		result.push(np.sum(convolve(kernel,values.slice(start,end))));
	}
	return result;

}

np.arange = function(start,end,step) {
	if(step == undefined){
		step = 1;
	}
	var range = new Array();
	for(var n=start; n < end; n+=step){
		range.push(n);
	}
	return range;
}

np.round = function(val, step){
	var remainder = val%step;
	if(remainder > step/2){
		val = (Math.round(val/step)+1)*step;
	}
	else {
		val = (Math.round(val/step))*step;
	}
	return val;
}

np.map = function(func, arr) {
	var result = new Array();
	for(var n=0; n < arr.length; n++){
		result.push(func(arr[n]));
	}
	return result;
}

np.max = function(arr){
	var max = -Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] > max){
			max = arr[n];
		}
	}
	return max;
}

np.min = function(arr){
	var min = Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] < min){
			min = arr[n];
		}
	}
	return min;
}

convolve = function(mat1,mat2) {
	var result = new Array();
	if(mat1.length != mat2.length){
		return false;
	}
	else {
		for(var n=0; n < mat1.length; n++){
			result.push(mat1[n]*mat2[n]);
		}
		return result;
	}
}

np.sum = function(values) {
	var result = 0;
	for(var n=0;n<values.length;n++) {
		if(!values[n].isNaN){
			result += values[n];
		}
	}
	return result;
}

Array.prototype.max = function(){
	var arr = this;
	var max = -Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] > max){
			max = arr[n];
		}
	}
	return max;
}

Array.prototype.min = function(){
	var arr = this;
	var min = Infinity;
	for(var n=0; n < arr.length; n++){
		if(arr[n] < min){
			min = arr[n];
		}
	}
	return min;
}

Array.prototype.find = function(val){
	var arr = this;
	var results = new Array();
	for(var n=0; n < arr.length; n++){
		if(arr[n] == val){
			results.push(n);
		}
	}

	return results;
}

Array.prototype.map = function(func) {
	var arr = this;
	var result = new Array();
	for(var n=0; n < arr.length; n++){
		result.push(func(arr[n]));
	}
	return result;
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import './AdminDashboard.css';
import DescriptiveTextBox from '../elements/DescriptiveTextBox';
import DeleteButton from '../elements/DeleteButton';
import api from '../api';
import auth from '../auth';
import Dropdown from "../elements/Dropdown";

const ENTER = 13;
const GMATLevels = ['200', '300', '400'];
const GMATCategories = ['Math', 'Verbal', 'Writing', 'Reasoning', 'Data'];
const MultipleChoiceOptions = ['A', 'B', 'C', 'D', 'E'];
const GMATQuestionLimit = ['10', '25', '50'];

export default class AdminDashboard extends Component {
  constructor(){
    super();
    this.state={
      error : null,
      successMSG: null,
      rowOffset: 0
    }
    this.createQuesEle = {}
    this.showRowsEle = {}
  }

  handleUserInput = (e) => {
    if (this.state && this.state.error) {
      this.setState({ error: null })
    }
    if (this.state && this.state.successMSG) {
      this.setState({ successMSG: null })
    }
    if (e.keyCode===ENTER) {
      this.processCreateQuestion()
    }
  }

  processCreateQuestion = () => {
    var questionObj = {};

    for (var ref in this.refs){
      if ( ref.match(/^answer[ABCDE]|title/) ){
        questionObj[ref] = (this.refs[ref].value);
      }

      if (!this.refs[ref].value) { //Check if form is empty
        this.setState({error: "Fill in the form!"});
        return;
      }
    }

    for (var dropdown in this.createQuesEle){
      questionObj[dropdown] = (this.createQuesEle[dropdown].value);
    }

    api.createQuestion(questionObj, auth.getToken())
      .then( (res) => {
        this.setState({successMSG: res.body.message})
      })
      .catch( (error) => {
        this.setState({error: "Error posting to questions table" + error})
      })
  }

  fetchLeQuestions = (rowOffset, limitRows, categoryId, level ) => {
    var arrayQuesObj = {};
    arrayQuesObj.rowOffset = rowOffset || 0;
    arrayQuesObj.limit = limitRows || 10;
    arrayQuesObj.catId = categoryId || undefined;
    arrayQuesObj.levelDifficulty = level || undefined;

    api.getArrayOfQuestions(arrayQuesObj, auth.getToken())
      .then(res => {
        if (res.body.length > 0) { //in case we don't get an array of rows back, moreover in case the user selects on the placeholder option
          this.setState({arrayQues: res.body, rowOffset: this.state.rowOffset + Number(this.showRowsEle.limitQuestions.value) });
        }
      })
  }

  showDiffQuestions = () => {
    this.setState({ rowOffset : 0}, //To reset the previous search we start at offset 0
      () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value))
      });
  }

  nextPage = () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value)) //Don't need to add to this.state.rowOffset in this function, as it gets added during the fetchLeQuestions
  }

  prevPage = () => {
    if (this.state.rowOffset - Number(this.showRowsEle.limitQuestions.value) < 1) { return }
    this.setState({ rowOffset : this.state.rowOffset - Number(this.showRowsEle.limitQuestions.value)*2 }, //We need multiply it by two as the offset goes up in fetchLeQuestions
      () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value))
      });
  }

  componentDidMount() {
    this.fetchLeQuestions();
  }

  deleteQuestion = (questionId, arrayIndex) => () => {
      api.deleteThisQuestion(questionId, auth.getToken())
        .then( () => { //Note here how I chose not to refetch the data to lessen server load, instead make it disappear on front-end - Vincent Lau
          this.setState({ arrayQues : this.state.arrayQues.slice(0, arrayIndex).concat( this.state.arrayQues.slice(arrayIndex + 1) ) }) // Slice out the deleted item
        })
  }

  render () {
    return (

        {(this.state.successMSG !== null) ?
          <DescriptiveTextBox theText={this.state.successMSG} bgColor="green"/>
          :
          null}
        {(this.state.error !== null) ?
          <DescriptiveTextBox theText={this.state.error} bgColor="red"/>
          :
          null}
        <input ref="title" type="text" onKeyUp={this.handleUserInput} placeholder={"Question"}/>
        {MultipleChoiceOptions.map( (letter) => {
          return <input type="text" onKeyUp={this.handleUserInput} placeholder={"Answer" + letter} ref={"answer"+letter} key={letter}/>
        })}
        <Dropdown innerRef={ (ele) => {this.createQuesEle.correctAnswer = ele} } onChange={this.handleUserInput} passedArray={MultipleChoiceOptions} useItemValueOrIndex={true} textBefore={"Answer "} showItem={true} textAfter={false}/>
        <Dropdown innerRef={ (ele) => {this.createQuesEle.level = ele} } onChange={this.handleUserInput} passedArray={GMATLevels} useItemValueOrIndex={true} textBefore={"Level "} showItem={true} textAfter={false}/>
        <Dropdown innerRef={ (ele) => {this.createQuesEle.categoryId = ele} } onChange={this.handleUserInput} passedArray={GMATCategories} useItemValueOrIndex={false} textBefore={false} showItem={true} textAfter={false}/>
        <DescriptiveTextBox theText="Create" onClick={this.processCreateQuestion}/>

Questions

        <Dropdown innerRef={ (ele) => {this.showRowsEle.levelShowQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATLevels} useItemValueOrIndex={true} textBefore={"Level "} showItem={true} textAfter={false}>
          <option>Level</option>
        </Dropdown>
        <Dropdown innerRef={ (ele) => {this.showRowsEle.categoryIdShowQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATCategories} useItemValueOrIndex={false} textBefore={false} showItem={true} textAfter={false}>
          <option>Category</option>
        </Dropdown>
        <Dropdown innerRef={ (ele) => {this.showRowsEle.limitQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATQuestionLimit} useItemValueOrIndex={true} textBefore={false} showItem={true} textAfter={" Per Page"}/>
        <button onClick={this.prevPage}>{"<"}</button>
        <button onClick={this.nextPage}>{">"}</button>
        {
          Array.isArray(this.state.arrayQues) && this.state.arrayQues.length > 0 ?

                  ID
                  Title
                  Category
                  Level

                {this.state.arrayQues.map((question, i) => {
                  return (

                      {question.id}
                      {question.title.substring(0, 21)}
                          {question.title.length > 20 ? "..." : null}
                      {question.categoryName}
                      {question.level}
                       <DeleteButton onClick={this.deleteQuestion(question.id, i)}/>

)
                })}

            :
            null
        }

    );
  }
}<commit_msg>Added small touchups, such as clear field on submitting an answerV<commit_after>import React, {Component} from 'react';
import './AdminDashboard.css';
import DescriptiveTextBox from '../elements/DescriptiveTextBox';
import DeleteButton from '../elements/DeleteButton';
import api from '../api';
import auth from '../auth';
import Dropdown from "../elements/Dropdown";

const ENTER = 13;
const GMATLevels = ['200', '300', '400'];
const GMATCategories = ['Math', 'Verbal', 'Writing', 'Reasoning', 'Data'];
const MultipleChoiceOptions = ['A', 'B', 'C', 'D', 'E'];
const GMATQuestionLimit = ['10', '25', '50'];

export default class AdminDashboard extends Component {
  constructor(){
    super();
    this.state={
      error : null,
      successMSG: null,
      rowOffset: 0
    }
    this.createQuesEle = {}
    this.showRowsEle = {}
  }

  handleUserInput = (e) => {
    if (this.state && this.state.error) { //clear error message on the page
      this.setState({ error: null })
    }
    if (this.state && this.state.successMSG) {
      this.setState({ successMSG: null })
    }
    if (e.keyCode===ENTER) {
      this.processCreateQuestion()
    }
  }

  processCreateQuestion = () => {
    var questionObj = {};

    for (var ref in this.refs){
      if ( ref.match(/^answer[ABCDE]|title/) ){
        questionObj[ref] = (this.refs[ref].value);
      }

      if (!this.refs[ref].value) { //Check if form is empty
        this.setState({error: "Fill in the form!"});
        return;
      }
    }

    for (var dropdown in this.createQuesEle){
      questionObj[dropdown] = (this.createQuesEle[dropdown].value);
    }

    api.createQuestion(questionObj, auth.getToken())
      .then( (res) => {
        this.setState({successMSG: res.body.message});
        for (var ref in this.refs){ //To clear the input fields
          if ( ref.match(/^answer[ABCDE]|title/) ){
            (this.refs[ref].value) = "";
          }
        }
      })
      .catch( (error) => {
        this.setState({error: "Error posting to questions table" + error})
      })
  }

  fetchLeQuestions = (rowOffset, limitRows, categoryId, level ) => {
    var arrayQuesObj = {};
    arrayQuesObj.rowOffset = rowOffset || 0;
    arrayQuesObj.limit = limitRows || 10;
    arrayQuesObj.catId = categoryId || undefined;
    arrayQuesObj.levelDifficulty = level || undefined;

    api.getArrayOfQuestions(arrayQuesObj, auth.getToken())
      .then(res => {
        if (res.body.length > 0) { //in case we don't get an array of rows back, moreover in case the user selects on the placeholder option
          this.setState({arrayQues: res.body, rowOffset: this.state.rowOffset + Number(this.showRowsEle.limitQuestions.value) });
        }
      })
  }

  showDiffQuestions = () => {
    this.setState({ rowOffset : 0}, //To reset the previous search we start at offset 0
      () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value))
      });
  }

  nextPage = () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value)) //Don't need to add to this.state.rowOffset in this function, as it gets added during the fetchLeQuestions
  }

  prevPage = () => {
    if (this.state.rowOffset - Number(this.showRowsEle.limitQuestions.value) < 1) { return }
    this.setState({ rowOffset : this.state.rowOffset - Number(this.showRowsEle.limitQuestions.value)*2 }, //We need multiply it by two as the offset goes up in fetchLeQuestions
      () => {
        this.fetchLeQuestions(this.state.rowOffset, this.showRowsEle.limitQuestions.value,
          (this.showRowsEle.categoryIdShowQuestions.value === "Category" ? undefined : this.showRowsEle.categoryIdShowQuestions.value ),
          (this.showRowsEle.levelShowQuestions.value === "Level" ? undefined : this.showRowsEle.levelShowQuestions.value))
      });
  }

  componentDidMount() {
    this.fetchLeQuestions();
  }

  deleteQuestion = (questionId, arrayIndex) => () => {
      api.deleteThisQuestion(questionId, auth.getToken())
        .then( () => { //Note here how I chose not to refetch the data to lessen server load, instead make it disappear on front-end - Vincent Lau
          this.setState({ arrayQues : this.state.arrayQues.slice(0, arrayIndex).concat( this.state.arrayQues.slice(arrayIndex + 1) ) }) // Slice out the deleted item
        })
  }

  render () {
    return (

        {(this.state.successMSG !== null) ?
          <DescriptiveTextBox theText={this.state.successMSG} bgColor="green"/>
          :
          null}
        {(this.state.error !== null) ?
          <DescriptiveTextBox theText={this.state.error} bgColor="red"/>
          :
          null}
        <input ref="title" type="text" onKeyUp={this.handleUserInput} placeholder={"Question"}/>
        {MultipleChoiceOptions.map( (letter) => {
          return <input type="text" onKeyUp={this.handleUserInput} placeholder={"Answer" + letter} ref={"answer"+letter} key={letter}/>
        })}
        <Dropdown innerRef={ (ele) => {this.createQuesEle.correctAnswer = ele} } onChange={this.handleUserInput} passedArray={MultipleChoiceOptions} useItemValueOrIndex={true} textBefore={"Answer "} showItem={true} textAfter={false}/>
        <Dropdown innerRef={ (ele) => {this.createQuesEle.level = ele} } onChange={this.handleUserInput} passedArray={GMATLevels} useItemValueOrIndex={true} textBefore={"Level "} showItem={true} textAfter={false}/>
        <Dropdown innerRef={ (ele) => {this.createQuesEle.categoryId = ele} } onChange={this.handleUserInput} passedArray={GMATCategories} useItemValueOrIndex={false} textBefore={false} showItem={true} textAfter={false}/>
        <DescriptiveTextBox theText="Create" onClick={this.processCreateQuestion}/>

Questions

        <Dropdown innerRef={ (ele) => {this.showRowsEle.levelShowQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATLevels} useItemValueOrIndex={true} textBefore={"Level "} showItem={true} textAfter={false}>
          <option>Level</option>
        </Dropdown>
        <Dropdown innerRef={ (ele) => {this.showRowsEle.categoryIdShowQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATCategories} useItemValueOrIndex={false} textBefore={false} showItem={true} textAfter={false}>
          <option>Category</option>
        </Dropdown>
        <Dropdown innerRef={ (ele) => {this.showRowsEle.limitQuestions = ele} } onChange={this.showDiffQuestions} passedArray={GMATQuestionLimit} useItemValueOrIndex={true} textBefore={false} showItem={true} textAfter={" Per Page"}/>
        <button onClick={this.prevPage}>{"<"}</button>
        <button onClick={this.nextPage}>{">"}</button>
        {
          Array.isArray(this.state.arrayQues) && this.state.arrayQues.length > 0 ?

                  ID
                  Title
                  Category
                  Level

                {this.state.arrayQues.map((question, i) => {
                  return (

                      {question.id}
                      {question.title.substring(0, 21)}
                          {question.title.length > 20 ? "..." : null}
                      {question.categoryName}
                      {question.level}
                       <DeleteButton onClick={this.deleteQuestion(question.id, i)}/>

)
                })}

            :
            null
        }

    );
  }
}<|endoftext|>


<commit_before>const fs = require("fs-extra-promise");
const path = require("path");

/* eslint-disable no-throw-literal */
exports.run = async (client, msg, [type, name]) => {
  const coreDir = client.coreBaseDir;
  const clientDir = client.clientBaseDir;
  const reload = {
    command: client.funcs.reloadCommand,
    function: client.funcs.reloadFunction,
    inhibitor: client.funcs.reloadInhibitor,
    finalizer: client.funcs.reloadFinalizer,
    event: client.funcs.reloadEvent,
    monitor: client.funcs.reloadMessageMonitor,
  };
  const isCommand = type === "command" ? "System/" : "";
  fs.copyAsync(path.resolve(`${coreDir}/${type}s/${isCommand}${name}.js`), path.resolve(`${clientDir}/${type}s/${isCommand}${name}.js`))
    .then(() => {
      reload[type](`System/${name}`).catch((response) => { throw `❌ ${response}`; });
      return msg.sendMessage(`✅ Successfully Transferred ${type}: ${name}`);
    })
    .catch((err) => {
      client.emit("error", err.stack);
      return msg.sendMessage(`Transfer of ${type}: ${name} to Client has failed. Please check your Console.`);
    });
};

exports.conf = {
  enabled: true,
  runIn: ["text", "dm", "group"],
  aliases: [],
  permLevel: 10,
  botPerms: [],
  requiredFuncs: [],
};

exports.help = {
  name: "transfer",
  description: "Transfers a core piece to its respected folder",
  usage: "<command|function|inhibitor|event|monitor> <name:str>",
  usageDelim: " ",
};
<commit_msg>Fixed Transfer command<commit_after>const fs = require("fs-extra-promise");
const path = require("path");

/* eslint-disable no-throw-literal */
exports.run = async (client, msg, [type, name]) => {
  const coreDir = client.coreBaseDir;
  const clientDir = client.clientBaseDir;
  const reload = {
    command: client.funcs.reloadCommand,
    function: client.funcs.reloadFunction,
    inhibitor: client.funcs.reloadInhibitor,
    finalizer: client.funcs.reloadFinalizer,
    event: client.funcs.reloadEvent,
    monitor: client.funcs.reloadMessageMonitor,
  };
  const isCommand = type === "command" ? "System/" : "";
  fs.copyAsync(path.resolve(`${coreDir}/${type}s/${isCommand}${name}.js`), path.resolve(`${clientDir}/${type}s/${isCommand}${name}.js`))
    .then(() => {
      reload[type].call(client.funcs, `${isCommand}${name}`).catch((response) => { throw `❌ ${response}`; });
      return msg.sendMessage(`✅ Successfully Transferred ${type}: ${name}`);
    })
    .catch((err) => {
      client.emit("error", err.stack);
      return msg.sendMessage(`Transfer of ${type}: ${name} to Client has failed. Please check your Console.`);
    });
};

exports.conf = {
  enabled: true,
  runIn: ["text", "dm", "group"],
  aliases: [],
  permLevel: 10,
  botPerms: [],
  requiredFuncs: [],
};

exports.help = {
  name: "transfer",
  description: "Transfers a core piece to its respected folder",
  usage: "<command|function|inhibitor|event|monitor> <name:str>",
  usageDelim: " ",
};
<|endoftext|>


<commit_before>/**
 * Z-BlogPHP JavaScript Framework
 * @author zsx<zsx@zsxsoft.com>
 */
(function () {
	/**
	 * Class ZBP
	 *
	 * @constructor
	 * @global
	 * @class ZBP
	 * @param options {OPTION} Init option
	 * @param jquery {object} jQuery
	 */
	var ZBP = function (options, jquery) {
		/** Load jQuery library */
		if (typeof jQuery == 'undefined' && typeof jquery == 'undefined') throw new Error('No jQuery!');
		this.$ = jquery || jQuery;

		/** Init self */
		var self = this;
		initMethods(this);

		/** Init option */
		options = options || {};
		options.cookiepath = options.cookiepath || "/";
		options.bloghost = options.bloghost || location.origin;
		options.ajaxurl = options.ajaxurl || location.origin;
		options.commentmaxlength = options.commentmaxlength || 1000;
		options.lang = options.lang || {};
		/**
		 * Class option
		 * @memberOf ZBP
		 * @typedef {OPTION}
		 * @property {string} cookiepath - Cookie Path
		 * @property {string} bloghost - Blog Host
		 * @property {string} ajaxurl - Ajax Url
		 * @property {string} commentmaxlength - Maximum acceptable length for comment
		 * @property {object} lang - Language
		 * @type {object}
		 */
		this.options = options;

		this.userinfo.username = this.cookie.get("name");
		this.userinfo.mail = this.cookie.get("email");
		this.userinfo.homepage = this.cookie.get("homepage");

		/** Register system events */
		this.plugin.on("userinfo.output", "system", function () {
			this.$("#inpName").val(this.userinfo.username);
			this.$("#inpEmail").val(this.userinfo.mail);
			this.$("#inpHomePage").val(this.userinfo.homepage);
		});

		this.plugin.on("userinfo.savefromhtml", "system", function () {
			this.userinfo.username = this.$("#inpName").val();
			this.userinfo.mail = this.$("#inpEmail").val();
			this.userinfo.homepage = this.$("#inpHomePage").val();
			this.userinfo.save();
		});

		this.plugin.on("userinfo.save", "system", function () {
			this.cookie.set("name", this.userinfo.username);
			this.cookie.set("email", this.userinfo.mail);
			this.cookie.set("homepage", this.userinfo.homepage);
		});

		this.plugin.on("comment.verifydata", "system", function (error, formData) {

			var regExList = {
				// [canBeEmpty, errorCode, RegExp]
				"name": [false, 72, /^[\.\_A-Za-z0-9\u4e00-\u9fa5]+$/ig],
				"email": [true, 29, /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/ig],
				"content": [false, 46, /./]
			};

			for (var item in regExList) {
				var object = regExList[item];
				if (((!object[0] && formData[item] == "")) || (!(object[2].test(formData[item])) && formData[item] != '')) {
					error.no = object[1];
					error.msg = this.options.lang.error[error.no];
					return error;
				}
			}

			var objSubmit = $("#inpId").parent("form").find(":submit");
			objSubmit.data("orig", objSubmit.val()).val("Waiting...").attr("disabled","disabled").addClass("loading");

		});

		this.plugin.on("comment.postsuccess", "system", function (formData, data, textStatus, jqXhr) {

			var objSubmit = $("#inpId").parent("form").find(":submit");
			objSubmit.removeClass("loading").removeAttr("disabled").val(objSubmit.data("orig"));

			if((data.search("faultCode") > 0) && (data.search("faultString")>0)) {
				var errorData = s.match("<string>.+?</string>")[0].replace("<string>","").replace("</string>","");
				alert(errorData);
				try {console.log(arguments); console.log("ERROR - " + errorData)} catch (e) { /* do nothing*/}
			}
			else {
				var cmt = data.match(/cmt\d+/);
				if(formData.replyid == 0){
					this.$(data).insertAfter("#AjaxCommentBegin");
				} else {
					this.$(data).insertAfter("#AjaxComment" + formData.replyid);
				}
				location.hash = "#" + cmt;
				this.$("#txaArticle").val("");

				this.userinfo.saveFromHtml();
			}

		});

		this.plugin.on("comment.get", "system", function (postid, page) {
			this.$.get(this.options.bloghost + "zb_system/cmd.php?act=getcmt&postid=" + postid + "&page=" + page, function (data, textStatus, jqXhr) {
				this.plugin.emit("comment.got", [postid, page], data, textStatus, jqXhr)
			});
		});

		this.plugin.on("comment.got", "system", function (formData, data, textStatus, jqXhr) {
			this.$('#AjaxCommentBegin').nextUntil('#AjaxCommentEnd').remove();
			this.$('#AjaxCommentBegin').after(data);
		});

		this.plugin.on("comment.revert", "system", function (id) {
			var me = this;
			this.$("#inpRevID").val(id);
			this.$("#cancel-reply").show().bind("click", function () {
				me.$("#inpRevID").val(0);
				me.$(this).hide();
				window.location.hash = "#comment";
				return false;
			});
			window.location.hash="#comment";
		});

		return this;

	};
	/**
	 * Private _plugins
	 *
	 * @type {Object}
	 */
	ZBP.prototype._plugins = {};
	/**
	 * Init prototype for ZBP
	 *
	 * @param  object
	 **/
	var initMethods = function (self) {

		/**
		 * PLUGIN
		 * @class PLUGIN
		 */
		var PLUGIN = function () {};
		/**
		 * Add listener
		 * @function
	 	 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @param pluginName {string}
		 * @param callback {Function}
		 * @return {object} this
		 */
		PLUGIN.prototype.bind = PLUGIN.prototype.on = PLUGIN.prototype.addListener = function (interfaceName, pluginName, callback) {
			if (typeof self._plugins[interfaceName] == 'undefined') self._plugins[interfaceName] = {};
			self._plugins[interfaceName][pluginName] = callback;
			return self;
		}
		/**
		 * Remove listener
		 * @function
		 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @param pluginName {string}
		 * @return {object} this
		 */
		PLUGIN.prototype.unbind = PLUGIN.prototype.removeListener = function (interfaceName, pluginName) {
			if (!pluginName) pluginName = "";
			if (pluginName == "") {
				self._plugins[interfaceName] = {};
			} else {
				self._plugins[interfaceName][pluginName] = null;
			}
			return self;
		}
		/**
		 * Call listener
		 * @function
		 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @return {object} this
		 */
		PLUGIN.prototype.emit = function (interfaceName) {
			// var argu = self.$.extend([], arguments);
			// argu.shift();
			// Let's fuck IE6 together!
			var argu = []
			for (var i = 1; i < arguments.length; i++) {
				argu.push(arguments[i]);
			}
			for (var item in self._plugins[interfaceName]) {
				self._plugins[interfaceName][item].apply(self, argu);
			}
			return self;
		}
		/**
		 * plugin
		 * @memberOf ZBP
		 * @type {PLUGIN}
		 */
		self.plugin = new PLUGIN();

		/**
		 * COOKIE
		 * @class COOKIE
		 */
		var COOKIE = function () {};
		/**
		 * Get Cookie
		 * @memberOf COOKIE
		 * @param sCookieName {string} Cookie Key
		 * @return cookieValue {string} Cookie Value
		 */
		COOKIE.prototype.get = function (sCookieName) {
			var arr = document.cookie.match(new RegExp("(^| )" + sCookieName + "=([^;]*)(;|$)"));
			return (arr ? unescape(arr[2]) : null);
		};
		/**
		 * Set Cookie
		 * @memberOf COOKIE
		 * @param sCookieName {string} Cookie Key
		 * @param sCookieValue {string} Cookie Value
		 * @param iExpireDays {int} Cookie Expires
		 * @return ZBP {ZBP}
		 */
		COOKIE.prototype.set = function (sCookieName, sCookieValue, iExpireDays) {
			var dExpire = new Date();
			if (iExpireDays) {
				dExpire.setTime(dExpire.getTime() + parseInt(iExpireDays * 24 * 60 * 60 * 1000));
			}
			document.cookie = sCookieName + "=" + escape(sCookieValue) + "; " + (iExpireDays ? "expires=" + dExpire.toGMTString() + "; " : "") + "path=" + self.options.cookiepath;
			return self;
		}
		/**
		 * cookie
		 * @memberOf ZBP
		 * @type {COOKIE}
		 */
		self.cookie = new COOKIE();

		/**
		 * USERINFO
		 * @class USERINFO
		 */
		var USERINFO = function () {};
		/**
		 * Output user information to DOM
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.output = function () {
			self.plugin.emit("userinfo.output");
			return self;
		}
		/**
		 * Save user information from class
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.save = function () {
			self.plugin.emit("userinfo.save");
			return self;
		}
		/**
		 * Save user information from DOM
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.saveFromHtml = function () {
			self.plugin.emit("userinfo.savefromhtml");
			return self;
		}
		/**
		 * userinfo
		 * @type {USERINFO}
		 * @memberOf ZBP
		 */
		self.userinfo = new USERINFO();

		/**
		 * COMMENT
		 * @class COMMENT
		 */
		var COMMENT = function () {};
		/**
		 * Get comments
		 * @memberOf COMMENT
		 * @param postid {int} Article ID
		 * @param page {int} Page
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.get = function (postid, page) {
			self.plugin.emit("comment.get", postid, page);
			return self;
		}
		/**
		 * Revert Comment
		 * @memberOf COMMENT
		 * @param int {int} Comment ID
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.revert = function (id) {
			self.plugin.emit("comment.revert", id);
			return self;
		}
		/**
		 * Post Comment
		 * @memberOf COMMENT
		 * @param formData {PostData}
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.post = function(formData) {

			/**
			 * Form Data
			 * @name POSTFORMDATA
			 * @typedef {Object} PostData
			 * @memberOf COMMENT
			 * @property {string} action - Post Url
			 * @property {string} postid - Article ID
			 * @property {string} verify - Verify code
			 * @property {string} name   - Comment user name
			 * @property {string} email  - Comment user E-mail
			 * @property {string} content - Comment content
			 * @property {string} homepage - Comment user Website
			 * @property {string} replyid - Comment Parent ID
			 * @property {string} isajax - Return Ajax String
			 * @type {object}
			 */
			formData = formData || {};
			formData.action   = formData.action   || $("#inpId").parent("form").attr("action");
			formData.postid   = formData.postid   || $("#inpId").val();
			formData.verify   = formData.verify   || $("#inpVerify").val();
			formData.name     = formData.name     || $("#inpName").val();
			formData.email    = formData.email    || $("#inpEmail").val();
			formData.content  = formData.content  || $("#txaArticle").val();
			formData.homepage = formData.homepage || $("#inpHomePage").val();
			formData.replyid  = formData.replyid  || $("#inpRevID").val();
			formData.isajax   = formData.isajax   || true;

			var error = {
				no: 0,
				msg: ""
			};

			self.plugin.emit("comment.verifydata", error, formData);

			if (error.no != 0) {
				alert(error.msg);
				try { console.log(formData); console.log("ERROR - " + error.msg)} catch (e) { /* do nothing */}
				return self;
			}
			self.$.post(formData.action, formData, function (data, textStatus, jqXhr) {
				self.plugin.emit("comment.postsuccess", formData, data, textStatus, jqXhr);
			});

			return self;
		}
		/**
		 * comment
		 * @memberOf ZBP
		 * @type {COMMENT}
		 */
		self.comment = new COMMENT();
	};

	/**
	 * ZBP Module
	 * (AMD & CMD compatible)
	 * @module zbp
	 */
	if (typeof define === "function" && define.amd) {
		define("zbp", [], function() {
			return ZBP;
		});
	} else if (typeof define === "function" && define.cmd) {
		define("zbp", [], function (require, exports, module) {
			module.exports = ZBP;
		});
	} else {
		window.ZBP = ZBP;
	}

})();<commit_msg>恢复 -> 回复……<commit_after>/**
 * Z-BlogPHP JavaScript Framework
 * @author zsx<zsx@zsxsoft.com>
 */
(function () {
	/**
	 * Class ZBP
	 *
	 * @constructor
	 * @global
	 * @class ZBP
	 * @param options {OPTION} Init option
	 * @param jquery {object} jQuery
	 */
	var ZBP = function (options, jquery) {
		/** Load jQuery library */
		if (typeof jQuery == 'undefined' && typeof jquery == 'undefined') throw new Error('No jQuery!');
		this.$ = jquery || jQuery;

		/** Init self */
		var self = this;
		initMethods(this);

		/** Init option */
		options = options || {};
		options.cookiepath = options.cookiepath || "/";
		options.bloghost = options.bloghost || location.origin;
		options.ajaxurl = options.ajaxurl || location.origin;
		options.commentmaxlength = options.commentmaxlength || 1000;
		options.lang = options.lang || {};
		/**
		 * Class option
		 * @memberOf ZBP
		 * @typedef {OPTION}
		 * @property {string} cookiepath - Cookie Path
		 * @property {string} bloghost - Blog Host
		 * @property {string} ajaxurl - Ajax Url
		 * @property {string} commentmaxlength - Maximum acceptable length for comment
		 * @property {object} lang - Language
		 * @type {object}
		 */
		this.options = options;

		this.userinfo.username = this.cookie.get("name");
		this.userinfo.mail = this.cookie.get("email");
		this.userinfo.homepage = this.cookie.get("homepage");

		/** Register system events */
		this.plugin.on("userinfo.output", "system", function () {
			this.$("#inpName").val(this.userinfo.username);
			this.$("#inpEmail").val(this.userinfo.mail);
			this.$("#inpHomePage").val(this.userinfo.homepage);
		});

		this.plugin.on("userinfo.savefromhtml", "system", function () {
			this.userinfo.username = this.$("#inpName").val();
			this.userinfo.mail = this.$("#inpEmail").val();
			this.userinfo.homepage = this.$("#inpHomePage").val();
			this.userinfo.save();
		});

		this.plugin.on("userinfo.save", "system", function () {
			this.cookie.set("name", this.userinfo.username);
			this.cookie.set("email", this.userinfo.mail);
			this.cookie.set("homepage", this.userinfo.homepage);
		});

		this.plugin.on("comment.verifydata", "system", function (error, formData) {

			var regExList = {
				// [canBeEmpty, errorCode, RegExp]
				"name": [false, 72, /^[\.\_A-Za-z0-9\u4e00-\u9fa5]+$/ig],
				"email": [true, 29, /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/ig],
				"content": [false, 46, /./]
			};

			for (var item in regExList) {
				var object = regExList[item];
				if (((!object[0] && formData[item] == "")) || (!(object[2].test(formData[item])) && formData[item] != '')) {
					error.no = object[1];
					error.msg = this.options.lang.error[error.no];
					return error;
				}
			}

			var objSubmit = $("#inpId").parent("form").find(":submit");
			objSubmit.data("orig", objSubmit.val()).val("Waiting...").attr("disabled","disabled").addClass("loading");

		});

		this.plugin.on("comment.postsuccess", "system", function (formData, data, textStatus, jqXhr) {

			var objSubmit = $("#inpId").parent("form").find(":submit");
			objSubmit.removeClass("loading").removeAttr("disabled").val(objSubmit.data("orig"));

			if((data.search("faultCode") > 0) && (data.search("faultString")>0)) {
				var errorData = s.match("<string>.+?</string>")[0].replace("<string>","").replace("</string>","");
				alert(errorData);
				try {console.log(arguments); console.log("ERROR - " + errorData)} catch (e) { /* do nothing*/}
			}
			else {
				var cmt = data.match(/cmt\d+/);
				if(formData.replyid == 0){
					this.$(data).insertAfter("#AjaxCommentBegin");
				} else {
					this.$(data).insertAfter("#AjaxComment" + formData.replyid);
				}
				location.hash = "#" + cmt;
				this.$("#txaArticle").val("");

				this.userinfo.saveFromHtml();
			}

		});

		this.plugin.on("comment.get", "system", function (postid, page) {
			this.$.get(this.options.bloghost + "zb_system/cmd.php?act=getcmt&postid=" + postid + "&page=" + page, function (data, textStatus, jqXhr) {
				this.plugin.emit("comment.got", [postid, page], data, textStatus, jqXhr)
			});
		});

		this.plugin.on("comment.got", "system", function (formData, data, textStatus, jqXhr) {
			this.$('#AjaxCommentBegin').nextUntil('#AjaxCommentEnd').remove();
			this.$('#AjaxCommentBegin').after(data);
		});

		this.plugin.on("comment.reply", "system", function (id) {
			var me = this;
			this.$("#inpRevID").val(id);
			this.$("#cancel-reply").show().bind("click", function () {
				me.$("#inpRevID").val(0);
				me.$(this).hide();
				window.location.hash = "#comment";
				return false;
			});
			window.location.hash="#comment";
		});

		return this;

	};
	/**
	 * Private _plugins
	 *
	 * @type {Object}
	 */
	ZBP.prototype._plugins = {};
	/**
	 * Init prototype for ZBP
	 *
	 * @param  object
	 **/
	var initMethods = function (self) {

		/**
		 * PLUGIN
		 * @class PLUGIN
		 */
		var PLUGIN = function () {};
		/**
		 * Add listener
		 * @function
	 	 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @param pluginName {string}
		 * @param callback {Function}
		 * @return {object} this
		 */
		PLUGIN.prototype.bind = PLUGIN.prototype.on = PLUGIN.prototype.addListener = function (interfaceName, pluginName, callback) {
			if (typeof self._plugins[interfaceName] == 'undefined') self._plugins[interfaceName] = {};
			self._plugins[interfaceName][pluginName] = callback;
			return self;
		}
		/**
		 * Remove listener
		 * @function
		 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @param pluginName {string}
		 * @return {object} this
		 */
		PLUGIN.prototype.unbind = PLUGIN.prototype.removeListener = function (interfaceName, pluginName) {
			if (!pluginName) pluginName = "";
			if (pluginName == "") {
				self._plugins[interfaceName] = {};
			} else {
				self._plugins[interfaceName][pluginName] = null;
			}
			return self;
		}
		/**
		 * Call listener
		 * @function
		 * @memberOf PLUGIN
		 * @param interfaceName {string}
		 * @return {object} this
		 */
		PLUGIN.prototype.emit = function (interfaceName) {
			// var argu = self.$.extend([], arguments);
			// argu.shift();
			// Let's fuck IE6 together!
			var argu = []
			for (var i = 1; i < arguments.length; i++) {
				argu.push(arguments[i]);
			}
			for (var item in self._plugins[interfaceName]) {
				self._plugins[interfaceName][item].apply(self, argu);
			}
			return self;
		}
		/**
		 * plugin
		 * @memberOf ZBP
		 * @type {PLUGIN}
		 */
		self.plugin = new PLUGIN();

		/**
		 * COOKIE
		 * @class COOKIE
		 */
		var COOKIE = function () {};
		/**
		 * Get Cookie
		 * @memberOf COOKIE
		 * @param sCookieName {string} Cookie Key
		 * @return cookieValue {string} Cookie Value
		 */
		COOKIE.prototype.get = function (sCookieName) {
			var arr = document.cookie.match(new RegExp("(^| )" + sCookieName + "=([^;]*)(;|$)"));
			return (arr ? unescape(arr[2]) : null);
		};
		/**
		 * Set Cookie
		 * @memberOf COOKIE
		 * @param sCookieName {string} Cookie Key
		 * @param sCookieValue {string} Cookie Value
		 * @param iExpireDays {int} Cookie Expires
		 * @return ZBP {ZBP}
		 */
		COOKIE.prototype.set = function (sCookieName, sCookieValue, iExpireDays) {
			var dExpire = new Date();
			if (iExpireDays) {
				dExpire.setTime(dExpire.getTime() + parseInt(iExpireDays * 24 * 60 * 60 * 1000));
			}
			document.cookie = sCookieName + "=" + escape(sCookieValue) + "; " + (iExpireDays ? "expires=" + dExpire.toGMTString() + "; " : "") + "path=" + self.options.cookiepath;
			return self;
		}
		/**
		 * cookie
		 * @memberOf ZBP
		 * @type {COOKIE}
		 */
		self.cookie = new COOKIE();

		/**
		 * USERINFO
		 * @class USERINFO
		 */
		var USERINFO = function () {};
		/**
		 * Output user information to DOM
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.output = function () {
			self.plugin.emit("userinfo.output");
			return self;
		}
		/**
		 * Save user information from class
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.save = function () {
			self.plugin.emit("userinfo.save");
			return self;
		}
		/**
		 * Save user information from DOM
		 * @memberOf USERINFO
		 * @return ZBP {ZBP}
		 */
		USERINFO.prototype.saveFromHtml = function () {
			self.plugin.emit("userinfo.savefromhtml");
			return self;
		}
		/**
		 * userinfo
		 * @type {USERINFO}
		 * @memberOf ZBP
		 */
		self.userinfo = new USERINFO();

		/**
		 * COMMENT
		 * @class COMMENT
		 */
		var COMMENT = function () {};
		/**
		 * Get comments
		 * @memberOf COMMENT
		 * @param postid {int} Article ID
		 * @param page {int} Page
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.get = function (postid, page) {
			self.plugin.emit("comment.get", postid, page);
			return self;
		}
		/**
		 * Reply Comment
		 * @memberOf COMMENT
		 * @param int {int} Comment ID
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.reply = function (id) {
			self.plugin.emit("comment.reply", id);
			return self;
		}
		/**
		 * Post Comment
		 * @memberOf COMMENT
		 * @param formData {PostData}
		 * @return ZBP {ZBP}
		 */
		COMMENT.prototype.post = function(formData) {

			/**
			 * Form Data
			 * @name POSTFORMDATA
			 * @typedef {Object} PostData
			 * @memberOf COMMENT
			 * @property {string} action - Post Url
			 * @property {string} postid - Article ID
			 * @property {string} verify - Verify code
			 * @property {string} name   - Comment user name
			 * @property {string} email  - Comment user E-mail
			 * @property {string} content - Comment content
			 * @property {string} homepage - Comment user Website
			 * @property {string} replyid - Comment Parent ID
			 * @property {string} isajax - Return Ajax String
			 * @type {object}
			 */
			formData = formData || {};
			formData.action   = formData.action   || $("#inpId").parent("form").attr("action");
			formData.postid   = formData.postid   || $("#inpId").val();
			formData.verify   = formData.verify   || $("#inpVerify").val();
			formData.name     = formData.name     || $("#inpName").val();
			formData.email    = formData.email    || $("#inpEmail").val();
			formData.content  = formData.content  || $("#txaArticle").val();
			formData.homepage = formData.homepage || $("#inpHomePage").val();
			formData.replyid  = formData.replyid  || $("#inpRevID").val();
			formData.isajax   = formData.isajax   || true;

			var error = {
				no: 0,
				msg: ""
			};

			self.plugin.emit("comment.verifydata", error, formData);

			if (error.no != 0) {
				alert(error.msg);
				try { console.log(formData); console.log("ERROR - " + error.msg)} catch (e) { /* do nothing */}
				return self;
			}
			self.$.post(formData.action, formData, function (data, textStatus, jqXhr) {
				self.plugin.emit("comment.postsuccess", formData, data, textStatus, jqXhr);
			});

			return self;
		}
		/**
		 * comment
		 * @memberOf ZBP
		 * @type {COMMENT}
		 */
		self.comment = new COMMENT();
	};

	/**
	 * ZBP Module
	 * (AMD & CMD compatible)
	 * @module zbp
	 */
	if (typeof define === "function" && define.amd) {
		define("zbp", [], function() {
			return ZBP;
		});
	} else if (typeof define === "function" && define.cmd) {
		define("zbp", [], function (require, exports, module) {
			module.exports = ZBP;
		});
	} else {
		window.ZBP = ZBP;
	}

})();<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: [
    './src/index.js',
  ],

  output: {
    filename: 'static/bundle.js',
    path: path.resolve(__dirname, 'build'),
    publicPath: 'file://' + path.resolve(__dirname, 'build') + '/'
  },

  resolve: {
    modules: [
      'node_modules',
      'src',
      'public'
    ],
    extensions: ['.js', '.jsx', '.scss', '.sass']
  },

  devtool: 'source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(png|jpg|svg|pdf)$/,
        include: [path.resolve(__dirname, './public/images')],
        use: 'url-loader?limit=5000'
      },
      {
        test: /\.sass$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader!sass-loader",
        })
      },
      {
        test: /\.(ttf|pdf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'file-loader'
      }
    ],
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      comments: false
    }),
    new ExtractTextPlugin("static/styles.css")
  ],
};
<commit_msg>Changed publicPath<commit_after>var path = require('path');
var webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: [
    './src/index.js',
  ],

  output: {
    filename: 'static/bundle.js',
    path: path.resolve(__dirname, 'build'),
    publicPath: 'https://phaze1d.github.io/Interactive-Resume/'
  },

  resolve: {
    modules: [
      'node_modules',
      'src',
      'public'
    ],
    extensions: ['.js', '.jsx', '.scss', '.sass']
  },

  devtool: 'source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(png|jpg|svg|pdf)$/,
        include: [path.resolve(__dirname, './public/images')],
        use: 'url-loader?limit=5000'
      },
      {
        test: /\.sass$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader!sass-loader",
        })
      },
      {
        test: /\.(ttf|pdf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'file-loader'
      }
    ],
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      comments: false
    }),
    new ExtractTextPlugin("static/styles.css")
  ],
};
<|endoftext|>


<commit_before>const loadCommand = (command) => require(`../${command}`)
const config = require('../../config.json')
const commandList = require('../../util/commandList.json')
const channelTracker = require('../../util/channelTracker.js')

module.exports = function (bot, message, isCallingCmd, command, callback) {
  if (commandList[command] != null) var commandFile = commandList[command].file
  var rssList = []
  try {rssList = require(`../../sources/${message.guild.id}.json`).sources} catch(e) {}

  var embed = {embed: {
    color: config.menuColor,
    description: `**Server Limit:** ${rssList.length}/${config.maxFeeds}\n`,
    author: {},
    fields: [],
    footer: {}
  }}

  function isCurrentChannel(channel) {
    if (isNaN(parseInt(channel,10))) {
      if (message.channel.name == channel) return true;
      else return false;
    }
    else {
      if (message.channel.id == channel) return true;
      else return false;
    }
  }

  function getChannel(channel) {
    if (isNaN(parseInt(channel,10)) && bot.channels.find("name", channel) != null) return `<#${bot.channels.find("name", channel).id}>`;
    else if (bot.channels.get(channel) != null) return `<#${channel}>`;
    else return `Error: ${channel} not found in guild.`;
  }

  var currentRSSList = [];
  for (var rssIndex in rssList){
    if (isCallingCmd && isCurrentChannel(rssList[rssIndex].channel)) currentRSSList.push( [rssList[rssIndex].link, rssIndex, rssList[rssIndex].title] );
    else if (!isCallingCmd) currentRSSList.push( [rssList[rssIndex].link, rssIndex, rssList[rssIndex].title, getChannel(rssList[rssIndex].channel)] )
  }

  if (currentRSSList.length <= 0) {
    if (isCallingCmd) return message.channel.sendMessage("No feeds assigned to this channel.");
    else return message.channel.sendMessage("There are no existing feeds.");
  }

  let returnMsg = "```Markdown\n# Feeds assigned to this channel: ``````Markdown\n"
  for (var x in currentRSSList) {
    let count = parseInt(x,10) + 1;
    returnMsg += `[${count}]: ${currentRSSList[x][0]}\n`
    embed.embed.fields.push({
      name: `${count})  ${currentRSSList[x][2]}`,
      value: ""
    })
    if (isCallingCmd) embed.embed.fields[embed.embed.fields.length - 1].value = `Link: ${currentRSSList[x][0]}`;
    else embed.embed.fields[embed.embed.fields.length - 1].value = `Channel: ${currentRSSList[x][3]}\nLink: ${currentRSSList[x][0]}`;
  }

  if (isCallingCmd) {
    embed.embed.author.name = "Feed Selection Menu";
    embed.embed.description += `**Channel:** #${message.channel.name}\n**Action**: ${commandList[command].action}\n\nChoose a feed to from this channel by typing the number to execute your requested action on. Type **exit** to cancel.\n_____`;
    var error = false;
    message.channel.sendEmbed(embed.embed).catch(err => {error = true; console.log(`Message Error: (${message.guild.id}, ${message.guild.name}) => Could not send message of embed feed selection list. Reason: ${err.response.body.message}`);});

  }
  else {
    embed.embed.author.name = "Current Active Feeds"
    embed.embed.description += `_____`;
    return message.channel.sendEmbed(embed.embed).catch(err => console.log(`Message Error: (${message.guild.id}, ${message.guild.name}) => Could not send message of embed feed list. Reason: ${err.response.body.message}`));
  }

  if (error) return;

  const filter = m => m.author.id == message.author.id
  const collector = message.channel.createCollector(filter,{time:60000})
  channelTracker.addCollector(message.channel.id)

  collector.on('message', function (m) {
    let chosenOption = m.content;
    if (chosenOption.toLowerCase() == "exit") return collector.stop("RSS Feed selection menu closed.");
    let index = parseInt(chosenOption, 10) - 1;

    if (isNaN(index) || chosenOption > currentRSSList.length || chosenOption < 1) return message.channel.sendMessage("That is not a valid number.");
    else {
      collector.stop();
      let rssIndex = currentRSSList[index][1];
      if (!commandList[command].specialCmd) loadCommand(commandFile)(message, rssIndex);
      else callback(rssIndex);
    }
  })
  collector.on('end', (collected, reason) => {
    channelTracker.removeCollector(message.channel.id)
    if (reason == "time") return message.channel.sendMessage(`I have closed the menu due to inactivity.`);
    else if (reason !== "user") return message.channel.sendMessage(reason);
  })

}
<commit_msg>solved potential issue with printing feeds<commit_after>const loadCommand = (command) => require(`../${command}`)
const config = require('../../config.json')
const commandList = require('../../util/commandList.json')
const channelTracker = require('../../util/channelTracker.js')

module.exports = function (bot, message, isCallingCmd, command, callback) {
  if (commandList[command] != null) var commandFile = commandList[command].file
  var rssList = []
  try {rssList = require(`../../sources/${message.guild.id}.json`).sources} catch(e) {}

  var embed = {embed: {
    color: config.menuColor,
    description: `**Server Limit:** ${rssList.length}/${config.maxFeeds}\n`,
    author: {},
    fields: [],
    footer: {}
  }}

  function isCurrentChannel(channel) {
    if (isNaN(parseInt(channel,10))) {
      if (message.channel.name == channel) return true;
      else return false;
    }
    else {
      if (message.channel.id == channel) return true;
      else return false;
    }
  }

  function getChannel(channel) {
    if (isNaN(parseInt(channel,10)) && bot.channels.find("name", channel) != null) return `<#${bot.channels.find("name", channel).id}>`;
    else if (bot.channels.get(channel) != null) return `${channel}`;
    else return `Error: ${channel} not found in guild.`;
  }

  var currentRSSList = [];
  for (var rssIndex in rssList){
    if (isCallingCmd && isCurrentChannel(rssList[rssIndex].channel)) currentRSSList.push( [rssList[rssIndex].link, rssIndex, rssList[rssIndex].title] );
    else if (!isCallingCmd) currentRSSList.push( [rssList[rssIndex].link, rssIndex, rssList[rssIndex].title, getChannel(rssList[rssIndex].channel)] )
  }

  if (currentRSSList.length <= 0) {
    if (isCallingCmd) return message.channel.sendMessage("No feeds assigned to this channel.");
    else return message.channel.sendMessage("There are no existing feeds.");
  }

  for (var x in currentRSSList) {
    let count = parseInt(x,10) + 1;
    let link = currentRSSList[x][0];
    let title =  currentRSSList[x][2]
    let channelID = currentRSSList[x][3];

    if (isCallingCmd) var info = `Link: ${link}`;
    else var info = `Channel: <#${channelID}> (#${bot.channels.get(channelID).name})\nLink: ${link}`;

    embed.embed.fields.push({
      name: `${count})  ${title}`,
      value: info
    })

  }

  if (isCallingCmd) {
    embed.embed.author.name = "Feed Selection Menu";
    embed.embed.description += `**Channel:** #${message.channel.name}\n**Action**: ${commandList[command].action}\n\nChoose a feed to from this channel by typing the number to execute your requested action on. Type **exit** to cancel.\n_____`;
    var error = false;
    message.channel.sendEmbed(embed.embed).catch(err => {error = true; console.log(`Message Error: (${message.guild.id}, ${message.guild.name}) => Could not send message of embed feed selection list. Reason: ${err.response.body.message}, embed is: `, embed.embed);});

  }
  else {
    embed.embed.author.name = "Current Active Feeds"
    embed.embed.description += `_____`;
    return message.channel.sendEmbed(embed.embed).catch(err => console.log(`Message Error: (${message.guild.id}, ${message.guild.name}) => Could not send message of embed feed list. Reason: ${err.response.body.message}`));
  }

  if (error) return;

  const filter = m => m.author.id == message.author.id
  const collector = message.channel.createCollector(filter,{time:60000})
  channelTracker.addCollector(message.channel.id)

  collector.on('message', function (m) {
    let chosenOption = m.content;
    if (chosenOption.toLowerCase() == "exit") return collector.stop("RSS Feed selection menu closed.");
    let index = parseInt(chosenOption, 10) - 1;

    if (isNaN(index) || chosenOption > currentRSSList.length || chosenOption < 1) return message.channel.sendMessage("That is not a valid number.");
    else {
      collector.stop();
      let rssIndex = currentRSSList[index][1];
      if (!commandList[command].specialCmd) loadCommand(commandFile)(message, rssIndex);
      else callback(rssIndex);
    }
  })
  collector.on('end', (collected, reason) => {
    channelTracker.removeCollector(message.channel.id)
    if (reason == "time") return message.channel.sendMessage(`I have closed the menu due to inactivity.`);
    else if (reason !== "user") return message.channel.sendMessage(reason);
  })

}
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    './src/ReactDashboard.js'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    libraryTarget: 'umd',
    publicPath: '/static/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        include: [
          path.join(__dirname, 'src')
        ]
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: "file-loader" }
    ]
  },
  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM'
	}
};
<commit_msg>Fix react dom externals<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    './src/ReactDashboard.js'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    libraryTarget: 'umd',
    publicPath: '/static/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        include: [
          path.join(__dirname, 'src')
        ]
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: "file-loader" }
    ]
  },
  externals: {
    react: {
      root: 'React',
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'react',
    },
    'react-dom': {
      root: 'ReactDOM',
      commonjs: 'react-dom',
      commonjs2: 'react-dom',
      amd: 'react-dom',
    },
  },
};
<|endoftext|>


<commit_before>/**
 * Created by elad.benedict on 8/23/2015.
 */

var config = require('./Configuration');
var path = require('path');
var qio = require('q-io/fs');
var _ = require('underscore');
var Q = require('q');

const tsChunktMatch =  new RegExp(/media-([^_]+).*?([\d]+)\.ts.*/);
var preserveOriginalHLS = config.get('preserveOriginalHLS').enable;
const rootFolder = config.get('rootFolderPath');

class PersistenceFormatBase {
    getEntryBasePath (entryId) {
        return path.join(rootFolder, this.getEntryHash(entryId), entryId);
    }

    getRelativePathFromFull (fullPath) {
        return fullPath.substr(this.getBasePathFromFull(fullPath).length);
    }

    getFlavorFullPath (entryId, flavorName) {
        return path.join(this.getEntryBasePath(entryId), flavorName.toString());
    }

    getMasterManifestName() {
        return 'playlist.json';
    }

    getMP4FileNamefromInfo(chunkPath){
        return chunkPath.replace('.ts','.mp4');
    }

    getTSChunknameFromMP4FileName(mp4FileName){
        return mp4FileName.replace('.mp4','.ts');
    }

    createHierarchyPath (destPath, entity, param) {
        let fullPath;
        let retVal = {};
        switch (entity) {
            case "entry":
                let dir = this.getEntryHash(param);
                fullPath = dir ? path.join(destPath, dir) : destPath;
                retVal = { fullPath };
                break;

            case "flavor":
                retVal = this.getFlavorPath(destPath,param)
                if ( _.isEqual(param ,retVal.hash) )
                    return Q.resolve(retVal);
                fullPath = retVal.fullPath;
                break;
        }

        return qio.makeTree(fullPath)
            .then(() => {
                return retVal;
            });
    }

    getEntryHash (entryId) {
        return entryId.charAt(entryId.length - 1);
    }
}

if(!preserveOriginalHLS) {
    class DefaultPersistenceFormat extends PersistenceFormatBase {

        getBasePathFromFull(fullPath) {
            // cut away both flavor and time components
            let lastSepIdx = _.lastIndexOf(fullPath,path.sep) - 1;
            return fullPath.substring(0,_.lastIndexOf(fullPath,path.sep,lastSepIdx)+1)
        }

        getFlavorPath (destPath,param) {
           let hours = new Date().getHours().toString();
            let hash = hours < 10 ? ("0" + hours) : hours;
            let fullPath = path.join(destPath, hash);
            return { fullPath, hash };
        }

        compressChunkName(tsChunkName) {
            var matched = tsChunktMatch.exec(tsChunkName);
            if (matched) {
                return matched[1] + '-' + matched[2] + '.mp4';
            }
            return tsChunkName;
        }

    }
    module.exports = new DefaultPersistenceFormat();
} else {
    class PreserveOriginalHLSFormat extends PersistenceFormatBase {
        getBasePathFromFull(fullPath) {
            return fullPath.substring(0,_.lastIndexOf(fullPath,path.sep)+1);
        }

        getFlavorPath (destPath,param) {
            return { fullPath:destPath, hash:param };
        }

        compressChunkName(tsChunkName) {
            return super.getMP4FileNamefromInfo(tsChunkName);
        }
    }
    module.exports = new PreserveOriginalHLSFormat();
}
<commit_msg>added missing method used for entry stream files cleanup (#342)<commit_after>/**
 * Created by elad.benedict on 8/23/2015.
 */

var config = require('./Configuration');
var path = require('path');
var qio = require('q-io/fs');
var _ = require('underscore');
var Q = require('q');

const tsChunktMatch =  new RegExp(/media-([^_]+).*?([\d]+)\.ts.*/);
var preserveOriginalHLS = config.get('preserveOriginalHLS').enable;
const rootFolder = config.get('rootFolderPath');

class PersistenceFormatBase {
    getEntryBasePath (entryId) {
        return path.join(rootFolder, this.getEntryHash(entryId), entryId);
    }

    getRelativePathFromFull (fullPath) {
        return fullPath.substr(this.getBasePathFromFull(fullPath).length);
    }

    getFlavorFullPath (entryId, flavorName) {
        return path.join(this.getEntryBasePath(entryId), flavorName.toString());
    }

    getMasterManifestName() {
        return 'playlist.json';
    }

    getMP4FileNamefromInfo(chunkPath){
        return chunkPath.replace('.ts','.mp4');
    }

    getTSChunknameFromMP4FileName(mp4FileName){
        return mp4FileName.replace('.mp4','.ts');
    }

    createHierarchyPath (destPath, entity, param) {
        let fullPath;
        let retVal = {};
        switch (entity) {
            case "entry":
                let dir = this.getEntryHash(param);
                fullPath = dir ? path.join(destPath, dir) : destPath;
                retVal = { fullPath };
                break;

            case "flavor":
                retVal = this.getFlavorPath(destPath,param)
                if ( _.isEqual(param ,retVal.hash) )
                    return Q.resolve(retVal);
                fullPath = retVal.fullPath;
                break;
        }

        return qio.makeTree(fullPath)
            .then(() => {
                return retVal;
            });
    }

    getEntryHash (entryId) {
        return entryId.charAt(entryId.length - 1);
    }
}

if(!preserveOriginalHLS) {
    class DefaultPersistenceFormat extends PersistenceFormatBase {

        getBasePathFromFull(fullPath) {
            // cut away both flavor and time components
            let lastSepIdx = _.lastIndexOf(fullPath,path.sep) - 1;
            return fullPath.substring(0,_.lastIndexOf(fullPath,path.sep,lastSepIdx)+1)
        }

        getFlavorPath (destPath,param) {
           let hours = new Date().getHours().toString();
            let hash = hours < 10 ? ("0" + hours) : hours;
            let fullPath = path.join(destPath, hash);
            return { fullPath, hash };
        }

        compressChunkName(tsChunkName) {
            var matched = tsChunktMatch.exec(tsChunkName);
            if (matched) {
                return matched[1] + '-' + matched[2] + '.mp4';
            }
            return tsChunkName;
        }

        compressTsChunkName(tsChunkName) {
            var matched = tsChunktMatch.exec(tsChunkName);
            if (matched) {
                return matched[1] + '-' + matched[2] + '.ts';
            }
            return tsChunkName;
        }

    }
    module.exports = new DefaultPersistenceFormat();
} else {
    class PreserveOriginalHLSFormat extends PersistenceFormatBase {
        getBasePathFromFull(fullPath) {
            return fullPath.substring(0,_.lastIndexOf(fullPath,path.sep)+1);
        }

        getFlavorPath (destPath,param) {
            return { fullPath:destPath, hash:param };
        }

        compressChunkName(tsChunkName) {
            return super.getMP4FileNamefromInfo(tsChunkName);
        }
    }
    module.exports = new PreserveOriginalHLSFormat();
}
<|endoftext|>


<commit_before>var path = require('path');
const webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');

process.env.BABEL_ENV = process.env.npm_lifecycle_event;

var PATHS = {
    rootPath: path.resolve(__dirname),
    appPath: path.resolve(__dirname, 'app'),
    buildPath: path.resolve(__dirname, 'build'),
    coveragePath: path.resolve(__dirname, 'coverage'),
    nodeModulesPath: path.resolve(__dirname, 'node_modules'),
    appEntry: path.resolve(__dirname, 'app/index.jsx')
};

var config = {
    entry: {
        app: PATHS.appEntry
    },
    output: {
        path: PATHS.buildPath,
        filename: '[name].[hash].js'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: PATHS.appPath
            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url?limit=25000'
            }
        ]
    },
    plugins: [
        new CleanPlugin([PATHS.buildPath, PATHS.coveragePath]),
        new HtmlWebpackPlugin({
            title: 'My first react app',
            filename: 'index.html'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.DefinePlugin({
            "process.env": {
                NODE_ENV: JSON.stringify("production")
            }
        })
    ]
};

module.exports = config;
<commit_msg>去掉webpack产品配置中css的sourcemap<commit_after>var path = require('path');
const webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');

process.env.BABEL_ENV = process.env.npm_lifecycle_event;

var PATHS = {
    rootPath: path.resolve(__dirname),
    appPath: path.resolve(__dirname, 'app'),
    buildPath: path.resolve(__dirname, 'build'),
    coveragePath: path.resolve(__dirname, 'coverage'),
    nodeModulesPath: path.resolve(__dirname, 'node_modules'),
    appEntry: path.resolve(__dirname, 'app/index.jsx')
};

var config = {
    entry: {
        app: PATHS.appEntry
    },
    output: {
        path: PATHS.buildPath,
        filename: '[name].[hash].js'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: PATHS.appPath
            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css', 'sass']
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url?limit=25000'
            }
        ]
    },
    plugins: [
        new CleanPlugin([PATHS.buildPath, PATHS.coveragePath]),
        new HtmlWebpackPlugin({
            title: 'My first react app',
            filename: 'index.html'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.DefinePlugin({
            "process.env": {
                NODE_ENV: JSON.stringify("production")
            }
        })
    ]
};

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var clean = require('clean-webpack-plugin');

var nodeModulesPath = path.join(__dirname, 'node_modules');
var modulePath = {
  React: path.join(nodeModulesPath, 'react/dist/react.min.js'),
  React_addons: path.join(nodeModulesPath, 'react/dist/react-with-addons.min.js')
};

module.exports = {
  entry: {
    browser: path.join(__dirname, 'app/App.js'),
    ieCompatible: path.join(__dirname, 'app/utils/ie-compatible.js'),
    mobile: path.join(__dirname, 'app/App-h5.js'),
    common: ['react', 'react-router']
  },
  output: {
    path: path.join(__dirname, '/dist/'),
    filename: '[name]-[hash].min.js'
  },
  resolve: {
    modulesDirectories: ['node_modules'],
  },
  plugins: [
    new clean(['dist']),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.CommonsChunkPlugin('common', 'common.js'),
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      filename: 'index.html',
      chunks: ['common', 'browser', 'ieCompatible']
    }),
    new HtmlWebpackPlugin({
      template: 'app/index-h5.html',
      inject: 'body',
      filename: 'index-h5.html',
      chunks: ['common', 'mobile']
    }),
    new ExtractTextPlugin('[name]-[hash].min.css'),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
        screw_ie8: true
      }
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ],
  module: {
    loaders: [{
      test: /\.js?$/,
      exclude: /node_modules/,
      loader: 'babel'
    }, {
      test: /\.json?$/,
      loader: 'json'
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]---[local]---[hash:base64:5]!postcss')
    }, {
      test: /\.less$/,
      loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
    }, {
      test: /\.(woff(2)?|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'file-loader'
    }, {
      test: /\.(png|jpg|jpeg|gif)$/,
      loader: 'file-loader?name=i/[name].[ext]'
    }],
    noParse: [modulePath.React, modulePath.React_addons]
  },
  postcss: [
    require('autoprefixer')
  ]
};
<commit_msg>use hash in output file.<commit_after>'use strict';

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var clean = require('clean-webpack-plugin');

var nodeModulesPath = path.join(__dirname, 'node_modules');
var modulePath = {
  React: path.join(nodeModulesPath, 'react/dist/react.min.js'),
  React_addons: path.join(nodeModulesPath, 'react/dist/react-with-addons.min.js')
};

module.exports = {
  entry: {
    browser: path.join(__dirname, 'app/App.js'),
    ieCompatible: path.join(__dirname, 'app/utils/ie-compatible.js'),
    mobile: path.join(__dirname, 'app/App-h5.js'),
    common: ['react', 'react-router']
  },
  output: {
    path: path.join(__dirname, '/dist/'),
    filename: '[name]-[hash].min.js'
  },
  resolve: {
    modulesDirectories: ['node_modules'],
  },
  plugins: [
    new clean(['dist']),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.CommonsChunkPlugin('common', 'common-[hash].min.js'),
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      filename: 'index.html',
      chunks: ['common', 'browser', 'ieCompatible']
    }),
    new HtmlWebpackPlugin({
      template: 'app/index-h5.html',
      inject: 'body',
      filename: 'index-h5.html',
      chunks: ['common', 'mobile']
    }),
    new ExtractTextPlugin('[name]-[hash].min.css'),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
        screw_ie8: true
      }
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ],
  module: {
    loaders: [{
      test: /\.js?$/,
      exclude: /node_modules/,
      loader: 'babel'
    }, {
      test: /\.json?$/,
      loader: 'json'
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]---[local]---[hash:base64:5]!postcss')
    }, {
      test: /\.less$/,
      loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
    }, {
      test: /\.(woff(2)?|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'file-loader'
    }, {
      test: /\.(png|jpg|jpeg|gif)$/,
      loader: 'file-loader?name=i/[name].[ext]'
    }],
    noParse: [modulePath.React, modulePath.React_addons]
  },
  postcss: [
    require('autoprefixer')
  ]
};
<|endoftext|>