<commit_before>//Fractoral Variables
var oneEight = 1 / 8; // 0.125
var oneSixth = 1 / 6; // 0.16
var oneFive = 1 / 5; // 0.2
var oneFour = 1 / 4; // 0.25
var oneThree = 1 / 3; // 0.33
var threeEight = 3 / 8; // 0.375
var twoFive = 2 / 5; // 0.4
var half = 1 / 2; // 0.5
var threeFive = 3 / 5; // 0.6
var fiveEight = 5 / 8; // 0.625
var twoThree = 2 / 3; // 0.66
var threeFour = 3 / 4; // 0.75
var fourFive = 4 / 5; // 0.8
var fiveSix = 5 / 6; // 0.83
var sevenEight = 7 / 8; // 0.875
// Addition
//
function add_oneEight() {
    var total = count + oneEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Eighth(0.125)");
    console.log(count);
}

function add_oneSix() {
    var total = count + oneSixth;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Sixth(0.16)");
    console.log(count);
}

function add_oneFive() {
    var total = count + oneFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Fith(0.2)");
    console.log(count);
}

function add_oneFour() {
    var total = count + oneFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Fourth(0.25)");
    console.log(count);
}

function add_oneThree() {
    var total = count + oneThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Third(0.33)");
    console.log(count);
}

function add_threeEight() {
    var total = count + threeEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Eighth(0.375)");
    console.log(count);
}

function add_twoFive() {
    var total = count + twoFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Two Fiths(0.4)");
    console.log(count);
}

function add_oneHalf() {
    var total = count + half;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Half(0.5)");
    console.log(count);
}

function add_threeFive() {
    var total = count + threeFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Fiths(0.6)");
    console.log(count);
}

function add_fiveEight() {
    var total = count + fiveEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Five Eigthts(0.625)");
    console.log(count);
}

function add_twoThree() {
    var total = count + twoThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Two Thirds(0.63)");
    console.log(count);
}

function add_threeFour() {
    var total = count + threeFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Fourths(0.75)");
    console.log(count);
}

function add_fourFive() {
    var total = count + fourFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Four Fiths(0.8)");
    console.log(count);
}

function add_fiveSix() {
    var total = count + fiveSix;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Five Sixth(0.83)");
    console.log(count);
}

function add_sevenEight() {
    var total = count + sevenEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Seven Eigthts(0.875)");
    console.log(count);
}
// Subtraction
//
function sub_oneEight() {
    var total = count - oneEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Eighth(0.125)");
    console.log(count);
}

function sub_oneSix() {
    var total = count - oneSixth;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Sixth(0.16)");
    console.log(count);
}

function sub_oneFive() {
    var total = count - oneFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Fith(0.2)");
    console.log(count);
}

function sub_oneFour() {
    var total = count - oneFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Fourth(0.25)");
    console.log(count);
}

function sub_oneThree() {
    var total = count - oneThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Third(0.33)");
    console.log(count);
}

function sub_threeEight() {
    var total = count - threeEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Eighth(0.375)");
    console.log(count);
}

function sub_twoFive() {
    var total = count - twoFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Two Fiths(2/5)");
    console.log(count);
}

function sub_oneHalf() {
    var total = count - half;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Half(0.5)");
    console.log(count);
}

function sub_threeFive() {
    var total = count - threeFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Fiths(0.6)");
    console.log(count);
}

function sub_fiveEight() {
    var total = count - fiveEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Five Eighths(0.625)");
    console.log(count);
}

function sub_twoThree() {
    var total = count - twoThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Two Thirds(0.33)");
    console.log(count);
}

function sub_threeFour() {
    var total = count - threeFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Fourths(0.75)");
    console.log(count);
}

function sub_fourFive() {
    var total = count - fourFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Four Fiths(0.8)");
    console.log(count);
}

function sub_fiveSix() {
    var total = count - fiveSix;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Five Sixths(0.83)");
    console.log(count);
}

function sub_sevenEight() {
    var total = count - sevenEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Seven Eigthts(0.875)");
    console.log(count);
}<commit_msg>Fixed twoThree<commit_after>//Fractoral Variables
var oneEight = 1 / 8; // 0.125
var oneSixth = 1 / 6; // 0.16
var oneFive = 1 / 5; // 0.2
var oneFour = 1 / 4; // 0.25
var oneThree = 1 / 3; // 0.33
var threeEight = 3 / 8; // 0.375
var twoFive = 2 / 5; // 0.4
var half = 1 / 2; // 0.5
var threeFive = 3 / 5; // 0.6
var fiveEight = 5 / 8; // 0.625
var twoThree = 2 / 3; // 0.66
var threeFour = 3 / 4; // 0.75
var fourFive = 4 / 5; // 0.8
var fiveSix = 5 / 6; // 0.83
var sevenEight = 7 / 8; // 0.875
// Addition
//
function add_oneEight() {
    var total = count + oneEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Eighth(0.125)");
    console.log(count);
}

function add_oneSix() {
    var total = count + oneSixth;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Sixth(0.16)");
    console.log(count);
}

function add_oneFive() {
    var total = count + oneFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Fith(0.2)");
    console.log(count);
}

function add_oneFour() {
    var total = count + oneFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Fourth(0.25)");
    console.log(count);
}

function add_oneThree() {
    var total = count + oneThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Third(0.33)");
    console.log(count);
}

function add_threeEight() {
    var total = count + threeEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Eighth(0.375)");
    console.log(count);
}

function add_twoFive() {
    var total = count + twoFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Two Fiths(0.4)");
    console.log(count);
}

function add_oneHalf() {
    var total = count + half;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added One Half(0.5)");
    console.log(count);
}

function add_threeFive() {
    var total = count + threeFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Fiths(0.6)");
    console.log(count);
}

function add_fiveEight() {
    var total = count + fiveEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Five Eigthts(0.625)");
    console.log(count);
}

function add_twoThree() {
    var total = count + twoThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Two Thirds(0.66)");
    console.log(count);
}

function add_threeFour() {
    var total = count + threeFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Three Fourths(0.75)");
    console.log(count);
}

function add_fourFive() {
    var total = count + fourFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Four Fiths(0.8)");
    console.log(count);
}

function add_fiveSix() {
    var total = count + fiveSix;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Five Sixth(0.83)");
    console.log(count);
}

function add_sevenEight() {
    var total = count + sevenEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Added Seven Eigthts(0.875)");
    console.log(count);
}
// Subtraction
//
function sub_oneEight() {
    var total = count - oneEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Eighth(0.125)");
    console.log(count);
}

function sub_oneSix() {
    var total = count - oneSixth;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Sixth(0.16)");
    console.log(count);
}

function sub_oneFive() {
    var total = count - oneFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Fith(0.2)");
    console.log(count);
}

function sub_oneFour() {
    var total = count - oneFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Fourth(0.25)");
    console.log(count);
}

function sub_oneThree() {
    var total = count - oneThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Third(0.33)");
    console.log(count);
}

function sub_threeEight() {
    var total = count - threeEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Eighth(0.375)");
    console.log(count);
}

function sub_twoFive() {
    var total = count - twoFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Two Fiths(2/5)");
    console.log(count);
}

function sub_oneHalf() {
    var total = count - half;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted One Half(0.5)");
    console.log(count);
}

function sub_threeFive() {
    var total = count - threeFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Fiths(0.6)");
    console.log(count);
}

function sub_fiveEight() {
    var total = count - fiveEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Five Eighths(0.625)");
    console.log(count);
}

function sub_twoThree() {
    var total = count - twoThree;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Two Thirds(0.66)");
    console.log(count);
}

function sub_threeFour() {
    var total = count - threeFour;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Three Fourths(0.75)");
    console.log(count);
}

function sub_fourFive() {
    var total = count - fourFive;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Four Fiths(0.8)");
    console.log(count);
}

function sub_fiveSix() {
    var total = count - fiveSix;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Five Sixths(0.83)");
    console.log(count);
}

function sub_sevenEight() {
    var total = count - sevenEight;
    document.getElementById('final').innerHTML = total;
    if (count !== count);
    count = total;
    console.log("Subtracted Seven Eigthts(0.875)");
    console.log(count);
}<|endoftext|>


<commit_before>
import React, { Component } from 'react';

import GivingChart from './GivingChart.js';

