<commit_before>import stream from 'readable-stream'
import uuid from 'uuid'
import { curry, noop, isString } from 'lodash'
import compose from 'lodash/fp/compose'
import eqFp from 'lodash/fp/eq'
import isEqualFp from 'lodash/fp/isEqual'
import negateFp from 'lodash/fp/negate'
import getFp from 'lodash/fp/get'

import {
  defer
} from './utils'

// Constants
import {
  REQUEST_TIMEOUT,
  REQUEST_LOST_WORKER
} from '../CONSTANTS'

// Messages
import {
  clientRequestMessage,

  workerPartialResponseMessage,
  workerFinalResponseMessage,
  workerErrorResponseMessage,

  ministerRequestLostStakeholder
} from './messages'

// Internals
const requestIsNotAssigned = negateFp(getFp('assignee'))
const requestIsAssigned = negateFp(requestIsNotAssigned)
const requestIsNotDispatched = negateFp(getFp('isDispatched'))
const requestIsDispatched = negateFp(requestIsNotDispatched)
const requestIsIdempotent = getFp('isIdempotent')
const requestHasUUID = (uuid) => compose(isEqualFp(uuid), getFp('uuid'))

// Exported
export let getMinisterRequestInstance = ({stakeholder, uuid, service, frames, options, onFinished, debug}) => {
  let request = {}
  let {idempotent, reconnectStream} = options

  let _isClean = true
  let _isAccomplished = false
  let _isFailed = false
  let _isFinished = false
  let _hasLostStakeholder = false
  let _hasLostWorker = false

  return Object.defineProperties(request, {
    uuid: {value: uuid},
    shortId: {value: uuid.substring(0, 8)},
    service: {value: service},
    stakeholder: {get: () => _hasLostStakeholder ? null : stakeholder},
    frames: {value: frames},
    isAccomplished: {value: () => _isAccomplished},
    isFailed: {value: () => _isFailed},
    isFinished: {value: () => _isFinished},
    isClean: {get: () => _isClean},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream},
    lostStakeholder: {value: () => {
      if (_hasLostStakeholder) return
      _hasLostStakeholder = true
      onFinished()
      if (request.assignee) request.assignee.send(ministerRequestLostStakeholder(uuid))
    }},
    lostWorker: {value: () => {
      if (_hasLostWorker) return
      _hasLostWorker = true
      request.sendErrorResponse(JSON.stringify(REQUEST_LOST_WORKER))
    }},
    sendPartialResponse: {value: (body) => {
      if (_isFinished) return
      _isClean = false
      if (!_hasLostStakeholder) stakeholder.send(workerPartialResponseMessage(uuid, body))
    }},
    sendFinalResponse: {value: (body) => {
      if (_isFinished) return
      _isClean = false
      _isAccomplished = true
      _isFinished = true
      onFinished()
      if (!_hasLostStakeholder) stakeholder.send(workerFinalResponseMessage(uuid, body))
    }},
    sendErrorResponse: {value: (errorMessage) => {
      if (_isFinished) return
      _isClean = false
      _isFailed = true
      _isFinished = true
      onFinished()
      if (!_hasLostStakeholder) stakeholder.send(workerErrorResponseMessage(uuid, errorMessage))
    }}
  })
}
export let getClientRequestInstance = ({service, options, bodyBuffer, onFinished, onDeactivation, debug}) => {
  let request = {}
  let readableInterface = new stream.Readable({read: noop})
  // Let's prevent the `Uncaught Error` behaviour which could happen in case
  // the user does not register an handler for the `error` event
  readableInterface.on('error', noop)
  let {timeout, idempotent, reconnectStream} = options

  let _isClean = true
  let _isAccomplished = false
  let _isTimedout = false
  let _isFailed = false
  let _isFinished = false
  let _receivedBytes = 0
  let _uuid = uuid.v4()
  let _options = JSON.stringify(options)
  let _deferred

  let _timeoutHandle
  let _setupTimeout = () => _timeoutHandle = setTimeout(() => {
    _isTimedout = true
    request.giveErrorResponse(REQUEST_TIMEOUT)
  }, timeout)
  if (timeout) _setupTimeout()

  Object.defineProperties(readableInterface, {
    promise: {value: () => {
      _deferred = _deferred || defer()
      return _deferred.promise
    }},
    deactivate: {value: () => {
      if (_isFinished) return readableInterface
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isFinished = true
      onFinished()
      onDeactivation()
      debug(`Request ${request.shortId} has been deactivated`)
      readableInterface.push(null)
      options.finalCallback()
      if (_deferred) _deferred.resolve()
      return readableInterface
    }},
    isClean: {get: () => _isClean},
    isAccomplished: {get: () => _isAccomplished},
    isTimedout: {get: () => _isTimedout},
    isFailed: {get: () => _isFailed},
    isFinished: {get: () => _isFinished},
    receivedBytes: {get: () => _receivedBytes},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream}
  })

  return Object.defineProperties(request, {
    uuid: {get: () => _uuid},
    shortId: {get: () => _uuid.substring(0, 8)},
    isClean: {get: () => _isClean},
    isAccomplished: {get: () => _isAccomplished},
    isTimedout: {get: () => _isTimedout},
    isFailed: {get: () => _isFailed},
    isFinished: {get: () => _isFinished},
    receivedBytes: {get: () => _receivedBytes},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream},
    readableInterface: {value: readableInterface},
    frames: {get: () => clientRequestMessage(_uuid, service, _options, bodyBuffer)},
    givePartialResponse: {value: (buffer) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _receivedBytes += buffer.length
      readableInterface.push(buffer)
      options.partialCallback(buffer)
    }},
    giveFinalResponse: {value: (buffer) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _isAccomplished = true
      _isFinished = true
      _receivedBytes += buffer.length
      onFinished()
      debug(`Request ${request.shortId} had final response`)
      readableInterface.push(buffer)
      readableInterface.push(null)
      options.finalCallback(null, buffer)
      if (_deferred) _deferred.resolve(buffer)
    }},
    giveErrorResponse: {value: (error) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _isFailed = true
      _isFinished = true
      onFinished()
      debug(`Request ${request.shortId} had error response: ${error}`)
      let errMsg = isString(error)
        ? error || `request failed`
        : error.message || `request failed`
      let e = isString(error)
        ? new Error(errMsg)
        : Object.assign(
          new Error(errMsg),
          error
        )
      readableInterface.emit('error', e)
      readableInterface.push(null)
      options.finalCallback(e)
      if (_deferred) _deferred.reject(e)
    }},
    reschedule: {value: () => {
      if (_isFinished) return
      delete request.isDispatched
      let oldId = request.shortId
      _uuid = uuid.v4()
      debug(`Rescheduling request ${oldId} -> ${request.shortId}`)
      if (timeout && !_timeoutHandle) _setupTimeout()
    }},
    lostWorker: {value: () => {
      debug(`Request ${request.shortId} lost connection with worker`)
      request.giveErrorResponse(REQUEST_LOST_WORKER)
    }}
  })
}
export let getWorkerRequestInstance = ({connection, uuid, body, options, onFinished, debug}) => {
  let _ended = false
  let _ending = false
  let _endingWithNull = false
  let _isError = false
  let _isActive = true

  let request = Object.defineProperties({}, {
    body: {value: {...body}, enumerable: true},
    options: {value: {...options}, enumerable: true},
    isActive: {get () { return _isActive }}
  })

  let response = new stream.Writable({
    objectMode: true,
    write (chunk, encoding, cb) {
      cb()

      if (_ended) return

      if (_isActive) {
        let body
        try {
          body = encoding === 'buffer'
            ? chunk
            : _isError
              ? new Buffer(chunk)
              : isString(chunk)
                ? new Buffer(chunk)
                : new Buffer(JSON.stringify(chunk))
        } catch (e) {}
        body = _endingWithNull ? new Buffer(0) : (body || new Buffer(0))

        let msg = _isError
          ? workerErrorResponseMessage(uuid, body)
          : _ending
            ? workerFinalResponseMessage(uuid, body)
            : workerPartialResponseMessage(uuid, body)

        connection.send(msg)
      }

      if (_ending) {
        _ended = true
        onFinished()
      }
    }
  })
  let responseEnd = response.end
  response.end = (chunk, encoding, cb) => {
    _ending = true
    if (chunk === undefined || chunk === null) {
      chunk = ''
      _endingWithNull = true
    }
    return responseEnd.apply(response, [chunk, encoding, cb])
  }
  response.send = (chunk) => response.end(chunk)
  response.error = (err) => {
    _isError = true
    let chunk
    try {
      chunk = JSON.stringify(err || '')
    } catch (e) {
      chunk = '""'
    }
    response.end(chunk)
  }

  return Object.defineProperties({}, {
    uuid: {value: uuid},
    shortId: {value: uuid.substring(0, 8)},
    request: {value: request},
    response: {value: response},
    lostStakeholder: {value: () => {
      _isActive = false
      response.on('error', noop)
      process.nextTick(() => response.end())
    }}
  })
}

export let findRequestsByStakeholder = curry((requests, stakeholder) =>
  requests.filter(compose(eqFp(stakeholder.id), getFp('id'), getFp('stakeholder'))))
export let findRequestsByAssignee = curry((requests, assignee) =>
  requests.filter(compose(eqFp(assignee.id), getFp('id'), getFp('assignee'))))
