<commit_before>// @flow

import {
	Student,
	Schedule,
	type AreaQuery,
	type FabricationType,
	type OnlyCourseLookupFunc,
} from '@gob/object-student'
import {List, Set, Map} from 'immutable'

type PartialCourse = {
	credits: number,
	number: number,
	clbid: string,
	graded: string,
	department: string,
	lab: boolean,
	section: string,
	name: string,

	year: number,
	semester: number,
	term: number,

	_fabrication?: true,
}

type PartialSchedule = {
	semester: number,
	year: number,
	courses: Array<PartialCourse>,
}

export type PartialStudent = {
	courses: Array<PartialCourse>,
	degrees: Array<string>,
	majors: Array<string>,
	concentrations: Array<string>,
	emphases: Array<string>,
	matriculation: number,
	graduation: number,
	advisor: string,
	name: string,
	schedules: Array<PartialSchedule>,
}

export async function convertStudent(
	student: PartialStudent,
	getCourse: OnlyCourseLookupFunc,
): Promise<Student> {
	let studies = processStudies(student)

	let {name, advisor, graduation, matriculation} = student
	let info = {name, advisor, graduation, matriculation}

	let {schedules, fabrications} = await processSchedules(
		student.schedules,
		getCourse,
	)

	let filledStudent = new Student({
		...info,
		schedules,
		fabrications,
		studies,
	})

	return filledStudent
}

export async function processSchedules(
	schedules: Array<PartialSchedule>,
	getCourse: OnlyCourseLookupFunc,
): Promise<{
	schedules: Map<string, Schedule>,
	fabrications: Map<string, FabricationType>,
}> {
	let listOfSchedules = List(schedules)
	let scheds = listOfSchedules.map(sched => {
		let {semester, year, courses} = sched
		let clbids = List(courses.map(c => c.clbid))

		return new Schedule({
			semester,
			year,
			clbids,
			active: true,
		})
	})

	let allCourses = listOfSchedules.flatMap(s => s.courses)
	let promisedFabrications = allCourses.map(course => {
		let {clbid, term} = course

		return getCourse({clbid, term}).then(resolved => {
			// we actually want to invert this; if we found the course, then it's not
			// a fabrication, so we return null; otoh, if we _didn't_ find the course,
			// it must be a fabrication, so we actually want to return it.
			if (resolved) {
				return null
			}
			return ((course: any): FabricationType)
		})
	})

	let resolvedFabrications = await Promise.all(promisedFabrications)

	let fabricationPairs = resolvedFabrications
		.filter(Boolean)
		.map(c => [c.clbid, c])

	return {
		schedules: Map(scheds.map(s => [s.id, s])),
		fabrications: Map(fabricationPairs),
	}
}

export function processStudies({
	majors: m,
	degrees: d,
	emphases: e,
	concentrations: c,
}: PartialStudent): Set<AreaQuery> {
	d = d.map(name => {
		switch (name) {
			case 'B.A.':
				return 'Bachelor of Arts'
			case 'B.M.':
				return 'Bachelor of Music'
			default:
				return name
		}
	})

	return Set([
		...d.map(name => ({name, type: 'degree', revision: 'latest'})),
		...m.map(name => ({name, type: 'major', revision: 'latest'})),
		...c.map(name => ({name, type: 'concentration', revision: 'latest'})),
		...e.map(name => ({name, type: 'emphasis', revision: 'latest'})),
	])
}
<commit_msg>update convertImportedStudent to produce proper Course objects<commit_after>// @flow

import {
	Student,
	Schedule,
	type AreaQuery,
	type CourseType,
	type CourseLookupFunc,
} from '@gob/object-student'
import {List, Set, Map} from 'immutable'

type PartialCourse = {
	credits: number,
	number: string,
	clbid: string,
	graded: string,
	department: string,
	lab: boolean,
	section: string,
	name: string,
	gereqs: Array<string>,

	year: number,
	semester: number,
	term: number,

	type?: string,
	title?: string,
	crsid?: string,
	status?: string,
	pf?: boolean,
	instructors?: Array<string>,
	enrolled?: number,
	max?: number,
	groupid?: string,
	prerequisites?: false | string,

	_fabrication?: true,
}

function fleshOutSisFabrication(input: PartialCourse): CourseType {
	let {
		clbid,
		credits,
		crsid = 'n/a',
		department,
		enrolled = 1,
		gereqs = [],
		groupid = 'fabrication',
		instructors = [],
		lab,
		max = 0,
		name,
		number,
		pf = false,
		prerequisites = false,
		section,
		semester,
		status = 'Closed',
		term,
		title = '',
		type = 'Research',
		year,
	} = input

	let revisions = []
	let notes = ''
	let description = []
	let level = Math.floor(
		(parseInt(number.replace(/^[0-9]/g, '')) / 100) * 100,
	)

	return {
		clbid,
		credits,
		crsid,
		department,
		description,
		enrolled,
		gereqs,
		groupid,
		instructors,
		lab,
		level,
		max,
		name,
		notes,
		number,
		pf,
		prerequisites,
		revisions,
		section,
		semester,
		status,
		term,
		title,
		type,
		year,
	}
}

type PartialSchedule = {
	semester: number,
	year: number,
	courses: Array<PartialCourse>,
}

export type PartialStudent = {
	courses: Array<PartialCourse>,
	degrees: Array<string>,
	majors: Array<string>,
	concentrations: Array<string>,
	emphases: Array<string>,
	matriculation: number,
	graduation: number,
	advisor: string,
	name: string,
	schedules: Array<PartialSchedule>,
}

export async function convertStudent(
	student: PartialStudent,
	getCourse: CourseLookupFunc,
): Promise<Student> {
	let studies = processStudies(student)

	let {name, advisor, graduation, matriculation} = student
	let info = {name, advisor, graduation, matriculation}

	let {schedules, fabrications} = await processSchedules(
		student.schedules,
		getCourse,
	)

	let filledStudent = new Student({
		...info,
		schedules,
		fabrications,
		studies,
	})

	return filledStudent
}

export async function processSchedules(
	schedules: Array<PartialSchedule>,
	getCourse: CourseLookupFunc,
): Promise<{
	schedules: Map<string, Schedule>,
	fabrications: List<CourseType>,
}> {
	let listOfSchedules = List(schedules)
	let scheds = listOfSchedules.map(sched => {
		let {semester, year, courses} = sched
		let clbids = List(courses.map(c => c.clbid))

		return new Schedule({
			semester,
			year,
			clbids,
			active: true,
		})
	})

	let allCourses = listOfSchedules.flatMap(s => s.courses)
	let promisedFabrications = allCourses.map(course => {
		let {clbid, term} = course

		return getCourse(clbid, term, []).then(resolved => {
			// we actually want to invert this; if we found the course, then it's not
			// a fabrication, so we return null; otoh, if we _didn't_ find the course,
			// it must be a fabrication, so we actually want to return it.
			if (resolved.error === false) {
				return null
			}
			return fleshOutSisFabrication(course)
		})
	})

	let resolvedFabrications = await Promise.all(promisedFabrications)

	let fabricationPairs = resolvedFabrications.filter(Boolean)

	return {
		schedules: Map(scheds.map(s => [s.id, s])),
		fabrications: List(fabricationPairs),
	}
}

export function processStudies({
	majors: m,
	degrees: d,
	emphases: e,
	concentrations: c,
}: PartialStudent): Set<AreaQuery> {
	d = d.map(name => {
		switch (name) {
			case 'B.A.':
				return 'Bachelor of Arts'
			case 'B.M.':
				return 'Bachelor of Music'
			default:
				return name
		}
	})

	return Set([
		...d.map(name => ({name, type: 'degree', revision: 'latest'})),
		...m.map(name => ({name, type: 'major', revision: 'latest'})),
		...c.map(name => ({name, type: 'concentration', revision: 'latest'})),
		...e.map(name => ({name, type: 'emphasis', revision: 'latest'})),
	])
}
<|endoftext|>


<commit_before>import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus';

const CRITICAL_MASSIVE_DAMAGE_BONUS = 0.1;

// Flamestrike damage events don't always hit on identical timestamps, and same with Critical Massive removal after a cast, so we give it a short window
const TOLERANCE_WINDOW_MS = 100;

/*
 * Pyroblast and Flamestrike critical strikes increases the damage of your next Pyroblast or Flamestrike by 10% for 8 sec.
 *
 * The proc is a buff on the player which is unfortunately removed on cast rather than on damage.
 * The buff fall seems to always happen after the cast, so we can use that to tell the difference between buff consumed and buff expired.
 */
class Tier20_4set extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  }

  lastCastTimestamp; // last cast timestamp of pyroblast or flamestrike... used close to buff falloff indicates proc consumed
  flamestrikeflamestrikeHitTimestamp; // used to associate multiple hits of same flamestrike cast
  boostNextHit = false; // set true when a proc has just been consumed, indicating next relevant damage event should be boosted
  totalProcs = 0;
  expiredProcs = 0;
  pyroblastProcs = 0;
  flamestrikeProcs = 0;
  damage = 0;

  on_initialized() {
	  this.active = this.combatants.selected.hasBuff(SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id);
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.PYROBLAST.id || spellId === SPELLS.FLAMESTRIKE.id) {
      this.lastCastTimestamp = this.owner.currentTimestamp;
    }
  }

  on_byPlayer_removebuff(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.CRITICAL_MASSIVE.id) {
      this.totalProcs += 1;
      if(this.lastCastTimestamp && this.lastCastTimestamp + TOLERANCE_WINDOW_MS > this.owner.currentTimestamp) {
        this.boostNextHit = true;
      } else {
        this.expiredProcs += 1;
      }
    }
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.PYROBLAST.id && this.boostNextHit) {
      this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
      this.pyroblastProcs += 1;
      this.boostNextHit = false;
    } else if(spellId === SPELLS.FLAMESTRIKE.id) {
      if(this.boostNextHit) {
        this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
        this.flamestrikeHitTimestamp = this.owner.currentTimestamp;
        this.flamestrikeProcs += 1;
        this.boostNextHit = false;
      } else if(this.flamestrikeHitTimestamp && this.flamestrikeHitTimestamp + TOLERANCE_WINDOW_MS > this.owner.currentTimestamp) {
        this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
      }
    }
  }

  item() {
    const ppm = this.totalProcs / (this.owner.fightDuration / 1000 / 60);
    return {
      id: `${SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id}`,
      icon: <SpellIcon id={SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id} />,
      title: <SpellLink id={SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id} />,
      result: (
        <dfn data-tip={`You got ${this.totalProcs} total procs (${ppm.toFixed(1)} PPM), consuming ${this.pyroblastProcs} with Pyroblast, ${this.flamestrikeProcs} with Flamestrike, and letting ${this.expiredProcs} procs expire. The damage numbers do not account for the additional Ignite damage from the boosted Pyroblasts.`}>
        {this.owner.formatItemDamageDone(this.damage)}
        </dfn>
      ),
    };
  }
}

