<commit_before>import { generateUUID } from 'react-native-database';
import { batch } from 'react-redux';

import { UIDatabase, createRecord } from '../../database';
import {
  selectHasRefused,
  selectSelectedBatches,
  selectSelectedVaccinator,
} from '../../selectors/Entities/vaccinePrescription';
import { selectEditingNameId } from '../../selectors/Entities/name';
import { NameActions } from './NameActions';
import { NameNoteActions } from './NameNoteActions';
import { goBack, gotoVaccineDispensingPage } from '../../navigation/actions';

export const VACCINE_PRESCRIPTION_ACTIONS = {
  CREATE: 'VACCINE_PRESCRIPTION/create',
  SET_REFUSAL: 'VACCINE_PRESCRIPTION/setRefusal',
  RESET: 'VACCINE_PRESCRIPTION/reset',
  SELECT_VACCINE: 'VACCINE_PRESCRIPTION/selectVaccine',
  SELECT_BATCH: 'VACCINE_PRESCRIPTION/selectBatch',
  SELECT_VACCINATOR: 'VACCINE_PRESCRIPTION/selectVaccinator',
};

const createDefaultVaccinePrescription = () => ({
  id: generateUUID(),
  name: '',
  code: '',
  type: 'patient',
  isCustomer: false,
  isSupplier: false,
  isManufacturer: false,
  isVisible: true,
});

const getDefaultVaccinator = () => {
  const [batches] = UIDatabase.objects('TransactionBatch')
    .filtered('medicineAdministrator != null && itemBatch.item.isVaccine == true')
    .sorted('transaction.confirmDate', true);

  if (batches) {
    return batches.medicineAdministrator;
  }

  return null;
};

const getDefaultVaccine = () => {
  const [mostRecentTrans] = UIDatabase.objects('Transaction')
    .filtered("type == 'customer_invoice' && (status == 'finalised' || status == 'confirmed')")
    .sorted('confirmDate', true);

  const [item] = mostRecentTrans?.items?.filtered('item.isVaccine == true') ?? [];

  return item?.item ?? null;
};

const getRecommendedBatch = vaccine => {
  const { batchesWithStock = [] } = vaccine ?? getDefaultVaccine() ?? {};

  if (batchesWithStock?.length) {
    const batchesByExpiry = batchesWithStock.sorted('expiryDate');
    const openVials = batchesByExpiry.filter(b => !Number.isInteger(b.numberOfPacks));

    return openVials.length ? openVials[0] : batchesByExpiry[0];
  }

  return null;
};

const create = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.CREATE,
  payload: {
    prescription: createDefaultVaccinePrescription(),
    vaccinator: getDefaultVaccinator(),
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const reset = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.RESET,
});

const selectVaccine = vaccine => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINE,
  payload: { vaccine, batch: getRecommendedBatch(vaccine) },
});

const selectBatch = itemBatch => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_BATCH,
  payload: { itemBatch },
});

const setRefusal = hasRefused => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SET_REFUSAL,
  payload: {
    hasRefused,
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const createPrescription = (patient, currentUser, selectedBatches, vaccinator) => {
  UIDatabase.write(() => {
    const prescription = createRecord(
      UIDatabase,
      'CustomerInvoice',
      patient,
      currentUser,
      'dispensary'
    );

    selectedBatches.forEach(itemBatch => {
      const { item } = itemBatch;
      const transactionItem = createRecord(UIDatabase, 'TransactionItem', prescription, item);
      createRecord(UIDatabase, 'TransactionBatch', transactionItem, itemBatch);
      transactionItem.setDoses(UIDatabase, 1);
      transactionItem.setVaccinator(UIDatabase, vaccinator);
    });
    prescription.finalise(UIDatabase);
  });
};

const createRefusalNameNote = name => {
  const [patientEvent] = UIDatabase.objects('PatientEvent').filtered('code == "RV"');
  const id = generateUUID();
  const newNameNote = { id, name, patientEvent, entryDate: new Date() };

  UIDatabase.write(() => UIDatabase.create('NameNote', newNameNote));
};

const confirm = () => (dispatch, getState) => {
  const { user } = getState();
  const { currentUser } = user;
  const hasRefused = selectHasRefused(getState());
  const patientID = selectEditingNameId(getState());
  const patient = UIDatabase.get('Name', patientID);
  const selectedBatches = selectSelectedBatches(getState());
  const vaccinator = selectSelectedVaccinator(getState());

  if (hasRefused) {
    createRefusalNameNote(patient);
  } else {
    createPrescription(patient, currentUser, selectedBatches, vaccinator);
  }

  batch(() => {
    dispatch(NameActions.saveEditing());
    dispatch(NameNoteActions.saveEditing());
    dispatch(reset());
  });
};

const selectVaccinator = vaccinator => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINATOR,
  payload: { vaccinator },
});

const cancel = () => goBack();

const confirmAndRepeat = () => dispatch =>
  batch(() => {
    dispatch(confirm());
    dispatch(goBack());
    dispatch(gotoVaccineDispensingPage());
  });

export const VaccinePrescriptionActions = {
  cancel,
  confirm,
  create,
  reset,
  selectBatch,
  selectVaccine,
  setRefusal,
  selectVaccinator,
  confirmAndRepeat,
};
<commit_msg>Add actually create a name note for new patients<commit_after>import { generateUUID } from 'react-native-database';
import { batch } from 'react-redux';

import { UIDatabase, createRecord } from '../../database';
import {
  selectHasRefused,
  selectSelectedBatches,
  selectSelectedVaccinator,
} from '../../selectors/Entities/vaccinePrescription';
import { selectEditingNameId } from '../../selectors/Entities/name';
import { NameActions } from './NameActions';
import { NameNoteActions } from './NameNoteActions';
import { goBack, gotoVaccineDispensingPage } from '../../navigation/actions';

export const VACCINE_PRESCRIPTION_ACTIONS = {
  CREATE: 'VACCINE_PRESCRIPTION/create',
  SET_REFUSAL: 'VACCINE_PRESCRIPTION/setRefusal',
  RESET: 'VACCINE_PRESCRIPTION/reset',
  SELECT_VACCINE: 'VACCINE_PRESCRIPTION/selectVaccine',
  SELECT_BATCH: 'VACCINE_PRESCRIPTION/selectBatch',
  SELECT_VACCINATOR: 'VACCINE_PRESCRIPTION/selectVaccinator',
};

const createDefaultVaccinePrescription = () => ({
  id: generateUUID(),
  name: '',
  code: '',
  type: 'patient',
  isCustomer: false,
  isSupplier: false,
  isManufacturer: false,
  isVisible: true,
});

const getDefaultVaccinator = () => {
  const [batches] = UIDatabase.objects('TransactionBatch')
    .filtered('medicineAdministrator != null && itemBatch.item.isVaccine == true')
    .sorted('transaction.confirmDate', true);

  if (batches) {
    return batches.medicineAdministrator;
  }

  return null;
};

const getDefaultVaccine = () => {
  const [mostRecentTrans] = UIDatabase.objects('Transaction')
    .filtered("type == 'customer_invoice' && (status == 'finalised' || status == 'confirmed')")
    .sorted('confirmDate', true);

  const [item] = mostRecentTrans?.items?.filtered('item.isVaccine == true') ?? [];

  return item?.item ?? null;
};

const getRecommendedBatch = vaccine => {
  const { batchesWithStock = [] } = vaccine ?? getDefaultVaccine() ?? {};

  if (batchesWithStock?.length) {
    const batchesByExpiry = batchesWithStock.sorted('expiryDate');
    const openVials = batchesByExpiry.filter(b => !Number.isInteger(b.numberOfPacks));

    return openVials.length ? openVials[0] : batchesByExpiry[0];
  }

  return null;
};

const create = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.CREATE,
  payload: {
    prescription: createDefaultVaccinePrescription(),
    vaccinator: getDefaultVaccinator(),
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const reset = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.RESET,
});

const selectVaccine = vaccine => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINE,
  payload: { vaccine, batch: getRecommendedBatch(vaccine) },
});

const selectBatch = itemBatch => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_BATCH,
  payload: { itemBatch },
});

const setRefusal = hasRefused => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SET_REFUSAL,
  payload: {
    hasRefused,
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const createPrescription = (patient, currentUser, selectedBatches, vaccinator) => {
  UIDatabase.write(() => {
    const prescription = createRecord(
      UIDatabase,
      'CustomerInvoice',
      patient,
      currentUser,
      'dispensary'
    );

    selectedBatches.forEach(itemBatch => {
      const { item } = itemBatch;
      const transactionItem = createRecord(UIDatabase, 'TransactionItem', prescription, item);
      createRecord(UIDatabase, 'TransactionBatch', transactionItem, itemBatch);
      transactionItem.setDoses(UIDatabase, 1);
      transactionItem.setVaccinator(UIDatabase, vaccinator);
    });
    prescription.finalise(UIDatabase);
  });
};

const createRefusalNameNote = name => {
  const [patientEvent] = UIDatabase.objects('PatientEvent').filtered('code == "RV"');
  const id = generateUUID();
  const newNameNote = { id, name, patientEvent, entryDate: new Date() };

  UIDatabase.write(() => UIDatabase.create('NameNote', newNameNote));
};

const confirm = () => (dispatch, getState) => {
  const { user } = getState();
  const { currentUser } = user;
  const hasRefused = selectHasRefused(getState());
  const patientID = selectEditingNameId(getState());
  const selectedBatches = selectSelectedBatches(getState());
  const vaccinator = selectSelectedVaccinator(getState());

  batch(() => {
    dispatch(NameActions.saveEditing());
    dispatch(NameNoteActions.saveEditing());
    dispatch(reset());
  });

  const patient = UIDatabase.get('Name', patientID);
  if (hasRefused) {
    createRefusalNameNote(patient);
  } else {
    createPrescription(patient, currentUser, selectedBatches, vaccinator);
  }
};

const selectVaccinator = vaccinator => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINATOR,
  payload: { vaccinator },
});

const cancel = () => goBack();

const confirmAndRepeat = () => dispatch =>
  batch(() => {
    dispatch(confirm());
    dispatch(goBack());
    dispatch(gotoVaccineDispensingPage());
  });

export const VaccinePrescriptionActions = {
  cancel,
  confirm,
  create,
  reset,
  selectBatch,
  selectVaccine,
  setRefusal,
  selectVaccinator,
  confirmAndRepeat,
};
<|endoftext|>