export let findRequestByUUID = curry((requests, uuid) => requests.find(requestHasUUID(uuid)))
export let findUnassignedRequests = (requests) => () => requests.filter(requestIsNotAssigned)
export let findAssignedRequests = (requests) => () => requests.filter(requestIsAssigned)
export let findNotDispatchedRequests = (requests) => () => requests.filter(requestIsNotDispatched)
export let findDispatchedRequests = (requests) => () => requests.filter(requestIsDispatched)
export let findIdempotentRequests = (requests) => () => requests.filter(requestIsIdempotent)
<commit_msg>v0.1.1 pre release<commit_after>import stream from 'readable-stream'
import uuid from 'uuid'
import { curry, noop, isString } from 'lodash'
import compose from 'lodash/fp/compose'
import eqFp from 'lodash/fp/eq'
import isEqualFp from 'lodash/fp/isEqual'
import negateFp from 'lodash/fp/negate'
import getFp from 'lodash/fp/get'

import {
  defer
} from './utils'

// Constants
import {
  REQUEST_TIMEOUT,
  REQUEST_LOST_WORKER
} from '../CONSTANTS'

// Messages
import {
  clientRequestMessage,

  workerPartialResponseMessage,
  workerFinalResponseMessage,
  workerErrorResponseMessage,

  ministerRequestLostStakeholder
} from './messages'

// Internals
const requestIsNotAssigned = negateFp(getFp('assignee'))
const requestIsAssigned = negateFp(requestIsNotAssigned)
const requestIsNotDispatched = negateFp(getFp('isDispatched'))
const requestIsDispatched = negateFp(requestIsNotDispatched)
const requestIsIdempotent = getFp('isIdempotent')
const requestHasUUID = (uuid) => compose(isEqualFp(uuid), getFp('uuid'))

// Exported
export let getMinisterRequestInstance = ({stakeholder, uuid, service, frames, options, onFinished, debug}) => {
  let request = {}
  let {idempotent, reconnectStream} = options

  let _isClean = true
  let _isAccomplished = false
  let _isFailed = false
  let _isFinished = false
  let _hasLostStakeholder = false
  let _hasLostWorker = false

  return Object.defineProperties(request, {
    uuid: {value: uuid},
    shortId: {value: uuid.substring(0, 8)},
    service: {value: service},
    stakeholder: {get: () => _hasLostStakeholder ? null : stakeholder},
    frames: {value: frames},
    isAccomplished: {value: () => _isAccomplished},
    isFailed: {value: () => _isFailed},
    isFinished: {value: () => _isFinished},
    isClean: {get: () => _isClean},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream},
    lostStakeholder: {value: () => {
      if (_hasLostStakeholder) return
      _hasLostStakeholder = true
      onFinished()
      if (request.assignee) request.assignee.send(ministerRequestLostStakeholder(uuid))
    }},
    lostWorker: {value: () => {
      if (_hasLostWorker) return
      _hasLostWorker = true
      request.sendErrorResponse(JSON.stringify(REQUEST_LOST_WORKER))
    }},
    sendPartialResponse: {value: (body) => {
      if (_isFinished) return
      _isClean = false
      if (!_hasLostStakeholder) stakeholder.send(workerPartialResponseMessage(uuid, body))
    }},
    sendFinalResponse: {value: (body) => {
      if (_isFinished) return
      _isClean = false
      _isAccomplished = true
      _isFinished = true
      onFinished()
      if (!_hasLostStakeholder) stakeholder.send(workerFinalResponseMessage(uuid, body))
    }},
    sendErrorResponse: {value: (errorMessage) => {
      if (_isFinished) return
      _isClean = false
      _isFailed = true
      _isFinished = true
      onFinished()
      if (!_hasLostStakeholder) stakeholder.send(workerErrorResponseMessage(uuid, errorMessage))
    }}
  })
}
export let getClientRequestInstance = ({service, options, bodyBuffer, onFinished, onDeactivation, debug}) => {
  let request = {}
  let readableInterface = new stream.Readable({read: noop})
  // Let's prevent the `Uncaught Error` behaviour which could happen in case
  // the user does not register an handler for the `error` event
  readableInterface.on('error', noop)
  let {timeout, idempotent, reconnectStream} = options

  let _isClean = true
  let _isAccomplished = false
  let _isTimedout = false
  let _isFailed = false
  let _isFinished = false
  let _receivedBytes = 0
  let _uuid = uuid.v4()
  let _options = JSON.stringify(options)
  let _deferred

  let _timeoutHandle
  let _setupTimeout = () => _timeoutHandle = setTimeout(() => {
    _isTimedout = true
    request.giveErrorResponse(REQUEST_TIMEOUT)
  }, timeout)
  if (timeout) _setupTimeout()

  Object.defineProperties(readableInterface, {
    promise: {value: () => {
      _deferred = _deferred || defer()
      return _deferred.promise
    }},
    deactivate: {value: () => {
      if (_isFinished) return readableInterface
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isFinished = true
      onFinished()
      onDeactivation()
      debug(`Request ${request.shortId} has been deactivated`)
      readableInterface.push(null)
      options.finalCallback()
      if (_deferred) _deferred.resolve()
      return readableInterface
    }},
    isClean: {get: () => _isClean},
    isAccomplished: {get: () => _isAccomplished},
    isTimedout: {get: () => _isTimedout},
    isFailed: {get: () => _isFailed},
    isFinished: {get: () => _isFinished},
    receivedBytes: {get: () => _receivedBytes},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream}
  })

  return Object.defineProperties(request, {
    uuid: {get: () => _uuid},
    shortId: {get: () => _uuid.substring(0, 8)},
    isClean: {get: () => _isClean},
    isAccomplished: {get: () => _isAccomplished},
    isTimedout: {get: () => _isTimedout},
    isFailed: {get: () => _isFailed},
    isFinished: {get: () => _isFinished},
    receivedBytes: {get: () => _receivedBytes},
    isIdempotent: {value: idempotent},
    canReconnectStream: {value: reconnectStream},
    readableInterface: {value: readableInterface},
    frames: {get: () => clientRequestMessage(_uuid, service, _options, bodyBuffer)},
    givePartialResponse: {value: (buffer) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _receivedBytes += buffer.length
      readableInterface.push(buffer)
      options.partialCallback(buffer)
    }},
    giveFinalResponse: {value: (buffer) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _isAccomplished = true
      _isFinished = true
      _receivedBytes += buffer.length
      onFinished()
      debug(`Request ${request.shortId} had final response`)
      readableInterface.push(buffer)
      readableInterface.push(null)
      options.finalCallback(null, buffer)
      if (_deferred) _deferred.resolve(buffer)
    }},
    giveErrorResponse: {value: (error) => {
      if (_isFinished) return
      clearTimeout(_timeoutHandle)
      _timeoutHandle = null
      _isClean = false
      _isFailed = true
      _isFinished = true
      onFinished()
      debug(`Request ${request.shortId} had error response: ${error}`)
      let errMsg = isString(error)
        ? error || `request failed`
        : error.message || `request failed`
      let e = isString(error)
        ? new Error(errMsg)
        : Object.assign(
          new Error(errMsg),
          error
        )
      readableInterface.emit('error', e)
      readableInterface.push(null)
      options.finalCallback(e)
      if (_deferred) _deferred.reject(e)
    }},
    reschedule: {value: () => {
      if (_isFinished) return
      delete request.isDispatched
      let oldId = request.shortId
      _uuid = uuid.v4()
      debug(`Rescheduling request ${oldId} -> ${request.shortId}`)
      if (timeout && !_timeoutHandle) _setupTimeout()
    }},
    lostWorker: {value: () => {
      debug(`Request ${request.shortId} lost connection with worker`)
      request.giveErrorResponse(REQUEST_LOST_WORKER)
    }}
  })
}
export let getWorkerRequestInstance = ({connection, uuid, body, options, onFinished, debug}) => {
  let _ended = false
  let _ending = false
  let _endingWithNull = false
  let _isError = false
  let _isActive = true

  let request = Object.defineProperties({}, {
    body: {value: {...body}, enumerable: true},
    options: {value: {...options}, enumerable: true},
    isActive: {get () { return _isActive }}
  })

  let response = new stream.Writable({
    objectMode: true,
    write (chunk, encoding, cb) {
      cb()

      if (_ended) return

      if (_isActive) {
        let body
        try {
          body = encoding === 'buffer'
            ? chunk
            : _isError
              ? new Buffer(chunk)
              : isString(chunk)
                ? new Buffer(chunk)
                : new Buffer(JSON.stringify(chunk))
        } catch (e) {
          console.error(e)
        }
        body = _endingWithNull ? new Buffer(0) : (body || new Buffer(0))

        let msg = _isError
          ? workerErrorResponseMessage(uuid, body)
          : _ending
            ? workerFinalResponseMessage(uuid, body)
            : workerPartialResponseMessage(uuid, body)

        connection.send(msg)
      }

      if (_ending) {
        _ended = true
        onFinished()
      }
    }
  })
  let responseEnd = response.end
  response.end = (chunk, encoding, cb) => {
    _ending = true
    if (chunk === undefined || chunk === null) {
      chunk = ''
      _endingWithNull = true
    }
    return responseEnd.apply(response, [chunk, encoding, cb])
  }
  response.send = (chunk) => response.end(chunk)
  response.error = (err) => {
    _isError = true
    let chunk
    try {
      chunk = JSON.stringify(err || '')
    } catch (e) {
      chunk = '""'
    }
    response.end(chunk)
  }

  return Object.defineProperties({}, {
    uuid: {value: uuid},
    shortId: {value: uuid.substring(0, 8)},
    request: {value: request},
    response: {value: response},
    lostStakeholder: {value: () => {
      _isActive = false
      response.on('error', noop)
      process.nextTick(() => response.end())
    }}
  })
}

export let findRequestsByStakeholder = curry((requests, stakeholder) =>
  requests.filter(compose(eqFp(stakeholder.id), getFp('id'), getFp('stakeholder'))))