export default Tier20_4set;
<commit_msg>Fixed typo<commit_after>import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus';

const CRITICAL_MASSIVE_DAMAGE_BONUS = 0.1;

// Flamestrike damage events don't always hit on identical timestamps, and same with Critical Massive removal after a cast, so we give it a short window
const TOLERANCE_WINDOW_MS = 100;

/*
 * Pyroblast and Flamestrike critical strikes increases the damage of your next Pyroblast or Flamestrike by 10% for 8 sec.
 *
 * The proc is a buff on the player which is unfortunately removed on cast rather than on damage.
 * The buff fall seems to always happen after the cast, so we can use that to tell the difference between buff consumed and buff expired.
 */
class Tier20_4set extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  }

  lastCastTimestamp; // last cast timestamp of pyroblast or flamestrike... used close to buff falloff indicates proc consumed
  flamestrikeHitTimestamp; // used to associate multiple hits of same flamestrike cast
  boostNextHit = false; // set true when a proc has just been consumed, indicating next relevant damage event should be boosted
  totalProcs = 0;
  expiredProcs = 0;
  pyroblastProcs = 0;
  flamestrikeProcs = 0;
  damage = 0;

  on_initialized() {
	  this.active = this.combatants.selected.hasBuff(SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id);
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.PYROBLAST.id || spellId === SPELLS.FLAMESTRIKE.id) {
      this.lastCastTimestamp = this.owner.currentTimestamp;
    }
  }

  on_byPlayer_removebuff(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.CRITICAL_MASSIVE.id) {
      this.totalProcs += 1;
      if(this.lastCastTimestamp && this.lastCastTimestamp + TOLERANCE_WINDOW_MS > this.owner.currentTimestamp) {
        this.boostNextHit = true;
      } else {
        this.expiredProcs += 1;
      }
    }
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    if(spellId === SPELLS.PYROBLAST.id && this.boostNextHit) {
      this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
      this.pyroblastProcs += 1;
      this.boostNextHit = false;
    } else if(spellId === SPELLS.FLAMESTRIKE.id) {
      if(this.boostNextHit) {
        this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
        this.flamestrikeHitTimestamp = this.owner.currentTimestamp;
        this.flamestrikeProcs += 1;
        this.boostNextHit = false;
      } else if(this.flamestrikeHitTimestamp && this.flamestrikeHitTimestamp + TOLERANCE_WINDOW_MS > this.owner.currentTimestamp) {
        this.damage += getDamageBonus(event, CRITICAL_MASSIVE_DAMAGE_BONUS);
      }
    }
  }

  item() {
    const ppm = this.totalProcs / (this.owner.fightDuration / 1000 / 60);
    return {
      id: `${SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id}`,
      icon: <SpellIcon id={SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id} />,
      title: <SpellLink id={SPELLS.FIRE_MAGE_T20_4SET_BONUS_BUFF.id} />,
      result: (
        <dfn data-tip={`You got ${this.totalProcs} total procs (${ppm.toFixed(1)} PPM), consuming ${this.pyroblastProcs} with Pyroblast, ${this.flamestrikeProcs} with Flamestrike, and letting ${this.expiredProcs} procs expire. The damage numbers do not account for the additional Ignite damage from the boosted Pyroblasts.`}>
        {this.owner.formatItemDamageDone(this.damage)}
        </dfn>
      ),
    };
  }
}

export default Tier20_4set;
<|endoftext|>


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

var sys = require("sys"),
    url = require('url'),
    lounge = require('./lounge');

var debug = true;

var version = toJSON(
  {
	couchdb : "Welcome",
	version : "0.10.0",
	lounge : {
	  lode : "Totally nodular, dude",
	  version : "0.0.1"
	}
  }
);

function toJSON(obj) {
    return obj !== null ? JSON.stringify(obj) : null;
}

function handle_request(client_request, client_response) {
  request_url_parsed = url.parse(client_request.url, true);
  path_parts = request_url_parsed['pathname'].match(/[^\/$]+/g);

  if(!path_parts) {
	client_response.writeHead(200, {"Content-Type": "text/plain"});
	client_response.write(version);
	client_response.end();
	return;
  }

  //This should probably turn into something like couch's *_handlers conf
  switch(path_parts.length) {
  case 1: //root space request (_all_tasks and the like)
	handle_basic_request(client_request, client_response, path_parts);
	break;
  case 2: //db request
	handle_db_request(client_request, client_response, path_parts);
	break;
  default:
	client_response.writeHead(400, {"Content-Type": "text/plain"});
	client_response.write("Check back soon...");
	client_response.end();
  }
};

function handle_basic_request(client_request, client_response, path_parts) {
  client_response.writeHead(400, {"Content-Type": "text/plain"});
  client_response.write("Nothing here yet");
  client_response.end();
};

function handle_db_request(client_request, client_response, path_parts) {
  db_name = path_parts[0];
  client_response.writeHead(400, {"Content-Type": "text/plain"});
  client_response.write("Nothing here yet, but here are the replica uris by shard\n");
  this.shards(db_name).forEach(
	function(repls, shard_no) {
	  client_response.write("Shard " + shard_no + "\n");
	  repls.forEach(
		function(uri) {
		  client_response.write("\t" + uri + "\n");
		});
	});
  client_response.end();
}

var port=6984;
lounge.createServer(
  function(request, response) {
	try {
	  handle_request(request, response);
	} catch(err) {
	  response.writeHead(500, {"Content-Type": "text/plain"});
	  response.write("Internal Server Error\n");
	  if(debug) {
		response.write(err.stack);
	  }
	  response.end();
	}
  }
).listen(port);
sys.puts("relax, lode listening on port " + port);
<commit_msg>send a body in all cases.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

var sys = require("sys"),
    url = require('url'),
    lounge = require('./lounge');

var debug = true;

var version = toJSON(
  {
	couchdb : "Welcome",
	version : "0.10.0",
	lounge : {
	  lode : "Totally nodular, dude",
	  version : "0.0.1"
	}
  }
);

function toJSON(obj) {
    return obj !== null ? JSON.stringify(obj) : null;
}

function handle_request(client_request, client_response) {
  request_url_parsed = url.parse(client_request.url, true);
  path_parts = request_url_parsed['pathname'].match(/[^\/$]+/g);

  if(!path_parts) {
	client_response.writeHead(200, {"Content-Type": "text/plain"});
	client_response.write(version);
	client_response.end();
	return;
  }

  //This should probably turn into something like couch's *_handlers conf
  switch(path_parts.length) {
  case 1: //root space request (_all_tasks and the like)
	handle_basic_request(client_request, client_response, path_parts);
	break;
  case 2: //db request
	handle_db_request(client_request, client_response, path_parts);
	break;
  default:
	client_response.writeHead(400, {"Content-Type": "text/plain"});
	client_response.write("Check back soon...\n");
	client_response.end();
  }
};

function handle_basic_request(client_request, client_response, path_parts) {
  client_response.writeHead(400, {"Content-Type": "text/plain"});
  client_response.write("Nothing here yet.\n");
  client_response.end();
};

function handle_db_request(client_request, client_response, path_parts) {
  db_name = path_parts[0];
  client_response.writeHead(400, {"Content-Type": "text/plain"});
  client_response.write("Nothing here yet.\n");
  client_response.end();
}

var port=6984;
lounge.createServer(
  function(request, response) {
	try {
	  handle_request(request, response);
	} catch(err) {
	  response.writeHead(500, {"Content-Type": "text/plain"});
	  response.write("Internal Server Error\n");
	  if(debug) {
		response.write(err.stack);
	  }
	  response.end();
	}
  }
).listen(port);
sys.puts("relax, lode listening on port " + port);
<|endoftext|>


<commit_before>'use strict';

const luhn = {
    /**
     * Check input value, must be not null, not undefined and of type string or number.
     * The stringified value must be only digits and longer than 1 (/^[0-9]{2,}$/).
     * Check the value against Luhn formula.
     *
     * @param {*} rawValue
     */
    isValid(rawValue) {
        const value = stringifyInput(rawValue);

        if (!value.match(FORMAT_ISVALID)) {
            throw new Error('Exception value of format \'' + FORMAT_ISVALID + '\', found: \'' + value + '\'');
        }

        return getLuhnRemainder(value) === 0;
    },

    /**
     * Check input value, must be not null, not undefined and of type string or number.
     * The stringified value must be only digits and longer than 0 (/^[0-9]{1,}$/).
     * Add check digit to the rawValue and return it.
     *
     * @param {*} rawValue
     */
    generate(rawValue) {
        const value = stringifyInput(rawValue);

        if (!value.match(FORMAT_GENERATE)) {
            throw new Error('Exception value of format \'' + FORMAT_GENERATE + '\', found: \'' + value + '\'');
        }

        return value + ((10 - getLuhnRemainder(value + '0')) % 10).toString();
    },

    /**
     * Compute remainder using Luhn formula.
     * Fast entry: we assume that the given parameter is a non-null string
     * containing only digits. It will crash otherwise.
     * Returns a number.
     *
     * Note: Remainder cannot be directly used as check digit.
     * To generate check digit, please refer to method generate.
     *
     * @param {*} rawValue
     */
    getRemainder(rawValue) {
        return getLuhnRemainder(rawValue);
    }
};

