<commit_before>import React, { Component } from 'react';
import * as FirebaseActions from '../firebaseFunctions';
import './style/Courses.css';

class Course extends Component {

	constructor() {
		// Required function call for every constructor
		super();

		// Bind every class function to 'this'
		this.retrieveCourses = this.retrieveCourses.bind(this);
		this.renderCourse = this.renderCourse.bind(this);
		//Set up our state
		this.state = {
			courses: []
		};
	}

	componentDidMount(){
		const props = this.props;
		props.checkAuth('Courses');
		window.$('.collapsible').collapsible();
		window.$('select').material_select();
		//Async call to retrieve courses
		this.retrieveCourses();
	}

	componentWillUnmount() {
		this.state.setState({courses: []});
	}

	renderCourse(course, keyName, taken) {
		let courseActions;
		if (taken) {
			courseActions = (

					<button className="btn waves-effect waves-light">Remove from Courses</button>

			);
		} else {
			courseActions = (

					<button className="btn waves-effect waves-light">Add to Courses</button>

			);
		}
		const courseItem = (

					{course.prettyClassNum}

					{course.name}

						{course.credits} credit(s)

						Available {course.semesters}

					{courseActions}

		);
		return courseItem;
	}

	retrieveCourses() {
		// Make modifications to an object referring the class's 'this'
		let coursesRef = this;
		// Fetch the data from firebase
		FirebaseActions.allCourses(function (response) {
			let courses = [];
			console.log('All courses are', response.courses);
			for (let course in response.courses) {
				if (response.courses.hasOwnProperty(course)) {
					const courseObject = response.courses[course];
					courses.push(
						coursesRef.renderCourse(courseObject, course)
					);
				}
			}
			coursesRef.setState({
				courses: courses
			});
		});
	}

	render() {
		return (

Course List

						Department
							<select className="browser-default custom-select" defaultValue="0">
								<option value="0" disabled>Choose your department</option>
								<option value="1">Accounting (ACC)</option>
								<option value="2">Air Force ROTC (AF)</option>
								<option value="3">Army ROTC (AR)</option>
								<option value="4">Atmospheric Science (ATM)</option>
								<option value="5">Biochem & Molecular Biology (BMB)</option>
								<option value="6">Biological Sciences (BL)</option>
								<option value="7">Biomedical Engineering (BE)</option>
								<option value="8">Business (BUS)</option>
								<option value="9">Business Administration (BA)</option>
								<option value="10">Chemical Engineering (CM)</option>
								<option value="11">Chemistry (CH)</option>
								<option value="12">Civil & Environmental Engineering (CEE)</option>
								<option value="13">Computational Science & Engineering (CSE)</option>
								<option value="14">Computer Science (CS)</option>
								<option value="15">Construction Management (CMG)</option>
								<option value="16">Economics (EC)</option>
								<option value="17">Education (ED)</option>
								<option value="18">Eletrical & Computer Engineering (EE)</option>
								<option value="19">Electrical Engineering Technology (EET)</option>
								<option value="20">Engineering Fundamentals (ENG)</option>
								<option value="21">English as a Second Language (ESL)</option>
								<option value="22">Enterprise (ENT)</option>
								<option value="23">Finance (FIN)</option>
								<option value="24">Forest Resources & Environmental Science (FW)</option>
								<option value="25">Geology & Mining Engineering & Sciences (GE)</option>
								<option value="26">Humanities (HU)</option>
								<option value="27">Kinesiology/Integ Physiology (EH)</option>
								<option value="28">Management (MGT)</option>
								<option value="29">Management Information Services (MIS)</option>
								<option value="30">Marketing (MKT)</option>
								<option value="31">Materials Science & Engineering (MY)</option>
								<option value="32">Mathematical Sciences (MA)</option>
								<option value="33">Mechanical Engineering - Engineering Mechanics (MEEM)</option>
								<option value="34">Mechanical Engineering TEchnology (MET)</option>
								<option value="35">Operations & Supply Chain Management (OSM)</option>
								<option value="36">Pavlis Honors (HON)</option>
								<option value="37">Physical Education (PE)</option>
								<option value="38">Physics (PH)</option>
								<option value="39">Psychology (PSY)</option>
								<option value="40">Sciences & Arts (SA)</option>
								<option value="41">Social Sciences (SS)</option>
								<option value="42">Surveying (SU)</option>
								<option value="43">Systems Administation Technology (SAT)</option>
								<option value="44">University Wide (UN)</option>
								<option value="45">Visual & Performing Arts (FA)</option>
							</select>

							{this.state.courses}

		);
	}
}

Course.contextTypes = {
	router: React.PropTypes.object
};

Course.PropTypes = {
	checkAuth: React.PropTypes.func
};

export default Course;
<commit_msg>Added ability to see courses based on department<commit_after>import React, { Component } from 'react';
import * as FirebaseActions from '../firebaseFunctions';
import './style/Courses.css';

class Course extends Component {

	constructor() {
		// Required function call for every constructor
		super();

		// Bind every class function to 'this'
		this.retrieveCourses = this.retrieveCourses.bind(this);
		this.renderCourse = this.renderCourse.bind(this);
		this.renderDept = this.renderDept.bind(this);
		this.retrieveDept = this.retrieveDept.bind(this);
		//Set up our state
		this.state = {courses: []};
	}

	componentDidMount(){
		const props = this.props;
		props.checkAuth('Courses');
		window.$('.collapsible').collapsible();
		window.$('select').material_select();
		//Async call to retrieve courses
		this.retrieveCourses();
	}

	componentWillUnmount() {
		this.state.setState({courses: []});
	}

	renderDept(course, keyName, taken, dept) {
		let courseActions;
		if (taken) {
			courseActions = (

					<button className="btn waves-effect waves-light">Remove from Courses</button>

			);
		} else {
			courseActions = (

					<button className="btn waves-effect waves-light">Add to Courses</button>

			);
		}
			const courseItem = (

						{course.prettyClassNum}

						{course.name}

							{course.credits} credit(s)

							Available {course.semesters}

						{courseActions}

			);
		if(course.department === 'CS')
			return courseItem;
	}

	retrieveDept() {
		// Make modifications to an object referring the class's 'this'
		let coursesRef = this;
		// Fetch the data from firebase
		FirebaseActions.allCourses(function (response) {
			let courses = [];
			console.log('All courses in dept are', response.courses);
			for (let course in response.courses) {
				if (response.courses.hasOwnProperty(course)) {
					const courseObject = response.courses[course];
					courses.push(
						coursesRef.renderDept(courseObject, course)
					);
				}
			}
			coursesRef.setState({
				courses: courses
			});
		});
	}

	renderCourse(course, keyName, taken) {
		let courseActions;
		if (taken) {
			courseActions = (

					<button className="btn waves-effect waves-light">Remove from Courses</button>

			);
		} else {
			courseActions = (

					<button className="btn waves-effect waves-light">Add to Courses</button>

			);
		}
		const courseItem = (

					{course.prettyClassNum}

					{course.name}

						{course.credits} credit(s)

						Available {course.semesters}

					{courseActions}

		);
		return courseItem;
	}

	retrieveCourses() {
		// Make modifications to an object referring the class's 'this'
		let coursesRef = this;
		// Fetch the data from firebase
		FirebaseActions.allCourses(function (response) {
			let courses = [];
			console.log('All courses are', response.courses);
			for (let course in response.courses) {
				if (response.courses.hasOwnProperty(course)) {
					const courseObject = response.courses[course];
					courses.push(
						coursesRef.renderCourse(courseObject, course)
					);
				}
			}
			coursesRef.setState({
				courses: courses
			});
		});
	}

	render() {
		return (

Course List

						Department
							{this.retrieveCourses}
							<select id="deptChoice" className="browser-default custom-select" defaultValue="0" onChange={this.retrieveDept} value={this.state.value}>
								<option value="0" disabled>Choose your department</option>
								<option value="ACC">Accounting (ACC)</option>
								<option value="AF">Air Force ROTC (AF)</option>
								<option value="AR">Army ROTC (AR)</option>
								<option value="ATM">Atmospheric Science (ATM)</option>
								<option value="BMB">Biochem & Molecular Biology (BMB)</option>
								<option value="BL">Biological Sciences (BL)</option>
								<option value="BE">Biomedical Engineering (BE)</option>
								<option value="BUS">Business (BUS)</option>
								<option value="BA">Business Administration (BA)</option>
								<option value="CM">Chemical Engineering (CM)</option>
								<option value="CH">Chemistry (CH)</option>
								<option value="CEE">Civil & Environmental Engineering (CEE)</option>
								<option value="CSE">Computational Science & Engineering (CSE)</option>
								<option value="CS">Computer Science (CS)</option>
								<option value="CMG">Construction Management (CMG)</option>
								<option value="EC">Economics (EC)</option>
								<option value="ED">Education (ED)</option>
								<option value="EE">Eletrical & Computer Engineering (EE)</option>
								<option value="EET">Electrical Engineering Technology (EET)</option>
								<option value="ENG">Engineering Fundamentals (ENG)</option>
								<option value="ESL">English as a Second Language (ESL)</option>
								<option value="ENT">Enterprise (ENT)</option>
								<option value="FIN">Finance (FIN)</option>
								<option value="FW">Forest Resources & Environmental Science (FW)</option>
								<option value="GE">Geology & Mining Engineering & Sciences (GE)</option>
								<option value="HU">Humanities (HU)</option>
								<option value="EH">Kinesiology/Integ Physiology (EH)</option>
								<option value="MGT">Management (MGT)</option>
								<option value="MIS">Management Information Services (MIS)</option>
								<option value="MKT">Marketing (MKT)</option>
								<option value="MY">Materials Science & Engineering (MY)</option>
								<option value="MA">Mathematical Sciences (MA)</option>
								<option value="MEEM">Mechanical Engineering - Engineering Mechanics (MEEM)</option>
								<option value="MET">Mechanical Engineering TEchnology (MET)</option>
								<option value="OMS">Operations & Supply Chain Management (OSM)</option>
								<option value="HON">Pavlis Honors (HON)</option>
								<option value="PE">Physical Education (PE)</option>
								<option value="PH">Physics (PH)</option>
								<option value="PSY">Psychology (PSY)</option>
								<option value="SA">Sciences & Arts (SA)</option>
								<option value="SS">Social Sciences (SS)</option>
								<option value="SU">Surveying (SU)</option>
								<option value="SAT">Systems Administation Technology (SAT)</option>
								<option value="UN">University Wide (UN)</option>
								<option value="FA">Visual & Performing Arts (FA)</option>
							</select>

{this.state.value}

							{this.state.courses}

		);
	}
}