<commit_before>var yaja = typeof yaja === 'undefined' ? {} : yaja;
(function (window, yaja, undefined) {

// Intials: ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ
// Command codes
var NULL = 11,       // ㅇ
    TERMINATE = 18,  // ㅎ
    ADD = 3,         // ㄷ
    MULTIPLY = 4,    // ㄸ
    DIVIDE = 2,      // ㄴ
    SUBTRACT = 16,   // ㅌ
    MODULO = 5,      // ㄹ
    POP = 6,         // ㅁ
    PUSH = 7,        // ㅂ
    DUPLICATE = 8,   // ㅃ
    SWAP = 17,       // ㅍ
    SELECT = 9,      // ㅅ
    TRANSFER = 10,   // ㅆ
    COMPARE = 12,    // ㅈ
    DECIDE = 14,     // ㅊ
    COMMAND_ARITY = [0, 0, 2, 2, 2, 2, 1, 0, 1, 0, 1, 0, 2, 0, 1, 0, 2, 2, 0];

// Medials: ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ
// Directions (bits 0,1)
var UP = 0,
    RIGHT = 1,
    DOWN = 3,
    LEFT = 2,
    DIRECTION = 3;  // 0b000011
// Inertia and deflection (bits 2,3,4)
var FORCE = 0,
    SAME = 4,
    REFLECT = 24,
    SAME_V_REFLECT_H = 8,
    REFLECT_V_SAME_H = 20,
    INERTIA = 28;  // 0b011100
// Speed (bit 5)
var ONE = 0,
    TWO = 32;
    SPEED = 32;  // 0b100000
// Movements
var MOVEMENTS = [RIGHT | ONE, SAME, RIGHT | TWO, SAME, LEFT | ONE, SAME,
      LEFT | TWO, SAME, UP | ONE, SAME, SAME, SAME, UP | TWO, DOWN | ONE,
      SAME, SAME, SAME, DOWN | TWO, REFLECT_V_SAME_H, REFLECT, SAME_V_REFLECT_H
    ];

// Finals: null ㄱ ㄲ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ
// Arguments for POP and PUSH
var INTEGER = 21,    // ㅇ
    CHARACTER = 27,  // ㅎ
    VALUES = [0, 2, 4, 4, 2, 5, 5, 3, 5, 7, 9, 9, 7, 9, 9, 8, 4, 4, 6, 2, 4,
      undefined, 3, 4, 3, 4, 4, undefined];

// Storage
var QUEUE = 21;

var NULL_INSTRUCTION = [NULL, 1, 0];

function Interpreter() {
  var self = this;
  this._buffer = [];
  this._bufferingMode = 'line-bufferred';
  this._out = {print: function () {}};
}

Interpreter.prototype.setOut = function (out, bufferingMode) {
  this._out = out;
  if (bufferingMode !== undefined) this._bufferingMode = bufferingMode;
};

Interpreter.prototype.setProgram = function (program) {
  var code = this._parse(program);
  this._process = {
    code: code,
    height: code.length
  };
  this.reset();
};

Interpreter.prototype.reset = function () {
  var process = this._process;
  process.instructionIndex = [0, 0];
  process.direction = DOWN;
  process.speed = ONE;
  process.storage = this._createStorage();
  process.storageIndex = 0;
  process.instructionCount = 0;
  process.terminated = true;
  for (var i = 0; i < process.code.length; ++i) {
    if (process.code[i].length > 0) {
      process.terminated = false;
      break;
    }
  }
};

Interpreter.prototype.run = function (maxInstructions) {
  var process = this._process;
  if (process.terminated) return true;
  var code = process.code,
      data = process.storage[process.storageIndex],
      index = process.instructionIndex,
      currentInstructionCount = 0;
  while (maxInstructions === undefined ||
         currentInstructionCount < maxInstructions) {
    var row = code[index[0]];
        instruction = row[index[1]];
    if (instruction !== undefined) {
      var commandCode = instruction[0],
          movement = MOVEMENTS[instruction[1]],
          direction = movement & DIRECTION,
          speed = movement & SPEED,
          argumentCode = instruction[2],
          arity = COMMAND_ARITY[commandCode],
          first,
          second;
      // Update current direction
      if ((movement & INERTIA) == FORCE) {
        // Simple movement
        process.direction = direction;
        process.speed = speed;
      } else if (movement != SAME) {
        var d = process.direction;
        if (movement == REFLECT ||
            (movement == SAME_V_REFLECT_H && (d == RIGHT || d == LEFT)) ||
            (movement == REFLECT_V_SAME_H && (d == UP || d == DOWN))) {
          process.direction = ~d & DIRECTION;
        }
      }
      // Check if current storage has enough values
      if (data.length < 2 &&
          (arity == 2 || data.length < 1 && arity == 1)) {
        commandCode = NULL;
        process.direction = ~process.direction & DIRECTION;
      }
      // Get values
      if (arity >= 1) {
        if (commandCode != DUPLICATE) first = data.pop();
        if (arity == 2) second = data.pop();
      }
      // Perform command
      switch (commandCode) {
        // Arithmetic commands
        case ADD:      data.push(second + first); break;
        case MULTIPLY: data.push(second * first); break;
        case DIVIDE:   data.push(Math.floor(second / first)); break;
        case SUBTRACT: data.push(second - first); break;
        case MODULO:   data.push(second % first); break;
        // Storage commands
        case POP:
          if (argumentCode == INTEGER) {
            this._write(first);
          } else if (argumentCode == CHARACTER) {
            this._write(String.fromCharCode(first));
          } else {
            // Invalid argument; discard value
          }
          break;
        case PUSH:
          var value;
          if (argumentCode == INTEGER) {
            value = Math.floor(window.prompt('Enter an integer:'));
          } else if (argumentCode == CHARACTER) {
            value = window.prompt('Enter a character:').charCodeAt(0);
          } else {
            value = VALUES[argumentCode];
          }
          data.push(value);
          break;
        case DUPLICATE:
          data.duplicate();
          break;
        case SWAP:
          data.push(first);
          data.push(second);
          break;
        // Miscellaneous commands
        case SELECT:
          data = process.storage[process.storageIndex = argumentCode];
          break;
        case TRANSFER:
          process.storage[argumentCode].push(first);
          break;
        case COMPARE:
          data.push(second >= first ? 1 : 0);
          break;
        case DECIDE:
          if (first == 0) process.direction = ~process.direction & DIRECTION;
          break;
        case TERMINATE:
          process.terminated = true;
          this._flush();
          return true;
        case NULL: default:
          break;
      }
      ++process.instructionCount;
      ++currentInstructionCount;
    }
    // Move to the next instruction
    var inc = process.speed == ONE ? 1 : 2,
        width = row.length,
        x;
    switch (process.direction) {
      case UP:    x = index[0] - inc; index[0] = x < 0 ? height - 1 : x; break;
      case DOWN:  x = index[0] + inc; index[0] = x >= height ? 0 : x; break;
      case RIGHT: x = index[1] + inc; index[1] = x >= width ? 0 : x; break;
      case LEFT:  x = index[1] - inc; index[1] = x < 0 ? width - 1 : x; break;
    }
  }
  this._flush();
};

Interpreter.prototype._parse = function (program) {
  var lines = program.split('\n')
      height = lines.length,
      rows = [];
  for (var i = 0; i < height; ++i) {
    var line = lines[i],
        width = line.length,
        row = [];
    for (var j = 0; j < width; ++j) {
      row.push(this._makeInstruction(line.charCodeAt(j)));
    }
    rows.push(row);
  }
  return rows;
};

Interpreter.prototype._makeInstruction = function (charCode) {
  // '가'.charCodeAt(0) == 0xac00
  // '힣'.charCodeAt(0) == 0xd7a3
  if (charCode < 0xac00 || charCode > 0xd7a3) return NULL_INSTRUCTION;
  var offset = charCode - 0xac00,
      argumentCode = offset % 28,  // final (종성)
      movementCode = Math.floor(offset / 28) % 21,  // medial (중성)
      commandCode = Math.floor(offset / 28 / 21);  // initial (초성)
  return [commandCode, movementCode, argumentCode];
};

Interpreter.prototype._createStorage = function () {
  var storage = [];
  for (var i = 0; i < 28; ++i) {
    storage[i] = i == QUEUE ? new yaja.Queue() : new yaja.Stack();
  }
  return storage;
};

Interpreter.prototype._write = function (c) {
  var bufferingMode = this._bufferingMode,
      buffer = this._buffer,
      out = this._out;
  if (bufferingMode == 'unbuffered') {
    out.print(c);
  } else {
    buffer.push(c);
    if (bufferingMode == 'line-buffered' && c == '\n') this._flush();
  }
};

Interpreter.prototype._flush = function () {
  this._out.print(this._buffer.join(''));
  this._buffer.length = 0;
};

yaja.Interpreter = Interpreter;

})(window, yaja);
<commit_msg>Remove window variable<commit_after>var yaja = typeof yaja === 'undefined' ? {} : yaja;
(function (yaja, undefined) {

// Intials: ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ
// Command codes
var NULL = 11,       // ㅇ
    TERMINATE = 18,  // ㅎ
    ADD = 3,         // ㄷ
    MULTIPLY = 4,    // ㄸ
    DIVIDE = 2,      // ㄴ
    SUBTRACT = 16,   // ㅌ
    MODULO = 5,      // ㄹ
    POP = 6,         // ㅁ
    PUSH = 7,        // ㅂ
    DUPLICATE = 8,   // ㅃ
    SWAP = 17,       // ㅍ
    SELECT = 9,      // ㅅ
    TRANSFER = 10,   // ㅆ
    COMPARE = 12,    // ㅈ
    DECIDE = 14,     // ㅊ
    COMMAND_ARITY = [0, 0, 2, 2, 2, 2, 1, 0, 1, 0, 1, 0, 2, 0, 1, 0, 2, 2, 0];

// Medials: ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ
// Directions (bits 0,1)
var UP = 0,
    RIGHT = 1,
    DOWN = 3,
    LEFT = 2,
    DIRECTION = 3;  // 0b000011
// Inertia and deflection (bits 2,3,4)
var FORCE = 0,
    SAME = 4,
    REFLECT = 24,
    SAME_V_REFLECT_H = 8,
    REFLECT_V_SAME_H = 20,
    INERTIA = 28;  // 0b011100
// Speed (bit 5)
var ONE = 0,
    TWO = 32;
    SPEED = 32;  // 0b100000
// Movements
var MOVEMENTS = [RIGHT | ONE, SAME, RIGHT | TWO, SAME, LEFT | ONE, SAME,
      LEFT | TWO, SAME, UP | ONE, SAME, SAME, SAME, UP | TWO, DOWN | ONE,
      SAME, SAME, SAME, DOWN | TWO, REFLECT_V_SAME_H, REFLECT, SAME_V_REFLECT_H
    ];

// Finals: null ㄱ ㄲ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ
// Arguments for POP and PUSH
var INTEGER = 21,    // ㅇ
    CHARACTER = 27,  // ㅎ
    VALUES = [0, 2, 4, 4, 2, 5, 5, 3, 5, 7, 9, 9, 7, 9, 9, 8, 4, 4, 6, 2, 4,
      undefined, 3, 4, 3, 4, 4, undefined];

// Storage
var QUEUE = 21;

var NULL_INSTRUCTION = [NULL, 1, 0];

function Interpreter() {
  var self = this;
  this._buffer = [];
  this._bufferingMode = 'line-bufferred';
  this._out = {print: function () {}};
}

Interpreter.prototype.setOut = function (out, bufferingMode) {
  this._out = out;
  if (bufferingMode !== undefined) this._bufferingMode = bufferingMode;
};

Interpreter.prototype.setProgram = function (program) {
  var code = this._parse(program);
  this._process = {
    code: code,
    height: code.length
  };
  this.reset();
};

Interpreter.prototype.reset = function () {
  var process = this._process;
  process.instructionIndex = [0, 0];
  process.direction = DOWN;
  process.speed = ONE;
  process.storage = this._createStorage();
  process.storageIndex = 0;
  process.instructionCount = 0;
  process.terminated = true;
  for (var i = 0; i < process.code.length; ++i) {
    if (process.code[i].length > 0) {
      process.terminated = false;
      break;
    }
  }
};

Interpreter.prototype.run = function (maxInstructions) {
  var process = this._process;
  if (process.terminated) return true;
  var code = process.code,
      data = process.storage[process.storageIndex],
      index = process.instructionIndex,
      currentInstructionCount = 0;
  while (maxInstructions === undefined ||
         currentInstructionCount < maxInstructions) {
    var row = code[index[0]];
        instruction = row[index[1]];
    if (instruction !== undefined) {
      var commandCode = instruction[0],
          movement = MOVEMENTS[instruction[1]],
          direction = movement & DIRECTION,
          speed = movement & SPEED,
          argumentCode = instruction[2],
          arity = COMMAND_ARITY[commandCode],
          first,
          second;
      // Update current direction
      if ((movement & INERTIA) == FORCE) {
        // Simple movement
        process.direction = direction;
        process.speed = speed;
      } else if (movement != SAME) {
        var d = process.direction;
        if (movement == REFLECT ||
            (movement == SAME_V_REFLECT_H && (d == RIGHT || d == LEFT)) ||
            (movement == REFLECT_V_SAME_H && (d == UP || d == DOWN))) {
          process.direction = ~d & DIRECTION;
        }
      }
      // Check if current storage has enough values
      if (data.length < 2 &&
          (arity == 2 || data.length < 1 && arity == 1)) {
        commandCode = NULL;
        process.direction = ~process.direction & DIRECTION;
      }
      // Get values
      if (arity >= 1) {
        if (commandCode != DUPLICATE) first = data.pop();
        if (arity == 2) second = data.pop();
      }
      // Perform command
      switch (commandCode) {
        // Arithmetic commands
        case ADD:      data.push(second + first); break;
        case MULTIPLY: data.push(second * first); break;
        case DIVIDE:   data.push(Math.floor(second / first)); break;
        case SUBTRACT: data.push(second - first); break;
        case MODULO:   data.push(second % first); break;
        // Storage commands
        case POP:
          if (argumentCode == INTEGER) {
            this._write(first);
          } else if (argumentCode == CHARACTER) {
            this._write(String.fromCharCode(first));
          } else {
            // Invalid argument; discard value
          }
          break;
        case PUSH:
          var value;
          if (argumentCode == INTEGER) {
            value = Math.floor(prompt('Enter an integer:'));
          } else if (argumentCode == CHARACTER) {
            value = prompt('Enter a character:').charCodeAt(0);
          } else {
            value = VALUES[argumentCode];
          }
          data.push(value);
          break;
        case DUPLICATE:
          data.duplicate();
          break;
        case SWAP:
          data.push(first);
          data.push(second);
          break;
        // Miscellaneous commands
        case SELECT:
          data = process.storage[process.storageIndex = argumentCode];
          break;
        case TRANSFER:
          process.storage[argumentCode].push(first);
          break;
        case COMPARE:
          data.push(second >= first ? 1 : 0);
          break;
        case DECIDE:
          if (first == 0) process.direction = ~process.direction & DIRECTION;
          break;
        case TERMINATE:
          process.terminated = true;
          this._flush();
          return true;
        case NULL: default:
          break;
      }
      ++process.instructionCount;
      ++currentInstructionCount;
    }
    // Move to the next instruction
    var inc = process.speed == ONE ? 1 : 2,
        width = row.length,
        x;
    switch (process.direction) {
      case UP:    x = index[0] - inc; index[0] = x < 0 ? height - 1 : x; break;
      case DOWN:  x = index[0] + inc; index[0] = x >= height ? 0 : x; break;
      case RIGHT: x = index[1] + inc; index[1] = x >= width ? 0 : x; break;
      case LEFT:  x = index[1] - inc; index[1] = x < 0 ? width - 1 : x; break;
    }
  }
  this._flush();
};

Interpreter.prototype._parse = function (program) {
  var lines = program.split('\n')
      height = lines.length,
      rows = [];
  for (var i = 0; i < height; ++i) {
    var line = lines[i],
        width = line.length,
        row = [];
    for (var j = 0; j < width; ++j) {
      row.push(this._makeInstruction(line.charCodeAt(j)));
    }
    rows.push(row);
  }
  return rows;
};

Interpreter.prototype._makeInstruction = function (charCode) {
  // '가'.charCodeAt(0) == 0xac00
  // '힣'.charCodeAt(0) == 0xd7a3
  if (charCode < 0xac00 || charCode > 0xd7a3) return NULL_INSTRUCTION;
  var offset = charCode - 0xac00,
      argumentCode = offset % 28,  // final (종성)
      movementCode = Math.floor(offset / 28) % 21,  // medial (중성)
      commandCode = Math.floor(offset / 28 / 21);  // initial (초성)
  return [commandCode, movementCode, argumentCode];
};

Interpreter.prototype._createStorage = function () {
  var storage = [];
  for (var i = 0; i < 28; ++i) {
    storage[i] = i == QUEUE ? new yaja.Queue() : new yaja.Stack();
  }
  return storage;
};

Interpreter.prototype._write = function (c) {
  var bufferingMode = this._bufferingMode,
      buffer = this._buffer,
      out = this._out;
  if (bufferingMode == 'unbuffered') {
    out.print(c);
  } else {
    buffer.push(c);
    if (bufferingMode == 'line-buffered' && c == '\n') this._flush();
  }
};

Interpreter.prototype._flush = function () {
  this._out.print(this._buffer.join(''));
  this._buffer.length = 0;
};

yaja.Interpreter = Interpreter;

})(yaja);
<|endoftext|>