const styles = {
  container: {
    marginTop: '2rem',
    flexDirection: 'columns',
  },
  rowContainer: {
    flexDirection: 'row',
    display: 'flex',
  },
  leftRightPadding: {
    margin: '0rem 2rem',
  },
  allPadding: {
    margin: '2rem',
  },
  rightAlignedText: {
    textAlign: 'right',
  }
}

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      year: "2017",
      month: "January",
      giving: 13,
      budget: 20,
      errorMessages: [],
    };

    this.checkForErrors = this.checkForErrors.bind(this);

    this.changedYear = this.changedYear.bind(this);
    this.changedMonth = this.changedMonth.bind(this);
    this.changedGiving = this.changedGiving.bind(this);
    this.changedBudget = this.changedBudget.bind(this);
    this.saveGraph = this.saveGraph.bind(this);
  }

  changedYear(event) {
    this.setState({year: event.target.value});
  }

  changedMonth(event) {
    this.setState({month: event.target.value});
  }

  checkForErrors(error, value) {
    const { errorMessages } = this.state;

    if (value <= 0) {
      if (!errorMessages.includes(error)) {
        this.setState({
          errorMessages: [...errorMessages, error],
        });
      }
    } else {
      this.setState({
        errorMessages: errorMessages.filter((item) => {
          return item !== error;
        })
      });
    }
  }

  changedGiving(event) {
    const value = parseInt(event.target.value, 10);
    this.checkForErrors('Giving cannot be 0 or negative', value);
    this.setState({giving: value});
  }

  changedBudget(event) {
    const value = parseInt(event.target.value, 10);
    this.checkForErrors('Budget cannot be 0 or negative', value);
    this.setState({budget: value});
  }

  saveGraph(event) {
    const imageData = this.refs.givingChart.getImageData();
    this.refs.downloadButton.href = imageData;
  }

  render() {
    const {
      year,
      month,
      giving,
      budget,
      errorMessages,
    } = this.state;

    let errorBox;
    let graph;
    let saveButton;
    if (errorMessages.length !== 0) {
      errorBox = (

            {errorMessages.join('\n')}

      );

      saveButton = (
        <button
          style={styles.allPadding}
          disabled
          className="button-primary"
        >
          Save Chart
        </button>
      );
    } else {
      graph = (

          <GivingChart
            ref="givingChart"
            year={year}
            month={month}
            giving={giving}
            budget={budget}
          />

      );

      const downloadTitle = `${month} ${year} Giving Chart`;
      saveButton = (

          Save Chart

      );
    }

    return (

Giving Chart Generator

            Month
            <select
              value={month}
              onChange={this.changedMonth}
            >
              <option value="January">January</option>
              <option value="February">February</option>
              <option value="March">March</option>
              <option value="April">April</option>
              <option value="May">May</option>
              <option value="June">June</option>
              <option value="July">July</option>
              <option value="August">August</option>
              <option value="September">September</option>
              <option value="October">October</option>
              <option value="November">November</option>
              <option value="December">December</option>
            </select>

            Year
            <select
              value={year}
              onChange={this.changedYear}
            >
              <option value="2025">2025</option>
              <option value="2024">2024</option>
              <option value="2023">2023</option>
              <option value="2022">2022</option>
              <option value="2021">2021</option>
              <option value="2020">2020</option>
              <option value="2019">2019</option>
              <option value="2018">2018</option>
              <option value="2017">2017</option>
            </select>

            Giving
            <input
              ref="giving"
              type="number"
              style={styles.rightAlignedText}
              value={giving}
              onChange={this.changedGiving}
            />

            Budget
            <input
              ref="budget"
              type="number"
              style={styles.rightAlignedText}
              value={budget}
              onChange={this.changedBudget}
            />

        {errorBox}
        {graph}

          {saveButton}

    );
  }
}

export default App;
<commit_msg>Prevent parseInt on empty string<commit_after>
import React, { Component } from 'react';

import GivingChart from './GivingChart.js';

const styles = {
  container: {
    marginTop: '2rem',
    flexDirection: 'columns',
  },
  rowContainer: {
    flexDirection: 'row',
    display: 'flex',
  },
  leftRightPadding: {
    margin: '0rem 2rem',
  },
  allPadding: {
    margin: '2rem',
  },
  rightAlignedText: {
    textAlign: 'right',
  }
}

function isEmpty(str) {
  return (!str || 0 === str.length);
}

function liberalParseInt(value) {
  return isEmpty(value) ? 0 : parseInt(value, 10);
}

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      year: "2017",
      month: "January",
      giving: 13,
      budget: 20,
      errorMessages: [],
    };

    this.checkForErrors = this.checkForErrors.bind(this);

    this.changedYear = this.changedYear.bind(this);
    this.changedMonth = this.changedMonth.bind(this);
    this.changedGiving = this.changedGiving.bind(this);
    this.changedBudget = this.changedBudget.bind(this);
    this.saveGraph = this.saveGraph.bind(this);
  }

  changedYear(event) {
    this.setState({year: event.target.value});
  }

  changedMonth(event) {
    this.setState({month: event.target.value});
  }

  checkForErrors(error, value) {
    const { errorMessages } = this.state;

    if (value <= 0) {
      if (!errorMessages.includes(error)) {
        this.setState({
          errorMessages: [...errorMessages, error],
        });
      }
    } else {
      this.setState({
        errorMessages: errorMessages.filter((item) => {
          return item !== error;
        })
      });
    }
  }

  changedGiving(event) {
    const value = liberalParseInt(event.target.value, 10);
    this.checkForErrors('Giving cannot be 0', value);
    this.setState({giving: value});
  }

  changedBudget(event) {
    const value = liberalParseInt(event.target.value, 10);
    this.checkForErrors('Budget cannot be 0', value);
    this.setState({budget: value});
  }

  saveGraph(event) {
    const imageData = this.refs.givingChart.getImageData();
    this.refs.downloadButton.href = imageData;
  }

  render() {
    const {
      year,
      month,
      giving,
      budget,
      errorMessages,
    } = this.state;

    let errorBox;
    let graph;
    let saveButton;
    if (errorMessages.length !== 0) {
      errorBox = (

            {errorMessages.join('\n')}

      );

      saveButton = (
        <button
          style={styles.allPadding}
          disabled
          className="button-primary"
        >
          Save Chart
        </button>
      );
    } else {
      graph = (

          <GivingChart
            ref="givingChart"
            year={year}
            month={month}
            giving={giving}
            budget={budget}
          />

      );

      const downloadTitle = `${month} ${year} Giving Chart`;
      saveButton = (

          Save Chart

      );
    }

    return (

Giving Chart Generator

            Month
            <select
              value={month}
              onChange={this.changedMonth}
            >
              <option value="January">January</option>
              <option value="February">February</option>
              <option value="March">March</option>
              <option value="April">April</option>
              <option value="May">May</option>
              <option value="June">June</option>
              <option value="July">July</option>
              <option value="August">August</option>
              <option value="September">September</option>
              <option value="October">October</option>
              <option value="November">November</option>
              <option value="December">December</option>
            </select>

            Year
            <select
              value={year}
              onChange={this.changedYear}
            >
              <option value="2025">2025</option>
              <option value="2024">2024</option>
              <option value="2023">2023</option>
              <option value="2022">2022</option>
              <option value="2021">2021</option>
              <option value="2020">2020</option>
              <option value="2019">2019</option>
              <option value="2018">2018</option>
              <option value="2017">2017</option>
            </select>

            Giving
            <input
              ref="giving"
              type="number"
              style={styles.rightAlignedText}
              value={giving}
              onChange={this.changedGiving}
            />

            Budget
            <input
              ref="budget"
              type="number"
              style={styles.rightAlignedText}
              value={budget}
              onChange={this.changedBudget}
            />

        {errorBox}
        {graph}

          {saveButton}

    );
  }
}

export default App;
<|endoftext|>


<commit_before>const Duplex = require("stream").Duplex;

class QueueStream extends Duplex {
  constructor(queue,options) {
		options = options || {};
		options.objectMode = true;

    super(options);
		this.queue = queue;
  }

	_write(chunk, encoding, callback) {
		this.queue.push(chunk,callback);
  }

  async _read(size) {
		try {
			let data = await this.queue.peek();
			this.push(data);
		}catch(err) {
			this.emit('error', err);
		}
  }
}

module.exports = QueueStream;
<commit_msg>queueStream managed error<commit_after>const
	logger = require('../logger'),
	Duplex = require("stream").Duplex;

class QueueStream extends Duplex {
  constructor(queue,options) {
		options = options || {};
		options.objectMode = true;

    super(options);
		this.queue = queue;
  }

	_write(chunk, encoding, callback) {
		this.queue.push(chunk,callback);
  }

  async _read(size) {
		let read = false;

		while(!read) {
			try {
				let data = await this.queue.peek();
				this.push(data);
				read = true;
			}catch(err) {
				logger.error(err);
				this.emit('stream_error', err);
			}
		}
  }
}

module.exports = QueueStream;
<|endoftext|>


<commit_before>var instances = require('./../taillard');
var seed = require('./../seed-random');
var Timer = require('./../timer');
var NEH = require('./../neh');
var IG = require('./../ig');

// Number of jobs and machines
var jobs = 100;
var machines = 5;

// Filter Taillard instances by jobs and machines
var filteredInstances = instances.filter(jobs, machines);

