<commit_before>import Promise from 'bluebird'
import Immutable from 'immutable'
import _ from 'lodash'
import {v4 as uuid} from 'node-uuid'

import {version as currentVersionString} from '../../package.json'

import randomChar from 'sto-helpers/lib/randomChar'
import countCredits from 'sto-helpers/lib/countCredits'

import Schedule from '../models/schedule'
import Study from '../models/study'

let StudentRecord = Immutable.Record({
	id: uuid(),
	name: 'Student ' + randomChar(),
	active: false,
	version: currentVersionString,

	creditsNeeded: 35,

	matriculation: 1894,
	graduation: 1898,

	studies: Immutable.Map(),
	schedules: Immutable.Map(),
	overrides: Immutable.Map(),
	fabrications: Immutable.Map(),

	settings: Immutable.Map(),
})

class Student extends StudentRecord {
	constructor(encodedStudent={}) {
		// Don't pass the list params into the StudentRecord constructor; it creates them as JS objects,
		// instead of our custom Studies, Schedules, and such.
		let toRemove = Immutable.Set(['studies', 'schedules', 'overrides', 'fabrications'])
		let filtered = Immutable.fromJS(encodedStudent).filterNot((val, key) => toRemove.has(key))

		super(filtered)

		// Then add them manually.
		if (encodedStudent) {
			return this.withMutations((student) => {
				Immutable.Seq(encodedStudent.studies || [])
					.forEach(study => { student = student.addArea(study) })

				Immutable.Seq(encodedStudent.schedules || [])
					.forEach(schedule => { student = student.addSchedule(schedule) })

				Immutable.Seq(encodedStudent.overrides || [])
					.forEach(override => { student = student.addOverride(override) })

				Immutable.Seq(encodedStudent.fabrications || [])
					.forEach(fabrication => { student = student.addFabrication(fabrication) })

				return student
			})
		}
	}

	changeName(newName) {
		return this.set('name', newName)
	}

	changeActive(isActive) {
		return this.set('active', isActive)
	}

	changeCreditsNeeded(newCreditsNeeded) {
		return this.set('creditsNeeded', newCreditsNeeded)
	}

	changeMatriculation(newMatriculation) {
		return this.set('matriculation', newMatriculation)
	}

	changeGraduation(newGraduation) {
		return this.set('graduation', newGraduation)
	}

	changeSetting(key, value) {
		return this.setIn(['settings', key], value)
	}

	// schedule methods

	get schedulesByYear() {
		return this.schedules.groupBy(sched => sched.year)
	}

	get activeSchedules() {
		return this.schedules.filter(sched => sched.active).sortBy(sched => sched.semester)
	}

	addSchedule(newSchedule) {
		let sched = new Schedule(newSchedule)
		return this.setIn(['schedules', sched.id], sched)
	}

	destroySchedule(scheduleId) {
		console.log(`removing schedule ${scheduleId}`)

		let deadSched = this.getIn(['schedules', scheduleId])
		let scheduleIsNoMore = this.set('schedules', this.schedules.delete(scheduleId))

		if (deadSched && deadSched.active) {
			let otherSchedKey = this.schedules.findKey((sched) =>
				sched.year === deadSched.year && sched.semester === deadSched.semester)

			if (otherSchedKey) {
				return scheduleIsNoMore.setIn(['schedules', otherSchedKey, 'active'], true)
			}
		}
		return scheduleIsNoMore
	}

	destroyMultipleSchedules(ids) {
		return this.withMutations((student) => {
			console.groupCollapsed('destroyMultipleSchedules')
			Immutable.Seq(ids).forEach((id) => {
				console.log('destroyMultipleSchedules', id)
				student = student.destroySchedule(id)
			})
			console.groupEnd('destroyMultipleSchedules')
			return student
		})
	}

	// area-of-study methods

	get areasByType() {
		return this.studies.groupBy((study) => study.type)
	}

	addArea(areaOfStudy) {
		let study = new Study(areaOfStudy, this.graduation)
		return this.setIn(['studies', study.id], study)
	}

	removeArea(id) {
		return this.set('studies', this.studies.delete(id))
	}

	removeMultipleAreas(ids) {
		Seq(ids).forEach(this.removeArea, this)
	}

	// override methods

	addOverride(override) {
		return this.setIn(['overrides', override.id], override)
	}

	removeOverride(overrideId) {
		return this.set('overrides', this.overrides.delete(overrideId))
	}

	// fabrication methods

	addFabrication(fabrication) {
		return this.setIn(['fabrications', fabrication.id], fabrication)
	}

	removeFabrication(fabricationId) {
		return this.set('fabrications', this.fabrications.delete(fabricationId))
	}

	// getters

	get courses() {
		let allCourses = this.activeSchedules.map((schedule) => schedule.courses).toArray()
		let scheduleCoursePromises = Promise.all(allCourses)
		return scheduleCoursePromises.then((results) => _.flatten(results))
	}

	get creditCount() {
		return this.courses.then(countCredits)
	}

	// helpers

	data() {
		return Promise.props({
			courses: this.courses,
			fabrications: this.fabrications.toList().toJS(),
			overrides: this.overrides.toList().toJS(),
			studies: this.studies.toList().toJS(),
			creditsNeeded: this.creditsNeeded,
			graduation: this.graduation,
			matriculation: this.matriculation,
		})
	}

	encode() {
		return encodeURIComponent(this.toJSON())
	}

	toString() {
		return JSON.stringify(this.toJS())
	}

	toJSON() {
		return JSON.stringify(this.toJS())
	}

	save() {
		console.log(`saving student ${this.name} (${this.id})`)
		localStorage.setItem(this.id, this.toJSON())

		if (this.active)
			localStorage.setItem('activeStudentId', this.id)
	}
}

export default Student
<commit_msg>Use lodash instead of Immutable.Seq for iteration<commit_after>import Promise from 'bluebird'
import Immutable from 'immutable'
import _ from 'lodash'
import {v4 as uuid} from 'node-uuid'

import {version as currentVersionString} from '../../package.json'

import randomChar from 'sto-helpers/lib/randomChar'
import countCredits from 'sto-helpers/lib/countCredits'

import Schedule from '../models/schedule'
import Study from '../models/study'

let StudentRecord = Immutable.Record({
	id: uuid(),
	name: 'Student ' + randomChar(),
	active: false,
	version: currentVersionString,

	creditsNeeded: 35,

	matriculation: 1894,
	graduation: 1898,

	studies: Immutable.Map(),
	schedules: Immutable.Map(),
	overrides: Immutable.Map(),
	fabrications: Immutable.Map(),

	settings: Immutable.Map(),
})

class Student extends StudentRecord {
	constructor(encodedStudent={}) {
		// Don't pass the list params into the StudentRecord constructor; it creates them as JS objects,
		// instead of our custom Studies, Schedules, and such.
		let toRemove = Immutable.Set(['studies', 'schedules', 'overrides', 'fabrications'])
		let filtered = Immutable.fromJS(encodedStudent).filterNot((val, key) => toRemove.has(key))

		super(filtered)

		// Then add them manually.
		if (encodedStudent) {
			return this.withMutations((student) => {
				_(encodedStudent.studies || []).forEach(study => {
					student = student.addArea(study)
				})

				_(encodedStudent.schedules || []).forEach(schedule => {
					student = student.addSchedule(schedule)
				})

				_(encodedStudent.overrides || []).forEach(override => {
					student = student.addOverride(override)
				})

				_(encodedStudent.fabrications || []).forEach(fabrication => {
					student = student.addFabrication(fabrication)
				})

				return student
			})
		}
	}

	changeName(newName) {
		return this.set('name', newName)
	}

	changeActive(isActive) {
		return this.set('active', isActive)
	}

	changeCreditsNeeded(newCreditsNeeded) {
		return this.set('creditsNeeded', newCreditsNeeded)
	}

	changeMatriculation(newMatriculation) {
		return this.set('matriculation', newMatriculation)
	}

	changeGraduation(newGraduation) {
		return this.set('graduation', newGraduation)
	}

	changeSetting(key, value) {
		return this.setIn(['settings', key], value)
	}

	// schedule methods

	get schedulesByYear() {
		return this.schedules.groupBy(sched => sched.year)
	}

	get activeSchedules() {
		return this.schedules.filter(sched => sched.active).sortBy(sched => sched.semester)
	}

	addSchedule(newSchedule) {
		let sched = new Schedule(newSchedule)
		return this.setIn(['schedules', sched.id], sched)
	}

	destroySchedule(scheduleId) {
		console.log(`removing schedule ${scheduleId}`)

		let deadSched = this.getIn(['schedules', scheduleId])
		let scheduleIsNoMore = this.set('schedules', this.schedules.delete(scheduleId))

		if (deadSched && deadSched.active) {
			let otherSchedKey = this.schedules.findKey((sched) =>
				sched.year === deadSched.year && sched.semester === deadSched.semester)

			if (otherSchedKey) {
				return scheduleIsNoMore.setIn(['schedules', otherSchedKey, 'active'], true)
			}
		}
		return scheduleIsNoMore
	}

	destroyMultipleSchedules(ids) {
		return this.withMutations((student) => {
			console.groupCollapsed('destroyMultipleSchedules')
			Immutable.Seq(ids).forEach((id) => {
				console.log('destroyMultipleSchedules', id)
				student = student.destroySchedule(id)
			})
			console.groupEnd('destroyMultipleSchedules')
			return student
		})
	}

	// area-of-study methods

	get areasByType() {
		return this.studies.groupBy((study) => study.type)
	}

	addArea(areaOfStudy) {
		let study = new Study(areaOfStudy, this.graduation)
		return this.setIn(['studies', study.id], study)
	}