export let findRequestsByAssignee = curry((requests, assignee) =>
  requests.filter(compose(eqFp(assignee.id), getFp('id'), getFp('assignee'))))
export let findRequestByUUID = curry((requests, uuid) => requests.find(requestHasUUID(uuid)))
export let findUnassignedRequests = (requests) => () => requests.filter(requestIsNotAssigned)
export let findAssignedRequests = (requests) => () => requests.filter(requestIsAssigned)
export let findNotDispatchedRequests = (requests) => () => requests.filter(requestIsNotDispatched)
export let findDispatchedRequests = (requests) => () => requests.filter(requestIsDispatched)
export let findIdempotentRequests = (requests) => () => requests.filter(requestIsIdempotent)
<|endoftext|>


<commit_before>// prefix
export const PREFIX_CLS = "ve-table-";

// locale comp name
export const LOCALE_COMP_NAME = "table";

// column types
export const COLUMN_TYPES = {
    // expand row
    EXPAND: "expand",
    // checkbox
    CHECKBOX: "checkbox",
    // radio
    RADIO: "radio",
};

// expand row trigger types
export const EXPAND_TRIGGER_TYPES = {
    // trigger by click icon
    ICON: "icon",
    // trigger by click cell(td)
    CELL: "cell",
    // trigger by click row
    ROW: "row",
};

// cell selection direction
export const CELL_SELECTION_DIRECTION = {
    UP: "up",
    RIGHT: "right",
    DOWN: "down",
    LEFT: "left",
};

// emit events
export const EMIT_EVENTS = {
    // body-td-width-change
    BODY_TD_WIDTH_CHANGE: "on-body-td-width-change",
    // header-tr-height-change
    HEADER_TR_HEIGHT_CHANGE: "on-header-tr-height-change",
    // footer-tr-height-change
    FOOTER_TR_HEIGHT_CHANGE: "on-footer-tr-height-change",
    // body-tr-height-change
    BODY_TR_HEIGHT_CHANGE: "on-body-tr-height-change",
    // body tr click
    BODY_TR_CLICK: "on-body-tr-click",
    // body td click
    BODY_TD_CLICK: "on-body-td-click",
    // body td double click
    BODY_TD_DOUBLE_CLICK: "on-body-td-double-click",
    // body td contextmenu
    BODY_TD_CONTEXTMENU: "on-body-td-contextmenu",
    // expand row change
    EXPAND_ROW_CHANGE: "on-expand-row-change",
    // checkbox selected row change
    CHECKBOX_SELECTED_ROW_CHANGE: "on-checkbox-selected-row-change",
    // checkbox selected all change
    CHECKBOX_SELECTED_ALL_CHANGE: "on-checkbox-selected-all-change",
    // checkbox selected all ino
    CHECKBOX_SELECTED_ALL_INFO: "on-checkbox-selected-all-info",
    // radio selected row change
    RADIO_SELECTED_ROW_CHANGE: "on-radio-selected-row-change",
    // sort change
    SORT_CHANGE: "on-sort-change",
    // on-cell-selection-key-change
    CELL_SELECTION_KEY_CHANGE: "on-cell-selection-key-change",
    // header filter confirm
    HEADER_FILTER_CONFIRM: "on-filter-confirm",
    // header filter reset
    HEADER_FILTER_RESET: "on-filter-reset",
    // highlight row change
    HIGHLIGHT_ROW_CHANGE: "on-highlight-row-change",

    // edit input clicked
    EDIT_INPUT_CLICK: "on-edit-input-click",
    // edit input blur
    EDIT_INPUT_BLUR: "on-edit-input-blur",
    // edit input value change
    EDIT_INPUT_VALUE_CHANGE: "on-edit-input-value-change",
};

// hooks name
export const HOOKS_NAME = {
    //table container scroll
    TABLE_CONTAINER_SCROLL: "table-container-scroll",
    // table size change
    TABLE_SIZE_CHANGE: "table-size-change",
};

// comps name
export const COMPS_NAME = {
    VE_TABLE: "VeTable",

    VE_TABLE_THADER: "VeTableHeader",
    VE_TABLE_THADER_TR: "VeTableHeaderTr",
    VE_TABLE_THADER_Th: "VeTableHeaderTh",
    VE_TABLE_HEADER_CHECKBOX_CONTENT: "VeTableHeaderCheckboxContent",
    VE_TABLE_HEADER_FILTER_CONTENT: "VeTableHeaderFilterContent",
    VE_TABLE_HEADER_FILTER_CUSTOM_CONTENT: "VeTableHeaderFilterCustomContent",

    VE_TABLE_BODY: "VeTableBody",
    VE_TABLE_BODY_TR: "VeTableBodyTr",
    VE_TABLE_BODY_TR_SCROLLING: "VeTableBodyTrScrolling",
    VE_TABLE_BODY_CHECKBOX_CONTENT: "VeTableBodyCheckboxContent",
    VE_TABLE_BODY_RADIO_CONTENT: "VeTableBodyRadioContent",
    VE_TABLE_BODY_TD: "VeTableBodyTd",

    VE_TABLE_COLGROUP: "VeTableColgroup",
    VE_TABLE_FOOTER: "VeTableFooter",

    VE_TABLE_EXPAND_TR: "VeTableExpandTr",
    VE_TABLE_EXPAND_TR_ICON: "VeTableExpandTrIcon",

    VE_TABLE_EDIT_INPUT: "VeTableEditIput",
};

// comps custom attrs
export const COMPS_CUSTOM_ATTRS = {
    // body row key
    BODY_ROW_KEY: "row-key",
    // body column key
    BODY_COLUMN_KEY: "col-key",
};

// instance methods
export const INSTANCE_METHODS = {
    // scroll to pixels
    SCROLL_TO: "scrollTo",
    // scroll to rowKey
    SCROLL_TO_ROW_KEY: "scrollToRowKey",
    // start editing cell
    START_EDITING_CELL: "startEditingCell",
    // stop editing cell
    STOP_EDITING_CELL: "stopEditingCell",
    // set highlight row
    SET_HIGHLIGHT_ROW: "setHighlightRow",
    // hide columns by keys
    HIDE_COLUMNS_BY_KEYS: "hideColumnsByKeys",
    // show columns by keys
    SHOW_COLUMNS_BY_KEYS: "showColumnsByKeys",
};

// contextmenu types
export const CONTEXTMENU_TYPES = {
    // separator
    SEPARATOR: "separator",
    // insert row above
    INSERT_ROW_ABOVE: "insertRowAbove",
    // insert row below
    INSERT_ROW_BELOW: "insertRowBelow",
    // remove row
    REMOVE_ROW: "removeRow",
};

// contextmenu body options
export const CONTEXTMENU_BODY_OPTIONS = [
    {
        label: "insert row above",
        type: "INSERT_ROW_ABOVE",
    },
    {
        label: "insert row below",
        type: "INSERT_ROW_BELOW",
    },
    {
        type: "separator",
    },
    {
        label: "remove row",
        type: "REMOVE_ROW",
    },
];
<commit_msg>Update constant.js<commit_after>// prefix
export const PREFIX_CLS = "ve-table-";

// locale comp name
export const LOCALE_COMP_NAME = "table";

// column types
export const COLUMN_TYPES = {
    // expand row
    EXPAND: "expand",
    // checkbox
    CHECKBOX: "checkbox",
    // radio
    RADIO: "radio",
};

// expand row trigger types
export const EXPAND_TRIGGER_TYPES = {
    // trigger by click icon
    ICON: "icon",
    // trigger by click cell(td)
    CELL: "cell",
    // trigger by click row
    ROW: "row",
};

// cell selection direction
export const CELL_SELECTION_DIRECTION = {
    UP: "up",
    RIGHT: "right",
    DOWN: "down",
    LEFT: "left",
};

// emit events
export const EMIT_EVENTS = {
    // body-td-width-change
    BODY_TD_WIDTH_CHANGE: "on-body-td-width-change",
    // header-tr-height-change
    HEADER_TR_HEIGHT_CHANGE: "on-header-tr-height-change",
    // footer-tr-height-change
    FOOTER_TR_HEIGHT_CHANGE: "on-footer-tr-height-change",
    // body-tr-height-change
    BODY_TR_HEIGHT_CHANGE: "on-body-tr-height-change",
    // body tr click
    BODY_TR_CLICK: "on-body-tr-click",
    // body td click
    BODY_TD_CLICK: "on-body-td-click",
    // body td double click
    BODY_TD_DOUBLE_CLICK: "on-body-td-double-click",
    // body td contextmenu
    BODY_TD_CONTEXTMENU: "on-body-td-contextmenu",
    // expand row change
    EXPAND_ROW_CHANGE: "on-expand-row-change",
    // checkbox selected row change
    CHECKBOX_SELECTED_ROW_CHANGE: "on-checkbox-selected-row-change",
    // checkbox selected all change
    CHECKBOX_SELECTED_ALL_CHANGE: "on-checkbox-selected-all-change",
    // checkbox selected all ino
    CHECKBOX_SELECTED_ALL_INFO: "on-checkbox-selected-all-info",
    // radio selected row change
    RADIO_SELECTED_ROW_CHANGE: "on-radio-selected-row-change",
    // sort change
    SORT_CHANGE: "on-sort-change",
    // on-cell-selection-key-change
    CELL_SELECTION_KEY_CHANGE: "on-cell-selection-key-change",
    // header filter confirm
    HEADER_FILTER_CONFIRM: "on-filter-confirm",
    // header filter reset
    HEADER_FILTER_RESET: "on-filter-reset",
    // highlight row change
    HIGHLIGHT_ROW_CHANGE: "on-highlight-row-change",

    // edit input clicked
    EDIT_INPUT_CLICK: "on-edit-input-click",
    // edit input blur
    EDIT_INPUT_BLUR: "on-edit-input-blur",
    // edit input value change
    EDIT_INPUT_VALUE_CHANGE: "on-edit-input-value-change",
};