// Relative percentage deviation
var rpdNEH = 0;
var rpdIG = 0;

// Reset timer
Timer.reset();

console.log('PROCESSING');
console.log('______________________________________________________________');

// Iterate over filtered instances
for(var i = 0; i < filteredInstances.length; i++) {

    // Overwrite Math.random by number generator with seed
    seed(filteredInstances[i].initialSeed, true);

    // Apply algorithms
    var $NEH = NEH.apply(filteredInstances[i].data);
    var $IG = IG.apply(filteredInstances[i].data);

    rpdNEH = rpdNEH + NEH.rpd(NEH.makespan($NEH), filteredInstances[i].upperBound);
    rpdIG = rpdIG + IG.rpd(IG.makespan($IG), filteredInstances[i].upperBound);

    console.log('          NAME:', filteredInstances[i].initialSeed);
    console.log('  NEH MAKESPAN:', NEH.makespan($NEH));
    console.log('      MAKESPAN:', IG.makespan($IG));
    console.log('  TIME ELAPSED:', Timer.diff(true) / 1000, 'SECS');
    console.log('______________________________________________________________');

}

console.log('      INSTANCE:', jobs + ' x ' + machines);
console.log('       RPD NEH:', Math.round(rpdNEH / filteredInstances.length * 100) / 100, '%');
console.log('        RPD IG:', Math.round(rpdIG / filteredInstances.length * 100) / 100, '%');
<commit_msg>Corrected to 20 jobs<commit_after>var instances = require('./../taillard');
var seed = require('./../seed-random');
var Timer = require('./../timer');
var NEH = require('./../neh');
var IG = require('./../ig');

// Number of jobs and machines
var jobs = 20;
var machines = 5;

// Filter Taillard instances by jobs and machines
var filteredInstances = instances.filter(jobs, machines);

// Relative percentage deviation
var rpdNEH = 0;
var rpdIG = 0;

// Reset timer
Timer.reset();

console.log('PROCESSING');
console.log('______________________________________________________________');

// Iterate over filtered instances
for(var i = 0; i < filteredInstances.length; i++) {

    // Overwrite Math.random by number generator with seed
    seed(filteredInstances[i].initialSeed, true);

    // Apply algorithms
    var $NEH = NEH.apply(filteredInstances[i].data);
    var $IG = IG.apply(filteredInstances[i].data);

    rpdNEH = rpdNEH + NEH.rpd(NEH.makespan($NEH), filteredInstances[i].upperBound);
    rpdIG = rpdIG + IG.rpd(IG.makespan($IG), filteredInstances[i].upperBound);

    console.log('          NAME:', filteredInstances[i].initialSeed);
    console.log('  NEH MAKESPAN:', NEH.makespan($NEH));
    console.log('      MAKESPAN:', IG.makespan($IG));
    console.log('  TIME ELAPSED:', Timer.diff(true) / 1000, 'SECS');
    console.log('______________________________________________________________');

}

console.log('      INSTANCE:', jobs + ' x ' + machines);
console.log('       RPD NEH:', Math.round(rpdNEH / filteredInstances.length * 100) / 100, '%');
console.log('        RPD IG:', Math.round(rpdIG / filteredInstances.length * 100) / 100, '%');
<|endoftext|>


<commit_before>'use strict';

var canvasWidth = 1366;
var canvasHeight = 768;

var game = new Phaser.Game(canvasWidth, canvasHeight, Phaser.AUTO, '', {
    preload: preload,
    create:  create,
    update:  update
});

function preload() {
    game.load.image('mg',       'assets/sprites/mg.png');
    game.load.image('santa',    'assets/sprites/santa.png');
    game.load.image('girl',     'assets/sprites/girl.png');
    game.load.image('platform', 'assets/sprites/platform.png');
    game.load.image('bullet',   'assets/sprites/bullet.png');
    game.load.image('present',  'assets/sprites/present.png');
}

var santa;
var children;
var bullets;
var platforms;
var presents;
var machineGun;
var points;
var gameOver;

var keycodes = {
    left  : [ 'a', 'ArrowLeft'],
    up    : [ 'w', 'ArrowUp', ' '],
    right : [ 'd', 'ArrowRight'],
    down  : [ 's', 'ArrowDown'],
    action: [ 'e']
};

function create() {
    points = new PointsManager();
    santa = new Santa();
    gameOver = new GameOver();
    game.stage.backgroundColor = "#ddffdd";

    platforms = game.add.group();
    platforms.enableBody = true;
    var ground = platforms.create(0, game.world.height - 64, 'platform');
    ground.scale.setTo(2, 1);
    ground.body.immovable = true;
    //var ledge = platforms.create(400, 400, 'platform');
    //ledge.body.immovable = true;

    presents = new PresentPile();

    var childGroup = game.add.group();
    children = new ChildManager(childGroup);
    machineGun = new MachineGun();

    game.input.keyboard.onDownCallback = function(event) {
        if(keycodes.left.includes(event.key)) {
            // ← left
            santa.movement.left = true;
        }
        else if(keycodes.right.includes(event.key)) {
            // → right
            santa.movement.right = true;
        }
        else if(keycodes.up.includes(event.key)) {
            // ↑ up
            santa.movement.up = true;
        }
        else if(keycodes.down.includes(event.key)) {
            // ↓ down
            santa.movement.down = true;
        }
    };
    game.input.keyboard.onUpCallback = function(event) {
        if(keycodes.action.includes(event.key)) {
            // E action
            santa.use(machineGun);
        }
        else if(keycodes.left.includes(event.key)) {
            // ← left
            santa.movement.left = false;
        }
        else if(keycodes.right.includes(event.key)) {
            // → right
            santa.movement.right = false;
        }
        else if(keycodes.up.includes(event.key)) {
            // ↑ up
            santa.movement.up = false;
        }
        else if(keycodes.down.includes(event.key)) {
            // ↓ down
            santa.movement.down = false;
        }
    };

}

function update() {
    // physics goes first, to make sure the updates work properly
    game.physics.arcade.collide(santa.santa, platforms);
    game.physics.arcade.collide(machineGun.bulletsGroup, children.childGroup, killChild);

    children.update(presents);
    machineGun.update();
    santa.update(presents);
    presents.update(gameOver);
    gameOver.update();

    if(game.input.activePointer.isDown) {
        machineGun.fireBullet();
    }

    function killChild(bullet, child) {
        if(child.present != undefined) {
            presents.dropPresent(child.present);
        }
        else {
            // drop ammo, but should the children holding presents drop ammo too?
        }
        machineGun.bulletsGroup.remove(bullet);
        children.childGroup.remove(child);
        if(child.from) {
            points.add(child.points.from);
        }
        else {
            points.add(child.points.to);
        }
        bullet.kill();
        child.kill();
    };
}
<commit_msg>introducing a primitive state system<commit_after>'use strict';

var canvasWidth = 1366;
var canvasHeight = 768;

var game = new Phaser.Game(canvasWidth, canvasHeight, Phaser.AUTO, '', {
    preload: preload,
    create:  create,
    update:  update
});

function preload() {
    game.load.image('mg',       'assets/sprites/mg.png');
    game.load.image('santa',    'assets/sprites/santa.png');
    game.load.image('girl',     'assets/sprites/girl.png');
    game.load.image('platform', 'assets/sprites/platform.png');
    game.load.image('bullet',   'assets/sprites/bullet.png');
    game.load.image('present',  'assets/sprites/present.png');
}

var santa;
var children;
var bullets;
var platforms;
var presents;
var machineGun;
var points;
var gameOver;
var states;
var state;

var keycodes = {
    left  : ['a', 'ArrowLeft'],
    up    : ['w', 'ArrowUp', ' '],
    right : ['d', 'ArrowRight'],
    down  : ['s', 'ArrowDown'],
    action: ['e']
};

function create() {
    points = new PointsManager();
    santa = new Santa();
    gameOver = new GameOver();
    game.stage.backgroundColor = "#ddffdd";
    states = Object.freeze({
        SPLASH: 0,
        MENU: 1
    });
    state = states.SPLASH;

    platforms = game.add.group();
    platforms.enableBody = true;
    var ground = platforms.create(0, game.world.height - 64, 'platform');
    ground.scale.setTo(2, 1);
    ground.body.immovable = true;
    //var ledge = platforms.create(400, 400, 'platform');
    //ledge.body.immovable = true;

    presents = new PresentPile();

    var childGroup = game.add.group();
    children = new ChildManager(childGroup);
    machineGun = new MachineGun();

    game.input.keyboard.onDownCallback = function(event) {
        if(keycodes.left.includes(event.key)) {
            // ← left
            santa.movement.left = true;
        }
        else if(keycodes.right.includes(event.key)) {
            // → right
            santa.movement.right = true;
        }
        else if(keycodes.up.includes(event.key)) {
            // ↑ up
            santa.movement.up = true;
        }
        else if(keycodes.down.includes(event.key)) {
            // ↓ down
            santa.movement.down = true;
        }
    };
    game.input.keyboard.onUpCallback = function(event) {
        if(keycodes.action.includes(event.key)) {
            // E action
            santa.use(machineGun);
        }
        else if(keycodes.left.includes(event.key)) {
            // ← left
            santa.movement.left = false;
        }
        else if(keycodes.right.includes(event.key)) {
            // → right
            santa.movement.right = false;
        }
        else if(keycodes.up.includes(event.key)) {
            // ↑ up
            santa.movement.up = false;
        }
        else if(keycodes.down.includes(event.key)) {
            // ↓ down
            santa.movement.down = false;
        }
    };

}