<commit_before>// This module defines the Angular controller that renders the Chord Diagram.
define(function(require) {

  // Load D3 v4 via our custom bundle build output.
  var d3 = require("../d3/d3.min");

  // Load the module that defines the Chord Diagram using D3.
  var ChordDiagram = require("./chordDiagram");

  // Load the module that defines the HTML Table using D3.
  var Table = require("./table");

  // Access the Kibana plugin Angular module.
  var module = require("ui/modules").get("kibana-chord");

  // Create a time formatter for the timestamp in the table.
  var formatTime = d3.timeFormat("%B %d, %Y %X");

  // Register the controller with the Kibana plugin Angular module.
  module.controller("ChordController", function($scope, $rootScope, Private, $element, $http) {

    // Access the DOM element provided by Angular's dependency injection.
    var div = $element[0];

    // Construct a Bootstrap Grid to position the Chord Diagram and Table.
    var container = d3.select(div)
            .style("width", "100%")
          .append("div")
            .attr("class", "container-fluid")
          .append("div")
            .attr("class", "row"),
        chordContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node(),
        tableContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node();

    // Construct an instance of the Chord Diagram.
    var chordDiagram = ChordDiagram(chordContainer);

    // Construct an instance of the HTML Table.
    var table = Table(tableContainer);

    // Converts hierarchical result set from ElasticSearch into a tabular form.
    // Returns an array of row objects, similar to the format returned by d3.csv.
    function tabify(response){
      var tabifyAggResponse = Private(require("ui/agg_response/tabify/tabify"));
      var tabified = tabifyAggResponse($scope.vis, response, { asAggConfigResults: true });

      // Handle the case of a filter being applied in "Split Chart",
      // which yields a nested data structure with the table one level deeper.
      if("tables" in tabified.tables[0]){
        tabified = tabified.tables[0];
      }

      return tabified.tables[0].rows.map(function (array){
        var row = {};
        array.forEach(function (entry){
          row[entry.aggConfig.id] = entry.value;
        });
        return row;
      });
    }

    // Update the visualization with new data as the query response changes.
    $scope.$watch("esResponse", function(response) {

      // Tabify the response.
      var data = tabify(response);

      // Render the Chord Diagram.
      chordDiagram(data);

    });

    // Updates the details table based on the selected chord.
    function updateTable(){

      // Get the currently selected ribbon.
      var selectedRibbon = chordDiagram.selectedRibbon();

      // Extract the time interval from the global timeFilter.
      var timeBounds = $rootScope.timefilter.getBounds();

      // Construct the HTTP POST payload for the query middleware.
      var options = {
        source: selectedRibbon.source,
        destination: selectedRibbon.destination,
        index: $scope.vis.indexPattern.id,
        time: {
          gte: timeBounds.min.toDate().getTime(),
          lte: timeBounds.max.toDate().getTime(),
          format: "epoch_millis"
        }
      };

      // Invoke the query middleware, then render it into the table.
      $http
        .post("/api/kibana-chord", options)
        .then(function successCallback(response){

          // Transform the response data into a form the table can use.
          var data = response.data.hits.hits.map(function (d){
            d = d._source;

            // Format timestamp as human-readable date.
            d.timestamp = formatTime(new Date(d.timestamp));

            // Add source and dest attribute to be used in table
            d.source = d.nuage_metadata.sourcepolicygroups;
            d.dest = d.nuage_metadata.destinationpolicygroups;

            return d;
          });

          // Render the HTML Table.
          table(data, [
            { title: "Source IP", property: "sourceip" },
            { title: "Dest IP", property: "destinationip" },
            { title: "Source PG", property: "source" },
            { title: "Dest PG", property: "dest" },
            { title: "Type", property: "type" },
            { title: "Timestamp", property: "timestamp" },
            { title: "Packets", property: "packets" }
          ]);

        }, function errorCallback(response){
          throw response;
        });
    }

    // Invoke our custom middleware for querying ElasticSearch
    // when the user clicks on the ribbon.
    chordDiagram.onSelectedRibbonChange(updateTable);
  });
});
<commit_msg>Update table when esResponse changes, handling auto-refresh case. Closes #42<commit_after>// This module defines the Angular controller that renders the Chord Diagram.
define(function(require) {

  // Load D3 v4 via our custom bundle build output.
  var d3 = require("../d3/d3.min");

  // Load the module that defines the Chord Diagram using D3.
  var ChordDiagram = require("./chordDiagram");

  // Load the module that defines the HTML Table using D3.
  var Table = require("./table");

  // Access the Kibana plugin Angular module.
  var module = require("ui/modules").get("kibana-chord");

  // Create a time formatter for the timestamp in the table.
  var formatTime = d3.timeFormat("%B %d, %Y %X");

  // Register the controller with the Kibana plugin Angular module.
  module.controller("ChordController", function($scope, $rootScope, Private, $element, $http) {

    // Access the DOM element provided by Angular's dependency injection.
    var div = $element[0];

    // Construct a Bootstrap Grid to position the Chord Diagram and Table.
    var container = d3.select(div)
            .style("width", "100%")
          .append("div")
            .attr("class", "container-fluid")
          .append("div")
            .attr("class", "row"),
        chordContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node(),
        tableContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node();

    // Construct an instance of the Chord Diagram.
    var chordDiagram = ChordDiagram(chordContainer);

    // Construct an instance of the HTML Table.
    var table = Table(tableContainer);

    // Converts hierarchical result set from ElasticSearch into a tabular form.
    // Returns an array of row objects, similar to the format returned by d3.csv.
    function tabify(response){
      var tabifyAggResponse = Private(require("ui/agg_response/tabify/tabify"));
      var tabified = tabifyAggResponse($scope.vis, response, { asAggConfigResults: true });

      // Handle the case of a filter being applied in "Split Chart",
      // which yields a nested data structure with the table one level deeper.
      if("tables" in tabified.tables[0]){
        tabified = tabified.tables[0];
      }

      return tabified.tables[0].rows.map(function (array){
        var row = {};
        array.forEach(function (entry){
          row[entry.aggConfig.id] = entry.value;
        });
        return row;
      });
    }

    // Update the visualization with new data as the query response changes.
    $scope.$watch("esResponse", function(response) {

      // Tabify the response.
      var data = tabify(response);

      // Render the Chord Diagram.
      chordDiagram(data);

      // Update the table (if a ribbon is currently selected).
      // This is invoked here to handle the case of auto-refresh.
      if(chordDiagram.selectedRibbon()){
        updateTable();
      }

    });

    // Updates the details table based on the selected chord.
    function updateTable(){

      // Get the currently selected ribbon.
      var selectedRibbon = chordDiagram.selectedRibbon();

      // Extract the time interval from the global timeFilter.
      var timeBounds = $rootScope.timefilter.getBounds();

      // Construct the HTTP POST payload for the query middleware.
      var options = {
        source: selectedRibbon.source,
        destination: selectedRibbon.destination,
        index: $scope.vis.indexPattern.id,
        time: {
          gte: timeBounds.min.toDate().getTime(),
          lte: timeBounds.max.toDate().getTime(),
          format: "epoch_millis"
        }
      };

      // Invoke the query middleware, then render it into the table.
      $http
        .post("/api/kibana-chord", options)
        .then(function successCallback(response){

          // Transform the response data into a form the table can use.
          var data = response.data.hits.hits.map(function (d){
            d = d._source;

            // Format timestamp as human-readable date.
            d.timestamp = formatTime(new Date(d.timestamp));

            // Add source and dest attribute to be used in table
            d.source = d.nuage_metadata.sourcepolicygroups;
            d.dest = d.nuage_metadata.destinationpolicygroups;

            return d;
          });

          // Render the HTML Table.
          table(data, [
            { title: "Source IP", property: "sourceip" },
            { title: "Dest IP", property: "destinationip" },
            { title: "Source PG", property: "source" },
            { title: "Dest PG", property: "dest" },
            { title: "Type", property: "type" },
            { title: "Timestamp", property: "timestamp" },
            { title: "Packets", property: "packets" }
          ]);

        }, function errorCallback(response){
          throw response;
        });
    }

    // Invoke our custom middleware for querying ElasticSearch
    // when the user clicks on the ribbon.
    chordDiagram.onSelectedRibbonChange(updateTable);
  });
});
<|endoftext|>