// hooks name
export const HOOKS_NAME = {
    //table container scroll
    TABLE_CONTAINER_SCROLL: "table-container-scroll",
    // table size change
    TABLE_SIZE_CHANGE: "table-size-change",
};

// comps name
export const COMPS_NAME = {
    VE_TABLE: "VeTable",

    VE_TABLE_THADER: "VeTableHeader",
    VE_TABLE_THADER_TR: "VeTableHeaderTr",
    VE_TABLE_THADER_Th: "VeTableHeaderTh",
    VE_TABLE_HEADER_CHECKBOX_CONTENT: "VeTableHeaderCheckboxContent",
    VE_TABLE_HEADER_FILTER_CONTENT: "VeTableHeaderFilterContent",
    VE_TABLE_HEADER_FILTER_CUSTOM_CONTENT: "VeTableHeaderFilterCustomContent",

    VE_TABLE_BODY: "VeTableBody",
    VE_TABLE_BODY_TR: "VeTableBodyTr",
    VE_TABLE_BODY_TR_SCROLLING: "VeTableBodyTrScrolling",
    VE_TABLE_BODY_CHECKBOX_CONTENT: "VeTableBodyCheckboxContent",
    VE_TABLE_BODY_RADIO_CONTENT: "VeTableBodyRadioContent",
    VE_TABLE_BODY_TD: "VeTableBodyTd",

    VE_TABLE_COLGROUP: "VeTableColgroup",
    VE_TABLE_FOOTER: "VeTableFooter",

    VE_TABLE_EXPAND_TR: "VeTableExpandTr",
    VE_TABLE_EXPAND_TR_ICON: "VeTableExpandTrIcon",

    VE_TABLE_EDIT_INPUT: "VeTableEditIput",
};

// comps custom attrs
export const COMPS_CUSTOM_ATTRS = {
    // body row key
    BODY_ROW_KEY: "row-key",
    // body column key
    BODY_COLUMN_KEY: "col-key",
};

// instance methods
export const INSTANCE_METHODS = {
    // scroll to pixels
    SCROLL_TO: "scrollTo",
    // scroll to rowKey
    SCROLL_TO_ROW_KEY: "scrollToRowKey",
    // start editing cell
    START_EDITING_CELL: "startEditingCell",
    // stop editing cell
    STOP_EDITING_CELL: "stopEditingCell",
    // set highlight row
    SET_HIGHLIGHT_ROW: "setHighlightRow",
    // hide columns by keys
    HIDE_COLUMNS_BY_KEYS: "hideColumnsByKeys",
    // show columns by keys
    SHOW_COLUMNS_BY_KEYS: "showColumnsByKeys",
};

// contextmenu types
export const CONTEXTMENU_TYPES = {
    // separator
    SEPARATOR: "separator",
    // insert row above
    INSERT_ROW_ABOVE: "insertRowAbove",
    // insert row below
    INSERT_ROW_BELOW: "insertRowBelow",
    // remove row
    REMOVE_ROW: "removeRow",
};
<|endoftext|>


<commit_before>import PropTypes from "prop-types";

const numberOrString = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]);

export const propTypes = {
  accountId: PropTypes.string.isRequired,
  height: numberOrString.isRequired,
  paidOnly: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  playerId: PropTypes.string,
  policyKey: PropTypes.string.isRequired,
  poster: PropTypes.shape({ uri: PropTypes.string.isRequired }),
  skySports: PropTypes.bool,
  videoId: PropTypes.string.isRequired,
  width: numberOrString.isRequired
};

export const defaultProps = {
  paidOnly: false,
  playerId: "default",
  skySports: false
};
<commit_msg>refactor: added missing default prop type (#1417)<commit_after>import PropTypes from "prop-types";

const numberOrString = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]);

export const propTypes = {
  accountId: PropTypes.string.isRequired,
  height: numberOrString.isRequired,
  paidOnly: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  playerId: PropTypes.string,
  policyKey: PropTypes.string.isRequired,
  poster: PropTypes.shape({ uri: PropTypes.string.isRequired }),
  skySports: PropTypes.bool,
  videoId: PropTypes.string.isRequired,
  width: numberOrString.isRequired
};

export const defaultProps = {
  paidOnly: false,
  playerId: "default",
  poster: null,
  skySports: false
};
<|endoftext|>


<commit_before>/* ======= Instance Methods ======= */

/**
 * Gets Value in Data
 * @param {String} key
 * @return {String} Value of key in data
 */
Moon.prototype.get = function(key) {
  return this.$data[key];
}

/**
 * Sets Value in Data
 * @param {String} key
 * @param {String} val
 */
Moon.prototype.set = function(key, val) {
  this.$data[key] = val;
  if(!this.$destroyed) this.build();
  this.$hooks.updated();
}

/**
 * Destroys Moon Instance
 */
Moon.prototype.destroy = function() {
  Object.defineProperty(this, '$data', {
    set: function(value) {
      _data = value;
    }
  });
  this.removeEvents();
  this.$destroyed = true;
  this.$hooks.destroyed();
}

/**
 * Calls a method
 * @param {String} method
 */
Moon.prototype.callMethod = function(method, args) {
  args = args || [];
  this.$methods[method].apply(this, args);
}

// Event Emitter, adapted from https://github.com/KingPixil/voke

/**
 * Attaches an Event Listener
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.on = function(eventName, action) {
  if(this.$events[eventName]) {
    this.$events[eventName].push(action);
  } else {
    this.$events[eventName] = [action];
  }
}

/**
 * Removes an Event Listener
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.off = function(eventName, action) {
  var index = this.$events[eventName].indexOf(action);
  if(index !== -1) {
    this.$events[eventName].splice(index, 1);
  }
}

/**
 * Removes All Event Listeners
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.removeEvents = function() {
  for(var evt in this.$events) {
    this.$events[evt] = [];
  }
}

/**
 * Emits an Event
 * @param {String} eventName
 * @param {Object} meta
 */
Moon.prototype.emit = function(eventName, meta) {
  meta = meta || {};
  meta.type = eventName;

  if(this.$events["*"]) {
    for(var i = 0; i < this.$events["*"].length; i++) {
      var globalHandler = this.$events["*"][i];
      globalHandler(meta);
    }
  }

  for(var i = 0; i < this.$events[eventName].length; i++) {
    var handler = this.$events[eventName][i];
    handler(meta);
  }
}

/**
 * Mounts Moon Element
 * @param {Object} el
 */
Moon.prototype.mount = function(el) {
  this.$el = document.querySelector(el);

  if(!this.$el) {
    this.error("Element " + this.$opts.el + " not found");
  }

  this.$template = this.$opts.template || this.$el.innerHTML;

  this.$el.innerHTML = this.$template;

  if(this.$render === noop) {
    this.$render = createRender(this.$template);
  }

  this.build();
  this.$hooks.mounted();
}

/**
 * Renders Virtual DOM
 * @return Virtual DOM
 */
Moon.prototype.render = function() {
  return this.$render(h);
}

/**
 * Diff then Patches Nodes With Data
 * @param {Object} node
 * @param {Object} vnode
 */
Moon.prototype.patch = function(node, vnode) {

}

/**
 * Render and Patches the DOM With Data
 */
Moon.prototype.build = function() {
  this.$dom = this.render();
  this.patch(this.$el, this.$dom);
}

/**
 * Initializes Moon
 */
Moon.prototype.init = function() {
  this.log("======= Moon =======");
  this.$hooks.created();

  if(this.$opts.el) {
    this.mount(this.$opts.el);
  }
}
<commit_msg>use utils<commit_after>/* ======= Instance Methods ======= */

/**
 * Gets Value in Data
 * @param {String} key
 * @return {String} Value of key in data
 */
Moon.prototype.get = function(key) {
  return this.$data[key];
}

/**
 * Sets Value in Data
 * @param {String} key
 * @param {String} val
 */
Moon.prototype.set = function(key, val) {
  this.$data[key] = val;
  if(!this.$destroyed) this.build();
  this.$hooks.updated();
}

/**
 * Destroys Moon Instance
 */
Moon.prototype.destroy = function() {
  Object.defineProperty(this, '$data', {
    set: function(value) {
      _data = value;
    }
  });
  this.removeEvents();
  this.$destroyed = true;
  this.$hooks.destroyed();
}

/**
 * Calls a method
 * @param {String} method
 */
Moon.prototype.callMethod = function(method, args) {
  args = args || [];
  this.$methods[method].apply(this, args);
}

// Event Emitter, adapted from https://github.com/KingPixil/voke

/**
 * Attaches an Event Listener
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.on = function(eventName, action) {
  if(this.$events[eventName]) {
    this.$events[eventName].push(action);
  } else {
    this.$events[eventName] = [action];
  }
}

/**
 * Removes an Event Listener
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.off = function(eventName, action) {
  var index = this.$events[eventName].indexOf(action);
  if(index !== -1) {
    this.$events[eventName].splice(index, 1);
  }
}

/**
 * Removes All Event Listeners
 * @param {String} eventName
 * @param {Function} action
 */
Moon.prototype.removeEvents = function() {
  for(var evt in this.$events) {
    this.$events[evt] = [];
  }
}

/**
 * Emits an Event
 * @param {String} eventName
 * @param {Object} meta
 */