function update() {
    if(state == states.SPLASH) {
    }
    // physics goes first, to make sure the updates work properly
    game.physics.arcade.collide(santa.santa, platforms);
    game.physics.arcade.collide(machineGun.bulletsGroup, children.childGroup, killChild);

    children.update(presents);
    machineGun.update();
    santa.update(presents);
    presents.update(gameOver);
    gameOver.update();

    if(game.input.activePointer.isDown) {
        machineGun.fireBullet();
    }

    function killChild(bullet, child) {
        if(child.present != undefined) {
            presents.dropPresent(child.present);
        }
        else {
            // drop ammo, but should the children holding presents drop ammo too?
        }
        machineGun.bulletsGroup.remove(bullet);
        children.childGroup.remove(child);
        if(child.from) {
            points.add(child.points.from);
        }
        else {
            points.add(child.points.to);
        }
        bullet.kill();
        child.kill();
    };
}
<|endoftext|>


<commit_before>import {promises as jsonld} from 'jsonld'
import urltemplate from 'url-template'

const PartialCollectionView = 'PartialCollectionView'
const IriTemplate = 'IriTemplate'

const COVAPI_NS = 'http://coverageapi.org/ns#'
const COVAPI_API = COVAPI_NS + 'api'
const CanInclude = COVAPI_NS + 'canInclude'

const COVJSON_NS = 'http://coveragejson.org/def#'
const Domain = COVJSON_NS + 'Domain'
const Range = COVJSON_NS + 'Range'

const OSGEO_NS = 'http://a9.com/-/opensearch/extensions/geo/1.0/'
const OSTIME_NS = 'http://a9.com/-/opensearch/extensions/time/1.0/'

const URL_PROPS = {
    filterBbox: OSGEO_NS + 'box',
    filterTimeStart: OSTIME_NS + 'start',
    filterTimeEnd: OSTIME_NS + 'end',
    filterVerticalStart: COVAPI_NS + 'verticalStart',
    filterVerticalEnd: COVAPI_NS + 'verticalEnd',
    subsetBbox: COVAPI_NS + 'subsetBbox',
    subsetTimeStart: COVAPI_NS + 'subsetTimeStart',
    subsetTimeEnd: COVAPI_NS + 'subsetTimeEnd',
    subsetVerticalStart: COVAPI_NS + 'subsetVerticalStart',
    subsetVerticalEnd: COVAPI_NS + 'subsetVerticalEnd',
    subsetVerticalTarget: COVAPI_NS + 'subsetVerticalTarget',
    subsetIndex: COVAPI_NS + 'subsetIndex'
}

const FRAME_CONTEXT = [
   // partial copy of http://www.hydra-cg.com/spec/latest/core/core.jsonld
   {
     "hydra": "http://www.w3.org/ns/hydra/core#",
     "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
     "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
     "xsd": "http://www.w3.org/2001/XMLSchema#",
     "owl": "http://www.w3.org/2002/07/owl#",
     "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
     "dc": "http://purl.org/dc/terms/",
     "cc": "http://creativecommons.org/ns#",
     "property": { "@id": "hydra:property", "@type": "@vocab" },
     "required": "hydra:required",
     "view": { "@id": "hydra:view", "@type": "@id" },
     "PartialCollectionView": "hydra:PartialCollectionView",
     "totalItems": "hydra:totalItems",
     "first": { "@id": "hydra:first", "@type": "@id" },
     "last": { "@id": "hydra:last", "@type": "@id" },
     "next": { "@id": "hydra:next", "@type": "@id" },
     "previous": { "@id": "hydra:previous", "@type": "@id" },
     "IriTemplate": "hydra:IriTemplate",
     "template": "hydra:template",
     "mapping": "hydra:mapping",
     "IriTemplateMapping": "hydra:IriTemplateMapping",
     "variable": "hydra:variable"
   },
   {
     'id': '@id',
     'type': '@type',
     // Hydra has "@type": "@vocab" which confuses the compaction -> we override it as workaround
     // see https://github.com/json-ld/json-ld.org/issues/400
     // we also want the full object form anyway, which we can force by omitting "@type"
     "property": { "@id": "hydra:property" },
     'api': COVAPI_API
     }
   ]

/**
 * Extracts API information from the given Coverage/CoverageCollection object
 * and returns an API object.
 */
export function discover (cov) {
  // Our main source of API information comes from data within the .ld property.
  // To query that we need the id of the coverage or coveragecollection.
  if (!cov.id) {
    return Promise.resolve(new API())
  }
  return jsonld.frame(cov.ld, {
    '@context': FRAME_CONTEXT,
    id: cov.id
  })
  .then(framed => jsonld.compact(framed, framed['@context']))
  .then(compacted => new API(compacted))
}

export class API {
  /**
   * @param ld A framed and compacted JSON-LD document from which Hydra data can be read.
   */
  constructor (ld) {
    this.supportedUrlProps = new Map()

    if (!ld) return
    console.log(ld)

    if (ld.view && ld.view.type === PartialCollectionView) {
      this.isPaged = true
      this.paging = ld.view
      this.paging.total = ld.totalItems

      console.log(ld.view)
    }

    if (ld.api && ld.api.type === IriTemplate) {
      this.hasUrlTemplate = true
      this.urlTemplate = ld.api
      console.log('URL template: ' + ld.api.template)

      let mappings = ld.api.mapping
      for (let mapping of mappings) {
        let propId = mapping.property.id
        for (let prop in URL_PROPS) {
          if (URL_PROPS[prop] === propId) {
            console.log('property recognized: ' + propId + ' (variable: ' + mapping.variable + ')')
            this.supportedUrlProps.set(propId, mapping.variable)
          }
        }
      }

      console.log(ld.api)
    }

    if (ld[CanInclude]) {
      // server supports optional inclusion via Prefer header
      this.supportsPreferHeaders = true
    }

    this._createCapabilities()
  }