	removeArea(id) {
		return this.set('studies', this.studies.delete(id))
	}

	removeMultipleAreas(ids) {
		Seq(ids).forEach(this.removeArea, this)
	}

	// override methods

	addOverride(override) {
		return this.setIn(['overrides', override.id], override)
	}

	removeOverride(overrideId) {
		return this.set('overrides', this.overrides.delete(overrideId))
	}

	// fabrication methods

	addFabrication(fabrication) {
		return this.setIn(['fabrications', fabrication.id], fabrication)
	}

	removeFabrication(fabricationId) {
		return this.set('fabrications', this.fabrications.delete(fabricationId))
	}

	// getters

	get courses() {
		let allCourses = this.activeSchedules.map((schedule) => schedule.courses).toArray()
		let scheduleCoursePromises = Promise.all(allCourses)
		return scheduleCoursePromises.then((results) => _.flatten(results))
	}

	get creditCount() {
		return this.courses.then(countCredits)
	}

	// helpers

	data() {
		return Promise.props({
			courses: this.courses,
			fabrications: this.fabrications.toList().toJS(),
			overrides: this.overrides.toList().toJS(),
			studies: this.studies.toList().toJS(),
			creditsNeeded: this.creditsNeeded,
			graduation: this.graduation,
			matriculation: this.matriculation,
		})
	}

	encode() {
		return encodeURIComponent(this.toJSON())
	}

	toString() {
		return JSON.stringify(this.toJS())
	}

	toJSON() {
		return JSON.stringify(this.toJS())
	}

	save() {
		console.log(`saving student ${this.name} (${this.id})`)
		localStorage.setItem(this.id, this.toJSON())

		if (this.active)
			localStorage.setItem('activeStudentId', this.id)
	}
}

export default Student
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from 'ember-bootstrap/templates/components/bs-accordion/title';

/**
 Component for an accordion item title.

 See [Components.Accordion](Components.Accordion.html) for examples.

 @class AccordionTitle
 @namespace Components
 @extends Ember.Component
 @public
 */
export default Ember.Component.extend({
  layout,
  ariaRole: 'tab',
  classNameBindings: ['collapsed:collapsed:expanded'],

  /**
   * @property collapsed
   * @type boolean
   * @public
   */
  collapsed: null,

  /**
   * @event onClick
   * @public
   */
  onClick() {},

  click() {
    this.get('onClick')();
  }

});
<commit_msg>fix(AccordionItem): preventDefault click on title link. Thanks to @dajk<commit_after>import Ember from 'ember';
import layout from 'ember-bootstrap/templates/components/bs-accordion/title';

/**
 Component for an accordion item title.

 See [Components.Accordion](Components.Accordion.html) for examples.

 @class AccordionTitle
 @namespace Components
 @extends Ember.Component
 @public
 */
export default Ember.Component.extend({
  layout,
  ariaRole: 'tab',
  classNameBindings: ['collapsed:collapsed:expanded'],

  /**
   * @property collapsed
   * @type boolean
   * @public
   */
  collapsed: null,

  /**
   * @event onClick
   * @public
   */
  onClick() {},

  click(e) {
    e.preventDefault();
    this.get('onClick')();
  }

});
<|endoftext|>


<commit_before>'use strict';

 var React = require('react-native');
 var {
   StyleSheet,
   View,
 } = React;

 var Triangle = React.createClass({

   propTypes: {
     direction: React.PropTypes.oneOf(['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']),
     width: React.PropTypes.number,
     height: React.PropTypes.number,
     color: React.PropTypes.string,
   },

   getDefaultProps: function() {
     return {
       direction: 'up',
       width: 0,
       height: 0,
       color: 'white',
     };
   },

   _borderStyles() {
     if (this.props.direction == 'up') {
       return {
         borderTopWidth: 0,
         borderRightWidth: this.props.width/2.0,
         borderBottomWidth: this.props.height,
         borderLeftWidth: this.props.width/2.0,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: this.props.color,
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'right') {
       return {
         borderTopWidth: this.props.height/2.0,
         borderRightWidth: 0,
         borderBottomWidth: this.props.height/2.0,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: this.props.color,
       };
     } else if (this.props.direction == 'down') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: this.props.width/2.0,
         borderBottomWidth: 0,
         borderLeftWidth: this.props.width/2.0,
         borderTopColor: this.props.color,
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'left') {
       return {
         borderTopWidth: this.props.height/2.0,
         borderRightWidth: this.props.width,
         borderBottomWidth: this.props.height/2.0,
         borderLeftWidth: 0,
         borderTopColor: 'transparent',
         borderRightColor: this.props.color,
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'up-left') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: this.props.width,
         borderBottomWidth: 0,
         borderLeftWidth: 0,
         borderTopColor: this.props.color,
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'up-right') {
       return {
         borderTopWidth: 0,
         borderRightWidth: this.props.width,
         borderBottomWidth: this.props.height,
         borderLeftWidth: 0,
         borderTopColor: 'transparent',
         borderRightColor: this.props.color,
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'down-left') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: 0,
         borderBottomWidth: 0,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: this.props.color,
       };
     } else if (this.props.direction == 'down-right') {
       return {
         borderTopWidth: 0,
         borderRightWidth: 0,
         borderBottomWidth: this.props.height,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: this.props.color,
         borderLeftColor: 'transparent',
       };
     } else {
       console.error('Triangle.js wrong direction. ' + this.props.direction + ' is invalid. Must be one of: ' + ['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']);
       return {};
     }
   },

   render: function() {
     var borderStyles = this._borderStyles();
     return (
       <View style={[styles.triangle, borderStyles, this.props.style]}/>
     )
   },

 });

 var styles = StyleSheet.create({
   triangle: {
     width: 0,
     height: 0,
     backgroundColor: 'transparent',
     borderStyle: 'solid',
   },
 });

 module.exports = Triangle;
<commit_msg>Changed the React Native imports to follow the pattern started with RN 0.25. See https://github.com/facebook/react-native/releases/tag/v0.25.1<commit_after>'use strict';

import React from 'react';
import {
  StyleSheet,
  View
} from 'react-native';

 var Triangle = React.createClass({

   propTypes: {
     direction: React.PropTypes.oneOf(['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']),
     width: React.PropTypes.number,
     height: React.PropTypes.number,
     color: React.PropTypes.string,
   },

   getDefaultProps: function() {
     return {
       direction: 'up',
       width: 0,
       height: 0,
       color: 'white',
     };
   },

   _borderStyles() {
     if (this.props.direction == 'up') {
       return {
         borderTopWidth: 0,
         borderRightWidth: this.props.width/2.0,
         borderBottomWidth: this.props.height,
         borderLeftWidth: this.props.width/2.0,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: this.props.color,
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'right') {
       return {
         borderTopWidth: this.props.height/2.0,
         borderRightWidth: 0,
         borderBottomWidth: this.props.height/2.0,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: this.props.color,
       };
     } else if (this.props.direction == 'down') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: this.props.width/2.0,
         borderBottomWidth: 0,
         borderLeftWidth: this.props.width/2.0,
         borderTopColor: this.props.color,
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'left') {
       return {
         borderTopWidth: this.props.height/2.0,
         borderRightWidth: this.props.width,
         borderBottomWidth: this.props.height/2.0,
         borderLeftWidth: 0,
         borderTopColor: 'transparent',
         borderRightColor: this.props.color,
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'up-left') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: this.props.width,
         borderBottomWidth: 0,
         borderLeftWidth: 0,
         borderTopColor: this.props.color,
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'up-right') {
       return {
         borderTopWidth: 0,
         borderRightWidth: this.props.width,
         borderBottomWidth: this.props.height,
         borderLeftWidth: 0,
         borderTopColor: 'transparent',
         borderRightColor: this.props.color,
         borderBottomColor: 'transparent',
         borderLeftColor: 'transparent',
       };
     } else if (this.props.direction == 'down-left') {
       return {
         borderTopWidth: this.props.height,
         borderRightWidth: 0,
         borderBottomWidth: 0,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: 'transparent',
         borderLeftColor: this.props.color,
       };
     } else if (this.props.direction == 'down-right') {
       return {
         borderTopWidth: 0,
         borderRightWidth: 0,
         borderBottomWidth: this.props.height,
         borderLeftWidth: this.props.width,
         borderTopColor: 'transparent',
         borderRightColor: 'transparent',
         borderBottomColor: this.props.color,
         borderLeftColor: 'transparent',
       };
     } else {
       console.error('Triangle.js wrong direction. ' + this.props.direction + ' is invalid. Must be one of: ' + ['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']);
       return {};
     }
   },

   render: function() {
     var borderStyles = this._borderStyles();
     return (
       <View style={[styles.triangle, borderStyles, this.props.style]}/>
     )
   },

 });

 var styles = StyleSheet.create({
   triangle: {
     width: 0,
     height: 0,
     backgroundColor: 'transparent',
     borderStyle: 'solid',
   },
 });

 module.exports = Triangle;
<|endoftext|>


<commit_before>import Promise from 'bluebird'
import Immutable from 'immutable'
import {flatten, forEach, omit} from 'lodash'
import {v4 as uuid} from 'node-uuid'

import {version as currentVersionString} from '../../package.json'

import {randomChar, countCredits} from 'sto-helpers'

import Schedule from './schedule'
import Study from './study'

let StudentRecord = Immutable.Record({
	id: null,
	name: null,
	version: currentVersionString,

	creditsNeeded: 35,

	matriculation: 1894,
	graduation: 1898,

	dateLastModified: null,
	dateCreated: null,

	studies: Immutable.OrderedMap(),
	schedules: Immutable.OrderedMap(),
	overrides: Immutable.OrderedMap(),
	fabrications: Immutable.OrderedMap(),

	settings: Immutable.Map(),
})