Course.contextTypes = {
	router: React.PropTypes.object
};

Course.PropTypes = {
	checkAuth: React.PropTypes.func
};

export default Course;
<|endoftext|>


<commit_before>// ==UserScript==
// @name        [HV]SellEquipment2
// @description
// @include     http*://hentaiverse.org/
// @include     http*://hentaiverse.org/?s=Character&ss=ch
// @include     http://alt.hentaiverse.org/
// @include     http://alt.hentaiverse.org/?s=Character&ss=ch
// @version     1.01
// @grant       none
// @author      Dodying
// @namespace   https://github.com/dodying/
// @supportURL  https://github.com/dodying//UserJs/issues
// @icon        https://raw.githubusercontent.com/dodying/UserJs/master/Logo.png
// @run-at      document-end
// ==/UserScript==
(function() {
  /**
   * [keepEqps description]
   * the Equipment that you DON'T want to sell
   * @type {Array}
   * Eg. ['Magnificent', 'Legendary', 'Peerless']
   * Eg. ['Legendary Arctic Redwood Staff of Destruction']
   */
  var keepEqps = ['Magnificent', 'Legendary', 'Peerless'];
  /**
   * [func description]
   * here put in what you want to do after sell the eqps
   */
  var func = function() {
    //grFunc();//start GrindFest
    //location.href = location.href;//page reload
  };
  /**
   * [price description]
   * here put in the price of each material
   */
  var price = [{ //Scrap
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //Low-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //Mid-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //High-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0
  }];
  /*
  var price = [{ //Scrap
    Cloth: 90,
    Leather: 85,
    Metal: 85,
    Wood: 90,
  }, { //Low-Grade
    Cloth: 200,
    Leather: 200,
    Metal: 200,
    Wood: 200,
  }, { //Mid-Grade
    Cloth: 600,
    Leather: 550,
    Metal: 550,
    Wood: 600,
  }, { //High-Grade
    Cloth: 20000,
    Leather: 800,
    Metal: 1200,
    Wood: 9500
  }];
  */
  /**
   *
   */
  if (!gE('#navbar')) return;
  var quality = [/Crude|Fair|Average/, /Superior/, /Exquisite/, /Magnificent|Legendary|Peerless/];
  var material = {
    '1handed': 'Metal',
    '2handed': 'Metal',
    staff: 'Wood',
    shield: 'Wood',
    acloth: 'Cloth',
    alight: 'Leather',
    aheavy: 'Metal',
  };
  var url = ['1handed', '2handed', 'staff', 'shield', 'acloth', 'alight', 'aheavy'];
  keepEqps = new RegExp(keepEqps.join('|'));
  var eids;
  var eidsSell = [];
  var eidsSalvage = {
    '1handed': [],
    '2handed': [],
    staff: [],
    shield: [],
    acloth: [],
    alight: [],
    aheavy: []
  };
  var amountSalvage = 0;
  var eqvalue;
  var valueSell;
  var valueSalvage;
  var len = 0;
  var i, j;
  var amount;
  var doSell;
  var doSalvage = 0;
  var result = {};
  var text;
  var html = '';
  url.forEach(function(i) {
    post('?s=Bazaar&ss=es&filter=' + i, function(data) {
      checkFunc(data, i);
    });
  });

  var checkFunc = function(data, url) {
    len++;
    eids = {};
    gE('#eqshop_outer>.eqshop_pane:nth-child(1) .eqp>.iu+div[id]', 'all', data).forEach(function(i) {
      if (!keepEqps.test(i.textContent)) eids[i.id.match(/\d+/)[0]] = i.textContent;
    });
    if (Object.keys(eids).length !== 0) {
      eqvalue = JSON.parse(gE('#mainpane>script[src]+script', data).text.match(/var eqvalue = (.*?);/)[1]);
      for (i in eids) {
        valueSell = eqvalue[i];
        if (quality[0].test(eids[i])) {
          amount = Math.ceil(valueSell / 100);
          valueSalvage = amount * price[0][material[url]];
        } else {
          amount = Math.ceil(valueSell / 500);
          valueSalvage = amount * price[0][material[url]];
          for (j = 1; j < quality.length; j++) {
            if (quality[j].test(eids[i])) break;
          }
          valueSalvage += price[j][material[url]];
        }
        if (valueSell >= valueSalvage) {
          eidsSell.push(i);
        } else {
          amountSalvage++;
          eidsSalvage[url].push(i);
        }
      }
    }
    if (len === 7) {
      console.log(eidsSell, eidsSalvage);
      if (eidsSell.length > 0) {
        post('?s=Bazaar&ss=es', function() {
          doSell = true;
          if (doSell && doSalvage === amountSalvage) doFunc();
        }, 'storetoken=' + gE('input[name="storetoken"]', data).value + '&select_group=item_pane&select_eids=' + encodeURIComponent(eidsSell.join()));
      } else {
        doSell = true;
      }
      salvageFunc(eidsSalvage);
    }
  };
  var salvageFunc = function(eidsSalvage) {
    for (i in eidsSalvage) {
      if (eidsSalvage[i].length === 0) {
        delete eidsSalvage[i];
        continue;
      } else {
        break;
      }
    }
    if (Object.keys(eidsSalvage).length === 0) return;
    post('?s=Forge&ss=sa&filter=' + i, function() {
      countResult(gE('#messagebox>div:nth-child(2)>div>div>div>div>div', 'all'));
      eidsSalvage[i].splice(0, 1);
      doSalvage++;
      if (doSell && doSalvage === amountSalvage) {
        doFunc();
      } else {
        salvageFunc(eidsSalvage);
      }
    }, 'select_item=' + eidsSalvage[i][0]);
  };
  var doFunc = function() {
    if (amountSalvage !== 0) {
      for (i in result) {
        html += '

Salvaged ' + result[i] + 'x ' + i + '

';
      }
      gE('#messagebox>div:nth-child(2)').innerHTML = html;
    }
    func();
  };
  var countResult = function(obj) {
    obj.forEach(function(i) {
      text = i.textContent.replace(/^Salvaged (\d+x )/, '');
      amount = i.textContent.match(/\d+/) ? i.textContent.match(/\d+/)[0] * 1 : 1;
      if (text in result) {
        result[text] += amount || 1;
      } else {
        result[text] = amount || 1;
      }
    });
  };
  var grFunc = function() {
    post('?s=Battle&ss=gr', function(data) {
      post('?s=Battle&ss=gr', function() {
        location.href = location.href;
      }, 'initid=1&inittoken=' + gE('img[src*="startgrindfest.png"]', data).getAttribute('onclick').match(/init_battle\(1, '(.*?)'\)/)[1]);
    });
  };

  function gE(ele, mode, parent) { //获取元素
    if (typeof ele === 'object') {
      return ele;
    } else if (mode === undefined && parent === undefined) {
      return (isNaN(ele * 1)) ? document.querySelector(ele) : document.getElementById(ele);
    } else if (mode === 'all') {
      return (parent === undefined) ? document.querySelectorAll(ele) : parent.querySelectorAll(ele);
    } else if (typeof mode === 'object' && parent === undefined) {
      return mode.querySelector(ele);
    }
  }

  function cE(name) { //创建元素
    return document.createElement(name);
  }

  function post(href, func, parm, type) { //post
    var xhr = new XMLHttpRequest();
    xhr.open(parm ? 'POST' : 'GET', href);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.responseType = type || 'document';
    xhr.onerror = function() {
      xhr = null;
      post(href, func, parm, type);
    };
    xhr.onload = function(e) {
      if (e.target.status >= 200 && e.target.status < 400 && typeof func === 'function') {
        var data = e.target.response;
        if (xhr.responseType === 'document' && gE('#messagebox', data)) {
          if (gE('#messagebox')) {
            gE('#csp').replaceChild(gE('#messagebox', data), gE('#messagebox'));
          } else {
            gE('#csp').appendChild(gE('#messagebox', data));
          }
        }
        func(data, e);
      }
      xhr = null;
    };
    xhr.send(parm);
  }
})();
<commit_msg>Update 元数据<commit_after>// ==UserScript==
// @name        [HV]SellEquipment2
// @description
// @include     http*://hentaiverse.org/
// @include     http*://hentaiverse.org/?s=Character&ss=ch
// @include     http*://hentaiverse.org/?s=Battle&ss=ba&encounter=*
// @include     http://alt.hentaiverse.org/
// @include     http://alt.hentaiverse.org/?s=Character&ss=ch
// @include     http://alt.hentaiverse.org/?s=Battle&ss=ba&encounter=*
// @version     1.01
// @grant       none
// @author      Dodying
// @namespace   https://github.com/dodying/
// @supportURL  https://github.com/dodying//UserJs/issues
// @icon        https://raw.githubusercontent.com/dodying/UserJs/master/Logo.png
// @run-at      document-end
// ==/UserScript==
(function() {
  /**
   * [keepEqps description]
   * the Equipment that you DON'T want to sell
   * @type {Array}
   * Eg. ['Magnificent', 'Legendary', 'Peerless']
   * Eg. ['Legendary Arctic Redwood Staff of Destruction']
   */
  var keepEqps = ['Magnificent', 'Legendary', 'Peerless'];
  /**
   * [func description]
   * here put in what you want to do after sell the eqps
   */
  var func = function() {
    //grFunc();//start GrindFest
    //location.href = location.href;//page reload
  };
  /**
   * [price description]
   * here put in the price of each material
   */
  var price = [{ //Scrap
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //Low-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //Mid-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0,
  }, { //High-Grade
    Cloth: 0,
    Leather: 0,
    Metal: 0,
    Wood: 0
  }];
  /*
  var price = [{ //Scrap
    Cloth: 90,
    Leather: 85,
    Metal: 85,
    Wood: 90,
  }, { //Low-Grade
    Cloth: 200,
    Leather: 200,
    Metal: 200,
    Wood: 200,
  }, { //Mid-Grade
    Cloth: 600,
    Leather: 550,
    Metal: 550,
    Wood: 600,
  }, { //High-Grade
    Cloth: 20000,
    Leather: 800,
    Metal: 1200,
    Wood: 9500
  }];
  */
  /**
   *
   */
  if (!gE('#navbar')) return;
  var quality = [/Crude|Fair|Average/, /Superior/, /Exquisite/, /Magnificent|Legendary|Peerless/];
  var material = {
    '1handed': 'Metal',
    '2handed': 'Metal',
    staff: 'Wood',
    shield: 'Wood',
    acloth: 'Cloth',
    alight: 'Leather',
    aheavy: 'Metal',
  };
  var url = ['1handed', '2handed', 'staff', 'shield', 'acloth', 'alight', 'aheavy'];
  keepEqps = new RegExp(keepEqps.join('|'));
  var eids;
  var eidsSell = [];
  var eidsSalvage = {
    '1handed': [],
    '2handed': [],
    staff: [],
    shield: [],
    acloth: [],
    alight: [],
    aheavy: []
  };
  var amountSalvage = 0;
  var eqvalue;
  var valueSell;
  var valueSalvage;
  var len = 0;
  var i, j;
  var amount;
  var doSell;
  var doSalvage = 0;
  var result = {};
  var text;
  var html = '';
  url.forEach(function(i) {
    post('?s=Bazaar&ss=es&filter=' + i, function(data) {
      checkFunc(data, i);
    });
  });

  var checkFunc = function(data, url) {
    len++;
    eids = {};
    gE('#eqshop_outer>.eqshop_pane:nth-child(1) .eqp>.iu+div[id]', 'all', data).forEach(function(i) {
      if (!keepEqps.test(i.textContent)) eids[i.id.match(/\d+/)[0]] = i.textContent;
    });
    if (Object.keys(eids).length !== 0) {
      eqvalue = JSON.parse(gE('#mainpane>script[src]+script', data).text.match(/var eqvalue = (.*?);/)[1]);
      for (i in eids) {
        valueSell = eqvalue[i];
        if (quality[0].test(eids[i])) {
          amount = Math.ceil(valueSell / 100);
          valueSalvage = amount * price[0][material[url]];
        } else {
          amount = Math.ceil(valueSell / 500);
          valueSalvage = amount * price[0][material[url]];
          for (j = 1; j < quality.length; j++) {
            if (quality[j].test(eids[i])) break;
          }
          valueSalvage += price[j][material[url]];
        }
        if (valueSell >= valueSalvage) {
          eidsSell.push(i);
        } else {
          amountSalvage++;
          eidsSalvage[url].push(i);
        }
      }
    }
    if (len === 7) {
      console.log(eidsSell, eidsSalvage);
      if (eidsSell.length > 0) {
        post('?s=Bazaar&ss=es', function() {
          doSell = true;
          if (doSell && doSalvage === amountSalvage) doFunc();
        }, 'storetoken=' + gE('input[name="storetoken"]', data).value + '&select_group=item_pane&select_eids=' + encodeURIComponent(eidsSell.join()));
      } else {
        doSell = true;
      }
      salvageFunc(eidsSalvage);
    }
  };
  var salvageFunc = function(eidsSalvage) {
    for (i in eidsSalvage) {
      if (eidsSalvage[i].length === 0) {
        delete eidsSalvage[i];
        continue;
      } else {
        break;
      }
    }
    if (Object.keys(eidsSalvage).length === 0) return;
    post('?s=Forge&ss=sa&filter=' + i, function() {
      countResult(gE('#messagebox>div:nth-child(2)>div>div>div>div>div', 'all'));
      eidsSalvage[i].splice(0, 1);
      doSalvage++;
      if (doSell && doSalvage === amountSalvage) {
        doFunc();
      } else {
        salvageFunc(eidsSalvage);
      }
    }, 'select_item=' + eidsSalvage[i][0]);
  };
  var doFunc = function() {
    if (amountSalvage !== 0) {
      for (i in result) {
        html += '

Salvaged ' + result[i] + 'x ' + i + '

';
      }
      gE('#messagebox>div:nth-child(2)').innerHTML = html;
    }
    func();
  };
  var countResult = function(obj) {
    obj.forEach(function(i) {
      text = i.textContent.replace(/^Salvaged (\d+x )/, '');
      amount = i.textContent.match(/\d+/) ? i.textContent.match(/\d+/)[0] * 1 : 1;
      if (text in result) {
        result[text] += amount || 1;
      } else {
        result[text] = amount || 1;
      }
    });
  };
  var grFunc = function() {
    post('?s=Battle&ss=gr', function(data) {
      post('?s=Battle&ss=gr', function() {
        location.href = location.href;
      }, 'initid=1&inittoken=' + gE('img[src*="startgrindfest.png"]', data).getAttribute('onclick').match(/init_battle\(1, '(.*?)'\)/)[1]);
    });
  };

  function gE(ele, mode, parent) { //获取元素
    if (typeof ele === 'object') {
      return ele;
    } else if (mode === undefined && parent === undefined) {
      return (isNaN(ele * 1)) ? document.querySelector(ele) : document.getElementById(ele);
    } else if (mode === 'all') {
      return (parent === undefined) ? document.querySelectorAll(ele) : parent.querySelectorAll(ele);
    } else if (typeof mode === 'object' && parent === undefined) {
      return mode.querySelector(ele);
    }
  }

  function cE(name) { //创建元素
    return document.createElement(name);
  }

  function post(href, func, parm, type) { //post
    var xhr = new XMLHttpRequest();
    xhr.open(parm ? 'POST' : 'GET', href);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.responseType = type || 'document';
    xhr.onerror = function() {
      xhr = null;
      post(href, func, parm, type);
    };
    xhr.onload = function(e) {
      if (e.target.status >= 200 && e.target.status < 400 && typeof func === 'function') {
        var data = e.target.response;
        if (xhr.responseType === 'document' && gE('#messagebox', data)) {
          if (gE('#messagebox')) {
            gE('#csp').replaceChild(gE('#messagebox', data), gE('#messagebox'));
          } else {
            gE('#csp').appendChild(gE('#messagebox', data));
          }
        }
        func(data, e);
      }
      xhr = null;
    };
    xhr.send(parm);
  }
})();
<|endoftext|>