  get supportsBboxFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterBbox)
  }

  get supportsBboxSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetBbox)
  }

  get supportsTimeFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterTimeEnd)
  }

  get supportsTimeSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetTimeEnd)
  }

  get supportsVerticalFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterVerticalEnd)
  }

  get supportsVerticalSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetVerticalEnd)
  }

  get supportsVerticalTargetSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalTarget)
  }

  get supportsIndexSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetIndex)
  }

  _createCapabilities () {
    let caps = {
      filter: {},
      subset: {},
      embed: {}
    }
    let startstop = () => ({
      start: true,
      stop: true
    })
    if (this.supportsBboxFiltering) {
      // 'x' is not the axis name, it just represents the x-axis in a horizontal CRS
      caps.filter.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.filter.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeFiltering) {
      caps.filter.time = startstop()
    }
    if (this.supportsVerticalFiltering) {
      caps.filter.vertical = startstop()
    }
    if (this.supportsBboxSubsetting) {
      caps.subset.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.subset.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeSubsetting) {
      caps.subset.time = startstop()
    }
    if (this.supportsVerticalSubsetting) {
      caps.subset.vertical = startstop()
    }
    if (this.supportsVerticalTargetSubsetting) {
      if (!caps.subset.vertical) {
        caps.subset.vertical = {}
      }
      caps.subset.vertical.target = true
    }
    if (this.supportsIndexSubsetting) {
      caps.subset.index = {
        start: true,
        stop: true,
        step: true
      }
    }
    if (this.supportsPreferHeaders) {
      caps.embed = {
        domain: true,
        range: true
      }
    }
    this.capabilities = caps
  }

  /**
   * Option keys: time, x, y, vertical, embed
   *
   * Each value except for 'embed' is one of (check this.capabilities to see which ones are supported!):
   *
   * {start, stop} // intersect match
   *
   * 'embed' is an object {domain: true, range: true} where both members are optional.
   */
  _getFilterTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeFiltering) {
        throw new Error('Time filtering not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.vertical) {
      if (!this.supportsVerticalFiltering) {
        throw new Error('Vertical filtering not supported!')
      }
      let start = getNumberString(options.vertical.start)
      let end = getNumberString(options.vertical.stop)
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalStart)] = start
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalEnd)] = end
      delete options.vertical
    }
    if (options.x) {
      if (!this.supportsBboxFiltering) {
        throw new Error('BBOX filtering not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    checkEmpty(options, 'Unrecognized filter options')

    return templateVars
  }

  /**
   * Option keys: time, x, y, vertical, index
   *
   * Each value is one of (check this.capabilities to see which ones are supported!):
   *
   * For time, x, y, vertical:
   * ISO string // exact match (time)
   * number // exact match (x, y, vertical) <- typically not supported by API
   * {start, stop} // intersect match
   * {target} // nearest neighbor match
   *
   * For index:
   * {<axisName>: integer, ...}
   * {<axisName>: {start,stop[,step]}, ...}
   */
  _getSubsetTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeSubsetting) {
        throw new Error('Time subsetting not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.x) {
      if (!this.supportsBboxSubsetting) {
        throw new Error('BBOX subsetting not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    if (options.vertical) {
      if (options.vertical.target) {
        if (!this.supportsVerticalTargetSubsetting) {
          throw new Error('vertical target subsetting not supported!')
        }
        let target = getNumberString(options.vertical.target)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalTarget)] = target
      }
      if (options.vertical.start) {
        if (!this.supportsVerticalSubsetting) {
          throw new Error('vertical subsetting not supported!')
        }
        let start = getNumberString(options.vertical.start)
        let end = getNumberString(options.vertical.stop)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalStart)] = start
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalEnd)] = end
      }
      delete options.vertical
    }
    if (options.index) {
      if (!this.supportsIndexSubsetting) {
        throw new Error('index subsetting not supported!')
      }
      let strings = []
      for (let axis of Object.keys(options.index)) {
        strings.push(getIndexSubsetString(axis, options.index[axis]))
      }
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetIndex)] = strings
    }
    checkEmpty(options, 'Unrecognized subset options')

    return templateVars
  }

  _getIncludeDomainAndRangeHeaders (options = {}) {
    if (!this.supportsPreferHeaders) {
      return {}
    }
    let uris = []
    if (options.domain) {
      uris.push(Domain)
    }
    if (options.range) {
      uris.push(Range)
    }
    return {
      Prefer: 'return=representation; ' +
              'include="' + uris.join(' ') + '"'
    }
  }

  getUrlAndHeaders (options) {
    // deep-copy as we delete properties after they are applied
    options = JSON.parse(JSON.stringify(options))
    let subsetTemplateVars = this._getSubsetTemplateVars(options.subset)
    let filterTemplateVars = this._getFilterTemplateVars(options.filter)

    let templateVars = subsetTemplateVars
    for (let key in filterTemplateVars) {
      templateVars[key] = filterTemplateVars[key]
    }

    let url = urltemplate.parse(this.urlTemplate.template).expand(templateVars)
    let headers = this._getIncludeDomainAndRangeHeaders(options.embed)
    return {url, headers}
  }

}

function checkEmpty (obj, err) {
  if (Object.keys(obj).length > 0) {
    throw new Error(err)
  }
}

function getBboxString (bbox) {
  return bbox.map(getNumberString).join(',')
}

/**
 * Converts a number to a decimal string in non-scientific notation.
 */
function getNumberString (num) {
  // try toString() to avoid trailing zeros from toFixed()
  let str = num.toString()
  // if this resulted in scientific notation, use toFixed() instead
  if (str.indexOf('e') !== -1) {
    str = num.toFixed(20)
  }
  return str
}

function getIndexSubsetString (axis, spec) {
  let slice
  if (typeof spec === 'number') {
    slice = getNumberString(spec)
  } else if (spec.start === spec.stop && (!spec.step || spec.step === 1)) {
    slice = getNumberString(spec.start)
  } else {
    slice = getNumberString(spec.start) + ':' + getNumberString(stop)
    if (spec.step) {
      slice += ':' + getNumberString(spec.step)
    }
  }
  return axis + '[' + slice + ']'
}

<commit_msg>use custom jsonld context loader to avoid delay and network issues<commit_after>import {promises as jsonld, default as jsonldOriginal} from 'jsonld'
import urltemplate from 'url-template'

const PartialCollectionView = 'PartialCollectionView'
const IriTemplate = 'IriTemplate'

const COVAPI_NS = 'http://coverageapi.org/ns#'
const COVAPI_API = COVAPI_NS + 'api'
const CanInclude = COVAPI_NS + 'canInclude'

const COVJSON_NS = 'http://coveragejson.org/def#'
const Domain = COVJSON_NS + 'Domain'
const Range = COVJSON_NS + 'Range'

const OSGEO_NS = 'http://a9.com/-/opensearch/extensions/geo/1.0/'
const OSTIME_NS = 'http://a9.com/-/opensearch/extensions/time/1.0/'

const URL_PROPS = {
    filterBbox: OSGEO_NS + 'box',
    filterTimeStart: OSTIME_NS + 'start',
    filterTimeEnd: OSTIME_NS + 'end',
    filterVerticalStart: COVAPI_NS + 'verticalStart',
    filterVerticalEnd: COVAPI_NS + 'verticalEnd',
    subsetBbox: COVAPI_NS + 'subsetBbox',
    subsetTimeStart: COVAPI_NS + 'subsetTimeStart',
    subsetTimeEnd: COVAPI_NS + 'subsetTimeEnd',
    subsetVerticalStart: COVAPI_NS + 'subsetVerticalStart',
    subsetVerticalEnd: COVAPI_NS + 'subsetVerticalEnd',
    subsetVerticalTarget: COVAPI_NS + 'subsetVerticalTarget',
    subsetIndex: COVAPI_NS + 'subsetIndex'
}

const FRAME_CONTEXT = [
   // partial copy of http://www.hydra-cg.com/spec/latest/core/core.jsonld
   {
     "hydra": "http://www.w3.org/ns/hydra/core#",
     "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
     "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
     "xsd": "http://www.w3.org/2001/XMLSchema#",
     "owl": "http://www.w3.org/2002/07/owl#",
     "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
     "dc": "http://purl.org/dc/terms/",
     "cc": "http://creativecommons.org/ns#",
     "property": { "@id": "hydra:property", "@type": "@vocab" },
     "required": "hydra:required",
     "view": { "@id": "hydra:view", "@type": "@id" },
     "PartialCollectionView": "hydra:PartialCollectionView",
     "totalItems": "hydra:totalItems",
     "first": { "@id": "hydra:first", "@type": "@id" },
     "last": { "@id": "hydra:last", "@type": "@id" },
     "next": { "@id": "hydra:next", "@type": "@id" },
     "previous": { "@id": "hydra:previous", "@type": "@id" },
     "IriTemplate": "hydra:IriTemplate",
     "template": "hydra:template",
     "mapping": "hydra:mapping",
     "IriTemplateMapping": "hydra:IriTemplateMapping",
     "variable": "hydra:variable"
   },
   {
     'id': '@id',
     'type': '@type',
     // Hydra has "@type": "@vocab" which confuses the compaction -> we override it as workaround
     // see https://github.com/json-ld/json-ld.org/issues/400
     // we also want the full object form anyway, which we can force by omitting "@type"
     "property": { "@id": "hydra:property" },
     'api': COVAPI_API
     }
   ]

/*
 * We are using a custom jsonld document loader to skip loading the CovJSON context URL
 * which may be included in the document. Instead we load a local partial copy of it.
 */
const CONTEXTS = {
  "https://rawgit.com/reading-escience-centre/coveragejson/master/contexts/coveragejson-base.jsonld":
    {
      "@context": {
        "id": "@id",
        "type": "@type"
      }
    }
}
const customLoader = function (url) {
  if (url in CONTEXTS) {
    return Promise.resolve({
      contextUrl: null, // this is for a context via a link header
      document: CONTEXTS[url], // this is the actual document that was loaded
      documentUrl: url // this is the actual context URL after redirects
    })
  }
  // fall-back to default loader
  return jsonldOriginal.documentLoader(url)
}
const jsonldOpts = {
  documentLoader: customLoader
}

/**
 * Extracts API information from the given Coverage/CoverageCollection object
 * and returns an API object.
 */
export function discover (cov) {
  // Our main source of API information comes from data within the .ld property.
  // To query that we need the id of the coverage or coveragecollection.
  if (!cov.id) {
    return Promise.resolve(new API())
  }
  return jsonld.frame(cov.ld, {
    '@context': FRAME_CONTEXT,
    id: cov.id
  }, jsonldOpts)
  .then(framed => jsonld.compact(framed, framed['@context'], jsonldOpts))
  .then(compacted => new API(compacted))
}