class Student extends StudentRecord {
	constructor(encodedStudent={}) {
		// let startTime = present()
		// Don't pass the list params into the StudentRecord constructor; it creates them as JS objects,
		// instead of our custom Studies, Schedules, and such.
		let toRemove = ['studies', 'schedules', 'overrides', 'fabrications', 'settings']
		let filtered = omit(encodedStudent, toRemove)
		let immutableStudent = Immutable.fromJS(filtered)

		super(immutableStudent)

		// Then add them manually.
		if (encodedStudent) {
			return this.withMutations((student) => {
				student = student.set('id', encodedStudent.id || uuid())
				student = student.set('name', encodedStudent.name || 'Student ' + randomChar())
				student = student.set('dateCreated', encodedStudent.dateCreated || new Date())
				student = student.set('dateLastModified', encodedStudent.dateLastModified || new Date())

				forEach((encodedStudent.studies || []), study => {
					student = student.addArea(study)
				})

				forEach((encodedStudent.schedules || []), schedule => {
					student = student.addSchedule(schedule)
				})

				forEach((encodedStudent.overrides || []), override => {
					student = student.addOverride(override)
				})

				forEach((encodedStudent.fabrications || []), fabrication => {
					student = student.addFabrication(fabrication)
				})

				forEach((encodedStudent.settings || {}), (value, key) => {
					student = student.changeSetting(key, value)
				})

				student = student.set('version', currentVersionString)

				// console.log('it took', present() - startTime, 'ms to make a student')

				return student
			})
		}
	}

	changeName(newName) {
		return this.set('name', newName)
	}

	changeCreditsNeeded(newCreditsNeeded) {
		return this.set('creditsNeeded', newCreditsNeeded)
	}

	changeMatriculation(newMatriculation) {
		return this.set('matriculation', newMatriculation)
	}

	changeGraduation(newGraduation) {
		return this.set('graduation', newGraduation)
	}

	changeSetting(key, value) {
		return this.setIn(['settings', key], value)
	}

	// schedule methods

	get schedulesByYear() {
		return this.schedules.groupBy(sched => sched.year)
	}

	get activeSchedules() {
		return this.schedules.filter(sched => sched.active).sortBy(sched => sched.semester)
	}

	addSchedule(newSchedule) {
		let sched = new Schedule(newSchedule)
		return this.setIn(['schedules', sched.id], sched)
	}

	destroySchedule(scheduleId) {
		// console.log(`removing schedule ${scheduleId}`)

		let deadSched = this.getIn(['schedules', scheduleId])
		let scheduleIsNoMore = this.set('schedules', this.schedules.delete(scheduleId))

		if (deadSched && deadSched.active) {
			let otherSchedKey = scheduleIsNoMore.findKey((sched) =>
				sched.year === deadSched.year &&
				sched.semester === deadSched.semester &&
				sched.id !== deadSched.id)

			if (otherSchedKey) {
				return scheduleIsNoMore.setIn(['schedules', otherSchedKey, 'active'], true)
			}
		}
		return scheduleIsNoMore
	}

	destroyMultipleSchedules(ids) {
		return this.withMutations((student) => {
			// console.groupCollapsed('destroyMultipleSchedules')
			Immutable.Seq(ids).forEach((id) => {
				// console.log('destroyMultipleSchedules', id)
				student = student.destroySchedule(id)
			})
			// console.groupEnd('destroyMultipleSchedules')
			return student
		})
	}

	moveCourse(fromScheduleId, toScheduleId, clbid) {
		// console.log(`moving course ${clbid} from schedule ${fromScheduleId} to schedule ${toScheduleId}`)
		return this.withMutations((student) => {
			student = student.setIn(['schedules', fromScheduleId], student.getIn(['schedules', fromScheduleId]).removeCourse(clbid))
			student = student.setIn(['schedules', toScheduleId], student.getIn(['schedules', toScheduleId]).addCourse(clbid))
		})
	}

	// area-of-study methods

	get areasByType() {
		return this.studies.groupBy(study => study.type || 'Unknown')
	}

	addArea(areaOfStudy) {
		let study = new Study(areaOfStudy)
		return this.setIn(['studies', study.id], study)
	}

	removeArea(id) {
		return this.set('studies', this.studies.delete(id))
	}

	removeMultipleAreas(ids) {
		Immutable.Seq(ids).forEach(this.removeArea, this)
	}

	// override methods

	addOverride(override) {
		return this.setIn(['overrides', override.what], override)
	}

	removeOverride(thingOverriden) {
		return this.set('overrides', this.overrides.delete(thingOverriden))
	}

	// fabrication methods

	addFabrication(fabrication) {
		return this.setIn(['fabrications', fabrication.id], fabrication)
	}

	removeFabrication(fabricationId) {
		return this.set('fabrications', this.fabrications.delete(fabricationId))
	}

	// getters

	get courses() {
		let allCourses = this.activeSchedules.map((schedule) => schedule.courses).toArray()
		let scheduleCoursePromises = Promise.all(allCourses)
		return scheduleCoursePromises.then((results) => flatten(results))
	}

	get creditCount() {
		return this.courses.then(countCredits)
	}

	// helpers

	data() {
		return Promise.props({
			courses: this.courses,
			fabrications: this.fabrications.toList().toJS(),
			overrides: this.overrides.toList().toJS(),
			studies: this.studies.toList().toJS(),
			creditsNeeded: this.creditsNeeded,
			graduation: this.graduation,
			matriculation: this.matriculation,
		})
	}

	encode() {
		return encodeURIComponent(JSON.stringify(this))
	}

	save() {
		let oldVersion = localStorage.getItem(this.id)
		let stringified = JSON.stringify(this)
		if (oldVersion !== stringified) {
			console.log(`saving student ${this.name} (${this.id})`)
			let student = this.set('dateLastModified', new Date())
			localStorage.setItem(student.id, stringified)
		}
	}
}

export default Student
<commit_msg>Fix the Student.removeMultipleAreas method<commit_after>import Promise from 'bluebird'
import Immutable from 'immutable'
import {flatten, forEach, omit} from 'lodash'
import {v4 as uuid} from 'node-uuid'

import {version as currentVersionString} from '../../package.json'

import {randomChar, countCredits} from 'sto-helpers'

import Schedule from './schedule'
import Study from './study'

let StudentRecord = Immutable.Record({
	id: null,
	name: null,
	version: currentVersionString,

	creditsNeeded: 35,

	matriculation: 1894,
	graduation: 1898,

	dateLastModified: null,
	dateCreated: null,

	studies: Immutable.OrderedMap(),
	schedules: Immutable.OrderedMap(),
	overrides: Immutable.OrderedMap(),
	fabrications: Immutable.OrderedMap(),

	settings: Immutable.Map(),
})

class Student extends StudentRecord {
	constructor(encodedStudent={}) {
		// let startTime = present()
		// Don't pass the list params into the StudentRecord constructor; it creates them as JS objects,
		// instead of our custom Studies, Schedules, and such.
		let toRemove = ['studies', 'schedules', 'overrides', 'fabrications', 'settings']
		let filtered = omit(encodedStudent, toRemove)
		let immutableStudent = Immutable.fromJS(filtered)

		super(immutableStudent)

		// Then add them manually.
		if (encodedStudent) {
			return this.withMutations((student) => {
				student = student.set('id', encodedStudent.id || uuid())
				student = student.set('name', encodedStudent.name || 'Student ' + randomChar())
				student = student.set('dateCreated', encodedStudent.dateCreated || new Date())
				student = student.set('dateLastModified', encodedStudent.dateLastModified || new Date())

				forEach((encodedStudent.studies || []), study => {
					student = student.addArea(study)
				})

				forEach((encodedStudent.schedules || []), schedule => {
					student = student.addSchedule(schedule)
				})

				forEach((encodedStudent.overrides || []), override => {
					student = student.addOverride(override)
				})

				forEach((encodedStudent.fabrications || []), fabrication => {
					student = student.addFabrication(fabrication)
				})

				forEach((encodedStudent.settings || {}), (value, key) => {
					student = student.changeSetting(key, value)
				})

				student = student.set('version', currentVersionString)

				// console.log('it took', present() - startTime, 'ms to make a student')

				return student
			})
		}
	}

	changeName(newName) {
		return this.set('name', newName)
	}

	changeCreditsNeeded(newCreditsNeeded) {
		return this.set('creditsNeeded', newCreditsNeeded)
	}

	changeMatriculation(newMatriculation) {
		return this.set('matriculation', newMatriculation)
	}

	changeGraduation(newGraduation) {
		return this.set('graduation', newGraduation)
	}

	changeSetting(key, value) {
		return this.setIn(['settings', key], value)
	}

	// schedule methods

	get schedulesByYear() {
		return this.schedules.groupBy(sched => sched.year)
	}

	get activeSchedules() {
		return this.schedules.filter(sched => sched.active).sortBy(sched => sched.semester)
	}

	addSchedule(newSchedule) {
		let sched = new Schedule(newSchedule)
		return this.setIn(['schedules', sched.id], sched)
	}

	destroySchedule(scheduleId) {
		// console.log(`removing schedule ${scheduleId}`)

		let deadSched = this.getIn(['schedules', scheduleId])
		let scheduleIsNoMore = this.set('schedules', this.schedules.delete(scheduleId))

		if (deadSched && deadSched.active) {
			let otherSchedKey = scheduleIsNoMore.findKey((sched) =>
				sched.year === deadSched.year &&
				sched.semester === deadSched.semester &&
				sched.id !== deadSched.id)

			if (otherSchedKey) {
				return scheduleIsNoMore.setIn(['schedules', otherSchedKey, 'active'], true)
			}
		}
		return scheduleIsNoMore
	}