<commit_before>$(document).ready(function() {

    var winwidth = $(window).width();

    if (winwidth > 1200) {
      var offset = 300;
      var shrinkoffset = 0;
    	var duration = 500;
      var duration2 = 1500;
    	$(window).scroll(function() {
      	if ($(this).scrollTop() > offset) {
      	   $('#scroll-to-top').fadeIn(duration);
           $('#flatmenu').addClass('flatmenu-dark');
      	} else {
      	   $('#scroll-to-top').fadeOut(duration);
           $('#flatmenu').removeClass('flatmenu-dark');
      	}
    	});

    	$('#scroll-to-top').click(function(event) {
      		event.preventDefault();
      	$('html, body').animate({scrollTop: 0}, 800);
      		return false;
    	});
    }

    $(".float-label").jvFloat();

    $('.header-holder').affix({
      offset: {
        top: $('header').height() + 1
      }
    });

    $('.frame > img').each(function(){
       var $el = $(this),
         staticSrc = $el.attr('src'),
         gifSrc = $el.data('animated');
       $el.hover(
         function(){
           $el.attr("src", gifSrc);
         },
         function(){
           $el.attr("src", staticSrc);
         });
     });

    // $('#home-main-text').css('padding-top', $(window).height()/2.8);
    $('[data-toggle="popover"]').popover();

    $("#talk-desc").showMore({
      minheight: 78, // measured in px
      buttontxtmore: 'show more',
      buttontxtless: 'show less',
      animationspeed: 250
    });

    if ($("body").data('schedule')) {
      // init controller
      var controller = new ScrollMagic.Controller();

      var $sclockminutes = $('.s-clock-minutes');
      var $sclockhours = $('.s-clock-hours');

      TweenMax.to($sclockminutes, 0.1, {rotation: 0,  ease:Linear.easeNone, transformOrigin: "center bottom"});
      TweenMax.to($sclockhours, 0.1, {rotation: 270, ease:Linear.easeNone, transformOrigin: "center bottom"});
      var tweenminutes = TweenMax.to($sclockminutes, 0.1, {rotation: 360*10,  ease:Linear.easeNone, transformOrigin: "center bottom"});
      var tweenhours = TweenMax.to($sclockhours, 0.1, {rotation: 300+270, ease:Linear.easeNone, transformOrigin: "center bottom"});

      if (winwidth > 1200) {

        var clockMinutes = new ScrollMagic.Scene({triggerElement: ".schedule-list",duration: 3600})
        .setTween(tweenminutes)
        .addTo(controller);

        var clockHours = new ScrollMagic.Scene({triggerElement: ".schedule-list",duration: 3600})
        .setTween(tweenhours)
        .addTo(controller);

        var clockPin = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600})
        .setPin('.s-clock')
        .addTo(controller);

        var trackPin1 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track1')
        .setClassToggle(".schedule-navbar", "bodybg")
        .addTo(controller);

        var trackPin2 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track2')
        .setClassToggle(".track-name", "more-z")
        .addTo(controller);

        var trackPin3 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track3')
        .setClassToggle("#flatmenu", "flatmenu-tall")
        .addTo(controller);

        var trackPin4 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track4')
        .setClassToggle(".day", "inline")
        .addTo(controller);

        var trackPin5 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track5')
        .addTo(controller);

        var cepelinTween = new ScrollMagic.Scene({triggerElement: "#cepelin-trigger"})
        .setTween(cepelinmove)
        .addTo(controller);

      } else {
        $(".schedule-item").each(function() {
          $(this).attr('style', 'padding-bottom: 15px;');
        })
      }

      $(window).bind('load', function () {
        var highlightTalk = $(location).attr('hash').slice(1);
        var slotheight = $(window).height()*Number(highlightTalk.slice(-1))
        if (highlightTalk) {
          $('html, body').animate({scrollTop: $(window).height()/2-10}, slotheight/2, function(){
            $("."+highlightTalk+"").addClass('highlighted');
              $('html, body').animate({
               scrollTop: $("."+highlightTalk+"").offset().top - ($(window).height()/2-10)
             }, slotheight/2);
          });
        }
      });
    }

    if ($("body").data('cepelin')) {
      var controller2 = new ScrollMagic.Controller();
      var addflip = function(){
        $('.cepelin').addClass('flip');
      }
      var removeflip = function(){
        $('.cepelin').removeClass('flip');
      }
      var cepelinmove = TweenMax.to(".cepelin", 10, {left: winwidth, ease:Linear.easeNone, onStart: removeflip, onComplete: addflip});
      if (winwidth > 1200) {
        var cepelinTween = new ScrollMagic.Scene({triggerElement: "#cepelin-trigger"})
        .setTween(cepelinmove)
        .addTo(controller2);
      }
    }

    $('#home-mainscreen-holder').css('height', $(window).height());

    $('div.tagsort-tags-container').tagSort({
		  items: '.speaker-tags',
		  tagElement: 'span',
		  itemTagsSeperator: ' ',
		  fadeTime: 0,
			sortType: 'inclusive',
      reset: '.tags-reset'
		});

    $('.tagsort-tags-container > span:empty').remove();

    $("[data-doughnut]").each(function(){
      var $this = $(this),
          start = 0,
          offset = 0,
          total = 0,
          n = 0;

      $this.find("> div").each(function(){
        var item = $(this);
        var value = item.data("doughnut-value") * 1;
        item.append('

');

        if(value > 50){
          item.addClass("big");
        }

        total += value;
        n++;
      }).each(function(index, el){
        var item = $(this);
        var value = Math.round(item.data("doughnut-value") * 3.6); //because the value is percent

        if(total >= 99.9 && n == index + 1){
          value = 360 - start;
        }

        item.css({
          '-webkit-transform': 'rotate(' + (start+offset) + 'deg)',
          '-moz-transform': 'rotate(' + (start+offset) + 'deg)',
          '-o-transform': 'rotate(' + (start+offset) + 'deg)',
          'transform': 'rotate(' + (start+offset) + 'deg)'
        });

        item.find('.before').css({
          '-webkit-transform': 'rotate(' + (value+1) + 'deg)',
          '-moz-transform': 'rotate(' + (value+1) + 'deg)',
          '-o-transform': 'rotate(' + (value+1) + 'deg)',
          'transform': 'rotate(' + (value+1) + 'deg)'
        });

        start += value;
      });
    });

    $('.tags-reset').hide();

    $('.tagsort-tags-container > span').on('click', function(){
        $('.tags-reset').show();
        if (!$('.tagsort-active').length) {
          $('.tags-reset').hide();
        }
    });

    $('.tags-reset').on('click', function(){
      if (!$('.tagsort-active').length) {
        $('.tags-reset').hide();
      }
    });

    $("#flatmenu").menumaker({
        title: "Menu",
        breakpoint: 768,
        format: "multitoggle"
    });

    $("#flatmenu").prepend("

");

    var foundActive = false, activeElement, linePosition = 0, menuLine = $("#flatmenu #menu-line"), lineWidth, defaultPosition, defaultWidth;

    $("#flatmenu > ul > li").each(function() {
        if ($(this).hasClass('active')) {
            activeElement = $(this);
            foundActive = true;
        }
    });

    if (foundActive === false) {
        activeElement = $("#flatmenu > ul > li").first();
    }

    defaultWidth = lineWidth = activeElement.width();

    defaultPosition = linePosition = activeElement.position().left;

    menuLine.css("width", lineWidth);
    menuLine.css("left", linePosition);

    $("#flatmenu > ul > li").hover(function() {
        activeElement = $(this);
        lineWidth = activeElement.width();
        linePosition = activeElement.position().left;
        menuLine.css("width", lineWidth);
        menuLine.css("left", linePosition);
    }, function() {
        menuLine.css("left", defaultPosition);
        menuLine.css("width", defaultWidth);
    });

    $('.navbar-toggle').on('click', function(){
        $('#navmenu').css('display', 'block');
    });

});
<commit_msg>schedule refresh update<commit_after>$(document).ready(function() {

    var winwidth = $(window).width();

    if (winwidth > 1200) {
      var offset = 300;
      var shrinkoffset = 0;
    	var duration = 500;
      var duration2 = 1500;
    	$(window).scroll(function() {
      	if ($(this).scrollTop() > offset) {
      	   $('#scroll-to-top').fadeIn(duration);
           $('#flatmenu').addClass('flatmenu-dark');
      	} else {
      	   $('#scroll-to-top').fadeOut(duration);
           $('#flatmenu').removeClass('flatmenu-dark');
      	}
    	});

    	$('#scroll-to-top').click(function(event) {
      		event.preventDefault();
      	$('html, body').animate({scrollTop: 0}, 800);
      		return false;
    	});
    }

    $(".float-label").jvFloat();

    $('.header-holder').affix({
      offset: {
        top: $('header').height() + 1
      }
    });

    $('.frame > img').each(function(){
       var $el = $(this),
         staticSrc = $el.attr('src'),
         gifSrc = $el.data('animated');
       $el.hover(
         function(){
           $el.attr("src", gifSrc);
         },
         function(){
           $el.attr("src", staticSrc);
         });
     });

    // $('#home-main-text').css('padding-top', $(window).height()/2.8);
    $('[data-toggle="popover"]').popover();

    $("#talk-desc").showMore({
      minheight: 78, // measured in px
      buttontxtmore: 'show more',
      buttontxtless: 'show less',
      animationspeed: 250
    });

    if ($("body").data('schedule')) {
      // init controller
      var controller = new ScrollMagic.Controller();

      var $sclockminutes = $('.s-clock-minutes');
      var $sclockhours = $('.s-clock-hours');

      TweenMax.to($sclockminutes, 0.1, {rotation: 0,  ease:Linear.easeNone, transformOrigin: "center bottom"});
      TweenMax.to($sclockhours, 0.1, {rotation: 270, ease:Linear.easeNone, transformOrigin: "center bottom"});
      var tweenminutes = TweenMax.to($sclockminutes, 0.1, {rotation: 360*10,  ease:Linear.easeNone, transformOrigin: "center bottom"});
      var tweenhours = TweenMax.to($sclockhours, 0.1, {rotation: 300+270, ease:Linear.easeNone, transformOrigin: "center bottom"});

      if (winwidth > 1200) {

        var clockMinutes = new ScrollMagic.Scene({triggerElement: ".schedule-list",duration: 3600})
        .setTween(tweenminutes)
        .addTo(controller);

        var clockHours = new ScrollMagic.Scene({triggerElement: ".schedule-list",duration: 3600})
        .setTween(tweenhours)
        .addTo(controller);

        var clockPin = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600})
        .setPin('.s-clock')
        .addTo(controller);

        var trackPin1 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track1')
        .setClassToggle(".schedule-navbar", "bodybg")
        .addTo(controller);

        var trackPin2 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track2')
        .setClassToggle(".track-name", "more-z")
        .addTo(controller);

        var trackPin3 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track3')
        .setClassToggle("#flatmenu", "flatmenu-tall")
        .addTo(controller);

        var trackPin4 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track4')
        .setClassToggle(".day", "inline")
        .addTo(controller);

        var trackPin5 = new ScrollMagic.Scene({triggerElement: ".schedule-list", duration: 3600, triggerHook: 'onLeave', offset: -104})
        .setPin('.track5')
        .addTo(controller);

        var cepelinTween = new ScrollMagic.Scene({triggerElement: "#cepelin-trigger"})
        .setTween(cepelinmove)
        .addTo(controller);

      } else {
        $(".schedule-item").each(function() {
          $(this).attr('style', 'padding-bottom: 15px;');
        })
      }

      $(window).bind('load', function () {
        var highlightTalk = $(location).attr('hash').slice(1);
        var slotheight = $(window).height()*Number(highlightTalk.slice(-1))
        if (highlightTalk ) {
          if ($(window).scrollTop() < $(window).height()/2-10) {
            $("."+highlightTalk+"").addClass('highlighted');
            $('html, body').animate({
             scrollTop: $("."+highlightTalk+"").offset().top - ($(window).height()/2-10)
            }, slotheight/2);
          } else {
            $('html, body').animate({scrollTop: $(window).height()/2-10}, slotheight/2, function(){
              $("."+highlightTalk+"").addClass('highlighted');
                $('html, body').animate({
                 scrollTop: $("."+highlightTalk+"").offset().top - ($(window).height()/2-10)
               }, slotheight/2);
            });
          }
        }
      });
    }

    if ($("body").data('cepelin')) {
      var controller2 = new ScrollMagic.Controller();
      var addflip = function(){
        $('.cepelin').addClass('flip');
      }
      var removeflip = function(){
        $('.cepelin').removeClass('flip');
      }
      var cepelinmove = TweenMax.to(".cepelin", 10, {left: winwidth, ease:Linear.easeNone, onStart: removeflip, onComplete: addflip});
      if (winwidth > 1200) {
        var cepelinTween = new ScrollMagic.Scene({triggerElement: "#cepelin-trigger"})
        .setTween(cepelinmove)
        .addTo(controller2);
      }
    }

    $('#home-mainscreen-holder').css('height', $(window).height());

    $('div.tagsort-tags-container').tagSort({
		  items: '.speaker-tags',
		  tagElement: 'span',
		  itemTagsSeperator: ' ',
		  fadeTime: 0,
			sortType: 'inclusive',
      reset: '.tags-reset'
		});

    $('.tagsort-tags-container > span:empty').remove();

    $("[data-doughnut]").each(function(){
      var $this = $(this),
          start = 0,
          offset = 0,
          total = 0,
          n = 0;

      $this.find("> div").each(function(){
        var item = $(this);
        var value = item.data("doughnut-value") * 1;
        item.append('

');

        if(value > 50){
          item.addClass("big");
        }

        total += value;
        n++;
      }).each(function(index, el){
        var item = $(this);
        var value = Math.round(item.data("doughnut-value") * 3.6); //because the value is percent

        if(total >= 99.9 && n == index + 1){
          value = 360 - start;
        }

        item.css({
          '-webkit-transform': 'rotate(' + (start+offset) + 'deg)',
          '-moz-transform': 'rotate(' + (start+offset) + 'deg)',
          '-o-transform': 'rotate(' + (start+offset) + 'deg)',
          'transform': 'rotate(' + (start+offset) + 'deg)'
        });

        item.find('.before').css({
          '-webkit-transform': 'rotate(' + (value+1) + 'deg)',
          '-moz-transform': 'rotate(' + (value+1) + 'deg)',
          '-o-transform': 'rotate(' + (value+1) + 'deg)',
          'transform': 'rotate(' + (value+1) + 'deg)'
        });

        start += value;
      });
    });

    $('.tags-reset').hide();

    $('.tagsort-tags-container > span').on('click', function(){
        $('.tags-reset').show();
        if (!$('.tagsort-active').length) {
          $('.tags-reset').hide();
        }
    });

    $('.tags-reset').on('click', function(){
      if (!$('.tagsort-active').length) {
        $('.tags-reset').hide();
      }
    });

    $("#flatmenu").menumaker({
        title: "Menu",
        breakpoint: 768,
        format: "multitoggle"
    });

    $("#flatmenu").prepend("

");

    var foundActive = false, activeElement, linePosition = 0, menuLine = $("#flatmenu #menu-line"), lineWidth, defaultPosition, defaultWidth;

    $("#flatmenu > ul > li").each(function() {
        if ($(this).hasClass('active')) {
            activeElement = $(this);
            foundActive = true;
        }
    });

    if (foundActive === false) {
        activeElement = $("#flatmenu > ul > li").first();
    }

    defaultWidth = lineWidth = activeElement.width();

    defaultPosition = linePosition = activeElement.position().left;

    menuLine.css("width", lineWidth);
    menuLine.css("left", linePosition);

    $("#flatmenu > ul > li").hover(function() {
        activeElement = $(this);
        lineWidth = activeElement.width();
        linePosition = activeElement.position().left;
        menuLine.css("width", lineWidth);
        menuLine.css("left", linePosition);
    }, function() {
        menuLine.css("left", defaultPosition);
        menuLine.css("width", defaultWidth);
    });

    $('.navbar-toggle').on('click', function(){
        $('#navmenu').css('display', 'block');
    });

});
<|endoftext|>