export class API {
  /**
   * @param ld A framed and compacted JSON-LD document from which Hydra data can be read.
   */
  constructor (ld) {
    this.supportedUrlProps = new Map()

    if (!ld) return
    console.log(ld)

    if (ld.view && ld.view.type === PartialCollectionView) {
      this.isPaged = true
      this.paging = ld.view
      this.paging.total = ld.totalItems

      console.log(ld.view)
    }

    if (ld.api && ld.api.type === IriTemplate) {
      this.hasUrlTemplate = true
      this.urlTemplate = ld.api
      console.log('URL template: ' + ld.api.template)

      let mappings = ld.api.mapping
      for (let mapping of mappings) {
        let propId = mapping.property.id
        for (let prop in URL_PROPS) {
          if (URL_PROPS[prop] === propId) {
            console.log('property recognized: ' + propId + ' (variable: ' + mapping.variable + ')')
            this.supportedUrlProps.set(propId, mapping.variable)
          }
        }
      }

      console.log(ld.api)
    }

    if (ld[CanInclude]) {
      // server supports optional inclusion via Prefer header
      this.supportsPreferHeaders = true
    }

    this._createCapabilities()
  }

  get supportsBboxFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterBbox)
  }

  get supportsBboxSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetBbox)
  }

  get supportsTimeFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterTimeEnd)
  }

  get supportsTimeSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetTimeEnd)
  }

  get supportsVerticalFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterVerticalEnd)
  }

  get supportsVerticalSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetVerticalEnd)
  }

  get supportsVerticalTargetSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalTarget)
  }

  get supportsIndexSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetIndex)
  }

  _createCapabilities () {
    let caps = {
      filter: {},
      subset: {},
      embed: {}
    }
    let startstop = () => ({
      start: true,
      stop: true
    })
    if (this.supportsBboxFiltering) {
      // 'x' is not the axis name, it just represents the x-axis in a horizontal CRS
      caps.filter.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.filter.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeFiltering) {
      caps.filter.time = startstop()
    }
    if (this.supportsVerticalFiltering) {
      caps.filter.vertical = startstop()
    }
    if (this.supportsBboxSubsetting) {
      caps.subset.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.subset.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeSubsetting) {
      caps.subset.time = startstop()
    }
    if (this.supportsVerticalSubsetting) {
      caps.subset.vertical = startstop()
    }
    if (this.supportsVerticalTargetSubsetting) {
      if (!caps.subset.vertical) {
        caps.subset.vertical = {}
      }
      caps.subset.vertical.target = true
    }
    if (this.supportsIndexSubsetting) {
      caps.subset.index = {
        start: true,
        stop: true,
        step: true
      }
    }
    if (this.supportsPreferHeaders) {
      caps.embed = {
        domain: true,
        range: true
      }
    }
    this.capabilities = caps
  }

  /**
   * Option keys: time, x, y, vertical, embed
   *
   * Each value except for 'embed' is one of (check this.capabilities to see which ones are supported!):
   *
   * {start, stop} // intersect match
   *
   * 'embed' is an object {domain: true, range: true} where both members are optional.
   */
  _getFilterTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeFiltering) {
        throw new Error('Time filtering not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.vertical) {
      if (!this.supportsVerticalFiltering) {
        throw new Error('Vertical filtering not supported!')
      }
      let start = getNumberString(options.vertical.start)
      let end = getNumberString(options.vertical.stop)
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalStart)] = start
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalEnd)] = end
      delete options.vertical
    }
    if (options.x) {
      if (!this.supportsBboxFiltering) {
        throw new Error('BBOX filtering not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    checkEmpty(options, 'Unrecognized filter options')

    return templateVars
  }

  /**
   * Option keys: time, x, y, vertical, index
   *
   * Each value is one of (check this.capabilities to see which ones are supported!):
   *
   * For time, x, y, vertical:
   * ISO string // exact match (time)
   * number // exact match (x, y, vertical) <- typically not supported by API
   * {start, stop} // intersect match
   * {target} // nearest neighbor match
   *
   * For index:
   * {<axisName>: integer, ...}
   * {<axisName>: {start,stop[,step]}, ...}
   */
  _getSubsetTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeSubsetting) {
        throw new Error('Time subsetting not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.x) {
      if (!this.supportsBboxSubsetting) {
        throw new Error('BBOX subsetting not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    if (options.vertical) {
      if (options.vertical.target) {
        if (!this.supportsVerticalTargetSubsetting) {
          throw new Error('vertical target subsetting not supported!')
        }
        let target = getNumberString(options.vertical.target)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalTarget)] = target
      }
      if (options.vertical.start) {
        if (!this.supportsVerticalSubsetting) {
          throw new Error('vertical subsetting not supported!')
        }
        let start = getNumberString(options.vertical.start)
        let end = getNumberString(options.vertical.stop)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalStart)] = start
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalEnd)] = end
      }
      delete options.vertical
    }
    if (options.index) {
      if (!this.supportsIndexSubsetting) {
        throw new Error('index subsetting not supported!')
      }
      let strings = []
      for (let axis of Object.keys(options.index)) {
        strings.push(getIndexSubsetString(axis, options.index[axis]))
      }
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetIndex)] = strings
    }
    checkEmpty(options, 'Unrecognized subset options')

    return templateVars
  }

  _getIncludeDomainAndRangeHeaders (options = {}) {
    if (!this.supportsPreferHeaders) {
      return {}
    }
    let uris = []
    if (options.domain) {
      uris.push(Domain)
    }
    if (options.range) {
      uris.push(Range)
    }
    return {
      Prefer: 'return=representation; ' +
              'include="' + uris.join(' ') + '"'
    }
  }

  getUrlAndHeaders (options) {
    // deep-copy as we delete properties after they are applied
    options = JSON.parse(JSON.stringify(options))
    let subsetTemplateVars = this._getSubsetTemplateVars(options.subset)
    let filterTemplateVars = this._getFilterTemplateVars(options.filter)

    let templateVars = subsetTemplateVars
    for (let key in filterTemplateVars) {
      templateVars[key] = filterTemplateVars[key]
    }

    let url = urltemplate.parse(this.urlTemplate.template).expand(templateVars)
    let headers = this._getIncludeDomainAndRangeHeaders(options.embed)
    return {url, headers}
  }

}

function checkEmpty (obj, err) {
  if (Object.keys(obj).length > 0) {
    throw new Error(err)
  }
}

function getBboxString (bbox) {
  return bbox.map(getNumberString).join(',')
}

/**
 * Converts a number to a decimal string in non-scientific notation.
 */
function getNumberString (num) {
  // try toString() to avoid trailing zeros from toFixed()
  let str = num.toString()
  // if this resulted in scientific notation, use toFixed() instead
  if (str.indexOf('e') !== -1) {
    str = num.toFixed(20)
  }
  return str
}

function getIndexSubsetString (axis, spec) {
  let slice
  if (typeof spec === 'number') {
    slice = getNumberString(spec)
  } else if (spec.start === spec.stop && (!spec.step || spec.step === 1)) {
    slice = getNumberString(spec.start)
  } else {
    slice = getNumberString(spec.start) + ':' + getNumberString(stop)
    if (spec.step) {
      slice += ':' + getNumberString(spec.step)
    }
  }
  return axis + '[' + slice + ']'
}

<|endoftext|>


<commit_before>const str1 = 'Cats are the best!';

console.log(str1.endsWith('best', 17));
// expected output: true

const str2 = 'Is this a question';