	destroyMultipleSchedules(ids) {
		return this.withMutations((student) => {
			// console.groupCollapsed('destroyMultipleSchedules')
			Immutable.Seq(ids).forEach((id) => {
				// console.log('destroyMultipleSchedules', id)
				student = student.destroySchedule(id)
			})
			// console.groupEnd('destroyMultipleSchedules')
			return student
		})
	}

	moveCourse(fromScheduleId, toScheduleId, clbid) {
		// console.log(`moving course ${clbid} from schedule ${fromScheduleId} to schedule ${toScheduleId}`)
		return this.withMutations((student) => {
			student = student.setIn(['schedules', fromScheduleId], student.getIn(['schedules', fromScheduleId]).removeCourse(clbid))
			student = student.setIn(['schedules', toScheduleId], student.getIn(['schedules', toScheduleId]).addCourse(clbid))
		})
	}

	// area-of-study methods

	get areasByType() {
		return this.studies.groupBy(study => study.type || 'Unknown')
	}

	addArea(areaOfStudy) {
		let study = new Study(areaOfStudy)
		return this.setIn(['studies', study.id], study)
	}

	removeArea(id) {
		return this.set('studies', this.studies.delete(id))
	}

	removeMultipleAreas(ids) {
		return this.withMutations((student) => {
			Immutable.Seq(ids).forEach((id) => {
				student = student.removeArea(id)
			})
			return student
		})
	}

	// override methods

	addOverride(override) {
		return this.setIn(['overrides', override.what], override)
	}

	removeOverride(thingOverriden) {
		return this.set('overrides', this.overrides.delete(thingOverriden))
	}

	// fabrication methods

	addFabrication(fabrication) {
		return this.setIn(['fabrications', fabrication.id], fabrication)
	}

	removeFabrication(fabricationId) {
		return this.set('fabrications', this.fabrications.delete(fabricationId))
	}

	// getters

	get courses() {
		let allCourses = this.activeSchedules.map((schedule) => schedule.courses).toArray()
		let scheduleCoursePromises = Promise.all(allCourses)
		return scheduleCoursePromises.then((results) => flatten(results))
	}

	get creditCount() {
		return this.courses.then(countCredits)
	}

	// helpers

	data() {
		return Promise.props({
			courses: this.courses,
			fabrications: this.fabrications.toList().toJS(),
			overrides: this.overrides.toList().toJS(),
			studies: this.studies.toList().toJS(),
			creditsNeeded: this.creditsNeeded,
			graduation: this.graduation,
			matriculation: this.matriculation,
		})
	}

	encode() {
		return encodeURIComponent(JSON.stringify(this))
	}

	save() {
		let oldVersion = localStorage.getItem(this.id)
		let stringified = JSON.stringify(this)
		if (oldVersion !== stringified) {
			console.log(`saving student ${this.name} (${this.id})`)
			let student = this.set('dateLastModified', new Date())
			localStorage.setItem(student.id, stringified)
		}
	}
}

export default Student
<|endoftext|>


<commit_before>// Add the finished solution here when you receive it.

// Sum Function
function sum(array) {
  return array.reduce(function(a, b) {
    return a + b;
  });
};

// Mean Function
function mean(array) {
  return sum(array) / array.length;
};

// Median Function
function median(array) {
  if (array.length % 2 != 0)
    var median = array[(array.length - 1) / 2];
  else
    var median = (array[array.length / 2] + array[array.length / 2 - 1]) / 2.0;
  console.log(median);
  return median;
};

// __________________________________________
// Tests:  Do not alter code below this line.

oddLengthArray  = [1, 2, 3, 4, 5, 5, 7]
evenLengthArray = [4, 4, 5, 5, 6, 6, 6, 7]

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

// tests for sum
assert(
  (sum instanceof Function),
  "sum should be a Function.",
  "1. "
)

assert(
  sum(oddLengthArray) === 27,
  "sum should return the sum of all elements in an array with an odd length.",
  "2. "
)

assert(
  sum(evenLengthArray) === 43,
  "sum should return the sum of all elements in an array with an even length.",
  "3. "
)

// tests for mean
assert(
  (mean instanceof Function),
  "mean should be a Function.",
  "4. "
)

assert(
  mean(oddLengthArray) === 3.857142857142857,
  "mean should return the average of all elements in an array with an odd length.",
  "5. "
)

assert(
  mean(evenLengthArray) === 5.375,
  "mean should return the average of all elements in an array with an even length.",
  "6. "
)

// tests for median
assert(
  (median instanceof Function),
  "median should be a Function.",
  "7. "
)

assert(
  median(oddLengthArray) === 4,
  "median should return the median value of all elements in an array with an odd length.",
  "8. "
)

assert(
  median(evenLengthArray) === 5.5,
  "median should return the median value of all elements in an array with an even length.",
  "9. "
)<commit_msg>Complete Release 3 of Challenge 7.8 for Practice<commit_after>// Add the finished solution here when you receive it.

// Initial Solution

// Sum Function
function sum(array){
  var sum = 0;
  if (array.length % 2 != 0)
    for (var i = 0; i < array.length; i++) {
      sum += array[i];
    }
  else {
    for (var i = 0; i < array.length; i++) {
      sum += array[i];
    }
  }
  return sum;
}

// Mean Function
function mean(array){
  var sum = 0;
  if (array.length % 2 != 0)
    for (var i = 0; i < array.length; i++) {
      sum += array[i];
    }
  else {
    for (var i = 0; i < array.length; i++) {
      sum += array[i];
    }
  }
  return sum/array.length;
}

// Median Function
function median(array){
  var median = 0;
  if (array.length % 2 != 0) {
    var index = array.length / 2;
    median = array[Math.floor(index)];
    }
  else {
    nums = 0;
    nums += array[(array.length / 2) - 1];
    nums += array[(array.length / 2)];
    median = nums / 2;
    }
  return median;
}

// Refactored Solution

// Sum Function
function sum(array) {
  return array.reduce(function(a, b) {
    return a + b;
  });
};

// Mean Function
function mean(array) {
  return sum(array) / array.length;
};

// Median Function
function median(array) {
  if (array.length % 2 != 0)
    var median = array[(array.length - 1) / 2];
  else
    var median = (array[array.length / 2] + array[array.length / 2 - 1]) / 2.0;
  return median;
};

// __________________________________________
// Tests:  Do not alter code below this line.

oddLengthArray  = [1, 2, 3, 4, 5, 5, 7]
evenLengthArray = [4, 4, 5, 5, 6, 6, 6, 7]

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

// tests for sum
assert(
  (sum instanceof Function),
  "sum should be a Function.",
  "1. "
)

assert(
  sum(oddLengthArray) === 27,
  "sum should return the sum of all elements in an array with an odd length.",
  "2. "
)

assert(
  sum(evenLengthArray) === 43,
  "sum should return the sum of all elements in an array with an even length.",
  "3. "
)

// tests for mean
assert(
  (mean instanceof Function),
  "mean should be a Function.",
  "4. "
)

assert(
  mean(oddLengthArray) === 3.857142857142857,
  "mean should return the average of all elements in an array with an odd length.",
  "5. "
)

assert(
  mean(evenLengthArray) === 5.375,
  "mean should return the average of all elements in an array with an even length.",
  "6. "
)

// tests for median
assert(
  (median instanceof Function),
  "median should be a Function.",
  "7. "
)

assert(
  median(oddLengthArray) === 4,
  "median should return the median value of all elements in an array with an odd length.",
  "8. "
)

assert(
  median(evenLengthArray) === 5.5,
  "median should return the median value of all elements in an array with an even length.",
  "9. "
)<|endoftext|>


<commit_before>import { assert } from '@ember/debug';

export function buildOperationUrl(record, opPath, urlType, instance = true) {
  assert('You must provide a path for instanceOp', opPath);
  let modelName = record.constructor.modelName || record.constructor.typeKey;
  let adapter = record.store.adapterFor(modelName);
  let path = opPath;
  let snapshot = record._createSnapshot();
  let baseUrl = adapter.buildURL(modelName, instance ? record.get('id') : null, snapshot, urlType);

  if (baseUrl.charAt(baseUrl.length - 1) === '/') {
    return `${baseUrl}${path}`;
  } else {
    return `${baseUrl}/${path}`;
  }
}

export default buildOperationUrl;
<commit_msg>feature: Allow empty paths<commit_after>export function buildOperationUrl(record, opPath, urlType, instance = true) {
  let modelName = record.constructor.modelName || record.constructor.typeKey;
  let adapter = record.store.adapterFor(modelName);
  let path = opPath;
  let snapshot = record._createSnapshot();
  let baseUrl = adapter.buildURL(modelName, instance ? record.get('id') : null, snapshot, urlType);

  if (!path) {
    return baseUrl;
  }

  if (baseUrl.charAt(baseUrl.length - 1) === '/') {
    return `${baseUrl}${path}`;
  } else {
    return `${baseUrl}/${path}`;
  }
}

export default buildOperationUrl;
<|endoftext|>


<commit_before>import Ember from 'ember';

const { assert } = Ember;

export default function buildOperationUrl(record, opPath, requestType, intance=true) {
  assert('You must provide a path for instanceOp', opPath);
  const modelName = record.constructor.modelName || record.constructor.typeKey;
  let adapter = record.store.adapterFor(modelName);
  let path = opPath;
  let baseUrl = adapter.buildURL(modelName, intance ? record.get('id') : null, requestType);

  if (baseUrl.charAt(baseUrl.length - 1) === '/') {
    return `${baseUrl}${path}`;
  } else {
    return `${baseUrl}/${path}`;
  }
}
<commit_msg>Fix buildURL to match ember-data signature.<commit_after>import Ember from 'ember';