const FORMAT_ISVALID = /^[0-9]{2,}$/;
const FORMAT_GENERATE = /^[0-9]{1,}$/;

const CHARCODE_0 = '0'.charCodeAt(0);
const MAPPING_EVEN = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];

function getLuhnRemainder(value) {
    var length = value.length;
    var accumulator = 0;
    var bit = 0;

    while (length-- > 0) {
        accumulator += (bit ^= 1) ? value.charCodeAt(length) - CHARCODE_0 : MAPPING_EVEN[value.charCodeAt(length) - CHARCODE_0];
    }

    return accumulator % 10;
}

function stringifyInput(rawValue) {
    if (rawValue !== null && rawValue !== undefined) {
        switch(typeof rawValue) {
        case 'string':
            return rawValue;
        case 'number':
            return rawValue.toString();
        default:
            throw new Error('Expecting value of type \'string\' or \'number\', found: \'' + (typeof rawValue) + '\'');
        }
    }

    throw new Error('Expecting value of type \'string\' or \'number\', found: \'' + rawValue + '\'');
}

module.exports = luhn;
<commit_msg>Remove number tolerance<commit_after>'use strict';

const luhn = {
    /**
     * Check input value, must be not null, not undefined and of type string.
     * The stringified value must be only digits and longer than 1 (/^[0-9]{2,}$/).
     * Check the value against Luhn formula.
     *
     * @param {*} rawValue
     */
    isValid(rawValue) {
        const value = stringifyInput(rawValue);

        if (!value.match(FORMAT_ISVALID)) {
            throw new Error('Exception value of format \'' + FORMAT_ISVALID + '\', found: \'' + value + '\'');
        }

        return getLuhnRemainder(value) === 0;
    },

    /**
     * Check input value, must be not null, not undefined and of type string.
     * The stringified value must be only digits and longer than 0 (/^[0-9]{1,}$/).
     * Add check digit to the rawValue and return it.
     *
     * @param {*} rawValue
     */
    generate(rawValue) {
        const value = stringifyInput(rawValue);

        if (!value.match(FORMAT_GENERATE)) {
            throw new Error('Exception value of format \'' + FORMAT_GENERATE + '\', found: \'' + value + '\'');
        }

        return value + ((10 - getLuhnRemainder(value + '0')) % 10).toString();
    },

    /**
     * Compute remainder using Luhn formula.
     * Fast entry: we assume that the given parameter is a non-null string
     * containing only digits. It will crash otherwise.
     * Returns a number.
     *
     * Note: Remainder cannot be directly used as check digit.
     * To generate check digit, please refer to method generate.
     *
     * @param {*} rawValue
     */
    getRemainder(rawValue) {
        return getLuhnRemainder(rawValue);
    }
};

const FORMAT_ISVALID = /^[0-9]{2,}$/;
const FORMAT_GENERATE = /^[0-9]{1,}$/;

const CHARCODE_0 = '0'.charCodeAt(0);
const MAPPING_EVEN = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];

function getLuhnRemainder(value) {
    var length = value.length;
    var accumulator = 0;
    var bit = 0;

    while (length-- > 0) {
        accumulator += (bit ^= 1) ? value.charCodeAt(length) - CHARCODE_0 : MAPPING_EVEN[value.charCodeAt(length) - CHARCODE_0];
    }

    return accumulator % 10;
}

function stringifyInput(rawValue) {
    if (rawValue !== null && rawValue !== undefined) {
        if (typeof rawValue === 'string') {
            return rawValue;

        }

        throw new Error('Expecting value of type \'string\', found: \'' + (typeof rawValue) + '\'');
    }

    throw new Error('Expecting value of type \'string\', found: \'' + rawValue + '\'');
}

module.exports = luhn;
<|endoftext|>