<commit_before>import React from 'react';
import { Step } from 'semantic-ui-react';

const StepBar = ({ steps, currentStepIndex, goToStep, snippets }) => {

  var cleanSteps = [];

  steps.forEach((step, index) => {
    var newStep = { title: snippets[ step.key ] };
    newStep.active = index === (currentStepIndex - 1);
    newStep.onClick = (e) => {
      goToStep(index + 1);
    };
    newStep.key = index;
    cleanSteps[ index ] = newStep;
  });

  return (<Step.Group
    className='six'
    size='mini'
    ordered
    items={ cleanSteps } />);
};

export default StepBar;
<commit_msg>Fix StepBar to use snippets in <spans><commit_after>import React from 'react';
import { Step } from 'semantic-ui-react';

const StepBar = ({ steps, currentStepIndex, goToStep, snippets }) => {

  var cleanSteps = [];

  steps.forEach((step, index) => {
    var newStep = { title: { content: snippets[ step.key ] }};
    newStep.active = index === (currentStepIndex - 1);
    newStep.onClick = (e) => {
      goToStep(index + 1);
    };
    newStep.key = index;
    cleanSteps[ index ] = newStep;
  });

  return (<Step.Group
    className='six'
    size='mini'
    ordered
    items={ cleanSteps } />);
};