const { assert } = Ember;

export default function buildOperationUrl(record, opPath, requestType, instance=true) {
  assert('You must provide a path for instanceOp', opPath);
  const modelName = record.constructor.modelName || record.constructor.typeKey;
  let adapter = record.store.adapterFor(modelName);
  let path = opPath;
  let snapshot = record._createSnapshot();
  let baseUrl = adapter.buildURL(modelName, instance ? record.get('id') : null, snapshot, requestType);

  if (baseUrl.charAt(baseUrl.length - 1) === '/') {
    return `${baseUrl}${path}`;
  } else {
    return `${baseUrl}/${path}`;
  }
}
<|endoftext|>


<commit_before>'use strict';

var http = require('superagent'),
  _ = require('lodash'),
  Q = require('q'),
  NEO4J = require('./neo4j');

var XEBIAN_TYPE = 'XEBIAN';
var SKILL_TYPE = 'SKILL';

var SKILLZ_RELATION = 'HAS';

exports.createXebian = function(userData) {
	return NEO4J.createNodePromise(XEBIAN_TYPE, userData);
};

exports.updateXebian = function(userData) {
	return NEO4J.updateNodePromise(XEBIAN_TYPE, 'email', userData.email, userData);
};

exports.createSkill = function(skill) {
  return NEO4J.createNodePromise(SKILL_TYPE, skill);
};

exports.deleteElement = function(elementURL) {
  var securedURL = NEO4J.makeURLSecured(elementURL);

  var deferred = Q.defer();
  http
    .del(securedURL)
    .end(function(res){
      console.log('deleted : ' + securedURL + ' with status ' + res.statusCode);
      deferred.resolve(res);
  });
  return deferred.promise;
};