<commit_before>define([
	"require",
	"intern!object",
	"intern/chai!assert",
	"dojo/on",
	"dojo/Deferred",
	"delite/DisplayContainer",
	"delite/Widget",
	"delite/register",
	"requirejs-domready/domReady!"
], function (require, registerSuite, assert, on, Deferred, DisplayContainer, Widget, register) {
	var container;
	registerSuite({
		name: "DisplayContainer",
		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},
		// test with no controller
		original: function () {
			this.timeout = 2500;
			var deferred = new Deferred();
			register("test-default-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-default-display-container");

			function initView(view) {
				dcontainer.appendChild(view);
				view.style.visibility = "hidden";
				view.style.display = "none";
			}

			function testView(view) {
				assert.strictEqual(view.style.visibility, "visible", "visibility");
				assert.strictEqual(view.style.display, "", "display");
			}

			var view1 = document.createElement("div");
			initView(view1);
			var view2 = document.createElement("div");
			view2.setAttribute("id", "view");
			initView(view2);
			container.appendChild(dcontainer);
			dcontainer.startup();
			// by node
			var transitionDeferred = dcontainer.show(view1);
			transitionDeferred.then(function () {
				testView(view1);
				// by id
				// test that a delite-after-show event is fired, if is not fired the test will fail by timeout
				on.once(dcontainer, "delite-after-show", function () {
					// test is finished
					deferred.resolve(true);
				});
				transitionDeferred = dcontainer.show("view");
				transitionDeferred.then(function () {
					testView(view2);
				});
			});
			return deferred.promise;
		},
		hide: function () {
			this.timeout = 2500;
			var deferred = new Deferred();
			register("test-hide-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-hide-display-container");

			function initView(view) {
				dcontainer.appendChild(view);
				view.style.visibility = "visible";
				view.style.display = "";
			}

			function testView(view) {
				assert.strictEqual(view.style.visibility, "hidden", "visibility");
				assert.strictEqual(view.style.display, "none", "display");
			}

			var view1 = document.createElement("div");
			initView(view1);
			var view2 = document.createElement("div");
			view2.setAttribute("id", "view");
			initView(view2);
			container.appendChild(dcontainer);
			dcontainer.startup();
			var beforeDisplayCalled = false;
			dcontainer.on("delite-before-hide", function () {
				beforeDisplayCalled = true;
			});
			// by node
			var transitionDeferred = dcontainer.hide(view1);
			transitionDeferred.then(function () {
				assert(beforeDisplayCalled, "before-hide event must be dispatched");
				testView(view1);
				// by id
				// test that a delite-after-show event is fired, if is not fired the test will fail by timeout
				on.once(dcontainer, "delite-after-hide", function () {
					// test is finished
					deferred.resolve(true);
				});
				transitionDeferred = dcontainer.hide("view");
				transitionDeferred.then(function () {
					testView(view2);
				});
			});
			return deferred.promise;
		},
		event: function () {
			this.timeout = 2500;
			var deferred = new Deferred(), handler;

			function initView(view, id) {
				view.style.visibility = "hidden";
				view.style.display = "none";
				view.setAttribute("id", id + "-event");
			}

			document.addEventListener("delite-display-load", handler = function (event) {
				event.preventDefault();
				var view = document.createElement("div");
				initView(view, event.dest);
				event.loadDeferred.resolve({
					child: view
				});
			});
			register("test-event-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-event-display-container");
			dcontainer.setAttribute("id", "dcontainer");
			container.appendChild(dcontainer);
			dcontainer.startup();
			var beforeDisplayCalled = false;
			dcontainer.on("delite-before-show", function () {
				beforeDisplayCalled = true;
			});
			// by node
			var transitionDeferred = dcontainer.show("view1-event");
			transitionDeferred.then(function () {
				assert(beforeDisplayCalled, "before show event must be dispatched");
				document.removeEventListener("delite-display-load", handler);
				deferred.resolve(true);
			});
			return deferred.promise;
		},
		// test with a controller
		custom: function () {
			this.timeout = 2500;
			var deferred = new Deferred(), handler;

			function initView(view, id) {
				view.style.visibility = "hidden";
				view.style.display = "none";
				view.setAttribute("id", id);
			}

			document.addEventListener("delite-display-load", handler = function (event) {
				event.preventDefault();
				var view = document.createElement("div");
				initView(view, event.dest);
				event.loadDeferred.resolve({
					child: view
				});
			});
			register("test-custom-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-custom-display-container");
			dcontainer.setAttribute("id", "dcontainer");
			container.appendChild(dcontainer);
			dcontainer.startup();
			function testView(view) {
				assert.strictEqual(view.style.visibility, "visible", "visibility");
				assert.strictEqual(view.style.display, "", "display");
				assert.strictEqual(view.parentNode, dcontainer, "parentNode");
			}

			// by node
			var transitionDeferred = dcontainer.show("view1");
			transitionDeferred.then(function () {
				testView(document.getElementById("view1"));
				transitionDeferred = dcontainer.show("view2");
				transitionDeferred.then(function () {
					testView(document.getElementById("view2"));
					document.removeEventListener("delite-display-load", handler);
					// test is finished
					deferred.resolve(true);
				});
			});
			return deferred.promise;
		},
		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<commit_msg>fixes #189 (unreported failures)<commit_after>define([
	"require",
	"intern!object",
	"intern/chai!assert",
	"dojo/on",
	"dojo/Deferred",
	"delite/DisplayContainer",
	"delite/Widget",
	"delite/register",
	"requirejs-domready/domReady!"
], function (require, registerSuite, assert, on, Deferred, DisplayContainer, Widget, register) {
	var container;
	registerSuite({
		name: "DisplayContainer",
		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},
		// test with no controller
		original: function () {
			this.timeout = 2500;
			register("test-default-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-default-display-container");

			function initView(view) {
				dcontainer.appendChild(view);
				view.style.visibility = "hidden";
				view.style.display = "none";
			}

			function testView(view) {
				assert.strictEqual(view.style.visibility, "visible", "visibility");
				assert.strictEqual(view.style.display, "", "display");
			}

			var view1 = document.createElement("div");
			initView(view1);
			var view2 = document.createElement("div");
			view2.setAttribute("id", "original-view");
			initView(view2);
			container.appendChild(dcontainer);
			dcontainer.startup();
			var beforeShowCalled = false;
			dcontainer.on("delite-before-show", function () {
				beforeShowCalled = true;
			});
			return dcontainer.show(view1).then(function () {
				assert(beforeShowCalled, "before-show event must be dispatched");
				testView(view1);
			}).then(function () {
				return dcontainer.show("original-view");
			}).then(function () {
				testView(view2);
			});
		},
		hide: function () {
			this.timeout = 2500;
			register("test-hide-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-hide-display-container");

			function initView(view) {
				dcontainer.appendChild(view);
				view.style.visibility = "visible";
				view.style.display = "";
			}

			function testView(view) {
				assert.strictEqual(view.style.visibility, "hidden", "visibility");
				assert.strictEqual(view.style.display, "none", "display");
			}

			var view1 = document.createElement("div");
			initView(view1);
			var view2 = document.createElement("div");
			view2.setAttribute("id", "hide-view");
			initView(view2);
			container.appendChild(dcontainer);
			dcontainer.startup();
			var beforeHideCalled = false;
			dcontainer.on("delite-before-hide", function () {
				beforeHideCalled = true;
			});
			// by node
			return dcontainer.hide(view1).then(function () {
				assert(beforeHideCalled, "before-hide event must be dispatched");
				testView(view1);
			}).then(function () {
				return dcontainer.hide("hide-view");
			}).then(function () {
				testView(view2);
			});
		},
		event: function () {
			this.timeout = 2500;
			var handler;

			function initView(view, id) {
				view.style.visibility = "hidden";
				view.style.display = "none";
				view.setAttribute("id", id + "-event");
			}

			document.addEventListener("delite-display-load", handler = function (event) {
				event.preventDefault();
				var view = document.createElement("div");
				initView(view, event.dest);
				event.loadDeferred.resolve({
					child: view
				});
			});
			register("test-event-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-event-display-container");
			dcontainer.setAttribute("id", "dcontainer");
			container.appendChild(dcontainer);
			dcontainer.startup();
			var beforeDisplayCalled = false;
			dcontainer.on("delite-before-show", function () {
				beforeDisplayCalled = true;
			});
			// by node
			return dcontainer.show("view1-event").then(function () {
				assert(beforeDisplayCalled, "before show event must be dispatched");
				document.removeEventListener("delite-display-load", handler);
			});
		},
		// test with a controller
		custom: function () {
			this.tiemout = 2500;
			var handler;

			function initView(view, id) {
				view.style.visibility = "hidden";
				view.style.display = "none";
				view.setAttribute("id", id);
			}

			document.addEventListener("delite-display-load", handler = function (event) {
				event.preventDefault();
				var view = document.createElement("div");
				initView(view, event.dest);
				event.loadDeferred.resolve({
					child: view
				});
			});
			register("test-custom-display-container", [HTMLElement, Widget, DisplayContainer]);
			var dcontainer = register.createElement("test-custom-display-container");
			dcontainer.setAttribute("id", "dcontainer");
			container.appendChild(dcontainer);
			dcontainer.startup();
			function testView(view) {
				assert.strictEqual(view.style.visibility, "visible", "visibility");
				assert.strictEqual(view.style.display, "", "display");
				assert.strictEqual(view.parentNode, dcontainer, "parentNode");
			}

			// by node
			return dcontainer.show("view1").then(function () {
				testView(document.getElementById("view1"));
			}).then(function () {
				return dcontainer.show("view2");
			}).then(function () {
				testView(document.getElementById("view2"));
				document.removeEventListener("delite-display-load", handler);
			});
		},
		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

const eventTypes = require('./resources/trackables.json').eventTypes;
const rewardTypes = require('./resources/trackables.json').rewardTypes;

function trackablesFromParameters (paramString) {
  const items = paramString.split(' ');

  const trackables = {
    events: [],
    items: [],
  }

  if (items[0].toLowerCase() === 'all') {
    trackables.events = trackables.events.concat(eventTypes);
    trackables.items = trackables.items.concat(rewardTypes);
  } else {
    items = items.map(item => item.trim());
    items.forEach((item) => {
      if (item.toLowerCase() === 'items') {
        trackables.items = trackables.items.concat(rewardTypes);
      } else if (item.toLowerCase() === 'events') {
        trackables.events = trackables.events.concat(eventTypes);
      } else if (item.toLowerCase === 'fissures') {
        trackables.events = trackables.events.concat([ 'fissures.t1', 'fissures.t2', 'fissures.t3', 'fissures.t4' ]);
      } else if (item.toLowerCase === 'syndicates') {
        trackables.events = trackables.events.concat([ 'syndicate.arbiters', 'syndicate.suda', 'syndicate.loka', 'syndicate.perrin', 'syndicate.veil', 'syndicate.meridian' ]);
      } else if (item.toLowerCase === 'conclave') {
        trackables.events = trackables.events.concat([ 'conclave.weeklies', 'conclave.dailies' ]);
      } else if (item.toLowerCase === 'deals') {
        trackables.events = trackables.events.concat([ "deals.featured", "deals.popular"  ]);
      } else if (rewardTypes.includes(item.trim()) && saveTrack) {
        trackables.items.push(item.trim());
      } else if (eventTypes.includes(item.trim()) && saveTrack) {
        trackables.events.push(item.trim());
      }
    });
  }
  return trackables;
}

function getTrackInstructionEmbed(message, prefix, call) {
  const embed = {
    type: 'rich',
    color: 0x0000ff,
    fields: [
      {
        name: `${prefix}${call} <event(s)/item(s) to ${call === 'untrack' ? 'un' : ''}track>`,
        value: 'Track events/items to be alerted in this channel.',
        inline: true,
      },
      {
        name: 'Possible values:',
        value: '_ _',
        inline: false,
      },
      {
        name: '**Events:**',
        value: `${eventTypes.concat(['all', 'events', 'fissures', 'syndicates', 'conclave']).join('\n')}`,
        inline: true,
      },
      {
        name: '**Rewards:**',
        value: `${rewardTypes.join('\n')}\nall\nitems`,
        inline: true,
      },
    ],
  };

  switch (call) {
    case 'track':
      embed.fields[0].value = 'Track events/items to be alerted in this channel.'
      break;
    case 'untrack':
      embed.fields[0].value = 'Untrack events/items to be alerted in this channel.'
      break;
    case 'set ping':
      embed.fields[0].value = 'Set the text added before an event/item notification.'
      embed.fields.push({
        name: '**Ping:**',
        value: 'Whatever string you want to be added before a notification for this item or event. If you leave this blank, the ping for this item/event will be cleared',
        inline: true,
      });
      break;
  }
  return embed;
}

module.exports = { trackablesFromParameters, getTrackInstructionEmbed };
<commit_msg>fix for assignment to a constant<commit_after>'use strict';

const eventTypes = require('./resources/trackables.json').eventTypes;
const rewardTypes = require('./resources/trackables.json').rewardTypes;

function trackablesFromParameters (paramString) {
  let items = paramString.split(' ');

  const trackables = {
    events: [],
    items: [],
  }

  if (items[0].toLowerCase() === 'all') {
    trackables.events = trackables.events.concat(eventTypes);
    trackables.items = trackables.items.concat(rewardTypes);
  } else {
    items = items.map(item => item.trim());
    items.forEach((item) => {
      if (item.toLowerCase() === 'items') {
        trackables.items = trackables.items.concat(rewardTypes);
      } else if (item.toLowerCase() === 'events') {
        trackables.events = trackables.events.concat(eventTypes);
      } else if (item.toLowerCase === 'fissures') {
        trackables.events = trackables.events.concat([ 'fissures.t1', 'fissures.t2', 'fissures.t3', 'fissures.t4' ]);
      } else if (item.toLowerCase === 'syndicates') {
        trackables.events = trackables.events.concat([ 'syndicate.arbiters', 'syndicate.suda', 'syndicate.loka', 'syndicate.perrin', 'syndicate.veil', 'syndicate.meridian' ]);
      } else if (item.toLowerCase === 'conclave') {
        trackables.events = trackables.events.concat([ 'conclave.weeklies', 'conclave.dailies' ]);
      } else if (item.toLowerCase === 'deals') {
        trackables.events = trackables.events.concat([ "deals.featured", "deals.popular"  ]);
      } else if (rewardTypes.includes(item.trim()) && saveTrack) {
        trackables.items.push(item.trim());
      } else if (eventTypes.includes(item.trim()) && saveTrack) {
        trackables.events.push(item.trim());
      }
    });
  }
  return trackables;
}

function getTrackInstructionEmbed(message, prefix, call) {
  const embed = {
    type: 'rich',
    color: 0x0000ff,
    fields: [
      {
        name: `${prefix}${call} <event(s)/item(s) to ${call === 'untrack' ? 'un' : ''}track>`,
        value: 'Track events/items to be alerted in this channel.',
        inline: true,
      },
      {
        name: 'Possible values:',
        value: '_ _',
        inline: false,
      },
      {
        name: '**Events:**',
        value: `${eventTypes.concat(['all', 'events', 'fissures', 'syndicates', 'conclave']).join('\n')}`,
        inline: true,
      },
      {
        name: '**Rewards:**',
        value: `${rewardTypes.join('\n')}\nall\nitems`,
        inline: true,
      },
    ],
  };

  switch (call) {
    case 'track':
      embed.fields[0].value = 'Track events/items to be alerted in this channel.'
      break;
    case 'untrack':
      embed.fields[0].value = 'Untrack events/items to be alerted in this channel.'
      break;
    case 'set ping':
      embed.fields[0].value = 'Set the text added before an event/item notification.'
      embed.fields.push({
        name: '**Ping:**',
        value: 'Whatever string you want to be added before a notification for this item or event. If you leave this blank, the ping for this item/event will be cleared',
        inline: true,
      });
      break;
  }
  return embed;
}

module.exports = { trackablesFromParameters, getTrackInstructionEmbed };
<|endoftext|>


<commit_before>/**
 * Copyright: (c) 2016 Max Klein
 * License: MIT
 */

var Editor = (function (window, document) {
	"use strict";

	function Editor(app) {
		this.log = new Logger("Editor");

		this.app = app;

		this.renderer = new Renderer(app);

		this.log.debug("Constructed");
	}

	return Editor;
})(window, document);
<commit_msg>Click+drag to move, scroll to zoom<commit_after>/**
 * Copyright: (c) 2016 Max Klein
 * License: MIT
 */

var Editor = (function (window, document) {
	"use strict";

	function Editor(app) {
		this.log = new Logger("Editor");

		this.app = app;

		this.renderer = new Renderer(app);

		this.registerListeners();

		this.log.debug("Constructed");
	}

	Editor.prototype.registerListeners = function () {
		var renderer = this.renderer;

		var $canvas = renderer.$svg;

		var moving = false;
		var startMouseX, startMouseY;
		var startX, startY;

		$canvas.addEventListener("mousedown", function (evt) {
			evt.preventDefault();
			evt.stopPropagation();

			moving = true;
			startMouseX = evt.clientX;
			startMouseY = evt.clientY;
			startX = renderer.viewport.x;
			startY = renderer.viewport.y;

			$canvas.style.cursor = "move";
		});

		var zoomInAmount = 1.1,
			zoomOutAmount = 1 / zoomInAmount;
		$canvas.addEventListener("wheel", function (evt) {
			if(evt.deltaY != 0) {
				var zoomAmount = evt.deltaY < 0 ? zoomInAmount : zoomOutAmount;
				renderer.viewport.zoom(zoomAmount, evt.clientX, evt.clientY);
			}
		});

		window.addEventListener("mousemove", function (evt) {
			evt.preventDefault();
			evt.stopPropagation();

			if(moving) {
				renderer.viewport.setPosition(startX + (evt.clientX - startMouseX), startY + (evt.clientY - startMouseY));
			}
		});

		window.addEventListener("mouseup", function (evt) {
			evt.preventDefault();
			evt.stopPropagation();

			moving = false;

			$canvas.style.removeProperty("cursor");
		});
	};

	return Editor;
})(window, document);
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const chalk = require('chalk');

const Faker = require('../Libs/Faker');
const Mocha = require('mocha');
const Log = require('../Libs/Log');

class Worker {
    constructor(scenario) {
        this.scenario = scenario;
        this.mocha = new Mocha();
        this.mocha.addFile(scenario.entrypoint);
        this.mocha.reporter('json');
        this.mocha.timeout(0);
        this.data = scenario.data;
        this.setGlobals();
    }
    setup(done) {
        done();
    }
    circularJsonParser(o) {
        var cache = [];
        var output = '';

        output = JSON.stringify(o, function(key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return;
                }
                cache.push(value);
            }
            return value;
        });

        cache = null;
        return output;
    }
    run(done) {
        let output = '';

        process.stdout.write = (str) => {
            output += str;
        };

        let runner = this.mocha.run((failures) => {
            done(output);
        });

        runner.on('test', (test) => {
            process.send({ mochaUpdate: { type: 'start', output: this.circularJsonParser(test) } });
        });
        runner.on('test end', (test) => {
            process.send({ mochaUpdate: { type: 'end', output: this.circularJsonParser(test) } });
        });
        runner.on('pass', (test) => {
            process.send({ mochaUpdate: { type: 'pass', output: this.circularJsonParser(test) } });
        });
        runner.on('fail', (test) => {
            process.send({ mochaUpdate: { type: 'fail', output: this.circularJsonParser(test) } });
        });
    }
    teardown(done) {
        done();
    }
    setGlobals() {
        global.Faker = new Faker;

        global.Save = (path, data) => {
            _.set(this.data, path, data);

            process.send({
                save: {
                    path: path,
                    data: data
                }
            });
        };

        global.Get = (path) => _.get(this.data, path);

        global.Runs = (path) => {
            var theSnippet = require(process.cwd() + '/' + path);

            if (typeof theSnippet == 'function') {
                theSnippet();
            }

            return theSnippet;
        };

        global.Log = (message) => {
            process.send({ log: `\b${chalk.magenta('[log]')} ${message}` });
        }

        if (this.scenario.globals) {
            try {
                _.each(require(this.scenario.globals), (globalsModule, moduleName) => {
                    global[moduleName] = globalsModule;
                    process.send({ log: `Adding module ${moduleName} to global` });
                });
            } catch (err) {

            }
        }
    }
}

module.exports = Worker;
<commit_msg>send repl messages to parent process<commit_after>'use strict';

const _ = require('lodash');
const chalk = require('chalk');

const Faker = require('../Libs/Faker');
const Mocha = require('mocha');
const Log = require('../Libs/Log');

class Worker {
    constructor(scenario) {
        this.scenario = scenario;
        this.mocha = new Mocha();
        this.mocha.addFile(scenario.entrypoint);
        this.mocha.reporter('json');
        this.mocha.timeout(0);
        this.data = scenario.data;
        this.setGlobals();
    }
    setup(done) {
        done();
    }
    circularJsonParser(o) {
        var cache = [];
        var output = '';

        output = JSON.stringify(o, function(key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return;
                }
                cache.push(value);
            }
            return value;
        });

        cache = null;
        return output;
    }
    run(done) {
        let output = '';

        process.stdout.write = (str) => {
            output += str;
            process.send({ repl: str });
        };

        let runner = this.mocha.run((failures) => {
            done(output);
        });

        runner.on('test', (test) => {
            process.send({ mochaUpdate: { type: 'start', output: this.circularJsonParser(test) } });
        });
        runner.on('test end', (test) => {
            process.send({ mochaUpdate: { type: 'end', output: this.circularJsonParser(test) } });
        });
        runner.on('pass', (test) => {
            process.send({ mochaUpdate: { type: 'pass', output: this.circularJsonParser(test) } });
        });
        runner.on('fail', (test) => {
            process.send({ mochaUpdate: { type: 'fail', output: this.circularJsonParser(test) } });
        });
    }
    teardown(done) {
        done();
    }
    setGlobals() {
        global.Faker = new Faker;

        global.Save = (path, data) => {
            _.set(this.data, path, data);

            process.send({
                save: {
                    path: path,
                    data: data
                }
            });
        };

        global.Get = (path) => _.get(this.data, path);

        global.Runs = (path) => {
            var theSnippet = require(process.cwd() + '/' + path);

            if (typeof theSnippet == 'function') {
                theSnippet();
            }

            return theSnippet;
        };

        global.Log = (message) => {
            process.send({ log: `\b${chalk.magenta('[log]')} ${message}` });
        }

        if (this.scenario.globals) {
            try {
                _.each(require(this.scenario.globals), (globalsModule, moduleName) => {
                    global[moduleName] = globalsModule;
                    process.send({ log: `Adding module ${moduleName} to global` });
                });
            } catch (err) {

            }
        }
    }
}