Moon.prototype.emit = function(eventName, meta) {
  meta = meta || {};
  meta.type = eventName;

  if(this.$events["*"]) {
    for(var i = 0; i < this.$events["*"].length; i++) {
      var globalHandler = this.$events["*"][i];
      globalHandler(meta);
    }
  }

  for(var i = 0; i < this.$events[eventName].length; i++) {
    var handler = this.$events[eventName][i];
    handler(meta);
  }
}

/**
 * Mounts Moon Element
 * @param {Object} el
 */
Moon.prototype.mount = function(el) {
  this.$el = document.querySelector(el);

  if(!this.$el) {
    error("Element " + this.$opts.el + " not found");
  }

  this.$template = this.$opts.template || this.$el.innerHTML;

  this.$el.innerHTML = this.$template;

  if(this.$render === noop) {
    this.$render = createRender(this.$template);
  }

  this.build();
  this.$hooks.mounted();
}

/**
 * Renders Virtual DOM
 * @return Virtual DOM
 */
Moon.prototype.render = function() {
  return this.$render(h);
}

/**
 * Diff then Patches Nodes With Data
 * @param {Object} node
 * @param {Object} vnode
 */
Moon.prototype.patch = function(node, vnode) {

}

/**
 * Render and Patches the DOM With Data
 */
Moon.prototype.build = function() {
  this.$dom = this.render();
  this.patch(this.$el, this.$dom);
}

/**
 * Initializes Moon
 */
Moon.prototype.init = function() {
  log("======= Moon =======");
  this.$hooks.created();

  if(this.$opts.el) {
    this.mount(this.$opts.el);
  }
}
<|endoftext|>


<commit_before>//By Rajeshwar Patlolla
//https://github.com/rajeshwarpatlolla

"use strict";
var app = angular.module('ionic-datepicker', ['ionic', 'ionic-datepicker.templates']);

app.service('DatepickerService', function () {

  this.monthsList = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  this.yearsList = [1900,
    1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910,
    1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920,
    1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930,
    1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940,
    1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950,
    1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960,
    1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970,
    1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980,
    1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990,
    1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
    2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020,
    2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030,
    2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040,
    2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050,
    2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060,
    2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070,
    2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080,
    2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090,
    2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100];

});

app.directive('ionicDatepicker', ['$ionicPopup', 'DatepickerService', function ($ionicPopup, DatepickerService) {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      ipDate: '=idate',
      disablePreviousDates: '=disablepreviousdates',
      callback: '=callback'
    },
    link: function (scope, element, attrs) {

      var monthsList = DatepickerService.monthsList;
      scope.monthsList = monthsList;
      scope.yearsList = DatepickerService.yearsList;

      scope.currentMonth = '';
      scope.currentYear = '';

      if (!scope.ipDate) {
        scope.ipDate = new Date();
      }

      scope.previousDayEpoch = (+(new Date()) - 86400000);
      var currentDate = angular.copy(scope.ipDate);
      currentDate.setHours(0);
      currentDate.setMinutes(0);
      currentDate.setSeconds(0);
      currentDate.setMilliseconds(0);

      scope.selctedDateString = currentDate.toString();
      scope.weekNames = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
      scope.today = {};

      var tempTodayObj = new Date();
      var tempToday = new Date(tempTodayObj.getFullYear(), tempTodayObj.getMonth(), tempTodayObj.getDate());

      scope.today = {
        dateObj: tempTodayObj,
        date: tempToday.getDate(),
        month: tempToday.getMonth(),
        year: tempToday.getFullYear(),
        day: tempToday.getDay(),
        dateString: tempToday.toString(),
        epochLocal: tempToday.getTime(),
        epochUTC: (tempToday.getTime() + (tempToday.getTimezoneOffset() * 60 * 1000))
      };

      var refreshDateList = function (current_date) {
        current_date.setHours(0);
        current_date.setMinutes(0);
        current_date.setSeconds(0);
        current_date.setMilliseconds(0);

        scope.selctedDateString = (new Date(current_date)).toString();
        currentDate = angular.copy(current_date);

        var firstDay = new Date(current_date.getFullYear(), current_date.getMonth(), 1).getDate();
        var lastDay = new Date(current_date.getFullYear(), current_date.getMonth() + 1, 0).getDate();

        scope.dayList = [];

        for (var i = firstDay; i <= lastDay; i++) {
          var tempDate = new Date(current_date.getFullYear(), current_date.getMonth(), i);
          scope.dayList.push({
            date: tempDate.getDate(),
            month: tempDate.getMonth(),
            year: tempDate.getFullYear(),
            day: tempDate.getDay(),
            dateString: tempDate.toString(),
            epochLocal: tempDate.getTime(),
            epochUTC: (tempDate.getTime() + (tempDate.getTimezoneOffset() * 60 * 1000))
          });
        }

        var firstDay = scope.dayList[0].day;

        scope.currentMonthFirstDayEpoch = scope.dayList[0].epochLocal;

        for (var j = 0; j < firstDay; j++) {
          scope.dayList.unshift({});
        }

        scope.rows = [];
        scope.cols = [];

        scope.currentMonth = monthsList[current_date.getMonth()];
        scope.currentYear = current_date.getFullYear();

        scope.numColumns = 7;
        scope.rows.length = 6;
        scope.cols.length = scope.numColumns;
      };

      scope.monthChanged = function (month) {
        var monthNumber = scope.monthsList.indexOf(month);
        currentDate.setMonth(monthNumber);
        refreshDateList(currentDate)
      };

      scope.yearChanged = function (year) {
        currentDate.setFullYear(year);
        refreshDateList(currentDate)
      };

      scope.prevMonth = function () {
        if (currentDate.getMonth() === 1) {
          currentDate.setFullYear(currentDate.getFullYear());
        }
        currentDate.setMonth(currentDate.getMonth() - 1);

        scope.currentMonth = monthsList[currentDate.getMonth()];
        scope.currentYear = currentDate.getFullYear();

        refreshDateList(currentDate)
      };

      scope.nextMonth = function () {
        if (currentDate.getMonth() === 11) {
          currentDate.setFullYear(currentDate.getFullYear());
        }
        currentDate.setMonth(currentDate.getMonth() + 1);

        scope.currentMonth = monthsList[currentDate.getMonth()];
        scope.currentYear = currentDate.getFullYear();

        refreshDateList(currentDate)
      };

      scope.date_selection = {selected: false, selectedDate: '', submitted: false};

      scope.dateSelected = function (date) {
        scope.selctedDateString = date.dateString;
        scope.date_selection.selected = true;
        scope.date_selection.selectedDate = new Date(date.dateString);
      };

      element.on("click", function () {
        if (!scope.ipDate) {
          var defaultDate = new Date();
          refreshDateList(defaultDate);
        } else {
          refreshDateList(angular.copy(scope.ipDate));
        }

        $ionicPopup.show({
          templateUrl: 'lib/ionic-datepicker/src/date-picker-modal.html',
          title: 'Select Date',
          subTitle: '',
          scope: scope,
          buttons: [
            {
              text: 'Close',
              onTap: function (e) {
                scope.callback(undefined);
              }
            },
            {
              text: 'Today',
              onTap: function (e) {

                var today = new Date();
                var tempEpoch = new Date(today.getFullYear(), today.getMonth(), today.getDate());
                var todayObj = {
                  date: today.getDate(),
                  month: today.getMonth(),
                  year: today.getFullYear(),
                  day: today.getDay(),
                  dateString: today.toString(),
                  epochLocal: tempEpoch.getTime(),
                  epochUTC: (tempEpoch.getTime() + (tempEpoch.getTimezoneOffset() * 60 * 1000))
                };

                scope.selctedDateString = todayObj.dateString;
                scope.date_selection.selected = true;
                scope.date_selection.selectedDate = new Date(todayObj.dateString);
                refreshDateList(new Date());
                e.preventDefault();
              }
            },
            {
              text: 'Set',
              type: 'button-positive',
              onTap: function (e) {
                scope.date_selection.submitted = true;

                if (scope.date_selection.selected === true) {
                  scope.ipDate = angular.copy(scope.date_selection.selectedDate);
                  scope.callback(scope.ipDate);
                } else {
                  e.preventDefault();
                }
              }
            }
          ]
        })
      })
    }
  }
}]);<commit_msg>chages in template path<commit_after>//By Rajeshwar Patlolla
//https://github.com/rajeshwarpatlolla

"use strict";
var app = angular.module('ionic-datepicker', ['ionic', 'ionic-datepicker.templates']);

app.service('DatepickerService', function () {

  this.monthsList = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  this.yearsList = [1900,
    1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910,
    1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920,
    1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930,
    1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940,
    1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950,
    1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960,
    1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970,
    1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980,
    1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990,
    1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
    2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020,
    2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030,
    2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040,
    2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050,
    2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060,
    2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070,
    2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080,
    2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090,
    2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100];

});