exports.findXebian = function(email) {
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.email = {email} RETURN n',
    'params' : {
      'email': email
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebianById = function(id) {
	var query = {
		'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n._id = {_id} RETURN n',
		'params' : {
			'_id': id
		}
	};
	return NEO4J.findPromise(query);
};

exports.findXebianByEmail = function(email) {
	var query = {
		'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.email = {email} RETURN n',
		'params' : {
			'email': email
		}
	};
	return NEO4J.findPromise(query);
};

exports.findXebianSkillz = function(email){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+')-[r:`'+SKILLZ_RELATION+'`]->s WHERE n.email = {email} RETURN s,r  order by r.like DESC, r.level DESC, s.name',
    'params' : {
      'email': email
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebiansByName = function(q){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.displayName =~ {q} RETURN n',
    'params': {
      'q': '(?i).*' + q + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebiansBySkillz = function (skillName){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+')-[r:`'+SKILLZ_RELATION+'`]->s WHERE s.name=~ {q} RETURN n,r, s',
    'params': {
      'q': '(?i).*' + skillName + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.findAvailableSkillzForXebian = function(email, skillQuery) {
  var query = {
    'query': 'MATCH (xebian: '+XEBIAN_TYPE+'), (skill: '+SKILL_TYPE+' ) WHERE skill.name =~ {skillQuery} and xebian.email = {email} and not (xebian) -[:HAS]-> (skill) RETURN skill.name',
    'params': {
      'email': email,
      'skillQuery': '(?i).*' + skillQuery + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.getSkill = function(skillName) {
  var query = {
    'query': 'MATCH (n: '+SKILL_TYPE+' ) WHERE n.name= {name} RETURN n',
    'params': {
      'name': skillName
    }
  };
  return NEO4J.findPromise(query);
};

exports.findAllSkills = function() {
  var query = {
    'query': 'MATCH (s:' + SKILL_TYPE + ') OPTIONAL MATCH s<-[r:`HAS`]-() return s.name, count(r),s order by upper(s.name)'
  };
  return NEO4J.findPromise(query);
};

var extractNodeIdPattern = /(\d*)$/;
var extractNodeId = function(nodeUrl) {
	return nodeUrl.match(extractNodeIdPattern)[1];
};

exports.userHasSkill = function(userNodeUrl, skillNodeUrl) {
	var userNodeId = extractNodeId(userNodeUrl);
	var skillNodeId = extractNodeId(skillNodeUrl);
	var query = {
		'query': 'start xebian=node( {userNodeId} ),skill=node( {skillNodeId} ) match (xebian)-[r:HAS]->(skill) return r',
		'params': {
			'userNodeId': Number(userNodeId),
			'skillNodeId': Number(skillNodeId)
		}
	};

	return NEO4J.findPromise(query);
};

exports.associateSkillToUser = function(userNodeUrl, skillNodeUrl, relation_properties) {
  var securedURL = NEO4J.makeURLSecured(userNodeUrl);

  var deferred = Q.defer();
  http
    .post(securedURL + '/relationships')
    .set('Accept', 'application/json; charset=UTF-8')
    .set('Content-Type', 'application/json')
    .send({
      'to' : skillNodeUrl,
      'type' : SKILLZ_RELATION,
      'data' : relation_properties
    })
    .end(function(err, res) {
      if (err) {
        deferred.reject(err);
      } else {
        console.log('associateSkillToUser', res.statusCode );
        deferred.resolve(res.body.self);
      }
    });
  return deferred.promise;
};

exports.orphanSkillz = function(){
  var query = {
    'query': 'match (orphan:SKILL) where not ()-[:HAS]->(orphan) return orphan order by upper(orphan.name)'
  };

  return NEO4J.findPromise(query);
};

exports.deleteSkill = function(source){
  var oldSkillId = NEO4J.extractNodeId(source);

  var removeOldSkillQuery = {
      'query' : 'start oldSkill=node( {oldSkillId} )  OPTIONAL MATCH (oldSkill)-[r]-() DELETE oldSkill,r',
      'params': {
        'oldSkillId' : oldSkillId
      }
    };

    return NEO4J.execute(removeOldSkillQuery);
};

exports.mergeSkill = function(source, destination){
  var oldSkillId = NEO4J.extractNodeId(source);
  var newSkillId = NEO4J.extractNodeId(destination);

  var addNewRelationsQuery = {
    'query' : 'START oldSkill=node( {oldSkillId} ), newSkill=node( {newSkillId} ) match  (x: `'+XEBIAN_TYPE+'`)-[oldRelation:`'+SKILLZ_RELATION+'`]->oldSkill WHERE NOT (x)-[:`'+SKILLZ_RELATION+'`]->newSkill  create (x)-[r:`'+SKILLZ_RELATION+'` {level: oldRelation.level, like: oldRelation.like }]->(newSkill)',
    'params' : {
      'oldSkillId': oldSkillId,
      'newSkillId': newSkillId
    }
  };

  var addNewRelations = NEO4J.execute(addNewRelationsQuery);

  var self = this;

  return addNewRelations.then(function(){
    return self.deleteSkill(source);
  });
};
<commit_msg>La liste des skillz possible pour mon profil est triée<commit_after>'use strict';

var http = require('superagent'),
  _ = require('lodash'),
  Q = require('q'),
  NEO4J = require('./neo4j');

var XEBIAN_TYPE = 'XEBIAN';
var SKILL_TYPE = 'SKILL';

var SKILLZ_RELATION = 'HAS';

exports.createXebian = function(userData) {
	return NEO4J.createNodePromise(XEBIAN_TYPE, userData);
};

exports.updateXebian = function(userData) {
	return NEO4J.updateNodePromise(XEBIAN_TYPE, 'email', userData.email, userData);
};

exports.createSkill = function(skill) {
  return NEO4J.createNodePromise(SKILL_TYPE, skill);
};

exports.deleteElement = function(elementURL) {
  var securedURL = NEO4J.makeURLSecured(elementURL);

  var deferred = Q.defer();
  http
    .del(securedURL)
    .end(function(res){
      console.log('deleted : ' + securedURL + ' with status ' + res.statusCode);
      deferred.resolve(res);
  });
  return deferred.promise;
};

exports.findXebian = function(email) {
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.email = {email} RETURN n',
    'params' : {
      'email': email
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebianById = function(id) {
	var query = {
		'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n._id = {_id} RETURN n',
		'params' : {
			'_id': id
		}
	};
	return NEO4J.findPromise(query);
};

exports.findXebianByEmail = function(email) {
	var query = {
		'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.email = {email} RETURN n',
		'params' : {
			'email': email
		}
	};
	return NEO4J.findPromise(query);
};

exports.findXebianSkillz = function(email){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+')-[r:`'+SKILLZ_RELATION+'`]->s WHERE n.email = {email} RETURN s,r  order by r.like DESC, r.level DESC, s.name',
    'params' : {
      'email': email
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebiansByName = function(q){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+') WHERE n.displayName =~ {q} RETURN n',
    'params': {
      'q': '(?i).*' + q + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.findXebiansBySkillz = function (skillName){
  var query = {
    'query' : 'MATCH (n: '+XEBIAN_TYPE+')-[r:`'+SKILLZ_RELATION+'`]->s WHERE s.name=~ {q} RETURN n,r, s',
    'params': {
      'q': '(?i).*' + skillName + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.findAvailableSkillzForXebian = function(email, skillQuery) {
  var query = {
    'query': 'MATCH (xebian: '+XEBIAN_TYPE+'), (skill: '+SKILL_TYPE+' ) WHERE skill.name =~ {skillQuery} and xebian.email = {email} and not (xebian) -[:HAS]-> (skill) RETURN skill.name order by upper(skill.name)',
    'params': {
      'email': email,
      'skillQuery': '(?i).*' + skillQuery + '.*'
    }
  };
  return NEO4J.findPromise(query);
};

exports.getSkill = function(skillName) {
  var query = {
    'query': 'MATCH (n: '+SKILL_TYPE+' ) WHERE n.name= {name} RETURN n',
    'params': {
      'name': skillName
    }
  };
  return NEO4J.findPromise(query);
};

exports.findAllSkills = function() {
  var query = {
    'query': 'MATCH (s:' + SKILL_TYPE + ') OPTIONAL MATCH s<-[r:`HAS`]-() return s.name, count(r),s order by upper(s.name)'
  };
  return NEO4J.findPromise(query);
};

var extractNodeIdPattern = /(\d*)$/;
var extractNodeId = function(nodeUrl) {
	return nodeUrl.match(extractNodeIdPattern)[1];
};

exports.userHasSkill = function(userNodeUrl, skillNodeUrl) {
	var userNodeId = extractNodeId(userNodeUrl);
	var skillNodeId = extractNodeId(skillNodeUrl);
	var query = {
		'query': 'start xebian=node( {userNodeId} ),skill=node( {skillNodeId} ) match (xebian)-[r:HAS]->(skill) return r',
		'params': {
			'userNodeId': Number(userNodeId),
			'skillNodeId': Number(skillNodeId)
		}
	};

	return NEO4J.findPromise(query);
};

exports.associateSkillToUser = function(userNodeUrl, skillNodeUrl, relation_properties) {
  var securedURL = NEO4J.makeURLSecured(userNodeUrl);

  var deferred = Q.defer();
  http
    .post(securedURL + '/relationships')
    .set('Accept', 'application/json; charset=UTF-8')
    .set('Content-Type', 'application/json')
    .send({
      'to' : skillNodeUrl,
      'type' : SKILLZ_RELATION,
      'data' : relation_properties
    })
    .end(function(err, res) {
      if (err) {
        deferred.reject(err);
      } else {
        console.log('associateSkillToUser', res.statusCode );
        deferred.resolve(res.body.self);
      }
    });
  return deferred.promise;
};

exports.orphanSkillz = function(){
  var query = {
    'query': 'match (orphan:SKILL) where not ()-[:HAS]->(orphan) return orphan order by upper(orphan.name)'
  };

  return NEO4J.findPromise(query);
};

exports.deleteSkill = function(source){
  var oldSkillId = NEO4J.extractNodeId(source);

  var removeOldSkillQuery = {
      'query' : 'start oldSkill=node( {oldSkillId} )  OPTIONAL MATCH (oldSkill)-[r]-() DELETE oldSkill,r',
      'params': {
        'oldSkillId' : oldSkillId
      }
    };

    return NEO4J.execute(removeOldSkillQuery);
};

exports.mergeSkill = function(source, destination){
  var oldSkillId = NEO4J.extractNodeId(source);
  var newSkillId = NEO4J.extractNodeId(destination);

  var addNewRelationsQuery = {
    'query' : 'START oldSkill=node( {oldSkillId} ), newSkill=node( {newSkillId} ) match  (x: `'+XEBIAN_TYPE+'`)-[oldRelation:`'+SKILLZ_RELATION+'`]->oldSkill WHERE NOT (x)-[:`'+SKILLZ_RELATION+'`]->newSkill  create (x)-[r:`'+SKILLZ_RELATION+'` {level: oldRelation.level, like: oldRelation.like }]->(newSkill)',
    'params' : {
      'oldSkillId': oldSkillId,
      'newSkillId': newSkillId
    }
  };

  var addNewRelations = NEO4J.execute(addNewRelationsQuery);

  var self = this;

  return addNewRelations.then(function(){
    return self.deleteSkill(source);
  });
};
<|endoftext|>


<commit_before>var d3 = {
  array: require("d3-arrays"),
  color: require("d3-color")
};

var settings = require("./defaults.js");

var Color = class {

  /**
      @param {Color|String|Number|true|false|null|undefined} color
      @param {object} [defaults = src/defaults.js]
  */
  constructor(color, defaults) {

    this.value = color;
    this.defaults = defaults || settings;

    // If the value is null or undefined, set to grey.
    if ([null, undefined].indexOf(color) >= 0) {
      this.color = this.defaults.missing;
    }
    // Else if the value is true, set to green.
    else if (color === true) {
      this.color = this.defaults.on;
    }
    // Else if the value is false, set to red.
    else if (color === false) {
      this.color = this.defaults.off;
    }

    this.d3 = d3.color.color(this.color || color);
    // If the value is not a valid color string, use the color scale.
    if (!this.d3) {
      this.color = this.defaults.scale(color);
      this.d3 = d3.color.color(this.color);
    }
    else if (!this.color) {
      this.color = color;
    }

  }

  /**
      Mixes a second color, returning a new Color object.
      @param {Color} c2 - The color to be mixed in. If it is not a d3plus-color Object, then it will be parsed into one.
      @returns {Color}
  */
  add(c2) {
    if (c2.constructor !== Color) { c2 = new Color(c2); }
    var o1 = this.opacity(), o2 = c2.opacity(), c1 = this.hsl();
    c2 = c2.hsl();
    var d = Math.abs(c2.h * o2 - c1.h * o1);
    if (d > 180) { d = d - 360; }
    var h = (d3.array.min([c1.h, c2.h]) + d / 2) % 360,
        s = c1.s + (c2.s * o2 - c1.s * o1) / 2,
        l = c1.l + (c2.l * o2 - c1.l * o1) / 2;
        // a = o1 + (o2 - o1) / 2;
    if (h < 0) { h = 360 + h; }
    return new Color("hsl(" + [h, s * 100 + "%", l * 100 + "%"].join(",") + ")");
    // return new Color("hsla(" + [h, s * 100 + "%", l * 100 + "%", a].join(",") + ")");
  }

  /**
      Returns true if the color is displayable.
      @returns {Boolean}
  */
  displayable() {
    return this.d3.displayable();
  }

  /**
      Returns the hexidecimal value.
      @returns {String}
  */
  hex() {
    return this.toString();
  }

  /** Returns the D3 hsl object. */
  hsl() {
    return d3.color.hsl(this.d3);
  }

  /**
      Darkens the color if it is too light to appear on white.
      @returns {Color}
  */
  legible() {
    var c = this.hsl();
    if (c.l > 0.45) {
      if (c.s > 0.8) { c.s = 0.8; }
      c.l = 0.45;
    }
    return new Color(c.toString());
  }

  /**
      Lightens the color while also reducing the saturation.
      @returns {Color}
  */
  lighter(i) {
    if (!i) { i = 0.5; }
    var c = this.hsl();
    i = (1 - c.l) * i;
    c.l += i; c.s -= i;
    return new Color(c.toString());
  }

  // Parses opacity from original rgba or hsla value.
  opacity() {
    return 1;
    // var c = this.value;
    // if (!c || c.constructor !== String) { return 1; }
    // c = c.replace(RegExp(" ", "g"), "").toLowerCase();
    // if (c.indexOf("hsla(") === 0 || c.indexOf("rgba(") === 0) {
    //   return parseFloat(c.split(")")[0].split(",")[3], 10);
    // }
    // else {
    //   return 1;
    // }
  }

  /** Returns the D3 rgb object. */
  rgb() {
    return this.d3;
  }

  /**
      Subtracts a second color, returning a new Color object.
      @param {Color} c2 - The color to be subtracted out. If it is not a d3plus-color Object, then it will be parsed into one.
      @returns {Color}
  */
  subtract(c2) {
    if (c2.constructor !== Color) { c2 = new Color(c2); }
    var o1 = this.opacity(), o2 = c2.opacity(), c1 = this.hsl();
    c2 = c2.hsl();
    var d = (c2.h * o2 - c1.h * o1);
    if (Math.abs(d) > 180) { d = d - 360; }
    var h = (c1.h - d) % 360,
        s = c1.s - (c2.s * o2 - c1.s * o1) / 2,
        l = c1.l - (c2.l * o2 - c1.l * o1) / 2;
        // a = o1 - (o2 - o1) / 2;
    if (h < 0) { h = 360 + h; }
    return new Color("hsl(" + [h, s * 100 + "%", l * 100 + "%"].join(",") + ")");
    // return new Color("hsla(" + [h, s * 100 + "%", l * 100 + "%", a].join(",") + ")");
  }

  /**
      Analyzes the color and determines an appropriate color for text to be placed on top of the color.
      @returns {Color}
  */
  text() {
    var rgb = this.rgb(), r = rgb.r, g = rgb.g, b = rgb.b,
        yiq = (r * 299 + g * 587 + b * 114) / 1000,
        c = yiq >= 128 ? this.defaults.dark : this.defaults.light;
    return new Color(c);
  }

  /**
      Pass-through method for D3 toString function.
      @returns {String}
  */
  toString() {
    return this.d3.toString();
  }

};

module.exports = Color;
<commit_msg>undid previous commit<commit_after>var d3 = {
  array: require("d3-arrays"),
  color: require("d3-color")
};

var settings = require("./defaults.js");

class Color {

  /**
      @param {Color|String|Number|true|false|null|undefined} color
      @param {object} [defaults = src/defaults.js]
  */
  constructor(color, defaults) {

    this.value = color;
    this.defaults = defaults || settings;

    // If the value is null or undefined, set to grey.
    if ([null, undefined].indexOf(color) >= 0) {
      this.color = this.defaults.missing;
    }
    // Else if the value is true, set to green.
    else if (color === true) {
      this.color = this.defaults.on;
    }
    // Else if the value is false, set to red.
    else if (color === false) {
      this.color = this.defaults.off;
    }

    this.d3 = d3.color.color(this.color || color);
    // If the value is not a valid color string, use the color scale.
    if (!this.d3) {
      this.color = this.defaults.scale(color);
      this.d3 = d3.color.color(this.color);
    }
    else if (!this.color) {
      this.color = color;
    }

  }

  /**
      Mixes a second color, returning a new Color object.
      @param {Color} c2 - The color to be mixed in. If it is not a d3plus-color Object, then it will be parsed into one.
      @returns {Color}
  */
  add(c2) {
    if (c2.constructor !== Color) { c2 = new Color(c2); }
    var o1 = this.opacity(), o2 = c2.opacity(), c1 = this.hsl();
    c2 = c2.hsl();
    var d = Math.abs(c2.h * o2 - c1.h * o1);
    if (d > 180) { d = d - 360; }
    var h = (d3.array.min([c1.h, c2.h]) + d / 2) % 360,
        s = c1.s + (c2.s * o2 - c1.s * o1) / 2,
        l = c1.l + (c2.l * o2 - c1.l * o1) / 2;
        // a = o1 + (o2 - o1) / 2;
    if (h < 0) { h = 360 + h; }
    return new Color("hsl(" + [h, s * 100 + "%", l * 100 + "%"].join(",") + ")");
    // return new Color("hsla(" + [h, s * 100 + "%", l * 100 + "%", a].join(",") + ")");
  }

  /**
      Returns true if the color is displayable.
      @returns {Boolean}
  */
  displayable() {
    return this.d3.displayable();
  }

  /**
      Returns the hexidecimal value.
      @returns {String}
  */
  hex() {
    return this.toString();
  }

  /** Returns the D3 hsl object. */
  hsl() {
    return d3.color.hsl(this.d3);
  }

  /**
      Darkens the color if it is too light to appear on white.
      @returns {Color}
  */
  legible() {
    var c = this.hsl();
    if (c.l > 0.45) {
      if (c.s > 0.8) { c.s = 0.8; }
      c.l = 0.45;
    }
    return new Color(c.toString());
  }

  /**
      Lightens the color while also reducing the saturation.
      @returns {Color}
  */
  lighter(i) {
    if (!i) { i = 0.5; }
    var c = this.hsl();
    i = (1 - c.l) * i;
    c.l += i; c.s -= i;
    return new Color(c.toString());
  }

  // Parses opacity from original rgba or hsla value.
  opacity() {
    return 1;
    // var c = this.value;
    // if (!c || c.constructor !== String) { return 1; }
    // c = c.replace(RegExp(" ", "g"), "").toLowerCase();
    // if (c.indexOf("hsla(") === 0 || c.indexOf("rgba(") === 0) {
    //   return parseFloat(c.split(")")[0].split(",")[3], 10);
    // }
    // else {
    //   return 1;
    // }
  }

  /** Returns the D3 rgb object. */
  rgb() {
    return this.d3;
  }

  /**
      Subtracts a second color, returning a new Color object.
      @param {Color} c2 - The color to be subtracted out. If it is not a d3plus-color Object, then it will be parsed into one.
      @returns {Color}
  */
  subtract(c2) {
    if (c2.constructor !== Color) { c2 = new Color(c2); }
    var o1 = this.opacity(), o2 = c2.opacity(), c1 = this.hsl();
    c2 = c2.hsl();
    var d = (c2.h * o2 - c1.h * o1);
    if (Math.abs(d) > 180) { d = d - 360; }
    var h = (c1.h - d) % 360,
        s = c1.s - (c2.s * o2 - c1.s * o1) / 2,
        l = c1.l - (c2.l * o2 - c1.l * o1) / 2;
        // a = o1 - (o2 - o1) / 2;
    if (h < 0) { h = 360 + h; }
    return new Color("hsl(" + [h, s * 100 + "%", l * 100 + "%"].join(",") + ")");
    // return new Color("hsla(" + [h, s * 100 + "%", l * 100 + "%", a].join(",") + ")");
  }

  /**
      Analyzes the color and determines an appropriate color for text to be placed on top of the color.
      @returns {Color}
  */
  text() {
    var rgb = this.rgb(), r = rgb.r, g = rgb.g, b = rgb.b,
        yiq = (r * 299 + g * 587 + b * 114) / 1000,
        c = yiq >= 128 ? this.defaults.dark : this.defaults.light;
    return new Color(c);
  }

  /**
      Pass-through method for D3 toString function.
      @returns {String}
  */
  toString() {
    return this.d3.toString();
  }

}

module.exports = Color;
<|endoftext|>


<commit_before>(function(window){

  /*
                    _   _     _                _
   __ _ _ __  _   _| |_| |__ (_)_ __   __ _   (_)___
  / _` | '_ \| | | | __| '_ \| | '_ \ / _` |  | / __|
 | (_| | | | | |_| | |_| | | | | | | | (_| |_ | \__ \
  \__,_|_| |_|\__, |\__|_| |_|_|_| |_|\__, (_)/ |___/
              |___/                   |___/ |__/
     */

    function anything() {

        this.version = "0.0.1"

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    function hash(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
        //from https://xkcd.com/221/
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    function negMod( n, m ) {
        return ((n % m) + m) % m;
    }

    var RGBtoCMYK = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r']/255;
        var g = rgb['g']/255;
        var b = rgb['b']/255;
        var k = 1 - (Math.max(r, g, b));
        if (k != 1) {
            var c = ((1 - r) - k) / (1 - k);
            var m = ((1 - g) - k) / (1 - k);
            var y = ((1 - b) - k) / (1 - k);
        } else {
            var c = 0;
            var m = 0;
            var y = 0;
        }
        return {c: c, m: m, y: y, k: k};
    }

    var CMYKtoRGB = function( cmyk ) {
        var r = 255 * (1-cmyk.c) * (1-cmyk.k);
        var g = 255 * (1-cmyk.m) * (1-cmyk.k);
        var b = 255 * (1-cmyk.y) * (1-cmyk.k);
        return {r: r, g: g, b: b};
    }

    var RGBtoHSL = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r'] / 255;
        var g = rgb['g'] / 255;
        var b = rgb['b'] / 255;
        var rgbOrdered = [r,g,b].sort();
        var l = ((rgbOrdered[0] + rgbOrdered[2]) / 2) * 100;
        var s, h;
        if (rgbOrdered[0] == rgbOrdered[2]) {
            s = 0;
            h = 0;
        } else {
            if (l >= 50) {
                s = ((rgbOrdered[2] - rgbOrdered[0])/((2.0 - rgbOrdered[2]) - rgbOrdered[0])) * 100;
            } else {
                s = ((rgbOrdered[2] - rgbOrdered[0])/(rgbOrdered[2] + rgbOrdered[0])) * 100;
            }
            if (rgbOrdered[2] == r) {
                h = ((g-b)/(rgbOrdered[2] - rgbOrdered[0])) * 60;
            } else if (rgbOrdered[2] == g) {
                h = (2+((b-r)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            } else {
                h = (4+((r-g)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            }
            if (h < 0) {
                h += 360;
            } else if (h > 360) {
                h = h % 360;
            }
        };
        return {
            h: h,
            s: s,
            l: l
        };
    }

    var HSLtoRGB = function( hsl ) {
        if (hsl.s == 0) {
            var grey = (hsl.l / 100) * 255;
            return {
                r: grey,
                g: grey,
                b: grey
            }
        } else {
            if (hsl.l >= 50) {
                tempOne = ((hsl.l/100) + (hsl.s/100)) - ((hsl.l/100) * (hsl.s/100));
            } else {
                tempOne = (hsl.l/100) * (1 + (hsl.s/100));
            }
            tempTwo = (2 * (hsl.l/100)) - tempOne;
            tempHue = hsl.h / 360;
            tempR = (tempHue + 0.333) % 1;
            tempG = tempHue;
            tempB = negMod((tempHue - 0.333), 1);
            var r,g,b;
            if ((6 * tempR) < 1) {
                r = tempTwo + ((tempOne - tempTwo) * 6 * tempR);
            } else if ((2 * tempR) < 1) {
                r = tempOne;
            } else if ((3 * tempR) < 2) {
                r = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempR) * 6));
            } else {
                r = tempTwo;
            }
            if ((6 * tempG) < 1) {
                g = tempTwo + ((tempOne - tempTwo) * 6 * tempG);
            } else if ((2 * tempG) < 1) {
                g = tempOne;
            } else if ((3 * tempG) < 2) {
                g = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempG) * 6));
            } else {
                g = tempTwo;
            }
            if ((6 * tempB) < 1) {
                b = tempTwo + ((tempOne - tempTwo) * 6 * tempB);
            } else if ((2 * tempB) < 1) {
                b = tempOne;
            } else if ((3 * tempB) < 2) {
                b = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempB) * 6));
            } else {
                b = tempTwo;
            }
            if (r < 0) r = 0;
            if (g < 0) g = 0;
            if (b < 0) b = 0;
            return {
                r: r * 255,
                g: g * 255,
                b: b * 255
            }
        }
    }

    var CMYKtoHSL = function( cmyk ) {
        var rgb = CMYKtoRGB(cmyk);
        return RGBtoHSL(rgb);
    }

    var HSLtoCMYK = function( hsl ) {
        var rgb = HSLtoRGB(hsl);
        return RGBtoCMYK(rgb);
    }

    var g = {
      build: function(base, shaft, end, tail) {
        return base + shaft + end + tail
      },
      base: {
        full: "8",
        half: "3"
      },
      shaftType: {
        double: "=",
        alternative: "═"
      },
      shaftLength: {
        nano: 0,
        macro: 1,
        milli: 2,
        kilo: 5,
        mega: 10,
        giga: 20,
        tera: 100
      },
      shaftBuilder: function(shaft, length) {
        return Array(length+1).join(shaft);
      },
      end: {
        circle: "D",
        circleDashed: "Ð",
        pointy: ">",
        rounded: ")",
        flat: "]"
      },
      tail: {
        wavy: "~",
        flat: "-",
        double: "="
      }
    }

    var nothing = function() {
		    noop();
	  }

	var divSort = function(numbers)
	{
		var sorted = [];
		var lilDivs = {};

		var bigDiv = document.createElement("div");
		bigDiv.style.display = "inline-block";

		for (var i = 0; i < numbers.length; i++)
		{
			var width = numbers[i];
			lilDiv = document.createElement("div");
			lilDiv.style.width = width;
			bigDiv.appendChild(lilDiv);
			lilDivs[width] = (lilDivs[width] || []).concat([lilDiv]);
		}

		document.body.appendChild(bigDiv);

		while (sorted.length < numbers.length)
		{
			var max = bigDiv.offsetWidth;
			bigDiv.removeChild(lilDivs[max].pop());
			sorted.push(max);
		}

		document.body.removeChild(bigDiv);

		return sorted;
	}

  var async_doThingTomorrow = function(cb) {
		var now = new Date();
		var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

		setTimeout(function() {
			cb(new Date());
		},  tomorrow - now);
	}

	var writeTomorrowDate = function() {
		async_doThingTomorrow(function(tomorrow) {
			document.write(tomorrow.toString());
		});
	}

    var isTrue = function(statement) {
        // Everybody lies (House, 2004)
        return false;
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;
    anything.prototype.RGBtoCMYK = RGBtoCMYK;
    anything.prototype.CMYKtoRGB = CMYKtoRGB;
    anything.prototype.RGBtoHSL = RGBtoHSL;
    anything.prototype.HSLtoRGB = HSLtoRGB;
    anything.prototype.CMYKtoHSL = CMYKtoHSL;
    anything.prototype.HSLtoCMYK = HSLtoCMYK;
    anything.prototype.g = g;
    anything.prototype.nothing = nothing;
    anything.prototype.divSort = divSort;
    anything.prototype.async_doThingTomorrow = async_doThingTomorrow;
    anything.prototype.writeTomorrowDate = writeTomorrowDate;
    anything.prototype.isTrue = isTrue;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<commit_msg>Add `returnArgument` function<commit_after>(function(window){

  /*
                    _   _     _                _
   __ _ _ __  _   _| |_| |__ (_)_ __   __ _   (_)___
  / _` | '_ \| | | | __| '_ \| | '_ \ / _` |  | / __|
 | (_| | | | | |_| | |_| | | | | | | | (_| |_ | \__ \
  \__,_|_| |_|\__, |\__|_| |_|_|_| |_|\__, (_)/ |___/
              |___/                   |___/ |__/
     */

    function anything() {

        this.version = "0.0.1"

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    function hash(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
        //from https://xkcd.com/221/
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    function negMod( n, m ) {
        return ((n % m) + m) % m;
    }

    var RGBtoCMYK = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r']/255;
        var g = rgb['g']/255;
        var b = rgb['b']/255;
        var k = 1 - (Math.max(r, g, b));
        if (k != 1) {
            var c = ((1 - r) - k) / (1 - k);
            var m = ((1 - g) - k) / (1 - k);
            var y = ((1 - b) - k) / (1 - k);
        } else {
            var c = 0;
            var m = 0;
            var y = 0;
        }
        return {c: c, m: m, y: y, k: k};
    }

    var CMYKtoRGB = function( cmyk ) {
        var r = 255 * (1-cmyk.c) * (1-cmyk.k);
        var g = 255 * (1-cmyk.m) * (1-cmyk.k);
        var b = 255 * (1-cmyk.y) * (1-cmyk.k);
        return {r: r, g: g, b: b};
    }

    var RGBtoHSL = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r'] / 255;
        var g = rgb['g'] / 255;
        var b = rgb['b'] / 255;
        var rgbOrdered = [r,g,b].sort();
        var l = ((rgbOrdered[0] + rgbOrdered[2]) / 2) * 100;
        var s, h;
        if (rgbOrdered[0] == rgbOrdered[2]) {
            s = 0;
            h = 0;
        } else {
            if (l >= 50) {
                s = ((rgbOrdered[2] - rgbOrdered[0])/((2.0 - rgbOrdered[2]) - rgbOrdered[0])) * 100;
            } else {
                s = ((rgbOrdered[2] - rgbOrdered[0])/(rgbOrdered[2] + rgbOrdered[0])) * 100;
            }
            if (rgbOrdered[2] == r) {
                h = ((g-b)/(rgbOrdered[2] - rgbOrdered[0])) * 60;
            } else if (rgbOrdered[2] == g) {
                h = (2+((b-r)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            } else {
                h = (4+((r-g)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            }
            if (h < 0) {
                h += 360;
            } else if (h > 360) {
                h = h % 360;
            }
        };
        return {
            h: h,
            s: s,
            l: l
        };
    }

    var HSLtoRGB = function( hsl ) {
        if (hsl.s == 0) {
            var grey = (hsl.l / 100) * 255;
            return {
                r: grey,
                g: grey,
                b: grey
            }
        } else {
            if (hsl.l >= 50) {
                tempOne = ((hsl.l/100) + (hsl.s/100)) - ((hsl.l/100) * (hsl.s/100));
            } else {
                tempOne = (hsl.l/100) * (1 + (hsl.s/100));
            }
            tempTwo = (2 * (hsl.l/100)) - tempOne;
            tempHue = hsl.h / 360;
            tempR = (tempHue + 0.333) % 1;
            tempG = tempHue;
            tempB = negMod((tempHue - 0.333), 1);
            var r,g,b;
            if ((6 * tempR) < 1) {
                r = tempTwo + ((tempOne - tempTwo) * 6 * tempR);
            } else if ((2 * tempR) < 1) {
                r = tempOne;
            } else if ((3 * tempR) < 2) {
                r = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempR) * 6));
            } else {
                r = tempTwo;
            }
            if ((6 * tempG) < 1) {
                g = tempTwo + ((tempOne - tempTwo) * 6 * tempG);
            } else if ((2 * tempG) < 1) {
                g = tempOne;
            } else if ((3 * tempG) < 2) {
                g = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempG) * 6));
            } else {
                g = tempTwo;
            }
            if ((6 * tempB) < 1) {
                b = tempTwo + ((tempOne - tempTwo) * 6 * tempB);
            } else if ((2 * tempB) < 1) {
                b = tempOne;
            } else if ((3 * tempB) < 2) {
                b = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempB) * 6));
            } else {
                b = tempTwo;
            }
            if (r < 0) r = 0;
            if (g < 0) g = 0;
            if (b < 0) b = 0;
            return {
                r: r * 255,
                g: g * 255,
                b: b * 255
            }
        }
    }

    var CMYKtoHSL = function( cmyk ) {
        var rgb = CMYKtoRGB(cmyk);
        return RGBtoHSL(rgb);
    }

    var HSLtoCMYK = function( hsl ) {
        var rgb = HSLtoRGB(hsl);
        return RGBtoCMYK(rgb);
    }

    var g = {
      build: function(base, shaft, end, tail) {
        return base + shaft + end + tail
      },
      base: {
        full: "8",
        half: "3"
      },
      shaftType: {
        double: "=",
        alternative: "═"
      },
      shaftLength: {
        nano: 0,
        macro: 1,
        milli: 2,
        kilo: 5,
        mega: 10,
        giga: 20,
        tera: 100
      },
      shaftBuilder: function(shaft, length) {
        return Array(length+1).join(shaft);
      },
      end: {
        circle: "D",
        circleDashed: "Ð",
        pointy: ">",
        rounded: ")",
        flat: "]"
      },
      tail: {
        wavy: "~",
        flat: "-",
        double: "="
      }
    }

    var nothing = function() {
		    noop();
	  }

	var divSort = function(numbers)
	{
		var sorted = [];
		var lilDivs = {};

		var bigDiv = document.createElement("div");
		bigDiv.style.display = "inline-block";

		for (var i = 0; i < numbers.length; i++)
		{
			var width = numbers[i];
			lilDiv = document.createElement("div");
			lilDiv.style.width = width;
			bigDiv.appendChild(lilDiv);
			lilDivs[width] = (lilDivs[width] || []).concat([lilDiv]);
		}

		document.body.appendChild(bigDiv);

		while (sorted.length < numbers.length)
		{
			var max = bigDiv.offsetWidth;
			bigDiv.removeChild(lilDivs[max].pop());
			sorted.push(max);
		}

		document.body.removeChild(bigDiv);

		return sorted;
	}

  var async_doThingTomorrow = function(cb) {
		var now = new Date();
		var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

		setTimeout(function() {
			cb(new Date());
		},  tomorrow - now);
	}

	var writeTomorrowDate = function() {
		async_doThingTomorrow(function(tomorrow) {
			document.write(tomorrow.toString());
		});
	}

    var isTrue = function(statement) {
        // Everybody lies (House, 2004)
        return false;
    }

    function returnArgument(x) {
        return x;
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;
    anything.prototype.RGBtoCMYK = RGBtoCMYK;
    anything.prototype.CMYKtoRGB = CMYKtoRGB;
    anything.prototype.RGBtoHSL = RGBtoHSL;
    anything.prototype.HSLtoRGB = HSLtoRGB;
    anything.prototype.CMYKtoHSL = CMYKtoHSL;
    anything.prototype.HSLtoCMYK = HSLtoCMYK;
    anything.prototype.g = g;
    anything.prototype.nothing = nothing;
    anything.prototype.divSort = divSort;
    anything.prototype.async_doThingTomorrow = async_doThingTomorrow;
    anything.prototype.writeTomorrowDate = writeTomorrowDate;
    anything.prototype.isTrue = isTrue;
    anything.prototype.returnArgument = returnArgument;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<|endoftext|>