module.exports = Worker;
<|endoftext|>


<commit_before>/* global Cesium  */
'use strict';

export var config = {
  versionString: 'v0.6.2Beta',
  resetViewTarget: {
    default: {
      destination: Cesium.Cartesian3.fromDegrees(-120.84, 39.44, 460000),
      orientation : {
        heading : 6.28,
        pitch : -0.85,
        roll : 6.28
      }
    },
    lookDownDestinaton: Cesium.Cartesian3.fromDegrees(-120.84, 43.82, 600000)
  },
  spinnerOpts : {
    color: '#939393',
    opacity: 0.1,
    shadow: true
  },
  imageryProviders: [
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            maximumLevel: 19,
            credit: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
          }
        ),
      name: 'World Imagery'
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            maximumLevel: 19,
            credit: '©OpenStreetMap'
          }
        ),
      name: 'OpenStreetMap'
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://services.arcgisonline.com/arcgis/rest/services/USA_Topo_Maps/MapServer/tile/{z}/{y}/{x}',
            maximumLevel: 15,
            credit: 'Esri, DeLorme, FAO, USGS, NOAA, EPA | © 2013 National Geographic Society, i-cubed'
          }
        ),
      name: 'USA Topo Maps'
    }
  ],
  overlayImageryProviders: [
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/oldgrowth/{z}/{x}/{y}.png',
            maximumLevel: 12,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5685,41.9595,-120.8112,45.9053)
          }
        ),
      name: 'Old Growth Forests on BLM Lands',
      alpha: 0.9,
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/clearcuts/{z}/{x}/{y}.png',
            maximumLevel: 12,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5026,41.9513,-116.7792,46.0275)
          }
        ),
      name: 'Clearcuts on Federal Lands',
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/wilderness/{z}/{x}/{y}.png',
            maximumLevel: 13,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5383,41.8818,-116.4359,46.0237)
          }
        ),
      name: 'Wilderness Areas',
      alpha: 0.9,
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/pwilderness/{z}/{x}/{y}.png',
            maximumLevel: 13,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5383,41.8818,-116.4359,46.0237)
          }
        ),
      name: 'Potential Forest Wilderness Areas',
      alpha: 0.9,
      legendSpan: ''
    }
  ],
  dataPaths: {
    stateBoundary: 'data/oregon/oregonl.json',
  },
  stateBoundaryOpts: {
    strokeWidth: 2000,
    strokeColor: '#1A1A1A',
    strokeOpacity: 0.7
  }
}
<commit_msg>Adjust state boundary color<commit_after>/* global Cesium  */
'use strict';