app.directive('ionicDatepicker', ['$ionicPopup', 'DatepickerService', function ($ionicPopup, DatepickerService) {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      ipDate: '=idate',
      disablePreviousDates: '=disablepreviousdates',
      callback: '=callback'
    },
    link: function (scope, element, attrs) {

      var monthsList = DatepickerService.monthsList;
      scope.monthsList = monthsList;
      scope.yearsList = DatepickerService.yearsList;

      scope.currentMonth = '';
      scope.currentYear = '';

      if (!scope.ipDate) {
        scope.ipDate = new Date();
      }

      scope.previousDayEpoch = (+(new Date()) - 86400000);
      var currentDate = angular.copy(scope.ipDate);
      currentDate.setHours(0);
      currentDate.setMinutes(0);
      currentDate.setSeconds(0);
      currentDate.setMilliseconds(0);

      scope.selctedDateString = currentDate.toString();
      scope.weekNames = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
      scope.today = {};

      var tempTodayObj = new Date();
      var tempToday = new Date(tempTodayObj.getFullYear(), tempTodayObj.getMonth(), tempTodayObj.getDate());

      scope.today = {
        dateObj: tempTodayObj,
        date: tempToday.getDate(),
        month: tempToday.getMonth(),
        year: tempToday.getFullYear(),
        day: tempToday.getDay(),
        dateString: tempToday.toString(),
        epochLocal: tempToday.getTime(),
        epochUTC: (tempToday.getTime() + (tempToday.getTimezoneOffset() * 60 * 1000))
      };

      var refreshDateList = function (current_date) {
        current_date.setHours(0);
        current_date.setMinutes(0);
        current_date.setSeconds(0);
        current_date.setMilliseconds(0);

        scope.selctedDateString = (new Date(current_date)).toString();
        currentDate = angular.copy(current_date);

        var firstDay = new Date(current_date.getFullYear(), current_date.getMonth(), 1).getDate();
        var lastDay = new Date(current_date.getFullYear(), current_date.getMonth() + 1, 0).getDate();

        scope.dayList = [];

        for (var i = firstDay; i <= lastDay; i++) {
          var tempDate = new Date(current_date.getFullYear(), current_date.getMonth(), i);
          scope.dayList.push({
            date: tempDate.getDate(),
            month: tempDate.getMonth(),
            year: tempDate.getFullYear(),
            day: tempDate.getDay(),
            dateString: tempDate.toString(),
            epochLocal: tempDate.getTime(),
            epochUTC: (tempDate.getTime() + (tempDate.getTimezoneOffset() * 60 * 1000))
          });
        }

        var firstDay = scope.dayList[0].day;

        scope.currentMonthFirstDayEpoch = scope.dayList[0].epochLocal;

        for (var j = 0; j < firstDay; j++) {
          scope.dayList.unshift({});
        }

        scope.rows = [];
        scope.cols = [];

        scope.currentMonth = monthsList[current_date.getMonth()];
        scope.currentYear = current_date.getFullYear();

        scope.numColumns = 7;
        scope.rows.length = 6;
        scope.cols.length = scope.numColumns;
      };

      scope.monthChanged = function (month) {
        var monthNumber = scope.monthsList.indexOf(month);
        currentDate.setMonth(monthNumber);
        refreshDateList(currentDate)
      };

      scope.yearChanged = function (year) {
        currentDate.setFullYear(year);
        refreshDateList(currentDate)
      };

      scope.prevMonth = function () {
        if (currentDate.getMonth() === 1) {
          currentDate.setFullYear(currentDate.getFullYear());
        }
        currentDate.setMonth(currentDate.getMonth() - 1);

        scope.currentMonth = monthsList[currentDate.getMonth()];
        scope.currentYear = currentDate.getFullYear();

        refreshDateList(currentDate)
      };

      scope.nextMonth = function () {
        if (currentDate.getMonth() === 11) {
          currentDate.setFullYear(currentDate.getFullYear());
        }
        currentDate.setMonth(currentDate.getMonth() + 1);

        scope.currentMonth = monthsList[currentDate.getMonth()];
        scope.currentYear = currentDate.getFullYear();

        refreshDateList(currentDate)
      };

      scope.date_selection = {selected: false, selectedDate: '', submitted: false};

      scope.dateSelected = function (date) {
        scope.selctedDateString = date.dateString;
        scope.date_selection.selected = true;
        scope.date_selection.selectedDate = new Date(date.dateString);
      };

      element.on("click", function () {
        if (!scope.ipDate) {
          var defaultDate = new Date();
          refreshDateList(defaultDate);
        } else {
          refreshDateList(angular.copy(scope.ipDate));
        }

        $ionicPopup.show({
          templateUrl: 'date-picker-modal.html',
          title: 'Select Date',
          subTitle: '',
          scope: scope,
          buttons: [
            {
              text: 'Close',
              onTap: function (e) {
                scope.callback(undefined);
              }
            },
            {
              text: 'Today',
              onTap: function (e) {

                var today = new Date();
                var tempEpoch = new Date(today.getFullYear(), today.getMonth(), today.getDate());
                var todayObj = {
                  date: today.getDate(),
                  month: today.getMonth(),
                  year: today.getFullYear(),
                  day: today.getDay(),
                  dateString: today.toString(),
                  epochLocal: tempEpoch.getTime(),
                  epochUTC: (tempEpoch.getTime() + (tempEpoch.getTimezoneOffset() * 60 * 1000))
                };

                scope.selctedDateString = todayObj.dateString;
                scope.date_selection.selected = true;
                scope.date_selection.selectedDate = new Date(todayObj.dateString);
                refreshDateList(new Date());
                e.preventDefault();
              }
            },
            {
              text: 'Set',
              type: 'button-positive',
              onTap: function (e) {
                scope.date_selection.submitted = true;

                if (scope.date_selection.selected === true) {
                  scope.ipDate = angular.copy(scope.date_selection.selectedDate);
                  scope.callback(scope.ipDate);
                } else {
                  e.preventDefault();
                }
              }
            }
          ]
        })
      })
    }
  }
}]);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { store } from "./redux_store.js";
import { connect } from 'react-redux';
import { HighlightsPanel } from "./highlight.js";
import MetricsGraphics from 'react-metrics-graphics';
import ReactTable from 'react-table';
import moment from 'moment';
import {offset} from "./utils.js";

class ForecastsPanel extends Component {

  mouseOver(d, i) {
    const selectPoint = document.getElementsByClassName("mg-active-datapoint")[0];
    var elems = document.getElementsByClassName("mg-line-rollover-circle");
    var selectedCircle = null;
    for(i in elems) {
      var elem = elems[i];
      if(elem.style && elem.style.opacity == 1) {
        selectedCircle = elem;
      }
    }

    if(selectedCircle === null) {
      return;
    }

    const pos = offset(selectedCircle);
    var tooltip = document.getElementById("forecasts-tooltip");
    tooltip.style.display = "block";
    tooltip.style.position = "absolute";
    var dateString = moment(d.date).format("MMMM YYYY");
    if(d.upper) {
      // d.upper is defined only for forecasts, different tool tip for it
      tooltip.innerHTML = "Forecast for " + dateString + "" + d.value +"";
      tooltip.innerHTML += "80% Confidence: " + d.lower + "-" + d.upper + "";
    } else {
      tooltip.innerHTML =  ""+ dateString + "" + d.value +"";
    }

    var width = tooltip.getBoundingClientRect().width;

    tooltip.style.top = (pos.top - 70)+ "px";
    tooltip.style.left = (pos.left - width / 2)+ "px";

  }

  mouseOut(d, i) {
    var tooltip = document.getElementById("forecasts-tooltip").style.display = "none";
  }

  render() {

    var data = [];
    var oneYearAgo = moment().subtract(365 * 2, 'days');
    this.props.data.data.forEach(function(d) {
      if(moment(d.Time) < oneYearAgo) {
        return;
      }
      data.push({
        value : Math.max(d.Data, 0),
        date: new Date(d.Time),
        upper: null,
        lower: null
      });
    });

    this.props.data.forecasts.forEach(function(d) {
      data.push({
        value: Math.max(0, Math.floor(d.Forecast)),
        date: new Date(d.Time),
        upper: Math.max(0, Math.floor(d.High_80)),
        lower: Math.max(Math.floor(d.Low_80)),
        color: "#fff"
      });
    })

    const columnSpec = [{
      header: "Year",
      accessor: "Year",
      id: "year"
    }, {
      header: "Month",
      accessor: "Month",
      id: "month"
    }, {
      header: "Point Forecast",
      accessor: props => Math.floor(props.Forecast),
      id: "pf"
    }, {
      header: "80% Confidence Range",
      accessor: props => {Math.floor(props.Low_80)} to {Math.floor(props.High_80)},
      id: "conf-80"
    }];

    var markers = [{
        'date': new Date(),
        'label': 'Today'
    }];

    return (

{this.props.complaint_type}

          <MetricsGraphics
            title="Downloads"
            description="This graphic shows a time-series of downloads."
            data={data}
            width={500}
            y_extended_ticks={true}
            x_label={"Time"}
            show_rollover_text={false}
            height={250}
            x_accessor="date"
            y_accessor="value"
            show_confidence_band = {["upper", "lower"]}
            color_accessor={"color"}
            area={false}
            mouseover={this.mouseOver}
            mouseout={this.mouseOut}
            markers={markers}
          />

          <ReactTable
            data={this.props.data.forecasts}
            columns={columnSpec}
            showPagination={false}
            showPageSizeOptions={false}
            defaultPageSize={this.props.data.forecasts.length} />

    );
  }
}

class ForecastsTab extends Component {

  constructor() {
    super();
    this.state = {
      currentComplaint: null
    };
  }

  componentWillMount() {
    this.setState({
      currentComplaint: Object.keys(this.props.forecasts)[0]
    });
  }

  showForecastFor(e){
    this.setState({
      currentComplaint: e.target.innerHTML
    });
  }

  render() {
    var panel = null,
        complaintTypeButtons = [];

    var currentComplaint = this.state.currentComplaint;
    for (var key in this.props.forecasts) {
      if ( !this.props.forecasts.hasOwnProperty(key) ) {
        continue;
      }

      if(key === currentComplaint) {
        panel = <ForecastsPanel key={key} complaint_type={key} data={this.props.forecasts[key]} />;
        complaintTypeButtons.push(

{key}

        );
      } else {
        complaintTypeButtons.push(

{key}

        );
      }

    }

    return (

          {complaintTypeButtons}

        {panel}

    );
  }
}