<commit_before>/**
 * Created by Michael on 13/04/2016.
 */
var graphs;

function drawCluster(chartYear) {
    var chartId = "#draw-" + chartYear;
    //var width = $(document).width();
    var width = d3.select(chartId).node().getBoundingClientRect().width;
    //var height = $(document).height();
    var height = d3.select(chartId).node().getBoundingClientRect().height - 4;
    console.log("Row - Width: " + width + " height: " + height);
    var middlePoint = {X: width / 2, Y: height / 2};

    var countries = [];
    var nodesData = [];
    var selectedCountry;

    const giveColour = "#082f6d";
    const receiveColour = "#cd0027";
    const radiusCenter = 50;
    const radiusOuter = 20;
    const buffer1 = 80; // buffer between outer nodes
    const buffer2 = 25; // buffer between mid circle and outer circles
    var radius = radiusOuter + radiusCenter + buffer2; // radius of circle on which outer nodes should be drawn

    var svgContainer = d3.select(chartId)
        .append("svg")
        .attr("width", width)
        .attr("height", height);

    d3.json("data/countries.json", function (error, data) {
        if (error) throw error;

        countries = data.countries;

        //aantal gegeven punten
        var pointsCount = countries.length - 1;

        // hoek tussen landen
        var slice = 2 * Math.PI / pointsCount;

        //dynamically changes the radius
        var temp = pointsCount * (buffer1 + radiusOuter * 2);
        while (radius * Math.PI * 2 < temp) {
            radius += 20;
        }

        //België
        selectedCountry = {
            country: countries[0],
            X: middlePoint.X,
            Y: middlePoint.Y,
            R: radiusCenter
        };

        function getScores(selectedCountry, otherCountry) {
            return [50, 50];
        }

        // selected country
        nodesData.push(selectedCountry);

        var links = [];

        var i = 1;
        countries.slice(1, countries.length).forEach(
            //calc absolute pixels
            function (c) {
                var angle = slice * (i - 1);
                var isNeighour = selectedCountry.country.neighbours.indexOf(c.countryCode) > -1;

                var outerCenterX = middlePoint.X + (isNeighour ? radius * .6 : radius) * Math.cos(angle);
                var outerCenterY = middlePoint.Y + (isNeighour ? radius * .6 : radius) * Math.sin(angle);

                var outerLinkX = middlePoint.X + ((isNeighour ? radius * .6 : radius) - radiusOuter) * Math.cos(angle);
                var outerLinkY = middlePoint.Y + ((isNeighour ? radius * .6 : radius) - radiusOuter) * Math.sin(angle);

                var innerLinkX = middlePoint.X + radiusCenter * Math.cos(angle);
                var innerLinkY = middlePoint.Y + radiusCenter * Math.sin(angle);

                // center between 2 links; x = (x1+x2)/2; y = (y1+y2)/2
                var centerLinkX = (innerLinkX + outerLinkX) / 2;
                var centerLinkY = (innerLinkY + outerLinkY) / 2;

                nodesData.push({country: countries[i], X: outerCenterX, Y: outerCenterY, R: radiusOuter});

                var scores = getScores(selectedCountry, countries[i]);
                links.push({
                    innerLinkX: innerLinkX,
                    innerLinkY: innerLinkY,
                    outerLinkX: outerLinkX,
                    outerLinkY: outerLinkY,
                    centerLinkX: centerLinkX,
                    centerLinkY: centerLinkY,
                    scoreGiven: scores[0],
                    scoreReceived: scores[1]
                });

                i++;
            });

        var lineFunction = d3.svg.line()
            .x(function (d) {
                return d.X;
            })
            .y(function (d) {
                return d.Y;
            });

        var layer1 = svgContainer.append('g');

        function drawLinks(visibility) {
            //remove the current lines
            d3.selectAll("#receiveMid-" + chartYear).remove();
            d3.selectAll("#receive-" + chartYear).remove();
            d3.selectAll("#giveMid-" + chartYear).remove();
            d3.selectAll("#give-" + chartYear).remove();

            switch (visibility) {
                //give
                case 0:
                    links.forEach(function (item, index) {
                        layer1.append("path")
                            .attr("id", "give-" + chartYear)
                            .attr("d", lineFunction([
                                {X: item.innerLinkX, Y: item.innerLinkY},
                                {X: item.outerLinkX, Y: item.outerLinkY}
                            ]))
                            .attr("stroke", giveColour)
                            .attr("stroke-width", 2)
                            .attr("fill", "none")
                            .attr("marker-end", "url(#giveArrowHead)");
                    });
                    break;
                //receive
                case 1:
                    links.forEach(function (item, index) {
                        layer1.append("path")
                            .attr("id", "receive-" + chartYear)
                            .attr("d", lineFunction([
                                {X: item.outerLinkX, Y: item.outerLinkY},
                                {X: item.innerLinkX, Y: item.innerLinkY}
                            ]))
                            .attr("stroke", receiveColour)
                            .attr("stroke-width", 2)
                            .attr("fill", "none")
                            .attr("marker-end", "url(#receiveArrowHead)");
                    });
                    break;
                //both
                case  2:
                    links.forEach(function (item, index) {
                        //give
                        layer1.append("path")
                            .attr("id", "give-" + chartYear)
                            .attr("d", lineFunction([
                                {X: item.innerLinkX, Y: item.innerLinkY},
                                {X: item.centerLinkX, Y: item.centerLinkY}
                            ]))
                            .attr("stroke", giveColour)
                            .attr("stroke-width", 2)
                            .attr("fill", "none")
                            .attr("marker-end", "url(#giveArrowHead)");
                        //receive
                        layer1.append("path")
                            .attr("id", "receive-" + chartYear)
                            .attr("d", lineFunction([
                                {X: item.outerLinkX, Y: item.outerLinkY},
                                {X: item.centerLinkX, Y: item.centerLinkY}
                            ]))
                            .attr("stroke", receiveColour)
                            .attr("stroke-width", 2)
                            .attr("fill", "none")
                            .attr("marker-end", "url(#receiveArrowHead)");
                    });
                    break;
            }

        }

        drawLinks(0);//draws the links; default is given

        var nodes = svgContainer.selectAll("node")
            .data(nodesData);

        var defs = nodes.enter().append('defs');

        defs.append('pattern')
            .attr('id', function (d) {
                return (d.country.countryCode + "-icon");
            })
            .attr('width', 1)
            .attr('height', 1)
            .attr('patternContentUnits', 'objectBoundingBox')
            .append("image")
            .attr("xlink:xlink:href", function (d) {
                return ("./images/flags/" + d.country.image);
            })
            .attr("height", 1)
            .attr("width", 1)
            .attr("preserveAspectRatio", "xMinYMin slice");

        defs.append("marker")
            .attr("id", "giveArrowHead")
            .attr("refX", 4) /*must be smarter way to calculate shift*/
            .attr("refY", 0)
            .attr("markerWidth", 6)
            .attr("markerHeight", 4)
            .attr("orient", "auto")
            .attr("viewBox", "-5 -5 10 10")
            .append("path")
            .attr("d", "M 0,0 m -5,-5 L 5,0 L -5,5 Z")
            .attr("fill", giveColour);

        defs.append("marker")
            .attr("id", "receiveArrowHead")
            .attr("refX", 4) /*must be smarter way to calculate shift*/
            .attr("refY", 0)
            .attr("markerWidth", 6)
            .attr("markerHeight", 4)
            .attr("orient", "auto")
            .attr("viewBox", "-5 -5 10 10")
            .append("path")
            .attr("d", "M 0,0 m -5,-5 L 5,0 L -5,5 Z")
            .attr("fill", receiveColour);

        nodes.enter().append("circle")
            .attr("class", "node")
            .attr("cx", function (d) {
                return d.X
            })
            .attr("cy", function (d) {
                return d.Y
            })
            .attr("r", function (d) {
                return d.R + 3.5
            })
            .style("fill", function (d) {
                return ("url(#" + d.country.countryCode + "-icon)");
            })
            .style("stroke", "10px solid black");

        //adds the buttons to choose the visible lines
        document.getElementById("giveButton-" + chartYear).onclick = function () {
            drawLinks(0);
        };
        document.getElementById("receiveButton-" + chartYear).onclick = function () {
            drawLinks(1);
        };
        document.getElementById("bothButton-" + chartYear).onclick = function () {
            drawLinks(2);
        };
    });
}<commit_msg>sorting none/neighbours TODO score<commit_after>/**
 * Created by Michael on 13/04/2016.
 */