export var config = {
  versionString: 'v0.6.2Beta',
  resetViewTarget: {
    default: {
      destination: Cesium.Cartesian3.fromDegrees(-120.84, 39.44, 460000),
      orientation : {
        heading : 6.28,
        pitch : -0.85,
        roll : 6.28
      }
    },
    lookDownDestinaton: Cesium.Cartesian3.fromDegrees(-120.84, 43.82, 600000)
  },
  spinnerOpts : {
    color: '#939393',
    opacity: 0.1,
    shadow: true
  },
  imageryProviders: [
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            maximumLevel: 19,
            credit: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
          }
        ),
      name: 'World Imagery'
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            maximumLevel: 19,
            credit: '©OpenStreetMap'
          }
        ),
      name: 'OpenStreetMap'
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'https://services.arcgisonline.com/arcgis/rest/services/USA_Topo_Maps/MapServer/tile/{z}/{y}/{x}',
            maximumLevel: 15,
            credit: 'Esri, DeLorme, FAO, USGS, NOAA, EPA | © 2013 National Geographic Society, i-cubed'
          }
        ),
      name: 'USA Topo Maps'
    }
  ],
  overlayImageryProviders: [
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/oldgrowth/{z}/{x}/{y}.png',
            maximumLevel: 12,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5685,41.9595,-120.8112,45.9053)
          }
        ),
      name: 'Old Growth Forests on BLM Lands',
      alpha: 0.9,
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/clearcuts/{z}/{x}/{y}.png',
            maximumLevel: 12,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5026,41.9513,-116.7792,46.0275)
          }
        ),
      name: 'Clearcuts on Federal Lands',
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/wilderness/{z}/{x}/{y}.png',
            maximumLevel: 13,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5383,41.8818,-116.4359,46.0237)
          }
        ),
      name: 'Wilderness Areas',
      alpha: 0.9,
      legendSpan: ''
    },
    {
      provider:
        new Cesium.UrlTemplateImageryProvider(
          {
            url: 'data/tiles/pwilderness/{z}/{x}/{y}.png',
            maximumLevel: 13,
            rectangle : Cesium.Rectangle.fromDegrees(-124.5383,41.8818,-116.4359,46.0237)
          }
        ),
      name: 'Potential Forest Wilderness Areas',
      alpha: 0.9,
      legendSpan: ''
    }
  ],
  dataPaths: {
    stateBoundary: 'data/oregon/oregonl.json',
  },
  stateBoundaryOpts: {
    strokeWidth: 2000,
    strokeColor: '#474747',
    strokeOpacity: 0.7
  }
}
<|endoftext|>


<commit_before>/*global define,encodeURIComponent*/
/*jslint white:true,browser:true*/
/* based on https://developer.mozilla.org/en-US/docs/Web/API/document.cookie?redirectlocale=en-US&redirectslug=DOM%2Fdocument.cookie */
define([], function () {
    'use strict';
    var Cookie = Object.create({}, {
        init: {
            value: function () {
                this.cookies = [];
                this.importCookies();
                return this;
            }
        },
        importCookies: {
            value: function () {
                this.cookies = this.readCookies();
            }
        },
        readCookies: {
            value: function () {
                var cookieString = document.cookie;
                if (cookieString) {
                    return cookieString.split(';')
                        .map(function (cookie) {
                            var pieces = cookie.split('='),
                                name = pieces[0].trim(' '),
                                value = pieces[1].trim(' ');
                            return {
                                name: name,
                                value: decodeURIComponent(value)
                            };
                        });
                }
                return [];
            }
        },
        findCookie: {
            value: function (key) {
                return this.cookies.filter(function (cookie) {
                    if (cookie.name === key) {
                        return true;
                    }
                });
            }
        },
        getItem: {
            value: function (key) {
                if (!key) {
                    return null;
                }
                this.importCookies();
                var cookie = this.findCookie(key), value;
                if (cookie.length > 1) {
                    throw new Error('Too many cookies returned, expected 1');
                }
                if (cookie.length === 0) {
                    return;
                }
                return cookie[0].value;
            }
        },
        getItems: {
            value: function (key) {
                if (!key) {
                    return null;
                }
                this.importCookies();
                return this.findCookie(key).map(function (cookie) {
                    return cookie.value;
                });
            }
        },
        setItem: {
            value: function (sKey, sValue, vEnd, sPath, sDomain, bSecure, bNoEncode) {
                if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
                    return false;
                }
                var sExpires, maxAge;
                if (vEnd) {
                    switch (vEnd.constructor) {
                        case Number:
                            if (vEnd === Infinity) {
                                sExpires = 'Fri, 31 Dec 9999 23:59:59 GMT';
                            } else {
                                maxAge = vEnd;
                            }
                            break;
                        case String:
                            sExpires = vEnd;
                            break;
                        case Date:
                            sExpires = vEnd.toUTCString();
                            break;
                    }
                }
                var newCookie = {
                    name: sKey,
                    value: sValue,
                    expires: sExpires,
                    'max-age': maxAge,
                    domain: sDomain,
                    path: sPath,
                    secure: bSecure,
                    noEncode: bNoEncode
                };
                this.cookies.push(newCookie);
                this.setCookie(newCookie);
                return true;
            }
        },
        setCookie: {
            value: function (cookie) {
                var cookieProps, propString,
                    cookieString;
                cookieProps = ['domain', 'path', 'secure', 'expires', 'max-age']
                    .map(function (key) {
                        if (cookie[key]) {
                            return {
                                key: key,
                                value: cookie[key]
                            };
                        }
                    })
                    .filter(function (prop) {
                        if (prop) {
                            return true;
                        }
                    });

                if (cookie.noEncode) {
                    // For compatability with services which do not decode cookies yet create cookies
                    // save for not encoding. Aka - Globus.
                    propString = cookieProps.map(function (prop) {
                        return [prop.key, prop.value].join('=');
                    }).join(';');
                    cookieString = [cookie.key, [cookie.value, propString].join(';')].join('=');
                } else {
                    propString = cookieProps.map(function (prop) {
                        return [prop.key, prop.value].join('=');
                    }).join(';');
                    cookieString = [encodeURIComponent(cookie.name), [encodeURIComponent(cookie.value), propString].join(';')].join('=');
                }
                document.cookie = cookieString;
                this.importCookies();
            }
        },
        removeItem: {
            value: function (sKey, sPath, sDomain) {
                this.setCookie({
                    name: sKey,
                    value: '*',
                    domain: sDomain,
                    path: sPath,
                    expires: '01 Jan 1970 00:00:00 GMT'
                });
                this.importCookies();
            }
        },
        hasItem: {
            value: function (key) {
                if (this.cookies[key]) {
                    return true;
                }
                return false;
            }
        },
        keys: {
            value: function () {
                return Object.keys(this.cookies);
            }
        }
    });
    return Cookie.init();
});<commit_msg>improve cookie to be stateless, state is in the browser after all.<commit_after>/*global define,encodeURIComponent*/
/*jslint white:true,browser:true*/
/* based on https://developer.mozilla.org/en-US/docs/Web/API/document.cookie?redirectlocale=en-US&redirectslug=DOM%2Fdocument.cookie */
define([], function () {
    'use strict';
    var Cookie = Object.create({}, {
        init: {
            value: function (options) {
                this.doc = options.doc || document;
                return this;
            }
        },
        importCookies: {
            value: function () {
                var cookieString = this.doc.cookie;
                if (cookieString) {
                    return cookieString.split(';')
                        .map(function (cookie) {
                            var pieces = cookie.split('='),
                                name = pieces[0].trim(' '),
                                value = pieces[1].trim(' ');
                            return {
                                name: name,
                                value: decodeURIComponent(value)
                            };
                        });
                }
                return [];
            }
        },
        getCookies: {
            value: function () {
                return this.importCookies();
            }
        },
        findCookie: {
            value: function (key) {
                var cookies = this.importCookies();
                return cookies.filter(function (cookie) {
                    if (cookie.name === key) {
                        return true;
                    }
                });
            }
        },
        getItem: {
            value: function (key) {
                if (!key) {
                    return null;
                }
                var cookie = this.findCookie(key), value;
                if (cookie.length > 1) {
                    throw new Error('Too many cookies returned, expected 1');
                }
                if (cookie.length === 0) {
                    return;
                }
                return cookie[0].value;
            }
        },
        getItems: {
            value: function (key) {
                if (!key) {
                    return null;
                }
                return this.findCookie(key).map(function (cookie) {
                    return cookie.value;
                });
            }
        },
        setItem: {
            value: function (sKey, sValue, vEnd, sPath, sDomain, bSecure, bNoEncode) {
                if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
                    return false;
                }
                var sExpires, maxAge;
                if (vEnd) {
                    switch (vEnd.constructor) {
                        case Number:
                            if (vEnd === Infinity) {
                                sExpires = 'Fri, 31 Dec 9999 23:59:59 GMT';
                            } else {
                                maxAge = vEnd;
                            }
                            break;
                        case String:
                            sExpires = vEnd;
                            break;
                        case Date:
                            sExpires = vEnd.toUTCString();
                            break;
                    }
                }
                var newCookie = {
                    name: sKey,
                    value: sValue,
                    expires: sExpires,
                    'max-age': maxAge,
                    domain: sDomain,
                    path: sPath,
                    secure: bSecure,
                    noEncode: bNoEncode
                };
                this.setCookie(newCookie);
                return true;
            }
        },
        setCookie: {
            value: function (cookie) {
                var cookieProps, propString,
                    cookieString;
                cookieProps = ['domain', 'path', 'secure', 'expires', 'max-age']
                    .map(function (key) {
                        if (cookie[key]) {
                            return {
                                key: key,
                                value: cookie[key]
                            };
                        }
                    })
                    .filter(function (prop) {
                        if (prop) {
                            return true;
                        }
                    });

                if (cookie.noEncode) {
                    // For compatability with services which do not decode cookies yet create cookies
                    // save for not encoding. Aka - Globus.
                    propString = cookieProps.map(function (prop) {
                        return [prop.key, prop.value].join('=');
                    }).join(';');
                    cookieString = [cookie.key, [cookie.value, propString].join(';')].join('=');
                } else {
                    propString = cookieProps.map(function (prop) {
                        return [prop.key, prop.value].join('=');
                    }).join(';');
                    cookieString = [encodeURIComponent(cookie.name), [encodeURIComponent(cookie.value), propString].join(';')].join('=');
                }
                this.doc.cookie = cookieString;
            }
        },
        removeItem: {
            value: function (sKey, sPath, sDomain) {
                this.setCookie({
                    name: sKey,
                    value: '*',
                    domain: sDomain,
                    path: sPath,
                    expires: '01 Jan 1970 00:00:00 GMT'
                });
            }
        },
        hasItem: {
            value: function (key) {
                var cookies = this.importCookies();
                if (cookies[key]) {
                    return true;
                }
                return false;
            }
        },
        keys: {
            value: function () {
                var cookies = this.importCookies();
                return Object.keys(cookies);
            }
        }
    });
    return Cookie;
});<|endoftext|>