/*
  <HighlightsPanel label='forecasts' highlights={this.props.highlights.forecasts}></HighlightsPanel>
*/

const mapStateToProps = function(store) {
  return {
    highlights: store.highlights,
    forecasts : store.forecasts
  };
}

export default connect(mapStateToProps)(ForecastsTab);
<commit_msg>Fix max() call<commit_after>import React, { Component } from 'react';
import { store } from "./redux_store.js";
import { connect } from 'react-redux';
import { HighlightsPanel } from "./highlight.js";
import MetricsGraphics from 'react-metrics-graphics';
import ReactTable from 'react-table';
import moment from 'moment';
import {offset} from "./utils.js";

class ForecastsPanel extends Component {

  mouseOver(d, i) {
    const selectPoint = document.getElementsByClassName("mg-active-datapoint")[0];
    var elems = document.getElementsByClassName("mg-line-rollover-circle");
    var selectedCircle = null;
    for(i in elems) {
      var elem = elems[i];
      if(elem.style && elem.style.opacity == 1) {
        selectedCircle = elem;
      }
    }

    if(selectedCircle === null) {
      return;
    }

    const pos = offset(selectedCircle);
    var tooltip = document.getElementById("forecasts-tooltip");
    tooltip.style.display = "block";
    tooltip.style.position = "absolute";
    var dateString = moment(d.date).format("MMMM YYYY");
    if(d.upper) {
      // d.upper is defined only for forecasts, different tool tip for it
      tooltip.innerHTML = "Forecast for " + dateString + "" + d.value +"";
      tooltip.innerHTML += "80% Confidence: " + d.lower + "-" + d.upper + "";
    } else {
      tooltip.innerHTML =  ""+ dateString + "" + d.value +"";
    }

    var width = tooltip.getBoundingClientRect().width;

    tooltip.style.top = (pos.top - 70)+ "px";
    tooltip.style.left = (pos.left - width / 2)+ "px";

  }

  mouseOut(d, i) {
    var tooltip = document.getElementById("forecasts-tooltip").style.display = "none";
  }

  render() {

    var data = [];
    var oneYearAgo = moment().subtract(365 * 2, 'days');
    this.props.data.data.forEach(function(d) {
      if(moment(d.Time) < oneYearAgo) {
        return;
      }
      data.push({
        value : Math.max(d.Data, 0),
        date: new Date(d.Time),
        upper: null,
        lower: null
      });
    });

    this.props.data.forecasts.forEach(function(d) {
      data.push({
        value: Math.max(0, Math.floor(d.Forecast)),
        date: new Date(d.Time),
        upper: Math.max(0, Math.floor(d.High_80)),
        lower: Math.max(0, Math.floor(d.Low_80)),
        color: "#fff"
      });
    })

    const columnSpec = [{
      header: "Year",
      accessor: "Year",
      id: "year"
    }, {
      header: "Month",
      accessor: "Month",
      id: "month"
    }, {
      header: "Point Forecast",
      accessor: props => Math.floor(props.Forecast),
      id: "pf"
    }, {
      header: "80% Confidence Range",
      accessor: props => {Math.floor(props.Low_80)} to {Math.floor(props.High_80)},
      id: "conf-80"
    }];

    var markers = [{
        'date': new Date(),
        'label': 'Today'
    }];

    return (

{this.props.complaint_type}

          <MetricsGraphics
            title="Downloads"
            description="This graphic shows a time-series of downloads."
            data={data}
            width={500}
            y_extended_ticks={true}
            x_label={"Time"}
            show_rollover_text={false}
            height={250}
            x_accessor="date"
            y_accessor="value"
            show_confidence_band = {["upper", "lower"]}
            color_accessor={"color"}
            area={false}
            mouseover={this.mouseOver}
            mouseout={this.mouseOut}
            markers={markers}
          />

          <ReactTable
            data={this.props.data.forecasts}
            columns={columnSpec}
            showPagination={false}
            showPageSizeOptions={false}
            defaultPageSize={this.props.data.forecasts.length} />

    );
  }
}

class ForecastsTab extends Component {

  constructor() {
    super();
    this.state = {
      currentComplaint: null
    };
  }

  componentWillMount() {
    this.setState({
      currentComplaint: Object.keys(this.props.forecasts)[0]
    });
  }

  showForecastFor(e){
    this.setState({
      currentComplaint: e.target.innerHTML
    });
  }

  render() {
    var panel = null,
        complaintTypeButtons = [];

    var currentComplaint = this.state.currentComplaint;
    for (var key in this.props.forecasts) {
      if ( !this.props.forecasts.hasOwnProperty(key) ) {
        continue;
      }

      if(key === currentComplaint) {
        panel = <ForecastsPanel key={key} complaint_type={key} data={this.props.forecasts[key]} />;
        complaintTypeButtons.push(

{key}

        );
      } else {
        complaintTypeButtons.push(

{key}

        );
      }

    }

    return (

          {complaintTypeButtons}

        {panel}

    );
  }
}

/*
  <HighlightsPanel label='forecasts' highlights={this.props.highlights.forecasts}></HighlightsPanel>
*/

const mapStateToProps = function(store) {
  return {
    highlights: store.highlights,
    forecasts : store.forecasts
  };
}

export default connect(mapStateToProps)(ForecastsTab);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
import '../../assets/stylesheets/application.css'
import { TX_STEP_DESCRIPTION } from '../../utils/constants'

@inject('tierStore')
@observer
export class TxProgressStatus extends Component {
  constructor (props) {
    super(props)

    this.state = {
      showModal: true
    }
  }

  txStatuses = () => {
    const { txMap } = this.props
    const table = []

    txMap.forEach((txStatus, txName) => {
      table.push({ txName, txStatus })
    })

    return table
  }

  render () {
    const { tierStore } = this.props
    const tiers = new Array(tierStore.tiers.length).fill(true)
    const tableContent = this.txStatuses()

    return (
      tableContent.length
        ?

Tx Name

              {tiers.map((value, index) =>
Tier {index + 1}
)}

              {tableContent.map(tx =>
                tx.txStatus.length
                  ?

{TX_STEP_DESCRIPTION[tx.txName]}

                    {tiers.map((value, index) => (

                        {tx.txStatus[index] === true
                          ? check
                          : tx.txStatus[index] === false
                            ? access_time
                            : ''
                        }

                    ))}

                  : null
              )}

        : null
    )
  }
}
<commit_msg>Add key attribute<commit_after>import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
import '../../assets/stylesheets/application.css'
import { TX_STEP_DESCRIPTION } from '../../utils/constants'

@inject('tierStore')
@observer
export class TxProgressStatus extends Component {
  constructor (props) {
    super(props)

    this.state = {
      showModal: true
    }
  }

  txStatuses = () => {
    const { txMap } = this.props
    const table = []

    txMap.forEach((txStatus, txName) => {
      table.push({ txName, txStatus })
    })

    return table
  }

  render () {
    const { tierStore } = this.props
    const tiers = new Array(tierStore.tiers.length).fill(true)
    const tableContent = this.txStatuses()

    return (
      tableContent.length
        ?

Tx Name

              {tiers.map((value, index) =>
Tier {index + 1}
)}

              {tableContent.map(tx =>
                tx.txStatus.length
                  ?

{TX_STEP_DESCRIPTION[tx.txName]}

                    {tiers.map((value, index) => (

                        {tx.txStatus[index] === true
                          ? check
                          : tx.txStatus[index] === false
                            ? access_time
                            : ''
                        }

                    ))}

                  : null
              )}

        : null
    )
  }
}
<|endoftext|>