var graphs;

function drawCluster(chartYear) {
    var chartId = "#draw-" + chartYear;
    //var width = $(document).width();
    var width = d3.select(chartId).node().getBoundingClientRect().width;
    //var height = $(document).height();
    var height = d3.select(chartId).node().getBoundingClientRect().height - 4;
    console.log("Row - Width: " + width + " height: " + height);
    var middlePoint = {X: width / 2, Y: height / 2};

    var countries = [];
    var nodesData = [];
    var selectedCountry;

    const giveColour = "#082f6d";
    const receiveColour = "#cd0027";
    const radiusCenter = 50;
    const radiusOuter = 20;
    const buffer1 = 80; // buffer between outer nodes
    const buffer2 = 25; // buffer between mid circle and outer circles
    var radius = radiusOuter + radiusCenter + buffer2; // radius of circle on which outer nodes should be drawn

    var svgContainer = d3.select(chartId)
        .append("svg")
        .attr("width", width)
        .attr("height", height);

    var sortMethod = 1; //0 = none; 1 = neighbours ; 2 = score

    d3.json("data/countries.json", function (error, data) {
            if (error) throw error;

            countries = data.countries;

            //aantal gegeven punten
            var pointsCount = countries.length - 1;

            // hoek tussen landen
            var slice = 2 * Math.PI / pointsCount;

            //dynamically changes the radius
            var temp = pointsCount * (buffer1 + radiusOuter * 2);
            while (radius * Math.PI * 2 < temp) {
                radius += 20;
            }

            //België
            selectedCountry = {
                country: countries[0],
                X: middlePoint.X,
                Y: middlePoint.Y,
                R: radiusCenter
            };

            function getScores(selectedCountry, otherCountry) {
                return [50, 50];
            }

            // selected country
            nodesData.push(selectedCountry);

            var links = [];

            function sortCountries() {
                if (sortMethod == 0)
                    countries.sort();
                else
                    countries.sort(function (c1, c2) {
                        if (sortMethod == 1) {
                            //neighbours
                            return selectedCountry.country.neighbours.indexOf(c1.countryCode) > -1 ? -1 : 1
                        } else {
                            //score
                            //TODO
                        }
                    });
            }

            sortCountries();

            var i = 1;
            countries.slice(1, countries.length).forEach(
                //calc absolute pixels
                function (c) {
                    var angle = slice * (i - 1);
                    var isNeighour = selectedCountry.country.neighbours.indexOf(c.countryCode) > -1;

                    var outerCenterX = middlePoint.X + (isNeighour ? radius * .6 : radius) * Math.cos(angle);
                    var outerCenterY = middlePoint.Y + (isNeighour ? radius * .6 : radius) * Math.sin(angle);

                    var outerLinkX = middlePoint.X + ((isNeighour ? radius * .6 : radius) - radiusOuter) * Math.cos(angle);
                    var outerLinkY = middlePoint.Y + ((isNeighour ? radius * .6 : radius) - radiusOuter) * Math.sin(angle);

                    var innerLinkX = middlePoint.X + radiusCenter * Math.cos(angle);
                    var innerLinkY = middlePoint.Y + radiusCenter * Math.sin(angle);

                    // center between 2 links; x = (x1+x2)/2; y = (y1+y2)/2
                    var centerLinkX = (innerLinkX + outerLinkX) / 2;
                    var centerLinkY = (innerLinkY + outerLinkY) / 2;

                    nodesData.push({country: countries[i], X: outerCenterX, Y: outerCenterY, R: radiusOuter});

                    var scores = getScores(selectedCountry, countries[i]);
                    links.push({
                        innerLinkX: innerLinkX,
                        innerLinkY: innerLinkY,
                        outerLinkX: outerLinkX,
                        outerLinkY: outerLinkY,
                        centerLinkX: centerLinkX,
                        centerLinkY: centerLinkY,
                        scoreGiven: scores[0],
                        scoreReceived: scores[1]
                    });

                    i++;
                });

            var lineFunction = d3.svg.line()
                .x(function (d) {
                    return d.X;
                })
                .y(function (d) {
                    return d.Y;
                });

            var layer1 = svgContainer.append('g');

            function drawLinks(visibility) {
                //remove the current lines
                d3.selectAll("#receiveMid-" + chartYear).remove();
                d3.selectAll("#receive-" + chartYear).remove();
                d3.selectAll("#giveMid-" + chartYear).remove();
                d3.selectAll("#give-" + chartYear).remove();

                switch (visibility) {
                    //give
                    case 0:
                        links.forEach(function (item, index) {
                            layer1.append("path")
                                .attr("id", "give-" + chartYear)
                                .attr("d", lineFunction([
                                    {X: item.innerLinkX, Y: item.innerLinkY},
                                    {X: item.outerLinkX, Y: item.outerLinkY}
                                ]))
                                .attr("stroke", giveColour)
                                .attr("stroke-width", 2)
                                .attr("fill", "none")
                                .attr("marker-end", "url(#giveArrowHead)");
                        });
                        break;
                    //receive
                    case 1:
                        links.forEach(function (item, index) {
                            layer1.append("path")
                                .attr("id", "receive-" + chartYear)
                                .attr("d", lineFunction([
                                    {X: item.outerLinkX, Y: item.outerLinkY},
                                    {X: item.innerLinkX, Y: item.innerLinkY}
                                ]))
                                .attr("stroke", receiveColour)
                                .attr("stroke-width", 2)
                                .attr("fill", "none")
                                .attr("marker-end", "url(#receiveArrowHead)");
                        });
                        break;
                    //both
                    case  2:
                        links.forEach(function (item, index) {
                            //give
                            layer1.append("path")
                                .attr("id", "give-" + chartYear)
                                .attr("d", lineFunction([
                                    {X: item.innerLinkX, Y: item.innerLinkY},
                                    {X: item.centerLinkX, Y: item.centerLinkY}
                                ]))
                                .attr("stroke", giveColour)
                                .attr("stroke-width", 2)
                                .attr("fill", "none")
                                .attr("marker-end", "url(#giveArrowHead)");
                            //receive
                            layer1.append("path")
                                .attr("id", "receive-" + chartYear)
                                .attr("d", lineFunction([
                                    {X: item.outerLinkX, Y: item.outerLinkY},
                                    {X: item.centerLinkX, Y: item.centerLinkY}
                                ]))
                                .attr("stroke", receiveColour)
                                .attr("stroke-width", 2)
                                .attr("fill", "none")
                                .attr("marker-end", "url(#receiveArrowHead)");
                        });
                        break;
                }

            }

            drawLinks(0);//draws the links; default is given

            var nodes = svgContainer.selectAll("node")
                .data(nodesData);

            var defs = nodes.enter().append('defs');

            defs.append('pattern')
                .attr('id', function (d) {
                    return (d.country.countryCode + "-icon");
                })
                .attr('width', 1)
                .attr('height', 1)
                .attr('patternContentUnits', 'objectBoundingBox')
                .append("image")
                .attr("xlink:xlink:href", function (d) {
                    return ("./images/flags/" + d.country.image);
                })
                .attr("height", 1)
                .attr("width", 1)
                .attr("preserveAspectRatio", "xMinYMin slice");

            defs.append("marker")
                .attr("id", "giveArrowHead")
                .attr("refX", 4) /*must be smarter way to calculate shift*/
                .attr("refY", 0)
                .attr("markerWidth", 6)
                .attr("markerHeight", 4)
                .attr("orient", "auto")
                .attr("viewBox", "-5 -5 10 10")
                .append("path")
                .attr("d", "M 0,0 m -5,-5 L 5,0 L -5,5 Z")
                .attr("fill", giveColour);

            defs.append("marker")
                .attr("id", "receiveArrowHead")
                .attr("refX", 4) /*must be smarter way to calculate shift*/
                .attr("refY", 0)
                .attr("markerWidth", 6)
                .attr("markerHeight", 4)
                .attr("orient", "auto")
                .attr("viewBox", "-5 -5 10 10")
                .append("path")
                .attr("d", "M 0,0 m -5,-5 L 5,0 L -5,5 Z")
                .attr("fill", receiveColour);

            nodes.enter().append("circle")
                .attr("class", "node")
                .attr("cx", function (d) {
                    return d.X
                })
                .attr("cy", function (d) {
                    return d.Y
                })
                .attr("r", function (d) {
                    return d.R + 3.5
                })
                .style("fill", function (d) {
                    return ("url(#" + d.country.countryCode + "-icon)");
                })
                .style("stroke", "10px solid black");

            //adds the buttons to choose the visible lines
            document.getElementById("giveButton-" + chartYear).onclick = function () {
                drawLinks(0);
            };
            document.getElementById("receiveButton-" + chartYear).onclick = function () {
                drawLinks(1);
            };
            document.getElementById("bothButton-" + chartYear).onclick = function () {
                drawLinks(2);
            };
        }
    )
    ;
}<|endoftext|>


<commit_before>//global directives go here