export default StepBar;
<|endoftext|>


<commit_before>
frappe.provide('frappe.views');

frappe.ui.GroupBy = class {
	constructor(report_view) {
		this.report_view = report_view;
		this.page = report_view.page;
		this.doctype = report_view.doctype;
		this.setup_group_by_area();
	}

	setup_group_by_area() {
		this.make_group_by_button();
		let sql_aggregate_function = [
			{name:'count', label: 'Count'},
			{name:'sum', label: 'Sum'},
			{name:'avg', label:'Average'}
		];
		this.groupby_edit_area = $(frappe.render_template("group_by", {
			doctype: this.doctype,
			groupby_conditions: this.get_group_by_fields(),
			aggregate_function_conditions: sql_aggregate_function,
		}));

		this.groupby_select = this.groupby_edit_area.find('select.groupby');
		this.aggregate_function_select = this.groupby_edit_area.find('select.aggregate-function');
		this.aggregate_on_select = this.groupby_edit_area.find('select.aggregate-on');

		// set default to count
		this.aggregate_function_select.val("count");
		this.page.wrapper.find(".frappe-list").append(
			this.groupby_edit_area);

		//Set aggregate on options as numeric fields if function is sum or average
		this.aggregate_function_select.on('change', () => {
			this.show_hide_aggregate_on();
		});

		// try running on change
		this.groupby_select.on('change', () => this.apply_group_by_and_refresh());
		this.aggregate_function_select.on('change', () => this.apply_group_by_and_refresh());
		this.aggregate_on_select.on('change', () => this.apply_group_by_and_refresh());

		$('.set-groupby-and-run').on('click', () => {
			this.apply_group_by_and_refresh();
		});

		$('.remove-groupby').on('click', () => {
			this.remove_group_by();
		});
	}

	show_hide_aggregate_on() {
		this.report_view.meta.fields.forEach((field) => {
			let fn = this.aggregate_function_select.val();
			if(fn === 'sum' || fn === 'avg') {
				// pick numeric fields for sum / avg
				if(frappe.model.is_numeric_field(field.fieldtype)) {
					this.aggregate_on_select.append(
						$('<option>', { value : field.fieldname })
							.text(field.label));
				}
				this.aggregate_on_select.show();
			} else {
				// count, so no aggregate function
				this.aggregate_on_select.hide();
			}
		});
	}

	get_settings() {
		if (this.group_by)  {
			return {
				group_by: this.group_by,
				aggregate_function: this.aggregate_function,
				aggregate_on: this.aggregate_on
			};
		} else {
			return null;
		}
	}

	apply_settings(settings) {

		// Extract fieldname from `tabdoctype`.`fieldname`
		let group_by_fieldname = settings.group_by.split('.')[1].replace('`', '');

		this.groupby_select.val(group_by_fieldname);
		this.aggregate_function_select.val(settings.aggregate_function);
		this.show_hide_aggregate_on();
		this.aggregate_on_select.val(settings.aggregate_on);
		this.groupby_edit_area.show();

		this.apply_group_by();
	}

	make_group_by_button() {
		let group_by_button =  $(`

				<button class="btn btn-default btn-xs add-groupby text-muted">
						${__("Add Group")}
				</button>

`);
		this.page.wrapper.find(".sort-selector").before(group_by_button);
		group_by_button.click(() => this.groupby_edit_area.show());
	}

	apply_group_by() {
		this.group_by_doctype = this.groupby_select.find(':selected').attr('data-doctype');
		this.group_by_field = this.groupby_select.val();
		this.group_by = '`tab' + this.group_by_doctype + '`.`' + this.group_by_field + '`';
		this.aggregate_function = this.aggregate_function_select.val();

		if (this.aggregate_function === 'count') {
			this.aggregate_on = 'name';
		} else {
			this.aggregate_on = this.aggregate_on_select.val();
		}

		//All necessary fields must be set before applying group by
		if(!this.group_by) {
			this.page.wrapper.find('.groupby').focus();
			return;
		} else if(!this.aggregate_function) {
			this.page.wrapper.find('.aggregate-function').focus();
			return;
		} else if(!this.aggregate_on && this.aggregate_function!=='count') {
			this.page.wrapper.find('.aggregate-on').focus();
			return;
		}

		return true;

	}

	apply_group_by_and_refresh() {
		if (this.apply_group_by()) {
			this.report_view.refresh();
		}
	}

	set_args(args) {
		if (this.aggregate_function && this.group_by) {
			let aggregate_column;
			if(this.aggregate_function === 'count') {
				aggregate_column = 'count(`tab'+ this.doctype + '`.`name`)';
			} else {
				aggregate_column = `${this.aggregate_function}(\`tab${this.doctype}\`.\`${this.aggregate_on}\`)`;
			}

			this.report_view.group_by = this.group_by;
			this.report_view.sort_by = '_aggregate_column';
			this.report_view.sort_order = 'desc';

			// save orignial fields
			if(!this.report_view.fields.map(f => f[0]).includes('_aggregate_column')) {
				this.original_fields = this.report_view.fields.map(f => f);
			}

			this.report_view.fields = [
				[this.group_by_field, this.group_by_doctype]
			];

			// rebuild fields for group by
			args.fields = this.report_view.get_fields();

			// add aggregate column in both query args and report view
			this.report_view.fields.push(['_aggregate_column', this.doctype]);
			args.fields.push(aggregate_column + ' as _aggregate_column');

			// setup columns in datatable
			this.report_view.setup_columns();

			Object.assign(args, {
				with_comment_count: false,
				group_by: this.report_view.group_by || null,
				order_by: '_aggregate_column desc'
			});
		}

	}

	get_group_by_docfield() {
		// called from build_column
		let docfield;
		if (this.aggregate_function === 'count') {
			docfield = {
				fieldtype: 'Int',
				label: __('Count'),
				parent: this.doctype,
				width: 120
			};
		} else {
			// get properties of "aggregate_on", for example Net Total
			docfield = Object.assign({}, frappe.meta.docfield_map[this.doctype][this.aggregate_on]);
			if (this.aggregate_function === 'sum') {
				docfield.label = __('Sum of {0}', [docfield.label]);
			} else {
				docfield.label = __('Average of {0}', [docfield.label]);
			}
		}
		docfield.fieldname = '_aggregate_column';

		return docfield;
	}

	remove_group_by() {
		this.groupby_edit_area.hide();

		this.order_by = '';
		this.group_by = null;
		this.aggregate_function = null;
		this.aggregate_on = null;
		$(".groupby").val("");
		$(".aggregate-function").val("count");
		$(".aggregate-on").empty().val("").hide();

		// restore original fields
		if (this.original_fields) {
			this.report_view.fields = this.original_fields;
		} else {
			this.report_view.set_default_fields();
		}
		this.report_view.setup_columns();
		this.original_fields = null;
		this.report_view.refresh();
	}

	get_group_by_fields() {
		let group_by_fields = {};
		let fields = this.report_view.meta.fields.filter(f => ["Select", "Link", "Data", "Int"].includes(f.fieldtype));
		group_by_fields[this.doctype] = fields;

		const standard_fields_filter = df =>
			!in_list(frappe.model.no_value_type, df.fieldtype) && !df.report_hide;

		const table_fields = frappe.meta.get_table_fields(this.doctype)
			.filter(df => !df.hidden);

		table_fields.forEach(df => {
			const cdt = df.options;
			const child_table_fields = frappe.meta.get_docfields(cdt).filter(standard_fields_filter);
			group_by_fields[cdt] = child_table_fields;
		});

		return group_by_fields;
	}

};
<commit_msg>fix: replace all occurrences of string in group by field (#9328)<commit_after>
frappe.provide('frappe.views');

frappe.ui.GroupBy = class {
	constructor(report_view) {
		this.report_view = report_view;
		this.page = report_view.page;
		this.doctype = report_view.doctype;
		this.setup_group_by_area();
	}

	setup_group_by_area() {
		this.make_group_by_button();
		let sql_aggregate_function = [
			{name:'count', label: 'Count'},
			{name:'sum', label: 'Sum'},
			{name:'avg', label:'Average'}
		];
		this.groupby_edit_area = $(frappe.render_template("group_by", {
			doctype: this.doctype,
			groupby_conditions: this.get_group_by_fields(),
			aggregate_function_conditions: sql_aggregate_function,
		}));

		this.groupby_select = this.groupby_edit_area.find('select.groupby');
		this.aggregate_function_select = this.groupby_edit_area.find('select.aggregate-function');
		this.aggregate_on_select = this.groupby_edit_area.find('select.aggregate-on');

		// set default to count
		this.aggregate_function_select.val("count");
		this.page.wrapper.find(".frappe-list").append(
			this.groupby_edit_area);

		//Set aggregate on options as numeric fields if function is sum or average
		this.aggregate_function_select.on('change', () => {
			this.show_hide_aggregate_on();
		});

		// try running on change
		this.groupby_select.on('change', () => this.apply_group_by_and_refresh());
		this.aggregate_function_select.on('change', () => this.apply_group_by_and_refresh());
		this.aggregate_on_select.on('change', () => this.apply_group_by_and_refresh());

		$('.set-groupby-and-run').on('click', () => {
			this.apply_group_by_and_refresh();
		});

		$('.remove-groupby').on('click', () => {
			this.remove_group_by();
		});
	}

	show_hide_aggregate_on() {
		this.report_view.meta.fields.forEach((field) => {
			let fn = this.aggregate_function_select.val();
			if(fn === 'sum' || fn === 'avg') {
				// pick numeric fields for sum / avg
				if(frappe.model.is_numeric_field(field.fieldtype)) {
					this.aggregate_on_select.append(
						$('<option>', { value : field.fieldname })
							.text(field.label));
				}
				this.aggregate_on_select.show();
			} else {
				// count, so no aggregate function
				this.aggregate_on_select.hide();
			}
		});
	}

	get_settings() {
		if (this.group_by)  {
			return {
				group_by: this.group_by,
				aggregate_function: this.aggregate_function,
				aggregate_on: this.aggregate_on
			};
		} else {
			return null;
		}
	}

	apply_settings(settings) {

		// Extract fieldname from `tabdoctype`.`fieldname`
		let group_by_fieldname = settings.group_by.split('.')[1].replace(/`/g, '');

		this.groupby_select.val(group_by_fieldname);
		this.aggregate_function_select.val(settings.aggregate_function);
		this.show_hide_aggregate_on();
		this.aggregate_on_select.val(settings.aggregate_on);
		this.groupby_edit_area.show();

		this.apply_group_by();
	}

	make_group_by_button() {
		let group_by_button =  $(`

				<button class="btn btn-default btn-xs add-groupby text-muted">
						${__("Add Group")}
				</button>

`);
		this.page.wrapper.find(".sort-selector").before(group_by_button);
		group_by_button.click(() => this.groupby_edit_area.show());
	}

	apply_group_by() {
		this.group_by_doctype = this.groupby_select.find(':selected').attr('data-doctype');
		this.group_by_field = this.groupby_select.val();
		this.group_by = '`tab' + this.group_by_doctype + '`.`' + this.group_by_field + '`';
		this.aggregate_function = this.aggregate_function_select.val();

		if (this.aggregate_function === 'count') {
			this.aggregate_on = 'name';
		} else {
			this.aggregate_on = this.aggregate_on_select.val();
		}

		//All necessary fields must be set before applying group by
		if(!this.group_by) {
			this.page.wrapper.find('.groupby').focus();
			return;
		} else if(!this.aggregate_function) {
			this.page.wrapper.find('.aggregate-function').focus();
			return;
		} else if(!this.aggregate_on && this.aggregate_function!=='count') {
			this.page.wrapper.find('.aggregate-on').focus();
			return;
		}

		return true;

	}

	apply_group_by_and_refresh() {
		if (this.apply_group_by()) {
			this.report_view.refresh();
		}
	}

	set_args(args) {
		if (this.aggregate_function && this.group_by) {
			let aggregate_column;
			if(this.aggregate_function === 'count') {
				aggregate_column = 'count(`tab'+ this.doctype + '`.`name`)';
			} else {
				aggregate_column = `${this.aggregate_function}(\`tab${this.doctype}\`.\`${this.aggregate_on}\`)`;
			}

			this.report_view.group_by = this.group_by;
			this.report_view.sort_by = '_aggregate_column';
			this.report_view.sort_order = 'desc';

			// save orignial fields
			if(!this.report_view.fields.map(f => f[0]).includes('_aggregate_column')) {
				this.original_fields = this.report_view.fields.map(f => f);
			}

			this.report_view.fields = [
				[this.group_by_field, this.group_by_doctype]
			];

			// rebuild fields for group by
			args.fields = this.report_view.get_fields();

			// add aggregate column in both query args and report view
			this.report_view.fields.push(['_aggregate_column', this.doctype]);
			args.fields.push(aggregate_column + ' as _aggregate_column');

			// setup columns in datatable
			this.report_view.setup_columns();

			Object.assign(args, {
				with_comment_count: false,
				group_by: this.report_view.group_by || null,
				order_by: '_aggregate_column desc'
			});
		}

	}

	get_group_by_docfield() {
		// called from build_column
		let docfield;
		if (this.aggregate_function === 'count') {
			docfield = {
				fieldtype: 'Int',
				label: __('Count'),
				parent: this.doctype,
				width: 120
			};
		} else {
			// get properties of "aggregate_on", for example Net Total
			docfield = Object.assign({}, frappe.meta.docfield_map[this.doctype][this.aggregate_on]);
			if (this.aggregate_function === 'sum') {
				docfield.label = __('Sum of {0}', [docfield.label]);
			} else {
				docfield.label = __('Average of {0}', [docfield.label]);
			}
		}
		docfield.fieldname = '_aggregate_column';

		return docfield;
	}

	remove_group_by() {
		this.groupby_edit_area.hide();

		this.order_by = '';
		this.group_by = null;
		this.aggregate_function = null;
		this.aggregate_on = null;
		$(".groupby").val("");
		$(".aggregate-function").val("count");
		$(".aggregate-on").empty().val("").hide();

		// restore original fields
		if (this.original_fields) {
			this.report_view.fields = this.original_fields;
		} else {
			this.report_view.set_default_fields();
		}
		this.report_view.setup_columns();
		this.original_fields = null;
		this.report_view.refresh();
	}

	get_group_by_fields() {
		let group_by_fields = {};
		let fields = this.report_view.meta.fields.filter(f => ["Select", "Link", "Data", "Int"].includes(f.fieldtype));
		group_by_fields[this.doctype] = fields;

		const standard_fields_filter = df =>
			!in_list(frappe.model.no_value_type, df.fieldtype) && !df.report_hide;

		const table_fields = frappe.meta.get_table_fields(this.doctype)
			.filter(df => !df.hidden);

		table_fields.forEach(df => {
			const cdt = df.options;
			const child_table_fields = frappe.meta.get_docfields(cdt).filter(standard_fields_filter);
			group_by_fields[cdt] = child_table_fields;
		});

		return group_by_fields;
	}

};
<|endoftext|>


<commit_before>function doTask()
{
    var list_messages = $('.subject, .commit-message');

    list_messages.each(function()
    {
        var $this = $(this);
        var text = $this.text();
        var filter = [
                         ['(core-\\d+)']
                        ,['(cs-\\d+)']
                        ,['(bemob-\\d+)']
                        ,['(temob-\\d+)']
                        ,['(maint-\\d+)']
                        ,['(dep-\\d+)']
                        ,['(ps-\\d+)']
                     ];

        for(var i=0,l=filter.length; i < l; i++)
        {
            var regex = new RegExp(filter[i][0], 'i');
            var text_found = text.search(regex);

            // Search returns -1 if text is not found
            if(text_found > -1)
            {
                replaceLink(text_found, regex);
            }
        };

        $this.html(text);

        function replaceLink(start,regex)
        {
            var ticket = text.match(regex);
            text = text.replace(regex, '' + ticket[0] + '');
        };
    });
};

$(document).on('click', function()
{
    window.setTimeout(doTask(), 2000);

});
doTask();
<commit_msg>Breakdown host and filter array<commit_after>function doTask()
{
    var commit_messages = $('.subject, .commit-message');

    commit_messages.each(function()
    {
        var $this = $(this);
        var text = $this.text();
        var filter = [
                         ['core']
                        ,['cs']
                        ,['bemob']
                        ,['temob']
                        ,['maint']
                        ,['dep']
                        ,['ps']
                     ];

        for(var i=0,l=filter.length; i < l; i++)
        {
            var regex = new RegExp('(' + filter[i] + '-\\d+)', 'i');
            var text_found = text.search(regex);

            // Search returns -1 if text is not found
            if(text_found > -1)
            {
                replaceLink(regex);
            }
        };

        $this.html(text);

        function replaceLink(regex)
        {
            var ticket = text.match(regex);
            var host_string = "issues.buildingengines.com"
            text = text.replace(regex, '' + ticket[0] + '');
        };
    });
};

$(document).on('click', function()
{
    window.setTimeout(doTask(), 2000);
});

doTask();
<|endoftext|>


<commit_before>/**
 * Mock for groupPost
 * @type {{groupId: number, groupPostId: number, groupPostData: {title: string, content: string, timeCreated: string, id: number, postownerid: number, postid: number, groupid: number, owner: {imageUrl: string, favoriteLibraries: Array, realm: null, email: string, id: number}, comments: *[]}}}
 */

export const groupPost = {
  groupId: 1,
  groupPostId: 1,
  groupPostData: {
    title: 'Pers post',
    content: 'Det her er Pers post',
    timeCreated: '2015-10-01T11:26:36.000Z',
    id: 1,
    postownerid: 1,
    postid: 2,
    groupid: 2,
    owner: {
      imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
      favoriteLibraries: [],
      realm: null,
      email: 'asd@mailinator.com',
      id: 1
    },
    comments: [{
      content: 'Dette er en kommentar',
      timeCreated: '2015-10-01T11:26:36.000Z',
      id: 1,
      commentownerid: 1,
      postid: 1,
      owner: {
        imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
        favoriteLibraries: [],
        email: 'asd@mailinator.com',
        id: 1
      }
    }, {
      content: 'per',
      timeCreated: '2015-10-01T13:54:01.000Z',
      id: 2,
      commentownerid: 1,
      postid: 1,
      owner: {
        imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
        favoriteLibraries: [],
        email: 'asd@mailinator.com',
        id: 1
      }
    }]
  }
};
<commit_msg>us77: fix lint on mock<commit_after>'use strict';

/**
 * Mock for groupPost
 */

export const groupPost = {
  groupId: 1,
  groupPostId: 1,
  groupPostData: {
    title: 'Pers post',
    content: 'Det her er Pers post',
    timeCreated: '2015-10-01T11:26:36.000Z',
    id: 1,
    postownerid: 1,
    postid: 2,
    groupid: 2,
    owner: {
      imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
      favoriteLibraries: [],
      realm: null,
      email: 'asd@mailinator.com',
      id: 1
    },
    comments: [{
      content: 'Dette er en kommentar',
      timeCreated: '2015-10-01T11:26:36.000Z',
      id: 1,
      commentownerid: 1,
      postid: 1,
      owner: {
        imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
        favoriteLibraries: [],
        email: 'asd@mailinator.com',
        id: 1
      }
    }, {
      content: 'per',
      timeCreated: '2015-10-01T13:54:01.000Z',
      id: 2,
      commentownerid: 1,
      postid: 1,
      owner: {
        imageUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQ…qKcqX5UEJbzyATS8Kd51J6gRrE/MyC7xDpMPHGNBo9Ifr5/y5yjHyVLRgeAAAAAElFTkSuQmCC',
        favoriteLibraries: [],
        email: 'asd@mailinator.com',
        id: 1
      }
    }]
  }
};
<|endoftext|>


<commit_before>'use strict';
const path = require('path')
const pascalCase = require('pascal-case')
const webpack = require('webpack')
const failPlugin = require('webpack-fail-plugin')
const pjson = require('./package.json')

const packageName = pjson.name
const filename = packageName.slice(1).split('/').join('-')
const version = pjson.version
const ns = pascalCase(filename)

module.exports = {
  externals: {
    // TODO: list external dependencies, e.g.:
    // lodash: '_'
  },
  devtool: 'inline-source-map',
  entry: {
    [filename]: './dist/commonjs/index'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: `${filename}.js`,
    library: ns,
    libraryTarget: 'var'
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: "source-map-loader"
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin(`${filename}.js, version: ${version}, generated on: ${new Date().toDateString()}`),
    failPlugin
  ],
  ts: {
    configFileName: 'tsconfig.webpack.json'
  }
}
<commit_msg>Fix global build name<commit_after>'use strict';
const path = require('path')
const pascalCase = require('pascal-case')
const webpack = require('webpack')
const failPlugin = require('webpack-fail-plugin')
const pjson = require('./package.json')

const packageName = pjson.name
const filename = (packageName.indexOf('@') === 0? packageName.slice(1): packageName).split('/').join('-')
const version = pjson.version
const ns = pascalCase(filename)

module.exports = {
  externals: {
    // TODO: list external dependencies, e.g.:
    // lodash: '_'
  },
  devtool: 'inline-source-map',
  entry: {
    [filename]: './dist/commonjs/index'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: `${filename}.js`,
    library: ns,
    libraryTarget: 'var'
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: "source-map-loader"
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin(`${filename}.js, version: ${version}, generated on: ${new Date().toDateString()}`),
    failPlugin
  ],
  ts: {
    configFileName: 'tsconfig.webpack.json'
  }
}
<|endoftext|>


<commit_before>define(["dojo/_base/lang", "dojo/_base/declare", "dojo/on", "../Controller", "../utils/hash"],
function(lang, declare, on, Controller, hash){
	// module:
	//		dojox/app/controllers/History
	// summary:
	//		Bind "app-domNode" event on dojox/app application instance,
	//		Bind "startTransition" event on dojox/app application domNode,
	//		Bind "popstate" event on window object.
	//		Maintain history by HTML5 "pushState" method and "popstate" event.

	return declare("dojox.app.controllers.History", Controller, {
		constructor: function(app){
			// summary:
			//		Bind "app-domNode" event on dojox/app application instance,
			//		Bind "startTransition" event on dojox/app application domNode,
			//		Bind "popstate" event on window object.
			//
			// app:
			//		dojox/app application instance.

			this.events = {
				"app-domNode": this.onDomNodeChange
			};
			if(this.app.domNode){
				this.onDomNodeChange({oldNode: null, newNode: this.app.domNode});
			}
			this.bind(window, "popstate", lang.hitch(this, this.onPopState));
		},

		onDomNodeChange: function(evt){
			if(evt.oldNode != null){
				this.unbind(evt.oldNode, "startTransition");
			}
			this.bind(evt.newNode, "startTransition", lang.hitch(this, this.onStartTransition));
		},

		onStartTransition: function(evt){
			// summary:
			//		Response to dojox/app "startTransition" event.
			//
			// example:
			//		Use "dojox/mobile/TransitionEvent" to trigger "startTransition" event, and this function will response the event. For example:
			//		|	var transOpts = {
			//		|		title:"List",
			//		|		target:"items,list",
			//		|		url: "#items,list",
			//		|		params: {"param1":"p1value"}
			//		|	};
			//		|	new TransitionEvent(domNode, transOpts, e).dispatch();
			//
			// evt: Object
			//		transition options parameter

			// bubbling "startTransition", so Transition controller can response to it.

			// TODO: useless code block, target is never used
			//var target = evt.detail.target;
			//var regex = /#(.+)/;
			//if(!target && regex.test(evt.detail.href)){
			//	target = evt.detail.href.match(regex)[1];
			//}

			// create url hash from target if it is not set
			var currentHash = evt.detail.url || "#"+evt.detail.target;
			if(evt.detail.params){
				currentHash = hash.buildWithParams(currentHash, evt.detail.params);
			}
			// push states to history list
			history.pushState(evt.detail, evt.detail.href, currentHash);
		},

		onPopState: function(evt){
			// summary:
			//		Response to dojox/app "popstate" event.
			//
			// evt: Object
			//		transition options parameter

			// Clean browser's cache and refresh the current page will trigger popState event,
			// but in this situation the application has not started and throws an error.
			// so we need to check application status, if application not STARTED, do nothing.
			if(this.app.getStatus() !== this.app.lifecycle.STARTED){
				return;
			}

			var state = evt.state;
			if(!state){
				if(window.location.hash){
					state = {
						target: hash.getTarget(location.hash),
						url: location.hash,
						params: hash.getParams(location.hash)
					}
				}else{
					state = {
						target: this.app.defaultView
					};
				}
			}

			// TODO explain what is the purpose of this, _sim is never set in dojox/app
			if(evt._sim){
				history.replaceState(state, state.title, state.href);
			}

			// transition to the target view
			this.app.emit("app-transition", {
				viewId: state.target,
				opts: lang.mixin({reverse: true}, evt.detail, {"params": state.params})
			});
		}
	});
});
<commit_msg>one more dojox/app code cleanup jslint type cleanup for trac #15340 thanks bill, along with some other cleanup as well.<commit_after>define(["dojo/_base/lang", "dojo/_base/declare", "dojo/on", "../Controller", "../utils/hash"],
function(lang, declare, on, Controller, hash){
	// module:
	//		dojox/app/controllers/History
	// summary:
	//		Bind "app-domNode" event on dojox/app application instance,
	//		Bind "startTransition" event on dojox/app application domNode,
	//		Bind "popstate" event on window object.
	//		Maintain history by HTML5 "pushState" method and "popstate" event.

	return declare("dojox.app.controllers.History", Controller, {
		constructor: function(app){
			// summary:
			//		Bind "app-domNode" event on dojox/app application instance,
			//		Bind "startTransition" event on dojox/app application domNode,
			//		Bind "popstate" event on window object.
			//
			// app:
			//		dojox/app application instance.

			this.events = {
				"app-domNode": this.onDomNodeChange
			};
			if(this.app.domNode){
				this.onDomNodeChange({oldNode: null, newNode: this.app.domNode});
			}
			this.bind(window, "popstate", lang.hitch(this, this.onPopState));
		},

		onDomNodeChange: function(evt){
			if(evt.oldNode != null){
				this.unbind(evt.oldNode, "startTransition");
			}
			this.bind(evt.newNode, "startTransition", lang.hitch(this, this.onStartTransition));
		},

		onStartTransition: function(evt){
			// summary:
			//		Response to dojox/app "startTransition" event.
			//
			// example:
			//		Use "dojox/mobile/TransitionEvent" to trigger "startTransition" event, and this function will response the event. For example:
			//		|	var transOpts = {
			//		|		title:"List",
			//		|		target:"items,list",
			//		|		url: "#items,list",
			//		|		params: {"param1":"p1value"}
			//		|	};
			//		|	new TransitionEvent(domNode, transOpts, e).dispatch();
			//
			// evt: Object
			//		transition options parameter

			// create url hash from target if it is not set
			var currentHash = evt.detail.url || "#"+evt.detail.target;
			if(evt.detail.params){
				currentHash = hash.buildWithParams(currentHash, evt.detail.params);
			}
			// push states to history list
			history.pushState(evt.detail, evt.detail.href, currentHash);
		},

		onPopState: function(evt){
			// summary:
			//		Response to dojox/app "popstate" event.
			//
			// evt: Object
			//		transition options parameter

			// Clean browser's cache and refresh the current page will trigger popState event,
			// but in this situation the application has not started and throws an error.
			// so we need to check application status, if application not STARTED, do nothing.
			if(this.app.getStatus() !== this.app.lifecycle.STARTED){
				return;
			}

			var state = evt.state;
			if(!state){
				if(window.location.hash){
					state = {
						target: hash.getTarget(location.hash),
						url: location.hash,
						params: hash.getParams(location.hash)
					}
				}else{
					state = {
						target: this.app.defaultView
					};
				}
			}

			// TODO explain what is the purpose of this, _sim is never set in dojox/app
			if(evt._sim){
				history.replaceState(state, state.title, state.href);
			}

			// transition to the target view
			this.app.emit("app-transition", {
				viewId: state.target,
				opts: lang.mixin({reverse: true}, evt.detail, {"params": state.params})
			});
		}
	});
});
<|endoftext|>