<commit_before>/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0],
    $BODY = $('body'),
    $MENU_TOGGLE = $('#menu_toggle'),
    $SIDEBAR_MENU = $('#sidebar-menu'),
    $SIDEBAR_FOOTER = $('.sidebar-footer'),
    $LEFT_COL = $('.left_col'),
    $RIGHT_COL = $('.right_col'),
    $NAV_MENU = $('.nav_menu'),
    $FOOTER = $('footer');

// Sidebar
$(document).ready(function() {
    // TODO: This is some kind of easy fix, maybe we can improve this
    var setContentHeight = function () {
        // reset height
        $RIGHT_COL.css('min-height', $(window).height());

        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

        // normalize content
        contentHeight -= $NAV_MENU.height() + footerHeight;

        $RIGHT_COL.css('min-height', contentHeight);
    };

    $SIDEBAR_MENU.find('a').on('click', function(ev) {
        var $li = $(this).parent();

        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $('ul:first', $li).slideUp(function() {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $SIDEBAR_MENU.find('li ul').slideUp();
            }

            $li.addClass('active');

            $('ul:first', $li).slideDown(function() {
                setContentHeight();
            });
        }
    });

    // toggle small or large menu
    $MENU_TOGGLE.on('click', function() {
        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();
    });

    // check active menu
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function() {
        setContentHeight();
    }).parent().addClass('active');

    // recompute content when resizing
    $(window).smartresize(function(){
        setContentHeight();
    });

    setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel:{ preventDefault: true }
        });
    }
});
// /Sidebar

// Panel toolbox
$(document).ready(function() {
    $('.collapse-link').on('click', function() {
        var $BOX_PANEL = $(this).closest('.x_panel'),
            $ICON = $(this).find('i'),
            $BOX_CONTENT = $BOX_PANEL.find('.x_content');

        // fix for some div with hardcoded fix class
        if ($BOX_PANEL.attr('style')) {
            $BOX_CONTENT.slideToggle(200, function(){
                $BOX_PANEL.removeAttr('style');
            });
        } else {
            $BOX_CONTENT.slideToggle(200);
            $BOX_PANEL.css('height', 'auto');
        }

        $ICON.toggleClass('fa-chevron-up fa-chevron-down');
    });

    $('.close-link').click(function () {
        var $BOX_PANEL = $(this).closest('.x_panel');

        $BOX_PANEL.remove();
    });
});
// /Panel toolbox

// Tooltip
$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });
});
// /Tooltip

// Progressbar
if ($(".progress .progress-bar")[0]) {
    $('.progress .progress-bar').progressbar();
}
// /Progressbar

// Switchery
$(document).ready(function() {
    if ($(".js-switch")[0]) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, {
                color: '#26B99A'
            });
        });
    }
});
// /Switchery

// iCheck
$(document).ready(function() {
    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
        });
    }
});
// /iCheck

// Table
$('table input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('table input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});

var checkState = '';

$('.bulk_action input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('.bulk_action input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});
$('.bulk_action input#check-all').on('ifChecked', function () {
    checkState = 'all';
    countChecked();
});
$('.bulk_action input#check-all').on('ifUnchecked', function () {
    checkState = 'none';
    countChecked();
});

function countChecked() {
    if (checkState === 'all') {
        $(".bulk_action input[name='table_records']").iCheck('check');
    }
    if (checkState === 'none') {
        $(".bulk_action input[name='table_records']").iCheck('uncheck');
    }

    var checkCount = $(".bulk_action input[name='table_records']:checked").length;

    if (checkCount) {
        $('.column-title').hide();
        $('.bulk-actions').show();
        $('.action-cnt').html(checkCount + ' Records Selected');
    } else {
        $('.column-title').show();
        $('.bulk-actions').hide();
    }
}

// Accordion
$(document).ready(function() {
    $(".expand").on("click", function () {
        $(this).next().slideToggle(200);
        $expand = $(this).find(">:first-child");

        if ($expand.text() == "+") {
            $expand.text("-");
        } else {
            $expand.text("+");
        }
    });
});

// NProgress
if (typeof NProgress != 'undefined') {
    $(document).ready(function () {
        NProgress.start();
    });

    $(window).load(function () {
        NProgress.done();
    });
}
<commit_msg>Update custom.js<commit_after>/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0],
    $BODY = $('body'),
    $MENU_TOGGLE = $('#menu_toggle'),
    $SIDEBAR_MENU = $('#sidebar-menu'),
    $SIDEBAR_FOOTER = $('.sidebar-footer'),
    $LEFT_COL = $('.left_col'),
    $RIGHT_COL = $('.right_col'),
    $NAV_MENU = $('.nav_menu'),
    $FOOTER = $('footer');

// Sidebar
$(document).ready(function() {
    // TODO: This is some kind of easy fix, maybe we can improve this
    var setContentHeight = function () {
        // reset height
        $RIGHT_COL.css('min-height', $(window).height());

        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

        // normalize content
        contentHeight -= $NAV_MENU.height() + footerHeight;

        $RIGHT_COL.css('min-height', contentHeight);
    };

    $SIDEBAR_MENU.find('a').on('click', function(ev) {
        var $li = $(this).parent();

        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $('ul:first', $li).slideUp(function() {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $SIDEBAR_MENU.find('li ul').slideUp();
            }

            $li.addClass('active');

            $('ul:first', $li).slideDown(function() {
                setContentHeight();
            });
        }
    });

    // toggle small or large menu
    $MENU_TOGGLE.on('click', function() {
        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();

        $('.dataTable').each ( function () { $(this).dataTable().fnDraw(); });
    });

    // check active menu
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function() {
        setContentHeight();
    }).parent().addClass('active');

    // recompute content when resizing
    $(window).smartresize(function(){
        setContentHeight();
    });

    setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel:{ preventDefault: true }
        });
    }
});
// /Sidebar

// Panel toolbox
$(document).ready(function() {
    $('.collapse-link').on('click', function() {
        var $BOX_PANEL = $(this).closest('.x_panel'),
            $ICON = $(this).find('i'),
            $BOX_CONTENT = $BOX_PANEL.find('.x_content');

        // fix for some div with hardcoded fix class
        if ($BOX_PANEL.attr('style')) {
            $BOX_CONTENT.slideToggle(200, function(){
                $BOX_PANEL.removeAttr('style');
            });
        } else {
            $BOX_CONTENT.slideToggle(200);
            $BOX_PANEL.css('height', 'auto');
        }

        $ICON.toggleClass('fa-chevron-up fa-chevron-down');
    });

    $('.close-link').click(function () {
        var $BOX_PANEL = $(this).closest('.x_panel');

        $BOX_PANEL.remove();
    });
});
// /Panel toolbox

// Tooltip
$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });
});
// /Tooltip

// Progressbar
if ($(".progress .progress-bar")[0]) {
    $('.progress .progress-bar').progressbar();
}
// /Progressbar

// Switchery
$(document).ready(function() {
    if ($(".js-switch")[0]) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, {
                color: '#26B99A'
            });
        });
    }
});
// /Switchery

// iCheck
$(document).ready(function() {
    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
        });
    }
});
// /iCheck

// Table
$('table input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('table input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});

var checkState = '';

$('.bulk_action input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('.bulk_action input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});
$('.bulk_action input#check-all').on('ifChecked', function () {
    checkState = 'all';
    countChecked();
});
$('.bulk_action input#check-all').on('ifUnchecked', function () {
    checkState = 'none';
    countChecked();
});

function countChecked() {
    if (checkState === 'all') {
        $(".bulk_action input[name='table_records']").iCheck('check');
    }
    if (checkState === 'none') {
        $(".bulk_action input[name='table_records']").iCheck('uncheck');
    }

    var checkCount = $(".bulk_action input[name='table_records']:checked").length;

    if (checkCount) {
        $('.column-title').hide();
        $('.bulk-actions').show();
        $('.action-cnt').html(checkCount + ' Records Selected');
    } else {
        $('.column-title').show();
        $('.bulk-actions').hide();
    }
}

// Accordion
$(document).ready(function() {
    $(".expand").on("click", function () {
        $(this).next().slideToggle(200);
        $expand = $(this).find(">:first-child");

        if ($expand.text() == "+") {
            $expand.text("-");
        } else {
            $expand.text("+");
        }
    });
});