angular.module('omniwallet').directive('d3PieChart', function() {
    return {
      template: '<svg></svg>',
      controller: function($scope, $element, $attrs) {

        $scope.chart = {
          width: 300,
          height: 300
        }
        $scope.radius = Math.min($scope.chart.width, $scope.chart.height) / 2

        $element.find('svg').attr('height', $scope.chart.height).attr('width', $scope.chart.width);

        var color = d3.scale.category20()

        var arc = d3.svg.arc()
        .outerRadius($scope.radius - 10)
        .innerRadius(0);

        var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
          return d.value;
        });

        var svg = d3.select("svg")

        $scope.totalsPromise.then(function(successData) {

          var data = [],
            keys = Object.keys($scope.totals);
          keys.forEach(function(e, i) {
            data.push({
              value: $scope.totals[e],
              name: keys[i],
              color: Math.floor(Math.random() * 10)
            });
          });

          var g = svg.selectAll(".arc")
          .data(pie(data))
          .enter().append("g")
          .attr("class", "arc");

          g.append("path")
            .attr("d", arc)
            .style("fill", function(d) {
              return color(d.data.color);
            })
            .attr('transform', 'translate(150,150)');

          g.append("text")
            .attr("transform", function(d) {
              var c = arc.centroid(d);
              return "translate(" + (150 + c[0]) + "," + (150 + c[1]) + ")";
            })
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .text(function(d) {
            return d.data.name;
          });
        });
      }
    }
  }).directive('omTooltip', function() {
    return {
      template: '(?)',
      link: function(scope, iElement, iAttrs, controller) {
        if (iAttrs.text)
          iElement.tooltip({
            title: iAttrs.text,
            placement: 'down',
            container: 'body'
          });
      }
    }
  }).directive('match', [function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {

        scope.$watch('[' + attrs.ngModel + ', ' + attrs.match + ']', function(value) {
          ctrl.$setValidity('match', value[0] === value[1]);
        }, true);

      }
    }
 }]).directive('autoFocus', function($timeout) {
  return {
    restrict: 'AC',
    scope: {
      'autoFocus': '=autoFocus'
    },
    link: function(scope, element) {
      scope.$watch('autoFocus', function() {
        if(scope.autoFocus) {
          $timeout(function(){
            $(element[0]).focus();
          }, 100);
        }
      });
    }
  };
}).directive('combobox', function(){
  return {
    restrict:'E',
    templateUrl:'/template/combobox/combobox.html',
    scope:{
      optionList: '=',
      modelValue:'=',
      label:'@',
      placeholder:'@',
      valueSelected:'&'
    },
    controller:function($scope){
      $scope.filteredList = $scope.optionList;
      $scope.selectedOption=false;

      $scope.filter=function(){
        $scope.filteredList = $scope.optionList.filter(function(option){
          var matcher = new RegExp("^"+$scope.modelValue);
          return matcher.test(option);
        });
      };

      $scope.$watch(function(){ return $scope.optionList; },function(options){
        $scope.filteredList = options;
      });

    },
    link: function(scope, element, attr){
      scope.open = function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "width":$('input',element).outerWidth(),
          "left":$('.input-group-addon',element).outerWidth()
        });
        $('.dropdown',element).addClass('open');
      };

      scope.close = function(){
        if(!scope.selectedOption)
          $('.dropdown',element).removeClass('open');
      };

      scope.optionSelected = function(option){
        scope.modelValue = option;
        $('.dropdown',element).removeClass('open');
        scope.valueSelected({category:option});
        scope.selectedOption=false;
      };

      element.on('mousedown','a',function(){
        scope.selectedOption = true;
      });

      scope.$watch(function(){ return scope.label; }, function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "width":$('input',element).width(),
          "left":$('.input-group-addon',element).outerWidth()
        });
      });
    }
  };
});
<commit_msg>Add *no results* option<commit_after>//global directives go here

angular.module('omniwallet').directive('d3PieChart', function() {
    return {
      template: '<svg></svg>',
      controller: function($scope, $element, $attrs) {

        $scope.chart = {
          width: 300,
          height: 300
        }
        $scope.radius = Math.min($scope.chart.width, $scope.chart.height) / 2

        $element.find('svg').attr('height', $scope.chart.height).attr('width', $scope.chart.width);

        var color = d3.scale.category20()

        var arc = d3.svg.arc()
        .outerRadius($scope.radius - 10)
        .innerRadius(0);

        var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
          return d.value;
        });

        var svg = d3.select("svg")

        $scope.totalsPromise.then(function(successData) {

          var data = [],
            keys = Object.keys($scope.totals);
          keys.forEach(function(e, i) {
            data.push({
              value: $scope.totals[e],
              name: keys[i],
              color: Math.floor(Math.random() * 10)
            });
          });

          var g = svg.selectAll(".arc")
          .data(pie(data))
          .enter().append("g")
          .attr("class", "arc");

          g.append("path")
            .attr("d", arc)
            .style("fill", function(d) {
              return color(d.data.color);
            })
            .attr('transform', 'translate(150,150)');

          g.append("text")
            .attr("transform", function(d) {
              var c = arc.centroid(d);
              return "translate(" + (150 + c[0]) + "," + (150 + c[1]) + ")";
            })
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .text(function(d) {
            return d.data.name;
          });
        });
      }
    }
  }).directive('omTooltip', function() {
    return {
      template: '(?)',
      link: function(scope, iElement, iAttrs, controller) {
        if (iAttrs.text)
          iElement.tooltip({
            title: iAttrs.text,
            placement: 'down',
            container: 'body'
          });
      }
    }
  }).directive('match', [function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {

        scope.$watch('[' + attrs.ngModel + ', ' + attrs.match + ']', function(value) {
          ctrl.$setValidity('match', value[0] === value[1]);
        }, true);

      }
    }
 }]).directive('autoFocus', function($timeout) {
  return {
    restrict: 'AC',
    scope: {
      'autoFocus': '=autoFocus'
    },
    link: function(scope, element) {
      scope.$watch('autoFocus', function() {
        if(scope.autoFocus) {
          $timeout(function(){
            $(element[0]).focus();
          }, 100);
        }
      });
    }
  };
}).directive('combobox', function(){
  return {
    restrict:'E',
    templateUrl:'/template/combobox/combobox.html',
    scope:{
      optionList: '=',
      modelValue:'=',
      label:'@',
      placeholder:'@',
      valueSelected:'&'
    },
    controller:function($scope){
      $scope.filteredList = $scope.optionList;
      $scope.selectedOption=false;

      $scope.filter=function(){
        var results = $scope.optionList.filter(function(option){
          var matcher = new RegExp("^"+$scope.modelValue);
          return matcher.test(option);
        }) ;

        $scope.filteredList = results.length > 0 ? results: ["No results"];
      };

      $scope.$watch(function(){ return $scope.optionList; },function(options){
        $scope.filteredList = options;
      });

    },
    link: function(scope, element, attr){
      scope.open = function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "width":$('input',element).outerWidth(),
          "left":$('.input-group-addon',element).outerWidth()
        });
        $('.dropdown',element).addClass('open');
      };

      scope.close = function(){
        if(!scope.selectedOption)
          $('.dropdown',element).removeClass('open');
      };

      scope.optionSelected = function(option){
        scope.modelValue = option;
        $('.dropdown',element).removeClass('open');
        scope.valueSelected({category:option});
        scope.selectedOption=false;
      };

      element.on('mousedown','a',function(){
        scope.selectedOption = true;
      });

      scope.$watch(function(){ return scope.label; }, function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "width":$('input',element).width(),
          "left":$('.input-group-addon',element).outerWidth()
        });
      });
    }
  };
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var express = require('express');
var cors = require('cors');
var fs = require('fs');
const path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'quick-bench-front-end', 'build')));
var exec = require('child_process').exec;
var sha1 = require('sha1');
var bodyParser = require('body-parser');
var multer = require('multer');

var upload = multer();

const MAX_CODE_LENGTH = 20000;
const WRITE_PATH = '/data';
const PREFIX_CODE_1 = `#include <benchmark/benchmark_api.h>
`;
const SUFFIX_CODE_1 = `

static void Noop(benchmark::State& state) {
  while (state.KeepRunning());
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;
const PREFIX_CODE_2 = `#include <benchmark/benchmark.h>
`;
const SUFFIX_CODE_2 = `

static void Noop(benchmark::State& state) {
  for (auto _ : state) benchmark::DoNotOptimize(0);
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;
const SUFFIX_CODE_3 = `

static void Noop(benchmark::State& state) {
  for (auto _ : state) benchmark::DoNotOptimize(0);
}
BENCHMARK(Noop);
BENCHMARK_MAIN();`;

const NOOP_BUILD = 'int main() {return 0;}';

app.use(bodyParser.json());
app.use(cors());

function write(fileName, code) {
    return new Promise((resolve, reject) => {
        fs.writeFile(fileName, code, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function read(fileName, acceptMissing) {
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (err, data) => {
            if (err) {
                if (acceptMissing && err.code === 'ENOENT') {
                    resolve(null);
                } else {
                    reject(err);
                }
            } else {
                resolve(data);
            }
        });
    });
}

function cleanFilename(text) {
    return text.replace(/[^\W-]/gi, '_');
}

function runDockerCommand(fileName, request, force) {
    return './run-docker-builder ' + fileName + ' ' + request.compiler + ' ' + request.optim + ' ' + request.cppVersion + ' ' + (request.isAnnotated || false) + ' ' + (force || false) + ' ' + (request.lib || 'gnu') + cleanFilename(request.title);
}

function optionsToString(request, protocolVersion) {
    let options = {
        "protocolVersion": protocolVersion,
        "compiler": request.compiler,
        "optim": request.optim,
        "cppVersion": request.cppVersion,
        "isAnnotated": request.isAnnotated,
        "lib": request.lib,
        "title": request.title
    };
    return JSON.stringify(options);
}

function execute(fileName, request, protocolVersion, force) {
    let options = {
        timeout: 60000,
        killSignal: 'SIGKILL'
    };
    return new Promise((resolve, reject) => {
        console.time(fileName);
        return exec(runDockerCommand(fileName, request, force), options, function (err, stdout, stderr) {
            if (err) {
                console.timeEnd(fileName);
                console.log('Bench failed ' + fileName);
                exec("./kill-docker " + fileName);
                reject("\u001b[0m\u001b[0;1;31mError or timeout\u001b[0m\u001b[1m
" + stdout + "
" + stderr);
            } else {
                console.timeEnd(fileName);
                console.log('Bench done ' + fileName + (stderr.indexOf('cached results') > -1 ? ' from cache' : ''));
                resolve({
                    res: fs.readFileSync(fileName + '.out'),
                    stdout: stderr,
                    id: encodeName(makeCodeName(request, protocolVersion))
                });
            }
        });
    });
}

function groupResults(results, id) {
    let code = results[0];
    let options = results[1];
    let graph = results[2];
    return { code: code, options: JSON.parse(options), graph: graph, id: id };
}

function makeCodeName(tab, protocolVersion) {
    return sha1(tab.title + tab.code + tab.compiler + tab.optim + tab.cppVersion + tab.lib + protocolVersion);
}
function makeName(request) {
    return sha1(request.tabs.reduce(u => makeCodeName(u, request.protocolVersion)) + request.protocolVersion);
}

function wrapCode(inputCode) {
    return PREFIX_CODE_2 + inputCode + SUFFIX_CODE_3;
}

function unwrapCode(inputCode) {
    if (inputCode.startsWith(PREFIX_CODE_1)) {
        inputCode = inputCode.slice(PREFIX_CODE_1.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_1)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_1.length);
    }
    if (inputCode.startsWith(PREFIX_CODE_2)) {
        inputCode = inputCode.slice(PREFIX_CODE_2.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_2)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_2.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_3)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_3.length);
    }
    return inputCode;
}

function encodeName(id) {
    let short = new Buffer(id, 'hex').toString('base64');
    short = short.replace(new RegExp('/', 'g'), '-').replace(new RegExp('\\+', 'g'), '_');
    return short.slice(0, -1);
}

function decodeName(short) {
    short = short.replace(new RegExp('\\-', 'g'), '/').replace(new RegExp('_', 'g'), '+ ') + '=';
    return new Buffer(short, 'base64').toString('hex');
}