<commit_before>var getContext = function(display, infos, curLevel) {

    var language_strings = {
        en: {
            categories: {
                barcode: 'Barcode'
            },
            label: {
                getPixelLuminosity: 'getPixelLuminosity(%1, %2)',
                setPixelLuminosity: 'setPixelLuminosity(%1, %2, %3)',
                width: 'width()',
                height: 'height()',
                printResult: 'printResult(%1)'
            },
            code: {
                getPixelLuminosity: 'getPixelLuminosity',
                setPixelLuminosity: 'setPixelLuminosity',
                width: 'width',
                height: 'height',
                printResult: 'printResult'
            },
            description: {
                getPixelLuminosity: '',
                setPixelLuminosity: '',
                width: '',
                height: '',
                printResult: ''
            },
            startingBlockName: "Program",
            messages: {
                success: 'Success',
                mistake_digit: 'The digit with a red background is incorrect',
                mistake_pixel: 'The pixel with a red border is incorrect',
                result: 'Result:'
            }
        }
    }

    var context = quickAlgoContext(display, infos)
    context.inlinePopupMessage = true;
    var strings = context.setLocalLanguageStrings(language_strings)

    /*
    var conceptBaseUrl = window.location.protocol + '//static4.castor-informatique.fr/help/index.html';
    context.conceptList = [
        {id: 'test', name: 'test', url: conceptBaseUrl+'#test'},
    ];
    */

    context.reset = function(taskInfos) {
        var grid = $('#grid');
        if(context.display) {
            grid.empty();
        }

        context.barcodeDisplay = DisplaysManager.get(
            'BarcodeDisplay',
            context.iTestCase,
            context.display,
            grid
        );

        context.stringDisplay = DisplaysManager.get(
            'StringDisplay',
            context.iTestCase,
            context.display,
            grid,
            {
                strings: strings
            }
        );

        context.userDisplay = DisplaysManager.get(
            'UserDisplay',
            context.iTestCase,
            context.display,
            grid
        );

        if(taskInfos) {
            context.valid_result = taskInfos.valid_result || {};
            context.barcodeDisplay.setImage(taskInfos.image);
            taskInfos.user_display && context.userDisplay.setSize(taskInfos.user_display);
        }

    }

    context.setScale = function(scale) {}
    context.updateScale = function() {
        context.barcodeDisplay && context.barcodeDisplay.render();
        context.userDisplay && context.userDisplay.render();
    }
    context.resetDisplay = function() {}
    context.unload = function() {}

    context.gradeResult = function() {
        switch(context.valid_result.type) {
            case 'string':
                context.success = context.stringDisplay.diff(context.valid_result.data);
                var error = strings.messages.mistake_digit;
                break;
            case 'array':
                context.success = context.userDisplay.diff(context.valid_result.data);
                var error = strings.messages.mistake_pixel;
                break;
        }
        if(context.success) {
            throw(strings.messages.success);
            return;
        }
        throw new Error(error);
    }

    context.barcode = {

        getPixelLuminosity: function(x, y, callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getPixelLuminosity(x, y, cb)
        },

        setPixelLuminosity: function(x, y, v, callback) {
            context.waitDelay(callback, context.userDisplay.setPixelLuminosity(x, y, v));
        },

        width: function(callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getSize(function(size) {
                cb(size.width);
            });
        },

        height: function(callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getSize(function(size) {
                cb(size.height);
            });
        },

        printResult: function(v, callback) {
            context.waitDelay(callback, context.stringDisplay.setData(v));
        }
    }

    context.customBlocks = {
        barcode: {
            barcode: [
                { name: 'getPixelLuminosity',
                    params: ['Number', 'Number'],
                    params_names: ['x', 'y'],
                    yieldsValue: true
                },
                { name: 'setPixelLuminosity',
                    params: ['Number', 'Number', 'Number'],
                    params_names: ['x', 'y', 'value']
                },
                { name: 'width',
                    params: [],
                    params_names: [],
                    yieldsValue: true
                },
                { name: 'height',
                    params: [],
                    params_names: [],
                    yieldsValue: true
                },
                { name: 'printResult',
                    params: ['String'],
                    params_names: ['v']
                },
            ]
        }
    }

    var typeData = {
        'Number': { bType: 'input_value', vType: 'math_number', fName: 'NUM', defVal: 0 },
        'String': { bType: 'input_value', vType: 'text', fName: 'TEXT', defVal: '' },
        'Block': { bType: 'input_value', fName: 'BLOCK', defVal: '' },
    }
    BlocksHelper.convertBlocks(context, 'barcode', typeData);
    return context;
}

if(window.quickAlgoLibraries) {
    quickAlgoLibraries.register('barcode', getContext);
} else {
    if(!window.quickAlgoLibrariesList) { window.quickAlgoLibrariesList = []; }
    window.quickAlgoLibrariesList.push(['barcode', getContext]);
}<commit_msg>barcode: Add delay on getPixelLuminosity<commit_after>var getContext = function(display, infos, curLevel) {

    var language_strings = {
        en: {
            categories: {
                barcode: 'Barcode'
            },
            label: {
                getPixelLuminosity: 'getPixelLuminosity(%1, %2)',
                setPixelLuminosity: 'setPixelLuminosity(%1, %2, %3)',
                width: 'width()',
                height: 'height()',
                printResult: 'printResult(%1)'
            },
            code: {
                getPixelLuminosity: 'getPixelLuminosity',
                setPixelLuminosity: 'setPixelLuminosity',
                width: 'width',
                height: 'height',
                printResult: 'printResult'
            },
            description: {
                getPixelLuminosity: '',
                setPixelLuminosity: '',
                width: '',
                height: '',
                printResult: ''
            },
            startingBlockName: "Program",
            messages: {
                success: 'Success',
                mistake_digit: 'The digit with a red background is incorrect',
                mistake_pixel: 'The pixel with a red border is incorrect',
                result: 'Result:'
            }
        }
    }

    var context = quickAlgoContext(display, infos)
    context.inlinePopupMessage = true;
    var strings = context.setLocalLanguageStrings(language_strings)

    /*
    var conceptBaseUrl = window.location.protocol + '//static4.castor-informatique.fr/help/index.html';
    context.conceptList = [
        {id: 'test', name: 'test', url: conceptBaseUrl+'#test'},
    ];
    */

    context.reset = function(taskInfos) {
        var grid = $('#grid');
        if(context.display) {
            grid.empty();
        }

        context.barcodeDisplay = DisplaysManager.get(
            'BarcodeDisplay',
            context.iTestCase,
            context.display,
            grid
        );

        context.stringDisplay = DisplaysManager.get(
            'StringDisplay',
            context.iTestCase,
            context.display,
            grid,
            {
                strings: strings
            }
        );

        context.userDisplay = DisplaysManager.get(
            'UserDisplay',
            context.iTestCase,
            context.display,
            grid
        );

        if(taskInfos) {
            context.valid_result = taskInfos.valid_result || {};
            context.barcodeDisplay.setImage(taskInfos.image);
            taskInfos.user_display && context.userDisplay.setSize(taskInfos.user_display);
        }

    }

    context.setScale = function(scale) {}
    context.updateScale = function() {
        context.barcodeDisplay && context.barcodeDisplay.render();
        context.userDisplay && context.userDisplay.render();
    }
    context.resetDisplay = function() {}
    context.unload = function() {}

    context.gradeResult = function() {
        switch(context.valid_result.type) {
            case 'string':
                context.success = context.stringDisplay.diff(context.valid_result.data);
                var error = strings.messages.mistake_digit;
                break;
            case 'array':
                context.success = context.userDisplay.diff(context.valid_result.data);
                var error = strings.messages.mistake_pixel;
                break;
        }
        if(context.success) {
            throw(strings.messages.success);
            return;
        }
        throw new Error(error);
    }

    context.barcode = {

        getPixelLuminosity: function(x, y, callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getPixelLuminosity(x, y, function(value) {
                // Add a delay
                setTimeout(function() {
                    cb(value);
                }, context.infos.actionDelay);
            })
        },

        setPixelLuminosity: function(x, y, v, callback) {
            context.waitDelay(callback, context.userDisplay.setPixelLuminosity(x, y, v));
        },

        width: function(callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getSize(function(size) {
                cb(size.width);
            });
        },

        height: function(callback) {
            var cb = context.runner.waitCallback(callback);
            context.barcodeDisplay.getSize(function(size) {
                cb(size.height);
            });
        },

        printResult: function(v, callback) {
            context.waitDelay(callback, context.stringDisplay.setData(v));
        }
    }

    context.customBlocks = {
        barcode: {
            barcode: [
                { name: 'getPixelLuminosity',
                    params: ['Number', 'Number'],
                    params_names: ['x', 'y'],
                    yieldsValue: true
                },
                { name: 'setPixelLuminosity',
                    params: ['Number', 'Number', 'Number'],
                    params_names: ['x', 'y', 'value']
                },
                { name: 'width',
                    params: [],
                    params_names: [],
                    yieldsValue: true
                },
                { name: 'height',
                    params: [],
                    params_names: [],
                    yieldsValue: true
                },
                { name: 'printResult',
                    params: ['String'],
                    params_names: ['v']
                },
            ]
        }
    }

    var typeData = {
        'Number': { bType: 'input_value', vType: 'math_number', fName: 'NUM', defVal: 0 },
        'String': { bType: 'input_value', vType: 'text', fName: 'TEXT', defVal: '' },
        'Block': { bType: 'input_value', fName: 'BLOCK', defVal: '' },
    }
    BlocksHelper.convertBlocks(context, 'barcode', typeData);
    return context;
}

if(window.quickAlgoLibraries) {
    quickAlgoLibraries.register('barcode', getContext);
} else {
    if(!window.quickAlgoLibrariesList) { window.quickAlgoLibrariesList = []; }
    window.quickAlgoLibrariesList.push(['barcode', getContext]);
}<|endoftext|>


<commit_before>/**
 * jQuery doubleTap() plugin
 * https://github.com/DanZiti/jQuery-doubleTap
 *
 * Custom jQuery event method that triggers a callback after double-tapping/double-clicking on the selected DOM element
 *
 * Copyright (c) 2015 Dan Zervoudakes
 * Released under the MIT license
 * https://github.com/DanZiti/jQuery-doubleTap/blob/master/LICENSE
 */

	(function($) {

		$.fn.doubleTap = function(_callback) {

			var active, interaction;

			active = false;
			interaction = ("createTouch" in document) ? "touchend" : "click";

			if (_callback) {

				$(this).on(interaction, function() {

					if (active) {
						_callback();
						return active = false;
					}

					active = true;

					setTimeout(function() {
						active = false;
					}, 350);

				});

			} else {
				throw new Error("jQuery double-tap/double-click callback is undefined.");
			}

			return this;
		};
	}(jQuery));<commit_msg>Slight code cleanup.<commit_after>/**
 * jQuery doubleTap() plugin
 * https://github.com/DanZiti/jQuery-doubleTap
 *
 * Custom jQuery event method that triggers a callback after double-tapping/double-clicking on the selected DOM element
 *
 * Copyright (c) 2015 Dan Zervoudakes
 * Released under the MIT license
 * https://github.com/DanZiti/jQuery-doubleTap/blob/master/LICENSE
 */

(function($) {

	$.fn.doubleTap = function(_callback) {

		var active, interaction;

		active = false;
		interaction = ("createTouch" in document) ? "touchend" : "click";

		if (_callback) {

			$(this).on(interaction, function() {

				if (active) {
					_callback();
					return active = false;
				}

				active = true;

				setTimeout(function() {
					active = false;
				}, 350);

			});

		} else {
			throw new Error("jQuery double-tap/double-click callback is undefined.");
		}

		return this;
	};

}(jQuery));<|endoftext|>