<commit_before>// polyfill webpack require.ensure for node environment
if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require)

import { AlignedImage } from './Image'
import { AlignedInfoBox } from './InfoBox'
import { Annotation } from './Annotation'
import { HeaderOne } from './HeaderOne'
import { HeaderTwo } from './HeaderTwo'
import { Paragraph } from './Paragraph'
import Loadable from 'react-loadable'
import React from 'react'

const modulePlaceHolder = null

export default function getArticleComponent(type = 'unstyled') {
  switch (type) {
    case 'annotation':
      return Annotation
    case 'audio':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "audio" */
          './Audio'
        ),
        render(loaded, props) {
          const { Audio } = loaded
          return <Audio {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'blockquote':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "blockquote" */
          './BlockQuote'
        ),
        render(loaded, props) {
          const { BlockQuote } = loaded
          return <BlockQuote {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'quoteby':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "quoteby" */
          './BlockQuote'
        ),
        render(loaded, props) {
          const { AlignedQuoteBy } = loaded
          return <AlignedQuoteBy {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'header-one':
      return HeaderOne
    case 'header-two':
      return HeaderTwo
    case 'code':
      return null
    case 'embeddedCode':
    case 'embeddedcode':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "embeddedcode" */
          './Embedded'
        ),
        render(loaded, props) {
          const { AlignedEmbedded } = loaded
          return <AlignedEmbedded {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'image':
      return AlignedImage
    case 'imageDiff':
    case 'imagediff':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "imagediff" */
          './ImageDiff'
        ),
        render(loaded, props) {
          const { AlignedImageDiff } = loaded
          return <AlignedImageDiff {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'infobox':
      return AlignedInfoBox
    case 'ordered-list-item':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "imagediff" */
          './OrderedList'
        ),
        render(loaded, props) {
          const { OrderedList } = loaded
          return <OrderedList {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'unordered-list-item':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "unorderedlist" */
          './UnorderedList'
        ),
        render(loaded, props) {
          const { UnorderedList } = loaded
          return <UnorderedList {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'unstyled':
      return Paragraph
    case 'slideshow':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "slideshow" */
          './slideshow/slideshow'
        ),
        render(loaded, props) {
          const { Slideshow } = loaded
          return <Slideshow {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    case 'youtube':
      return Loadable({
        loader: () => import(
          /* webpackChunkName: "youtube" */
          './Youtube'
        ),
        render(loaded, props) {
          const { AlignedYoutube } = loaded
          return <AlignedYoutube {...props}/>
        },
        loading() {
          return modulePlaceHolder
        }
      })
    default:
      return
  }
}
<commit_msg>Save return value of Loadable into closure<commit_after>// polyfill webpack require.ensure for node environment
if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require)

import { AlignedImage } from './Image'
import { AlignedInfoBox } from './InfoBox'
import { Annotation } from './Annotation'
import { HeaderOne } from './HeaderOne'
import { HeaderTwo } from './HeaderTwo'
import { Paragraph } from './Paragraph'
import Loadable from 'react-loadable'
import React from 'react'

const modulePlaceHolder = null

const audioLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "audio" */
    './Audio'
  ),
  render(loaded, props) {
    const { Audio } = loaded
    return <Audio {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const blockquoteLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "blockquote" */
    './BlockQuote'
  ),
  render(loaded, props) {
    const { BlockQuote } = loaded
    return <BlockQuote {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const quotebyLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "quoteby" */
    './BlockQuote'
  ),
  render(loaded, props) {
    const { AlignedQuoteBy } = loaded
    return <AlignedQuoteBy {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const embeddedCodeLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "embeddedcode" */
    './Embedded'
  ),
  render(loaded, props) {
    const { AlignedEmbedded } = loaded
    return <AlignedEmbedded {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const imageDiffLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "imagediff" */
    './ImageDiff'
  ),
  render(loaded, props) {
    const { AlignedImageDiff } = loaded
    return <AlignedImageDiff {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const orderedListLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "imagediff" */
    './OrderedList'
  ),
  render(loaded, props) {
    const { OrderedList } = loaded
    return <OrderedList {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const unorderedListLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "unorderedlist" */
    './UnorderedList'
  ),
  render(loaded, props) {
    const { UnorderedList } = loaded
    return <UnorderedList {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const slideshowLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "slideshow" */
    './slideshow/slideshow'
  ),
  render(loaded, props) {
    const { Slideshow } = loaded
    return <Slideshow {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

const youtubeLoadable = Loadable({
  loader: () => import(
    /* webpackChunkName: "youtube" */
    './Youtube'
  ),
  render(loaded, props) {
    const { AlignedYoutube } = loaded
    return <AlignedYoutube {...props}/>
  },
  loading() {
    return modulePlaceHolder
  }
})

export default function getArticleComponent(type = 'unstyled') {
  switch (type) {
    case 'annotation':
      return Annotation
    case 'audio':
      return audioLoadable
    case 'blockquote':
      return blockquoteLoadable
    case 'quoteby':
      return quotebyLoadable
    case 'header-one':
      return HeaderOne
    case 'header-two':
      return HeaderTwo
    case 'code':
      return null
    case 'embeddedCode':
    case 'embeddedcode':
      return embeddedCodeLoadable
    case 'image':
      return AlignedImage
    case 'imageDiff':
    case 'imagediff':
      return imageDiffLoadable
    case 'infobox':
      return AlignedInfoBox
    case 'ordered-list-item':
      return orderedListLoadable
    case 'unordered-list-item':
      return unorderedListLoadable
    case 'unstyled':
      return Paragraph
    case 'slideshow':
      return slideshowLoadable
    case 'youtube':
      return youtubeLoadable
    default:
      return
  }
}
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const {CheckerPlugin} = require('awesome-typescript-loader');
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
const {createLodashTransformer} = require('typescript-plugin-lodash');
const lodashTransformer = createLodashTransformer();

const extractSass = new ExtractTextPlugin({
  filename: "css/[name].css"
});

module.exports = {
  entry: {
    app: [
      './src/entry.tsx'
    ]
  },

  output: {
    path: path.resolve(__dirname, "..", "commandment", "static"),
    filename: 'app.js',
    publicPath: '/static/'
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    alias: { // avoid lodash duplication: https://www.contentful.com/blog/2017/10/27/put-your-webpack-bundle-on-a-diet-part-3/
      'lodash-es': 'lodash',
      'lodash.get': 'lodash/get',
      'lodash.isfunction': 'lodash/isFunction',
      'lodash.isobject': 'lodash/isObject',
      'lodash.merge': 'lodash/merge',
      'lodash.reduce': 'lodash/reduce',
      'lodash.set': 'lodash/set',
      'lodash.unset': 'lodash/unset'
    }
  },
  target: 'web',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: ['awesome-typescript-loader']
      },
      {
        test: /\.js$/,
        include: /node_modules\/semantic-ui-react/,
        loader: "babel-loader"
      },
      {
        test: /\.scss$/,
        use: extractSass.extract({
          use: [{
            loader: 'css-loader'
          }, {
            loader: 'resolve-url-loader'
          }, {
            loader: 'sass-loader?sourceMap'
          }],
          fallback: 'style-loader'
        })
      },
      {
        test: /\.css$/,
        use: extractSass.extract({
          use: [{
            loader: 'css-loader'
          }, {
            loader: 'resolve-url-loader'
          }]
        })
      },
      {
        test: /\.(png|jpg|svg|gif)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: '[name]-[hash].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(ttf|eot|svg|woff|woff2)$/,
        use: [{
          loader: 'file-loader',
          options: {
            outputPath: 'fonts/'
          }
        }]
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    extractSass,
    new CheckerPlugin(),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new BundleAnalyzerPlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ]
};<commit_msg>remove bundle analyzer from prod config, it should be in a testing webpack config.<commit_after>const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const {CheckerPlugin} = require('awesome-typescript-loader');
const {createLodashTransformer} = require('typescript-plugin-lodash');
const lodashTransformer = createLodashTransformer();

const extractSass = new ExtractTextPlugin({
  filename: "css/[name].css"
});

module.exports = {
  entry: {
    app: [
      './src/entry.tsx'
    ]
  },

  output: {
    path: path.resolve(__dirname, "..", "commandment", "static"),
    filename: 'app.js',
    publicPath: '/static/'
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    alias: { // avoid lodash duplication: https://www.contentful.com/blog/2017/10/27/put-your-webpack-bundle-on-a-diet-part-3/
      'lodash-es': 'lodash',
      'lodash.get': 'lodash/get',
      'lodash.isfunction': 'lodash/isFunction',
      'lodash.isobject': 'lodash/isObject',
      'lodash.merge': 'lodash/merge',
      'lodash.reduce': 'lodash/reduce',
      'lodash.set': 'lodash/set',
      'lodash.unset': 'lodash/unset'
    }
  },
  target: 'web',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: ['awesome-typescript-loader']
      },
      {
        test: /\.js$/,
        include: /node_modules\/semantic-ui-react/,
        loader: "babel-loader"
      },
      {
        test: /\.scss$/,
        use: extractSass.extract({
          use: [{
            loader: 'css-loader'
          }, {
            loader: 'resolve-url-loader'
          }, {
            loader: 'sass-loader?sourceMap'
          }],
          fallback: 'style-loader'
        })
      },
      {
        test: /\.css$/,
        use: extractSass.extract({
          use: [{
            loader: 'css-loader'
          }, {
            loader: 'resolve-url-loader'
          }]
        })
      },
      {
        test: /\.(png|jpg|svg|gif)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: '[name]-[hash].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(ttf|eot|svg|woff|woff2)$/,
        use: [{
          loader: 'file-loader',
          options: {
            outputPath: 'fonts/'
          }
        }]
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    extractSass,
    new CheckerPlugin(),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.optimize.UglifyJsPlugin()
  ]
};<|endoftext|>


<commit_before>export default ApplicationStatusConst = {
  Unknown: 'Unknown',
  Healthy: 'Healthy',
  Warning: 'Warning',
  Down: 'Down'
}
<commit_msg>fix validation issue<commit_after>export default {
  Unknown: 'Unknown',
  Healthy: 'Healthy',
  Warning: 'Warning',
  Down: 'Down'
};
<|endoftext|>