function getFunctions(code) {
    RE = /BENCHMARK\s*\(\s*([A-Za-z0-9_]+)\s*\)/g;
    let content='';
    let res;
    while ((res = RE.exec(code)) !== null) {
        content+= res[1] + '\n';
    }
    return content;
}

function filename(name) {
    let dir = WRITE_PATH + '/' + name.substr(0, 2);
    return  dir + '/' + name;
}

async function benchmarkOneBuild(tab, protocolVersion, force) {
    try {
	if (tab.code.length > MAX_CODE_LENGTH) {
            return Promise.reject(`\u001b[0m\u001b[0;1;31mError: Unauthorized code length in {$unit.title}.\u001b[0m\u001b[1m`);
	}
	let name = makeCodeName(tab, protocolVersion);
	console.log('Bench ' + name + ' < ' + optionsToString(tab, protocolVersion));
	let fileName = filename(name);
	await write(fileName + '.cpp', tab.code);
	await write(fileName + '.opt', optionsToString(tab, protocolVersion));
	return await execute(fileName, tab, protocolVersion, force);
    } catch (e) {
	return { stdout: e };
    }
}

async function benchmark(request, header) {
    return await Promise.all(request.tabs.map(u => benchmarkOneBuild(u, request.protocolVersion, request.force)));
}

async function reloadOne(id) {
    const fileName = filename(id);
    const values = await Promise.all([read(fileName + '.cpp'), read(fileName + '.opt'), read(fileName + '.out')]);
    return groupResults(values, id);
}

async function reload(encodedName) {
    let fileName = filename(decodeName(encodedName));
    const ids = await read(fileName + '.res');
    return await Promise.all(ids.split("\n").map(id => reloadOne(decodeName(id))));
}

function readBuildResults(values) {
    if (values.res == null) return {};
    let results = values.res.toString().split('\n');
    let times = [];
    let memories = [];
    for (let i = 0; i < results.length; i++) {
	let s = results[i].split('\t');
	if (s.length === 2) {
	    times.push(s[0]);
	    memories.push(s[1]);
	}
    }
    return {
	times: times,
	memories: memories,
    };
}

function makeBuildGraphResult(values) {
    let result = values.map(v => readBuildResults(v));
    let message = values.map(v => v.stdout).reduce((r, v) => r + '\n' + v);
    let idsList = values.map(v => v.id).reduce((r, v) => r + '\n' + v);
    let id = sha1(idsList);
    write(filename(id) + '.res', idsList);
    return {
        result: result,
        message: message,
        id: encodeName(id)
    };
}

function makeOneResult(done) {
    return {
        code: done.code,
        compiler: done.options.compiler,
        optim: done.options.optim,
        cppVersion: done.options.cppVersion,
        lib: done.options.lib,
        protocolVersion: done.options.protocolVersion
    };
}

function makeWholeResult(done) {
    return Object.assign({ tabs: done.map(d => makeOneResult(d)) }, makeBuildGraphResult(done.map(d => {
        return {
            res: d.graph,
            stdout: '',
            id: encodeName(d.id)
        };
    })));
}

app.post('/build', upload.array(), function (req, res) {
    Promise.resolve(benchmark(req.body, req.headers))
        .then((done) => res.json(makeBuildGraphResult(done)))
        .catch((err) => res.json({ message: err }));
});

app.get('/build/:id', upload.array(), function (req, res) {
    console.log('Get ' + req.params.id + ' ' + JSON.stringify(req.headers));
    Promise.resolve(reload(req.params.id))
        .then((done) => res.json(makeWholeResult(done)))
        .catch(() => res.json({ message: 'Could not load given id' }));
});

app.get('/:id', upload.array(), function (req, res) {
    res.redirect(`/b/${req.params.id}`);
});

app.get('/b/:id', upload.array(), function (req, res) {
    res.sendFile(path.join(__dirname, 'quick-bench-front-end', 'build', 'index.html'));
});

app.listen(3000, function () {
    console.log('Listening to commands');
});

exports.makeName = makeName;
exports.encodeName = encodeName;
exports.decodeName = decodeName;
exports.wrapCode = wrapCode;
exports.unwrapCode = unwrapCode;
exports.groupResults = groupResults;
exports.getFunctions = getFunctions;
exports.optionsToString = optionsToString;
exports.execute = execute;
<commit_msg>Store tab titles at the root level so that we don't recompile for a title change.<commit_after>#!/usr/bin/env node

var express = require('express');
var cors = require('cors');
var fs = require('fs');
const path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'quick-bench-front-end', 'build')));
var exec = require('child_process').exec;
var sha1 = require('sha1');
var bodyParser = require('body-parser');
var multer = require('multer');

var upload = multer();

const MAX_CODE_LENGTH = 20000;
const WRITE_PATH = '/data';
const PREFIX_CODE_1 = `#include <benchmark/benchmark_api.h>
`;
const SUFFIX_CODE_1 = `

static void Noop(benchmark::State& state) {
  while (state.KeepRunning());
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;
const PREFIX_CODE_2 = `#include <benchmark/benchmark.h>
`;
const SUFFIX_CODE_2 = `

static void Noop(benchmark::State& state) {
  for (auto _ : state) benchmark::DoNotOptimize(0);
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;
const SUFFIX_CODE_3 = `

static void Noop(benchmark::State& state) {
  for (auto _ : state) benchmark::DoNotOptimize(0);
}
BENCHMARK(Noop);
BENCHMARK_MAIN();`;

const NOOP_BUILD = 'int main() {return 0;}';

app.use(bodyParser.json());
app.use(cors());

function write(fileName, code) {
    return new Promise((resolve, reject) => {
        fs.writeFile(fileName, code, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function read(fileName, acceptMissing) {
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (err, data) => {
            if (err) {
                if (acceptMissing && err.code === 'ENOENT') {
                    resolve(null);
                } else {
                    reject(err);
                }
            } else {
                resolve(data);
            }
        });
    });
}

function cleanFilename(text) {
    return text.replace(/[^\W-]/gi, '_');
}

function runDockerCommand(fileName, request, force) {
    return './run-docker-builder ' + fileName + ' ' + request.compiler + ' ' + request.optim + ' ' + request.cppVersion + ' ' + (request.isAnnotated || false) + ' ' + (force || false) + ' ' + (request.lib || 'gnu') + cleanFilename(request.title);
}

function optionsToString(request, protocolVersion) {
    let options = {
        "protocolVersion": protocolVersion,
        "compiler": request.compiler,
        "optim": request.optim,
        "cppVersion": request.cppVersion,
        "isAnnotated": request.isAnnotated,
        "lib": request.lib
    };
    return JSON.stringify(options);
}

function execute(fileName, request, protocolVersion, force) {
    let options = {
        timeout: 60000,
        killSignal: 'SIGKILL'
    };
    return new Promise((resolve, reject) => {
        console.time(fileName);
        return exec(runDockerCommand(fileName, request, force), options, function (err, stdout, stderr) {
            if (err) {
                console.timeEnd(fileName);
                console.log('Bench failed ' + fileName);
                exec("./kill-docker " + fileName);
                reject("\u001b[0m\u001b[0;1;31mError or timeout\u001b[0m\u001b[1m
" + stdout + "
" + stderr);
            } else {
                console.timeEnd(fileName);
                console.log('Bench done ' + fileName + (stderr.indexOf('cached results') > -1 ? ' from cache' : ''));
                resolve({
                    res: fs.readFileSync(fileName + '.out'),
                    stdout: stderr,
                    id: encodeName(makeCodeName(request, protocolVersion)),
                    title: request.title
                });
            }
        });
    });
}

function groupResults(results, id, name) {
    let code = results[0];
    let options = results[1];
    let graph = results[2];
    return { code: code, options: JSON.parse(options), graph: graph, id: id, title: name };
}

function makeCodeName(tab, protocolVersion) {
    return sha1(tab.code + tab.compiler + tab.optim + tab.cppVersion + tab.lib + protocolVersion);
}
function makeName(request) {
    return sha1(request.tabs.reduce(u => makeCodeName(u, request.protocolVersion)) + request.protocolVersion);
}

function wrapCode(inputCode) {
    return PREFIX_CODE_2 + inputCode + SUFFIX_CODE_3;
}

function unwrapCode(inputCode) {
    if (inputCode.startsWith(PREFIX_CODE_1)) {
        inputCode = inputCode.slice(PREFIX_CODE_1.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_1)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_1.length);
    }
    if (inputCode.startsWith(PREFIX_CODE_2)) {
        inputCode = inputCode.slice(PREFIX_CODE_2.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_2)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_2.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_3)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_3.length);
    }
    return inputCode;
}

function encodeName(id) {
    let short = new Buffer(id, 'hex').toString('base64');
    short = short.replace(new RegExp('/', 'g'), '-').replace(new RegExp('\\+', 'g'), '_');
    return short.slice(0, -1);
}

function decodeName(short) {
    short = short.replace(new RegExp('\\-', 'g'), '/').replace(new RegExp('_', 'g'), '+ ') + '=';
    return new Buffer(short, 'base64').toString('hex');
}

function getFunctions(code) {
    RE = /BENCHMARK\s*\(\s*([A-Za-z0-9_]+)\s*\)/g;
    let content = '';
    let res;
    while ((res = RE.exec(code)) !== null) {
        content += res[1] + '\n';
    }
    return content;
}

function filename(name) {
    let dir = WRITE_PATH + '/' + name.substr(0, 2);
    return dir + '/' + name;
}

async function benchmarkOneBuild(tab, protocolVersion, force) {
    try {
        if (tab.code.length > MAX_CODE_LENGTH) {
            return Promise.reject(`\u001b[0m\u001b[0;1;31mError: Unauthorized code length in {$unit.title}.\u001b[0m\u001b[1m`);
        }
        let name = makeCodeName(tab, protocolVersion);
        console.log('Bench ' + name + ' < ' + optionsToString(tab, protocolVersion));
        let fileName = filename(name);
        await write(fileName + '.cpp', tab.code);
        await write(fileName + '.opt', optionsToString(tab, protocolVersion));
        return await execute(fileName, tab, protocolVersion, force);
    } catch (e) {
        return { stdout: e };
    }
}

async function benchmark(request, header) {
    return await Promise.all(request.tabs.map(u => benchmarkOneBuild(u, request.protocolVersion, request.force)));
}

async function reloadOne(id, name) {
    const fileName = filename(id);
    const values = await Promise.all([read(fileName + '.cpp'), read(fileName + '.opt'), read(fileName + '.out')]);
    return groupResults(values, id, name);
}

async function reload(encodedName) {
    let fileName = filename(decodeName(encodedName));
    const ids = await read(fileName + '.res');
    return await Promise.all(ids.split("\n").map(s => {
        const info = s.split("\t");
        return reloadOne(decodeName(info[0]), info[1]);
    }));
}