console.log(str2.endsWith('?'));
// expected output: false
<commit_msg>fix: Clarify string-endswith examples (#1705)<commit_after>const str1 = 'Cats are the best!';

console.log(str1.endsWith('best!'));
// expected output: true

console.log(str1.endsWith('best', 17));
// expected output: true

const str2 = 'Is this a question?';

console.log(str2.endsWith('question'));
// expected output: false
<|endoftext|>


<commit_before>require("should");
var dataUtil = require("../../data-util/sales/production-order-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator.sales.productionOrder;
var codeGenerator = require('../../../src/utils/code-generator');
var processTypeDataUtil = require("../../data-util/master/process-type-data-util");
var orderTypeDataUtil = require("../../data-util/master/order-type-data-util");
var ProductionOrderManager= require("../../../src/managers/sales/production-order-manager");
var manager;
var OrderTypeManager= require("../../../src/managers/master/order-type-manager");
var managerOrderType;
var ProcessTypeManager= require("../../../src/managers/master/process-type-manager");
var managerProcessType;

before('#00. connect db', function(done) {
    helper.getDb()
        .then(db => {
            manager = new ProductionOrderManager(db, {
                username: 'dev'
            });

            managerOrderType = new OrderTypeManager(db, {
                username: 'dev'
            });

            managerProcessType = new ProcessTypeManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#01. should error when create with empty data", function(done) {
        manager.create({})
            .then((id) => {
                done("Should not be able to create with empty data");
            })
            .catch((e) => {
                try {
                    e.name.should.equal("ValidationError");
                    e.should.have.property("errors");
                    e.errors.should.instanceof(Object);
                    done();
                }
                catch (ex) {
                    done(e);
                }
            });
    });

var createdDataOrderType;
var createdDataOrderTypeId;
it("#02. should success when create new order type data printing", function(done) {
    orderTypeDataUtil.getNewData()
    .then((data) =>{
        data.name="Printing";
        createdDataOrderType=data;
        managerOrderType.create(data)
        .then((id) => {
            id.should.be.Object();
            createdDataOrderTypeId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
    });
});
var createdDataProcessType;
var createdDataProcessTypeId;
it("#03. should success when create new process type data printing", function(done) {
    processTypeDataUtil.getNewData()
    .then((data) =>{
        data.orderTypeId=createdDataOrderTypeId;
        data.orderType=createdDataOrderType;
        data.name="OP";
        createdDataProcessType=data;
        managerProcessType.create(data)
        .then((id) => {
            id.should.be.Object();
            createdDataProcessTypeId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
    });
});

var createdId;
var createdData;
it("#04. should success when create new data", function(done) {
        dataUtil.getNewData()
            .then((data) =>{
                data.processType=createdDataProcessType;
                data.processTypeId=createdDataProcessTypeId;
                data.orderType=createdDataOrderType;
                data.orderTypeId=createdDataOrderTypeId;
                data.RUN="2 RUN";
                data.RUNWidth=[10,20];
                data.designNumber="No.1/01/17";
                data.designCode="DSGCD01";
                manager.create(data)
            .then((id) => {
                id.should.be.Object();
                createdId = id;
                done();
            })
            .catch((e) => {
                done(e);
            });
    });
});

it("#05. should error when create new data without RUN,RUNWidth,designNumber,designCode", function(done) {
        dataUtil.getNewData()
            .then((data) =>{
                data.processType=createdDataProcessType;
                data.processTypeId=createdDataProcessTypeId;
                data.orderType=createdDataOrderType;
                data.orderTypeId=createdDataOrderTypeId;
                manager.create(data)
                .then((id) => {
                    done("Should not be able to create new data without RUN,RUNWidth,designNumber,designCode");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });
            });
    });

    it('#06. should error when create new data with RUN but without RUNWidth', function (done) {
    dataUtil.getNewData()
        .then(data => {

            data.RUN = "1 RUN";
            data.processType=createdDataProcessType;
            data.processTypeId=createdDataProcessTypeId;
            data.orderType=createdDataOrderType;
            data.orderTypeId=createdDataOrderTypeId;
            data.RUNWidth=[0];

            manager.create(data)
                .then(id => {
                    done("should error when create new data with RUN but without RUNWidth");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });
            });
});

    it("#07. should success when destroy data processType with id", function(done) {
        managerProcessType.destroy(createdDataProcessTypeId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#08. should success when destroy data orderType with id", function(done) {
        managerOrderType.destroy(createdDataOrderTypeId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#09. should success when destroy data production Order with id", function(done) {
        manager.destroy(createdId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });<commit_msg>fix unit test<commit_after>require("should");
var dataUtil = require("../../data-util/sales/production-order-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator.sales.productionOrder;
var codeGenerator = require('../../../src/utils/code-generator');
var processTypeDataUtil = require("../../data-util/master/process-type-data-util");
var orderTypeDataUtil = require("../../data-util/master/order-type-data-util");
var ProductionOrderManager= require("../../../src/managers/sales/production-order-manager");
var manager;
var OrderTypeManager= require("../../../src/managers/master/order-type-manager");
var managerOrderType;
var ProcessTypeManager= require("../../../src/managers/master/process-type-manager");
var managerProcessType;

before('#00. connect db', function(done) {
    helper.getDb()
        .then(db => {
            manager = new ProductionOrderManager(db, {
                username: 'dev'
            });

            managerOrderType = new OrderTypeManager(db, {
                username: 'dev'
            });

            managerProcessType = new ProcessTypeManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#01. should error when create with empty data", function(done) {
        manager.create({})
            .then((id) => {
                done("Should not be able to create with empty data");
            })
            .catch((e) => {
                try {
                    e.name.should.equal("ValidationError");
                    e.should.have.property("errors");
                    e.errors.should.instanceof(Object);
                    done();
                }
                catch (ex) {
                    done(e);
                }
            });
    });

var createdDataOrderType;
var createdDataOrderTypeId;
it("#02. should success when create new order type data printing", function(done) {
    orderTypeDataUtil.getNewData()
    .then((data) =>{
        data.name="Printing";
        createdDataOrderType=data;
        managerOrderType.create(data)
        .then((id) => {
            id.should.be.Object();
            createdDataOrderTypeId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
    });
});
var createdDataProcessType;
var createdDataProcessTypeId;
it("#03. should success when create new process type data printing", function(done) {
    processTypeDataUtil.getNewData()
    .then((data) =>{
        data.orderTypeId=createdDataOrderTypeId;
        data.orderType=createdDataOrderType;
        data.name="OP";
        createdDataProcessType=data;
        managerProcessType.create(data)
        .then((id) => {
            id.should.be.Object();
            createdDataProcessTypeId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
    });
});

var createdId;
var createdData;
it("#04. should success when create new data", function(done) {
        dataUtil.getNewData()
            .then((data) =>{
                data.processType=createdDataProcessType;
                data.processTypeId=createdDataProcessTypeId;
                data.orderType=createdDataOrderType;
                data.orderTypeId=createdDataOrderTypeId;
                data.RUN="2 RUN";
                data.RUNWidth=[10,20];
                data.designNumber="No.1/01/17";
                data.designCode="DSGCD01";
                manager.create(data)
            .then((id) => {
                id.should.be.Object();
                createdId = id;
                done();
            })
            .catch((e) => {
                done(e);
            });
    });
});

it("#05. should error when create new data without RUN,RUNWidth,designNumber,designCode", function(done) {
        dataUtil.getNewData()
            .then((data) =>{
                data.processType=createdDataProcessType;
                data.processTypeId=createdDataProcessTypeId;
                data.orderType=createdDataOrderType;
                data.orderTypeId=createdDataOrderTypeId;
                manager.create(data)
                .then((id) => {
                    done("Should not be able to create new data without RUN,RUNWidth,designNumber,designCode");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });
            });
    });

    it('#06. should error when create new data with RUN but with RUNWidth=0', function (done) {
    dataUtil.getNewData()
        .then(data => {

            data.RUN = "1 RUN";
            data.processType=createdDataProcessType;
            data.processTypeId=createdDataProcessTypeId;
            data.orderType=createdDataOrderType;
            data.orderTypeId=createdDataOrderTypeId;
            data.RUNWidth=[0];

            manager.create(data)
                .then(id => {
                    done("should error when create new data with RUN but with RUNWidth=0");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });
            });
});

it('#07. should error when create new data with RUN but without RUNWidth', function (done) {
    dataUtil.getNewData()
        .then(data => {

            data.RUN = "1 RUN";
            data.processType=createdDataProcessType;
            data.processTypeId=createdDataProcessTypeId;
            data.orderType=createdDataOrderType;
            data.orderTypeId=createdDataOrderTypeId;
            data.RUNWidth=[];

            manager.create(data)
                .then(id => {
                    done("should error when create new data with RUN but without RUNWidth");
                })
                .catch((e) => {
                    try {
                        e.name.should.equal("ValidationError");
                        e.should.have.property("errors");
                        e.errors.should.instanceof(Object);
                        done();
                    }
                    catch (ex) {
                        done(e);
                    }
                });
            });
});

    it("#08. should success when destroy data processType with id", function(done) {
        managerProcessType.destroy(createdDataProcessTypeId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#09. should success when destroy data orderType with id", function(done) {
        managerOrderType.destroy(createdDataOrderTypeId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });

    it("#10. should success when destroy data production Order with id", function(done) {
        manager.destroy(createdId)
            .then((result) => {
                result.should.be.Boolean();
                result.should.equal(true);
                done();
            })
            .catch((e) => {
                done(e);
            });
    });<|endoftext|>


<commit_before>(function(){
  'use strict';

  angular.module('cla.controllers.operator')
    .controller('CaseDetailSuspendCtrl',
      ['$scope', '$modal',
        function($scope, $modal){
          $scope.suspend = function() {
            $modal.open({
              templateUrl: 'case_detail.outcome_modal.html',
              controller: 'OutcomesModalCtl',
              resolve: {
                'tplVars': function() {
                  return {
                    title: 'Suspend Case'
                  };
                },
                'case': function() { return $scope.case; },
                'event_key': function() { return 'suspend_case'; },  //this is also the function name on Case model
                'notes': function() { return ''; },
                'success_msg': function() { return 'Case '+$scope.case.reference+' suspended successfully'; }
              }
            });
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('CaseDetailDeclineHelpCtrl',
      ['$scope', '$modal', '$q',
        function($scope, $modal, $q){
          $scope.decline_help = function(notes) {
            var parentQ = $q.when(true);
            if ($scope.$parent && $scope.$parent.decline_help) {
              parentQ = $scope.$parent.decline_help();
            }

            parentQ.then(function () {
              $modal.open({
                templateUrl: 'case_detail.outcome_modal.html',
                controller: 'OutcomesModalCtl',
                resolve: {
                  'tplVars': function() {
                    return {
                      'title': 'Decline Help'
                    };
                  },
                  'case': function() { return $scope.case; },
                  'event_key': function() { return 'decline_help'; },  //this is also the function name on Case model
                  'notes': function() { return notes || ''; },
                  'success_msg': function() { return 'Declined help for Case '+$scope.case.reference; }
                }
              });
            });
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('CaseDetailAssignProviderCtrl',
      ['$rootScope', '$scope', '$modal', '$state',
        function($rootScope, $scope, $modal, $state){
          // function to create a list of warnings/errors from an obj
          function setMessages (fields, list) {
            angular.forEach(fields, function (obj) {
              var field = $scope[obj.object][obj.field];
              if (field === undefined || (field !== undefined && !field)) {
                list.push({message: obj.message});
              }
            });
          }

          // Case validation
          $scope.resetCaseErrors = function () {
            $scope.case_errors = [];
            $scope.case_warnings = [];
          };
          $scope.resetCaseErrors();

          $scope.validateCase = function () {
            var required_fields = [
                  {object: 'case', field: 'notes', message: 'Case notes must be added to close a case'},
                  {object: 'case', field: 'media_code', message: 'A media code is required to close a case'},
                  {object: 'personal_details', field: 'full_name', message: 'Name is required to close a case'},
                  {object: 'personal_details', field: 'dob', message: 'Date of birth is required to close a case'},
                  {object: 'personal_details', field: 'mobile_phone', message: 'A contact number is required to close a case'}
                ],
                warning_fields = [
                  {object: 'personal_details', field: 'postcode', message: 'It is recommended to include postcode before closing a case'},
                  {object: 'personal_details', field: 'street', message: 'It is recommended to include an address before closing a case'},
                  {object: 'personal_details', field: 'ni_number', message: 'National Insurance number is not required to close a case but the specialist will ask for it once assigned'}
                ];

            // clear errors
            $scope.case_errors = [];
            $scope.case_warnings = [];

            // find errors
            setMessages(required_fields, $scope.case_errors);
            setMessages(warning_fields, $scope.case_warnings);

            if ($scope.case_errors.length === 0 && $scope.case_warnings.length === 0) {
              return true;
            } else {
              return false;
            }
          };
          var offStateChange = $rootScope.$on('$stateChangeSuccess', function() {
            $scope.resetCaseErrors();
          });
          $scope.$on('$destroy', function () {
            offStateChange();
          });

          $scope.assign_to_provider = function () {
            var child_scope = $scope.$new(),
                transition_to = 'case_detail.assign';

            child_scope.next = transition_to;

            if (!$scope.validateCase() && !$scope.case.warned) {
              $modal.open({
                templateUrl: 'call_centre/case_detail.invalid.html',
                controller: 'InvalidCtrl',
                scope: child_scope
              });
            } else if (!($scope.case.matter_type1 && $scope.case.matter_type2)) {
              $scope.edit_matter_types(transition_to);
            } else {
              $state.go(transition_to);
            }
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('InvalidCtrl',
    ['$scope', '$modalInstance',
      function ($scope, $modalInstance) {
        $scope.close = function () {
          $modalInstance.dismiss('cancel');
        };

        $scope.proceed = function() {
          $modalInstance.close();
          $scope.case.warned = true;
          $scope.assign_to_provider();
        };
      }
    ]
  );
})();
<commit_msg>Add controller for alternative help menu option, which checks diagnosis category is set<commit_after>(function(){
  'use strict';

  angular.module('cla.controllers.operator')
    .controller('CaseDetailSuspendCtrl',
      ['$scope', '$modal',
        function($scope, $modal){
          $scope.suspend = function() {
            $modal.open({
              templateUrl: 'case_detail.outcome_modal.html',
              controller: 'OutcomesModalCtl',
              resolve: {
                'tplVars': function() {
                  return {
                    title: 'Suspend Case'
                  };
                },
                'case': function() { return $scope.case; },
                'event_key': function() { return 'suspend_case'; },  //this is also the function name on Case model
                'notes': function() { return ''; },
                'success_msg': function() { return 'Case '+$scope.case.reference+' suspended successfully'; }
              }
            });
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('CaseDetailDeclineHelpCtrl',
      ['$scope', '$modal', '$q',
        function($scope, $modal, $q){
          $scope.decline_help = function(notes) {
            var parentQ = $q.when(true);
            if ($scope.$parent && $scope.$parent.decline_help) {
              parentQ = $scope.$parent.decline_help();
            }

            parentQ.then(function () {
              $modal.open({
                templateUrl: 'case_detail.outcome_modal.html',
                controller: 'OutcomesModalCtl',
                resolve: {
                  'tplVars': function() {
                    return {
                      'title': 'Decline Help'
                    };
                  },
                  'case': function() { return $scope.case; },
                  'event_key': function() { return 'decline_help'; },  //this is also the function name on Case model
                  'notes': function() { return notes || ''; },
                  'success_msg': function() { return 'Declined help for Case '+$scope.case.reference; }
                }
              });
            });
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('CaseDetailAssignProviderCtrl',
      ['$rootScope', '$scope', '$modal', '$state',
        function($rootScope, $scope, $modal, $state){
          // function to create a list of warnings/errors from an obj
          function setMessages (fields, list) {
            angular.forEach(fields, function (obj) {
              var field = $scope[obj.object][obj.field];
              if (field === undefined || (field !== undefined && !field)) {
                list.push({message: obj.message});
              }
            });
          }

          // Case validation
          $scope.resetCaseErrors = function () {
            $scope.case_errors = [];
            $scope.case_warnings = [];
          };
          $scope.resetCaseErrors();

          $scope.validateCase = function () {
            var required_fields = [
                  {object: 'case', field: 'notes', message: 'Case notes must be added to close a case'},
                  {object: 'case', field: 'media_code', message: 'A media code is required to close a case'},
                  {object: 'personal_details', field: 'full_name', message: 'Name is required to close a case'},
                  {object: 'personal_details', field: 'dob', message: 'Date of birth is required to close a case'},
                  {object: 'personal_details', field: 'mobile_phone', message: 'A contact number is required to close a case'}
                ],
                warning_fields = [
                  {object: 'personal_details', field: 'postcode', message: 'It is recommended to include postcode before closing a case'},
                  {object: 'personal_details', field: 'street', message: 'It is recommended to include an address before closing a case'},
                  {object: 'personal_details', field: 'ni_number', message: 'National Insurance number is not required to close a case but the specialist will ask for it once assigned'}
                ];

            // clear errors
            $scope.case_errors = [];
            $scope.case_warnings = [];

            // find errors
            setMessages(required_fields, $scope.case_errors);
            setMessages(warning_fields, $scope.case_warnings);

            if ($scope.case_errors.length === 0 && $scope.case_warnings.length === 0) {
              return true;
            } else {
              return false;
            }
          };
          var offStateChange = $rootScope.$on('$stateChangeSuccess', function() {
            $scope.resetCaseErrors();
          });
          $scope.$on('$destroy', function () {
            offStateChange();
          });

          $scope.assign_to_provider = function () {
            var child_scope = $scope.$new(),
                transition_to = 'case_detail.assign';

            child_scope.next = transition_to;

            if (!$scope.validateCase() && !$scope.case.warned) {
              $modal.open({
                templateUrl: 'call_centre/case_detail.invalid.html',
                controller: 'InvalidCtrl',
                scope: child_scope
              });
            } else if (!($scope.case.matter_type1 && $scope.case.matter_type2)) {
              $scope.edit_matter_types(transition_to);
            } else {
              $state.go(transition_to);
            }
          };
        }
      ]
    );

  angular.module('cla.controllers.operator')
    .controller('InvalidCtrl',
    ['$scope', '$modalInstance',
      function ($scope, $modalInstance) {
        $scope.close = function () {
          $modalInstance.dismiss('cancel');
        };

        $scope.proceed = function() {
          $modalInstance.close();
          $scope.case.warned = true;
          $scope.assign_to_provider();
        };
      }
    ]
  );

  angular.module('cla.controllers.operator')
    .controller('CaseDetailValidateAltHelpCtrl',
      ['$scope', '$modal', '$state',
        function($scope, $modal, $state){
          $scope.validateAltHelp = function() {

            if (!$scope.diagnosis || !$scope.diagnosis.category) {
              $modal.open({
                templateUrl: 'case_detail.alt_help_modal.html',
                controller: 'InvalidCtrl'
              });
            } else {
              $state.go('case_detail.alternative_help');
            }
          };
        }
      ]
    );

})();
<|endoftext|>