// NProgress
if (typeof NProgress != 'undefined') {
    $(document).ready(function () {
        NProgress.start();
    });

    $(window).load(function () {
        NProgress.done();
    });
}
<|endoftext|>


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

	var tpl = {
		detailTou : '<div data-uid="<%=detail.uid%>">'+
                        '
'+
                            '<img src="<%=detail.photo%>">'+
                        '
'+
                        '
<%=detail.count%>
'+
                        '
<%=detail.name%>
'+
                        '
'+
                            '<%=detail.company%>'+
                            '<%=detail.worker%>'+
                        '
'+
                        '
<%=detail.intro%>
'+
                    '
'+
                    '
'+
                        '<span class="tou-piao" data-status="<%=detail.is_vote%>">立即投票'+
                        '帮忙投票'+
                    '
'
        detailChuang : '<div data-uid="<%=detail.uid%>">'+
	                        '
'+
	                            '<img src="<%=detail.photo%>">'+
	                        '
'+
	                        '
<%=detail.count%>
'+
	                        '
<%=detail.name%>/第<%=detail.session_number%>届
'+
	                        '
'+
	                            '<%=detail.project%>'+
	                        '
'+
	                        '
<%=detail.intro%>
'+
	                    '
'+
	                    '
'+
	                        '立即投票'+
	                        '帮忙投票'+
	                    '
'
	};

	// 创业者事件
	var chuang = {
		init : function() {
			this.piaoStatus = true;

			var url = window.location.href;
			if(url.indexOf('tou') > 0) {
				this.getDetailTou();
			}else if(url.indexOf('chuang') > 0) {
				this.getDetailChuang();
			}
		},

		getDetailTou : function() {
			var _this = this;

			// var data = {

			// };

			// $.ajax({
		 //        url : '/home/banner',
		 //        type : 'get',
		 //        data : data,
		 //        dataType : 'json',
		 //        success : function(msg) {
		 //            if (msg.code != '0000') {
		 //                return;
		 //            }
		 //            var first = template.compile(tpl.firstPage),
   //              	html = render({data : msg.data[0]});

   //              	var other = template.compile(tpl.otherPage),
   //              	html = render({data : msg.data[0]});
		 //            $('.head-time').append(html);

		 //            _this.bind();
		 //        }
		 	//    });
			var data = {
			    "message": "",
			    "code": 200,
			    "data": {
			        "count": 0,
			        "is_vote": false,
			        "session_number": 1,
			        "uid": 2,
			        "photo": "http://7xpr29.com1.z0.glb.clouddn.com/liuchuanjun.jpg",
			        "project": "美菜",
			        "intro": "中国科学院空间物理学硕士，前窝窝团联合创始人，期望用互联网的方式来改变农业、农村和农民。",
			        "name": "刘传军"
			    }
			};
			var render = template.compile(tpl.detailChuang),
	            html = render({
	            	detail : data.data
	            });
	        $('.content').html(html);
	        // 投过之后就不再进行投票了
			if(this.$('.tou-piao').data('status') == true) {
				this.$('.tou-piao').css({
					'background' : '#ccc'
				}).html('已投票');
				this.piaoStatus = false;
			}
	        _this.bind();
		},

		getDetailChuang : function() {
			var _this = this;

			var data = {
			    "message": "",
			    "code": 200,
			    "data": {
			        "count": 0,
			        "uid": 2,
			        "photo": "http://7xpr29.com1.z0.glb.clouddn.com/chenxin.jpg",
			        "company": "红杉资本",
			        "worker": "投资经理",
			        "is_vote": false,
			        "intro": "关注交易平台、互联网房产及蓝领服务，负责杭州地区，投资项目包括房产销冠、觅食、窝客等。",
			        "name": "陈新"
			    }
			};
			var render = template.compile(tpl.detailTou),
	            html = render({
	            	detail : data.data
	            });
	        $('.content').html(html);
	        // 投过之后就不再进行投票了
			if(this.$('.tou-piao').data('status') == true) {
				this.$('.tou-piao').css({
					'background' : '#ccc'
				}).html('已投票');
				this.piaoStatus = false;
			}
	        _this.bind();
		},

		postTouVote : function(data) {
			var _this = this;

			var data = {
				vote : data
			};
			$.ajax({
		        url : '/home/banner',
		        type : 'post',
		        data : data,
		        dataType : 'json',
		        success : function(msg) {
		            window.reload();
		        }
		 	});
		},

		postChuangVote : function(data) {
			var _this = this;

			var data = {
				vote : data
			};
			$.ajax({
		        url : '/home/banner',
		        type : 'post',
		        data : data,
		        dataType : 'json',
		        success : function(msg) {
		            window.reload();
		        }
		 	});
		},

		bind : function() {
			var _this = this;

		    // 点击投票
		    _this.$('.tou-piao').on('click', function() {
		    	if(_this.piaoStatus == false) {
		    		return;
		    	}else{
		    		var count = Number(_this.$('.piao-count').text());
		    		var url = window.location.href;
			    	count++;
			    	_this.$('.piao-count').html(count);
			    	if(url.indexOf('tou') > 0) {
						_this.postTouVote(count);
					}else if(url.indexOf('chuang') > 0) {
						_this.postChuangVote(count);
					}
			    	$(this).css({
						'background' : '#ccc'
					}).html('已投票');
					_this.piaoStatus = false;
		    	}
		    });

		    // 帮忙拉票
		    _this.$('.bang-piao').on('click', function(event) {
		    	event.preventDefault();
		    	event.stopPropagation();
		    	_this.$('.share').show();
		    });

		    // 取消分享mask
		    $(document).on('click', function() {
		    	_this.$('.share').hide();
		    });

		    // 返回首页
		    _this.$('.back-home').on('click', function() {
		    	window.location.href="../../index.html";
		    });

		    // 查看其它人
		    _this.$('.other-person').on('click', function() {
		    	window.location.href="list.html";
		    });
		}
	}

	chuang.init();
});<commit_msg>false<commit_after>$(document).ready(function() {

	var tpl = {
		detailTou : '<div data-uid="<%=detail.uid%>">'+
                        '
'+
                            '<img src="<%=detail.photo%>">'+
                        '
'+
                        '
<%=detail.count%>
'+
                        '
<%=detail.name%>
'+
                        '
'+
                            '<%=detail.company%>'+
                            '<%=detail.worker%>'+
                        '
'+
                        '
<%=detail.intro%>
'+
                    '
'+
                    '
'+
                        '<span class="tou-piao" data-status="<%=detail.is_vote%>">立即投票'+
                        '帮忙投票'+
                    '
',
        detailChuang : '<div data-uid="<%=detail.uid%>">'+
	                        '
'+
	                            '<img src="<%=detail.photo%>">'+
	                        '
'+
	                        '
<%=detail.count%>
'+
	                        '
<%=detail.name%>/第<%=detail.session_number%>届
'+
	                        '
'+
	                            '<%=detail.project%>'+
	                        '
'+
	                        '
<%=detail.intro%>
'+
	                    '
'+
	                    '
'+
	                        '立即投票'+
	                        '帮忙投票'+
	                    '
'
	};

	// 创业者事件
	var chuang = {
		init : function() {
			this.piaoStatus = true;

			var url = window.location.href;
			if(url.indexOf('tou') > 0) {
				this.getDetailTou();
			}else if(url.indexOf('chuang') > 0) {
				this.getDetailChuang();
			}
		},

		getDetailTou : function() {
			var _this = this;

			// var data = {

			// };

			// $.ajax({
		 //        url : '/home/banner',
		 //        type : 'get',
		 //        data : data,
		 //        dataType : 'json',
		 //        success : function(msg) {
		 //            if (msg.code != '0000') {
		 //                return;
		 //            }
		 //            var first = template.compile(tpl.firstPage),
   //              	html = render({data : msg.data[0]});

   //              	var other = template.compile(tpl.otherPage),
   //              	html = render({data : msg.data[0]});
		 //            $('.head-time').append(html);

		 //            _this.bind();
		 //        }
		 	//    });
			var data = {
			    "message": "",
			    "code": 200,
			    "data": {
			        "count": 0,
			        "is_vote": false,
			        "session_number": 1,
			        "uid": 2,
			        "photo": "http://7xpr29.com1.z0.glb.clouddn.com/liuchuanjun.jpg",
			        "project": "美菜",
			        "intro": "中国科学院空间物理学硕士，前窝窝团联合创始人，期望用互联网的方式来改变农业、农村和农民。",
			        "name": "刘传军"
			    }
			};
			var render = template.compile(tpl.detailChuang),
	            html = render({
	            	detail : data.data
	            });
	        $('.content').html(html);
	        // 投过之后就不再进行投票了
			if(this.$('.tou-piao').data('status') == true) {
				this.$('.tou-piao').css({
					'background' : '#ccc'
				}).html('已投票');
				this.piaoStatus = false;
			}
	        _this.bind();
		},

		getDetailChuang : function() {
			var _this = this;

			var data = {
			    "message": "",
			    "code": 200,
			    "data": {
			        "count": 0,
			        "uid": 2,
			        "photo": "http://7xpr29.com1.z0.glb.clouddn.com/chenxin.jpg",
			        "company": "红杉资本",
			        "worker": "投资经理",
			        "is_vote": false,
			        "intro": "关注交易平台、互联网房产及蓝领服务，负责杭州地区，投资项目包括房产销冠、觅食、窝客等。",
			        "name": "陈新"
			    }
			};
			var render = template.compile(tpl.detailTou),
	            html = render({
	            	detail : data.data
	            });
	        $('.content').html(html);
	        // 投过之后就不再进行投票了
			if(this.$('.tou-piao').data('status') == true) {
				this.$('.tou-piao').css({
					'background' : '#ccc'
				}).html('已投票');
				this.piaoStatus = false;
			}
	        _this.bind();
		},

		postTouVote : function(data) {
			var _this = this;

			var data = {
				vote : data
			};
			$.ajax({
		        url : '/home/banner',
		        type : 'post',
		        data : data,
		        dataType : 'json',
		        success : function(msg) {
		            window.reload();
		        }
		 	});
		},

		postChuangVote : function(data) {
			var _this = this;

			var data = {
				vote : data
			};
			$.ajax({
		        url : '/home/banner',
		        type : 'post',
		        data : data,
		        dataType : 'json',
		        success : function(msg) {
		            window.reload();
		        }
		 	});
		},

		bind : function() {
			var _this = this;

		    // 点击投票
		    _this.$('.tou-piao').on('click', function() {
		    	if(_this.piaoStatus == false) {
		    		return;
		    	}else{
		    		var count = Number(_this.$('.piao-count').text());
		    		var url = window.location.href;
			    	count++;
			    	_this.$('.piao-count').html(count);
			    	if(url.indexOf('tou') > 0) {
						_this.postTouVote(count);
					}else if(url.indexOf('chuang') > 0) {
						_this.postChuangVote(count);
					}
			    	$(this).css({
						'background' : '#ccc'
					}).html('已投票');
					_this.piaoStatus = false;
		    	}
		    });

		    // 帮忙拉票
		    _this.$('.bang-piao').on('click', function(event) {
		    	event.preventDefault();
		    	event.stopPropagation();
		    	_this.$('.share').show();
		    });

		    // 取消分享mask
		    $(document).on('click', function() {
		    	_this.$('.share').hide();
		    });

		    // 返回首页
		    _this.$('.back-home').on('click', function() {
		    	window.location.href="../../index.html";
		    });

		    // 查看其它人
		    _this.$('.other-person').on('click', function() {
		    	window.location.href="list.html";
		    });
		}
	}

	chuang.init();
});<|endoftext|>