function readBuildResults(values) {
    if (values.res == null) return {};
    let results = values.res.toString().split('\n');
    let times = [];
    let memories = [];
    for (let i = 0; i < results.length; i++) {
        let s = results[i].split('\t');
        if (s.length === 2) {
            times.push(s[0]);
            memories.push(s[1]);
        }
    }
    return {
        times: times,
        memories: memories,
    };
}

function makeBuildGraphResult(values) {
    let result = values.map(v => readBuildResults(v));
    let message = values.map(v => v.stdout).reduce((r, v) => r + '\n' + v);
    let idsList = values.map(v => `${v.id}\t${v.title}`).reduce((r, v) => r + '\n' + v);
    let id = sha1(idsList);
    write(filename(id) + '.res', idsList);
    return {
        result: result,
        message: message,
        id: encodeName(id)
    };
}

function makeOneResult(done) {
    return {
        code: done.code,
        compiler: done.options.compiler,
        optim: done.options.optim,
        cppVersion: done.options.cppVersion,
        lib: done.options.lib,
        protocolVersion: done.options.protocolVersion,
        title: done.title
    };
}

function makeWholeResult(done) {
    return Object.assign({ tabs: done.map(d => makeOneResult(d)) }, makeBuildGraphResult(done.map(d => {
        return {
            res: d.graph,
            stdout: '',
            id: encodeName(d.id)
        };
    })));
}

app.post('/build', upload.array(), function (req, res) {
    Promise.resolve(benchmark(req.body, req.headers))
        .then((done) => res.json(makeBuildGraphResult(done)))
        .catch((err) => res.json({ message: err }));
});

app.get('/build/:id', upload.array(), function (req, res) {
    console.log('Get ' + req.params.id + ' ' + JSON.stringify(req.headers));
    Promise.resolve(reload(req.params.id))
        .then((done) => res.json(makeWholeResult(done)))
        .catch(() => res.json({ message: 'Could not load given id' }));
});

app.get('/:id', upload.array(), function (req, res) {
    res.redirect(`/b/${req.params.id}`);
});

app.get('/b/:id', upload.array(), function (req, res) {
    res.sendFile(path.join(__dirname, 'quick-bench-front-end', 'build', 'index.html'));
});

app.listen(3000, function () {
    console.log('Listening to commands');
});

exports.makeName = makeName;
exports.encodeName = encodeName;
exports.decodeName = decodeName;
exports.wrapCode = wrapCode;
exports.unwrapCode = unwrapCode;
exports.groupResults = groupResults;
exports.getFunctions = getFunctions;
exports.optionsToString = optionsToString;
exports.execute = execute;
<|endoftext|>


<commit_before>UIPlayer = {

	building : document.getElementById('countBuilding'),
	army : document.getElementById('countArmy'),
	players : document.getElementById('players'),
	endTurn : document.getElementById('endTurn'),
	playerTurn : document.getElementById('playerTurn'),
	playerGold : document.getElementById('playerGold'),
	armyStats : document.getElementById('armyStats'),
	nickName : document.getElementById('nickName'),
	armyStatsImg : document.getElementById('armyStatsImg'),
	endTurnAudio : document.getElementById('endTurnAudio'),
	yourTurn : document.getElementById('yourTurn'),

	selectedObject : null,

	init : function()
	{
		this.endTurn.addEventListener('click', function(evt) {
			GameEngine.sendNextTurn();
    	}, false);

	},

	_getRow : function(key, value)
	{
		return "
 " + key +" : " + value + "
"
	},

	setSelectedObject: function(object)
	{
		UIDynamic.setSelectedObject(object);
	},

	refreshUi: function(player)
	{
		this.nickName.innerHTML = player.name;
		this.players.innerHTML = "";

		var players = GameEngine.gameManager.getPlayers();

		for(var i = 0; i < players.length; i++)
		{
			var obj = players[i];

			this.players.innerHTML = this.players.innerHTML + "
 " + i +" : " + obj.name + "
";
		}

		this.building.innerHTML = player.building.length;
		this.army.innerHTML = player.army.length;
		this.yourTurn.style = "display: none";

		if(GameEngine.gameManager.turnPlayer)
		{
			this.playerTurn.innerHTML =  "" + GameEngine.gameManager.turnPlayer.name + "";
		}
		if(GameEngine.gameManager.turnPlayer == GameEngine.gameManager.getControllPlayer())
		{
			this.yourTurn.style = "display: block";
		}

		this.playerGold.innerHTML =  GameEngine.gameManager.getControllPlayer().gold;
	}
};<commit_msg>faster 100x<commit_after>UIPlayer = {

	building : document.getElementById('countBuilding'),
	army : document.getElementById('countArmy'),
	players : document.getElementById('players'),
	endTurn : document.getElementById('endTurn'),
	playerTurn : document.getElementById('playerTurn'),
	playerGold : document.getElementById('playerGold'),
	armyStats : document.getElementById('armyStats'),
	nickName : document.getElementById('nickName'),
	armyStatsImg : document.getElementById('armyStatsImg'),
	endTurnAudio : document.getElementById('endTurnAudio'),
	yourTurn : document.getElementById('yourTurn'),

	selectedObject : null,

	init : function()
	{
		this.endTurn.addEventListener('click', function(evt) {
			GameEngine.sendNextTurn();
    	}, false);

	},

	_getRow : function(key, value)
	{
		return "
 " + key +" : " + value + "
"
	},

	setSelectedObject: function(object)
	{
		UIDynamic.setSelectedObject(object);
	},

	refreshPlayers: function()
	{
		var players = GameEngine.gameManager.getPlayers();

		this.players.innerHTML = "";

		for(var i = 0; i < players.length; i++)
		{
			var obj = players[i];

			this.players.innerHTML = this.players.innerHTML + "
 " + i +" : " + obj.name + "
";
		}
	},

	refreshTurn: function()
	{

	},

	refreshUi: function(player)
	{
		//this.nickName.innerHTML = player.name;

		//this.building.innerHTML = player.building.length;
		//this.army.innerHTML = player.army.length;
		//this.yourTurn.style = "display: none";

		if(GameEngine.gameManager.turnPlayer)
		{
		//	this.playerTurn.innerHTML =  "" + GameEngine.gameManager.turnPlayer.name + "";
		}
		if(GameEngine.gameManager.turnPlayer == GameEngine.gameManager.getControllPlayer())
		{
		//	this.yourTurn.style = "display: block";
		}

		//this.playerGold.innerHTML =  GameEngine.gameManager.getControllPlayer().gold;
	}
};<|endoftext|>


<commit_before>// Main dicey application.

// Load libraries.
var React = require('react');
var ReactDOM = require('react-dom');

var DiceyApp = require('./jsx/DiceyApp').DiceyApp;

// TODO Load from JSON file? From LocalStorage?
var data = {
	pageTitle: 'Dicey, now with Zocchi.',
	diceGroups: [
		[
			{die: '1d3'},
			{die: '1d5'},
			{die: '1d7'},
			{die: '1d10'},
			{die: '1d14'},
			{die: '1d20', cssClass: 'btn-success'},
			{die: '1d100', cssClass: 'btn-success'},
			{die: '2d6', cssClass: 'btn-success'},
			{die: '2d10'}
		],
		[
			{die: '1d4'},
			{die: '1d6'},
			{die: '1d8'},
			{die: '1d12'},
			{die: '1d16'},
			{die: '1d24'},
			{die: '1d30'},
			{die: '3d6'},
			{die: '4d6'},
			{die: '11d10'}
		]
	],
	resultsLog: []
};

ReactDOM.render(
	<DiceyApp {...data} />,
	document.getElementById('appContainer')
);<commit_msg>Make 3d6 green too.<commit_after>// Main dicey application.

// Load libraries.
var React = require('react');
var ReactDOM = require('react-dom');

var DiceyApp = require('./jsx/DiceyApp').DiceyApp;

// TODO Load from JSON file? From LocalStorage?
var data = {
	pageTitle: 'Dicey, now with Zocchi.',
	diceGroups: [
		[
			{die: '1d3'},
			{die: '1d5'},
			{die: '1d7'},
			{die: '1d10'},
			{die: '1d14'},
			{die: '1d20', cssClass: 'btn-success'},
			{die: '1d100', cssClass: 'btn-success'},
			{die: '2d6', cssClass: 'btn-success'},
			{die: '2d10'}
		],
		[
			{die: '1d4'},
			{die: '1d6'},
			{die: '1d8'},
			{die: '1d12'},
			{die: '1d16'},
			{die: '1d24'},
			{die: '1d30'},
			{die: '3d6', cssClass: 'btn-success'},
			{die: '4d6'},
			{die: '11d10'}
		]
	],
	resultsLog: []
};

ReactDOM.render(
	<DiceyApp {...data} />,
	document.getElementById('appContainer')
);<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2014 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *   http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *   Bryan Boyd - Initial implementation
 *******************************************************************************/

var config = {
	iot_deviceType: "vehicle",     // replace with your deviceType
	iot_deviceOrg: "jdwkfn",       // replace with your IoT Foundation organization
	iot_deviceSet: [               // replace with your registered device(s)
		{ deviceId: "ABC", token: "UiFoIyWC+gKvM8Qtb?
" },
		{ deviceId: "DEF", token: "0f3vsBt7h-p9TApl)f
" },
		{ deviceId: "GHI", token: "uU_&9agQkv?4y&63v_
" }
	],
	iot_apiKey: "a-jdwkfn-3yz77s3rwg",    // replace with the key for a generated API token
	iot_apiToken: "u6N0GOD3&fhEx5Ne+i",  // replace with the generated API token

	// these topics will be used by Geospatial Analytics
	notifyTopic: "iot-2/type/api/id/geospatial/cmd/geoAlert/fmt/json",
	inputTopic: "iot-2/type/vehicle/id/+/evt/telemetry/fmt/json",
};

try {
	module.exports = config;
} catch (e) { window.config = config; }
<commit_msg>Update settings.js<commit_after>/*******************************************************************************
 * Copyright (c) 2014 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *   http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *   Bryan Boyd - Initial implementation
 *******************************************************************************/

var config = {
	iot_deviceType: "vehicle",     // replace with your deviceType
	iot_deviceOrg: "jdwkfn",       // replace with your IoT Foundation organization
	iot_deviceSet: [               // replace with your registered device(s)
		{ deviceId: "ABC", token: "UiFoIyWC+gKvM8Qtb?
" },
		{ deviceId: "DEF", token: "0f3vsBt7h-p9TApl)f
" },
		{ deviceId: "GHI", token: "uU_&9agQkv?4y&63v_
" }
	],
	iot_apiKey: "a-jdwkfn-qidysy4crk",    // replace with the key for a generated API token
	iot_apiToken: "u6N0GOD3&fhEx5Ne+i",  // replace with the generated API token

	// these topics will be used by Geospatial Analytics
	notifyTopic: "iot-2/type/api/id/geospatial/cmd/geoAlert/fmt/json",
	inputTopic: "iot-2/type/vehicle/id/+/evt/telemetry/fmt/json",
};

try {
	module.exports = config;
} catch (e) { window.config = config; }
<|endoftext|>