text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("video.js"));
	else if(typeof define === 'function' && define.amd)
		define("VideojsRecord", ["video.js"], factory);
	else if(typeof exports === 'object')
		exports["VideojsRecord"] = factory(require("video.js"));
	else
		root["VideojsRecord"] = root["VideojsRecord"] || {}, root["VideojsRecord"]["vmsg"] = factory(root["videojs"]);
})(self, (__WEBPACK_EXTERNAL_MODULE_video_js__) => {
return /******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js":
/*!**********************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
  \**********************************************************************/
/***/ ((module) => {

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

module.exports = _assertThisInitialized;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js":
/*!***************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
  \***************************************************************/
/***/ ((module) => {

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

module.exports = _classCallCheck;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/createClass.js":
/*!************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
  \************************************************************/
/***/ ((module) => {

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

module.exports = _createClass;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js":
/*!***************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
  \***************************************************************/
/***/ ((module) => {

function _getPrototypeOf(o) {
  module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

module.exports = _getPrototypeOf;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/inherits.js":
/*!*********************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/inherits.js ***!
  \*********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) setPrototypeOf(subClass, superClass);
}

module.exports = _inherits;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js":
/*!**********************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
  \**********************************************************************/
/***/ ((module) => {

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
}

module.exports = _interopRequireDefault;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
/*!**************************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
  \**************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");

var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  }

  return assertThisInitialized(self);
}

module.exports = _possibleConstructorReturn;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js":
/*!***************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
  \***************************************************************/
/***/ ((module) => {

function _setPrototypeOf(o, p) {
  module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}

module.exports = _setPrototypeOf;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/typeof.js":
/*!*******************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
  \*******************************************************/
/***/ ((module) => {

function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    module.exports = _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    module.exports = _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

module.exports = _typeof;

/***/ }),

/***/ "./src/js/plugins/vmsg-plugin.js":
/*!***************************************!*\
  !*** ./src/js/plugins/vmsg-plugin.js ***!
  \***************************************/
/***/ ((module, exports, __webpack_require__) => {

"use strict";

var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"));
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
var _video = _interopRequireDefault(__webpack_require__(/*! video.js */ "video.js"));
var _vmsg = __webpack_require__(/*! vmsg */ "./node_modules/vmsg/vmsg.js");
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var RecordEngine = _video.default.getComponent('RecordEngine');

var VmsgEngine = function (_RecordEngine) {
  (0, _inherits2.default)(VmsgEngine, _RecordEngine);
  var _super = _createSuper(VmsgEngine);
  function VmsgEngine(player, options) {
    var _this;
    (0, _classCallCheck2.default)(this, VmsgEngine);
    _this = _super.call(this, player, options);

    _this.debug = false;
    _this.audioWebAssemblyURL = 'vmsg.wasm';
    _this.pluginLibraryOptions = {};
    return _this;
  }

  (0, _createClass2.default)(VmsgEngine, [{
    key: "setup",
    value:
    function setup(stream, mediaType, debug) {
      var _this2 = this;
      this.inputStream = stream;
      this.mediaType = mediaType;
      this.debug = debug;

      this.config = {
        wasmURL: this.audioWebAssemblyURL
      };

      this.config = Object.assign(this.config, this.pluginLibraryOptions);
      this.engine = new _vmsg.Recorder(this.config, this.onRecordingAvailable.bind(this));
      this.engine.stream = this.inputStream;
      var AudioContext = window.AudioContext || window.webkitAudioContext;
      this.audioContext = new AudioContext();
      this.audioSourceNode = this.audioContext.createMediaStreamSource(this.inputStream);
      this.processor = this.audioContext.createScriptProcessor(0, 1, 1);
      this.audioSourceNode.connect(this.processor);
      this.engine.initWorker().catch(function (err) {
        _this2.player().trigger('error', err);
      });
    }

  }, {
    key: "start",
    value:
    function start() {
      this.engine.blob = null;
      if (this.engine.blobURL) {
        URL.revokeObjectURL(this.engine.blobURL);
      }
      this.engine.blobURL = null;
      this.engine.worker.postMessage({
        type: 'start',
        data: this.audioContext.sampleRate
      });
      this.processor.onaudioprocess = this.onAudioProcess.bind(this);
      this.processor.connect(this.audioContext.destination);
    }

  }, {
    key: "stop",
    value:
    function stop() {
      if (this.processor) {
        this.processor.disconnect();
        this.processor.onaudioprocess = null;
      }
      if (this.engine && this.engine.worker !== undefined) {
        this.engine.worker.postMessage({
          type: 'stop',
          data: null
        });
      }
    }

  }, {
    key: "destroy",
    value:
    function destroy() {
      if (this.engine && typeof this.engine.close === 'function') {
        this.engine.close();
      }
    }

  }, {
    key: "onAudioProcess",
    value:
    function onAudioProcess(event) {
      var samples = event.inputBuffer.getChannelData(0);
      this.engine.worker.postMessage({
        type: 'data',
        data: samples
      });
    }

  }, {
    key: "onRecordingAvailable",
    value:
    function onRecordingAvailable() {
      this.onStopRecording(this.engine.blob);
    }
  }]);
  return VmsgEngine;
}(RecordEngine);
_video.default.VmsgEngine = VmsgEngine;
var _default = VmsgEngine;
exports["default"] = _default;
module.exports = exports.default;

/***/ }),

/***/ "./node_modules/vmsg/vmsg.js":
/*!***********************************!*\
  !*** ./node_modules/vmsg/vmsg.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Form": () => (/* binding */ Form),
/* harmony export */   "Recorder": () => (/* binding */ Recorder),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "record": () => (/* binding */ record)
/* harmony export */ });
/* eslint-disable */

function pad2(n) {
  n |= 0;
  return n < 10 ? `0${n}` : `${Math.min(n, 99)}`;
}

function inlineWorker() {
  // TODO(Kagami): Cache compiled module in IndexedDB? It works in FF
  // and Edge, see: https://github.com/mdn/webassembly-examples/issues/4
  // Though gzipped WASM module currently weights ~70kb so it should be
  // perfectly cached by the browser itself.
  function fetchAndInstantiate(url, imports) {
    if (!WebAssembly.instantiateStreaming) return fetchAndInstantiateFallback(url, imports);
    const req = fetch(url, {credentials: "same-origin"});
    return WebAssembly.instantiateStreaming(req, imports).catch(err => {
      // https://github.com/Kagami/vmsg/issues/11
      if (err.message && err.message.indexOf("Argument 0 must be provided and must be a Response") > 0) {
        return fetchAndInstantiateFallback(url, imports);
      } else {
        throw err;
      }
    });
  }

  function fetchAndInstantiateFallback(url, imports) {
    return new Promise((resolve, reject) => {
      const req = new XMLHttpRequest();
      req.open("GET", url);
      req.responseType = "arraybuffer";
      req.onload = () => {
        resolve(WebAssembly.instantiate(req.response, imports));
      };
      req.onerror = reject;
      req.send();
    });
  }

  // Must be in sync with emcc settings!
  const TOTAL_STACK = 5 * 1024 * 1024;
  const TOTAL_MEMORY = 16 * 1024 * 1024;
  const WASM_PAGE_SIZE = 64 * 1024;
  let memory = null;
  let dynamicTop = TOTAL_STACK;
  // TODO(Kagami): Grow memory?
  function sbrk(increment) {
    const oldDynamicTop = dynamicTop;
    dynamicTop += increment;
    return oldDynamicTop;
  }
  // TODO(Kagami): LAME calls exit(-1) on internal error. Would be nice
  // to provide custom DEBUGF/ERRORF for easier debugging. Currenty
  // those functions do nothing.
  function exit(status) {
    postMessage({type: "internal-error", data: status});
  }

  let FFI = null;
  let ref = null;
  let pcm_l = null;
  function vmsg_init(rate) {
    ref = FFI.vmsg_init(rate);
    if (!ref) return false;
    const pcm_l_ref = new Uint32Array(memory.buffer, ref, 1)[0];
    pcm_l = new Float32Array(memory.buffer, pcm_l_ref);
    return true;
  }
  function vmsg_encode(data) {
    pcm_l.set(data);
    return FFI.vmsg_encode(ref, data.length) >= 0;
  }
  function vmsg_flush() {
    if (FFI.vmsg_flush(ref) < 0) return null;
    const mp3_ref = new Uint32Array(memory.buffer, ref + 4, 1)[0];
    const size = new Uint32Array(memory.buffer, ref + 8, 1)[0];
    const mp3 = new Uint8Array(memory.buffer, mp3_ref, size);
    const blob = new Blob([mp3], {type: "audio/mpeg"});
    FFI.vmsg_free(ref);
    ref = null;
    pcm_l = null;
    return blob;
  }

  // https://github.com/brion/min-wasm-fail
  function testSafariWebAssemblyBug() {
    const bin = new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,127,1,127,3,2,1,0,5,3,1,0,1,7,8,1,4,116,101,115,116,0,0,10,16,1,14,0,32,0,65,1,54,2,0,32,0,40,2,0,11]);
    const mod = new WebAssembly.Module(bin);
    const inst = new WebAssembly.Instance(mod, {});
    // test storing to and loading from a non-zero location via a parameter.
    // Safari on iOS 11.2.5 returns 0 unexpectedly at non-zero locations
    return (inst.exports.test(4) !== 0);
  }

  onmessage = (e) => {
    const msg = e.data;
    switch (msg.type) {
    case "init":
      const { wasmURL, shimURL } = msg.data;
      Promise.resolve().then(() => {
        if (self.WebAssembly && !testSafariWebAssemblyBug()) {
          delete self.WebAssembly;
        }
        if (!self.WebAssembly) {
          importScripts(shimURL);
        }
        memory = new WebAssembly.Memory({
          initial: TOTAL_MEMORY / WASM_PAGE_SIZE,
          maximum: TOTAL_MEMORY / WASM_PAGE_SIZE,
        });
        return {
          memory: memory,
          pow: Math.pow,
          exit: exit,
          powf: Math.pow,
          exp: Math.exp,
          sqrtf: Math.sqrt,
          cos: Math.cos,
          log: Math.log,
          sin: Math.sin,
          sbrk: sbrk,
        };
      }).then(Runtime => {
        return fetchAndInstantiate(wasmURL, {env: Runtime})
      }).then(wasm => {
        FFI = wasm.instance.exports;
        postMessage({type: "init", data: null});
      }).catch(err => {
        postMessage({type: "init-error", data: err.toString()});
      });
      break;
    case "start":
      if (!vmsg_init(msg.data)) return postMessage({type: "error", data: "vmsg_init"});
      break;
    case "data":
      if (!vmsg_encode(msg.data)) return postMessage({type: "error", data: "vmsg_encode"});
      break;
    case "stop":
      const blob = vmsg_flush();
      if (!blob) return postMessage({type: "error", data: "vmsg_flush"});
      postMessage({type: "stop", data: blob});
      break;
    }
  };
}

class Recorder {
  constructor(opts = {}, onStop = null) {
    // Can't use relative URL in blob worker, see:
    // https://stackoverflow.com/a/22582695
    this.wasmURL = new URL(opts.wasmURL || "/static/js/vmsg.wasm", location).href;
    this.shimURL = new URL(opts.shimURL || "/static/js/wasm-polyfill.js", location).href;
    this.onStop = onStop;
    this.pitch = opts.pitch || 0;
    this.stream = null;
    this.audioCtx = null;
    this.gainNode = null;
    this.pitchFX = null;
    this.encNode = null;
    this.worker = null;
    this.workerURL = null;
    this.blob = null;
    this.blobURL = null;
    this.resolve = null;
    this.reject = null;
    Object.seal(this);
  }

  close() {
    if (this.encNode) this.encNode.disconnect();
    if (this.encNode) this.encNode.onaudioprocess = null;
    if (this.stream) this.stopTracks();
    if (this.audioCtx) this.audioCtx.close();
    if (this.worker) {
      this.worker.terminate();
      this.worker = null;
    }
    if (this.workerURL) URL.revokeObjectURL(this.workerURL);
    if (this.blobURL) URL.revokeObjectURL(this.blobURL);
  }

  // Without pitch shift:
  //   [sourceNode] -> [gainNode] -> [encNode] -> [audioCtx.destination]
  //                                     |
  //                                     -> [worker]
  // With pitch shift:
  //   [sourceNode] -> [gainNode] -> [pitchFX] -> [encNode] -> [audioCtx.destination]
  //                                                  |
  //                                                  -> [worker]
  initAudio() {
    const getUserMedia = navigator.mediaDevices && navigator.mediaDevices.getUserMedia
      ? function(constraints) {
          return navigator.mediaDevices.getUserMedia(constraints);
        }
      : function(constraints) {
          const oldGetUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
          if (!oldGetUserMedia) {
            return Promise.reject(new Error("getUserMedia is not implemented in this browser"));
          }
          return new Promise(function(resolve, reject) {
            oldGetUserMedia.call(navigator, constraints, resolve, reject);
          });
        };

    return getUserMedia({audio: true}).then((stream) => {
      this.stream = stream;
      const audioCtx = this.audioCtx = new (window.AudioContext
        || window.webkitAudioContext)();

      const sourceNode = audioCtx.createMediaStreamSource(stream);
      const gainNode = this.gainNode = (audioCtx.createGain
        || audioCtx.createGainNode).call(audioCtx);
      gainNode.gain.value = 1;
      sourceNode.connect(gainNode);

      const pitchFX = this.pitchFX = new Jungle(audioCtx);
      pitchFX.setPitchOffset(this.pitch);

      const encNode = this.encNode = (audioCtx.createScriptProcessor
        || audioCtx.createJavaScriptNode).call(audioCtx, 0, 1, 1);
      pitchFX.output.connect(encNode);

      gainNode.connect(this.pitch === 0 ? encNode : pitchFX.input);
    });
  }

  initWorker() {
    if (this.worker) return Promise.resolve();
    // https://stackoverflow.com/a/19201292
    const blob = new Blob(
      ["(", inlineWorker.toString(), ")()"],
      {type: "application/javascript"});
    const workerURL = this.workerURL = URL.createObjectURL(blob);
    const worker = this.worker = new Worker(workerURL);
    const { wasmURL, shimURL } = this;
    worker.postMessage({type: "init", data: {wasmURL, shimURL}});
    return new Promise((resolve, reject) => {
      worker.onmessage = (e) => {
        const msg = e.data;
        switch (msg.type) {
        case "init":
          resolve();
          break;
        case "init-error":
          this.close();
          reject(new Error(msg.data));
          break;
        // TODO(Kagami): Error handling.
        case "error":
        case "internal-error":
          this.close();
          console.error("Worker error:", msg.data);
          if (this.reject) this.reject(msg.data);
          break;
        case "stop":
          this.blob = msg.data;
          this.blobURL = URL.createObjectURL(msg.data);
          if (this.onStop) this.onStop();
          if (this.resolve) this.resolve(this.blob);
          break;
        }
      }
    });
  }

  init() {
    return this.initAudio().then(this.initWorker.bind(this));
  }

  startRecording() {
    if (!this.stream) throw new Error("missing audio initialization");
    if (!this.worker) throw new Error("missing worker initialization");
    this.blob = null;
    if (this.blobURL) URL.revokeObjectURL(this.blobURL);
    this.blobURL = null;
    this.resolve = null;
    this.reject = null;
    this.worker.postMessage({type: "start", data: this.audioCtx.sampleRate});
    this.encNode.onaudioprocess = (e) => {
      const samples = e.inputBuffer.getChannelData(0);
      this.worker.postMessage({type: "data", data: samples});
    };
    this.encNode.connect(this.audioCtx.destination);
  }

  stopRecording() {
    if (!this.stream) throw new Error("missing audio initialization");
    if (!this.worker) throw new Error("missing worker initialization");
    this.encNode.disconnect();
    this.encNode.onaudioprocess = null;
    this.stopTracks();
    this.audioCtx.close();
    this.worker.postMessage({type: "stop", data: null});
    return new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }

  stopTracks() {
    // Might be missed in Safari and old FF/Chrome per MDN.
    if (this.stream.getTracks) {
      // Hide browser's recording indicator.
      this.stream.getTracks().forEach((track) => track.stop());
    }
  }
}

class Form {
  constructor(opts = {}, resolve, reject) {
    this.recorder = new Recorder(opts, this.onStop.bind(this));
    this.resolve = resolve;
    this.reject = reject;
    this.backdrop = null;
    this.popup = null;
    this.recordBtn = null;
    this.stopBtn = null;
    this.timer = null;
    this.audio = null;
    this.saveBtn = null;
    this.tid = 0;
    this.start = 0;
    Object.seal(this);

    this.recorder.initAudio()
      .then(() => this.drawInit())
      .then(() => this.recorder.initWorker())
      .then(() => this.drawAll())
      .catch((err) => this.drawError(err));
  }

  drawInit() {
    if (this.backdrop) return;
    const backdrop = this.backdrop = document.createElement("div");
    backdrop.className = "vmsg-backdrop";
    backdrop.addEventListener("click", () => this.close(null));

    const popup = this.popup = document.createElement("div");
    popup.className = "vmsg-popup";
    popup.addEventListener("click", (e) => e.stopPropagation());

    const progress = document.createElement("div");
    progress.className = "vmsg-progress";
    for (let i = 0; i < 3; i++) {
      const progressDot = document.createElement("div");
      progressDot.className = "vmsg-progress-dot";
      progress.appendChild(progressDot);
    }
    popup.appendChild(progress);

    backdrop.appendChild(popup);
    document.body.appendChild(backdrop);
  }

  drawTime(msecs) {
    const secs = Math.round(msecs / 1000);
    this.timer.textContent = pad2(secs / 60) + ":" + pad2(secs % 60);
  }

  drawAll() {
    this.drawInit();
    this.clearAll();

    const recordRow = document.createElement("div");
    recordRow.className = "vmsg-record-row";
    this.popup.appendChild(recordRow);

    const recordBtn = this.recordBtn = document.createElement("button");
    recordBtn.className = "vmsg-button vmsg-record-button";
    recordBtn.textContent = "●";
    recordBtn.title = "Start Recording";
    recordBtn.addEventListener("click", () => this.startRecording());
    recordRow.appendChild(recordBtn);

    const stopBtn = this.stopBtn = document.createElement("button");
    stopBtn.className = "vmsg-button vmsg-stop-button";
    stopBtn.style.display = "none";
    stopBtn.textContent = "■";
    stopBtn.title = "Stop Recording";
    stopBtn.addEventListener("click", () => this.stopRecording());
    recordRow.appendChild(stopBtn);

    const audio = this.audio = new Audio();
    audio.autoplay = true;

    const timer = this.timer = document.createElement("span");
    timer.className = "vmsg-timer";
    timer.title = "Preview Recording";
    timer.addEventListener("click", () => {
      if (audio.paused) {
        if (this.recorder.blobURL) {
          audio.src = this.recorder.blobURL;
        }
      } else {
        audio.pause();
      }
    });
    this.drawTime(0);
    recordRow.appendChild(timer);

    const saveBtn = this.saveBtn = document.createElement("button");
    saveBtn.className = "vmsg-button vmsg-save-button";
    saveBtn.textContent = "✓";
    saveBtn.title = "Save Recording";
    saveBtn.disabled = true;
    saveBtn.addEventListener("click", () => this.close(this.recorder.blob));
    recordRow.appendChild(saveBtn);

    const gainWrapper = document.createElement("div");
    gainWrapper.className = "vmsg-slider-wrapper vmsg-gain-slider-wrapper";
    const gainSlider = document.createElement("input");
    gainSlider.className = "vmsg-slider vmsg-gain-slider";
    gainSlider.setAttribute("type", "range");
    gainSlider.min = 0;
    gainSlider.max = 2;
    gainSlider.step = 0.2;
    gainSlider.value = 1;
    gainSlider.onchange = () => {
      const gain = +gainSlider.value;
      this.recorder.gainNode.gain.value = gain;
    };
    gainWrapper.appendChild(gainSlider);
    this.popup.appendChild(gainWrapper);

    const pitchWrapper = document.createElement("div");
    pitchWrapper.className = "vmsg-slider-wrapper vmsg-pitch-slider-wrapper";
    const pitchSlider = document.createElement("input");
    pitchSlider.className = "vmsg-slider vmsg-pitch-slider";
    pitchSlider.setAttribute("type", "range");
    pitchSlider.min = -1;
    pitchSlider.max = 1;
    pitchSlider.step = 0.2;
    pitchSlider.value = this.recorder.pitch;
    pitchSlider.onchange = () => {
      const pitch = +pitchSlider.value;
      this.recorder.pitchFX.setPitchOffset(pitch);
      this.recorder.gainNode.disconnect();
      this.recorder.gainNode.connect(
        pitch === 0 ? this.recorder.encNode : this.recorder.pitchFX.input
      );
    };
    pitchWrapper.appendChild(pitchSlider);
    this.popup.appendChild(pitchWrapper);
    recordBtn.focus();
  }

  drawError(err) {
    console.error(err);
    this.drawInit();
    this.clearAll();
    const error = document.createElement("div");
    error.className = "vmsg-error";
    error.textContent = err.toString();
    this.popup.appendChild(error);
  }

  clearAll() {
    if (!this.popup) return;
    this.popup.innerHTML = "";
  }

  close(blob) {
    if (this.audio) this.audio.pause();
    if (this.tid) clearTimeout(this.tid);
    this.recorder.close();
    this.backdrop.remove();
    if (blob) {
      this.resolve(blob);
    } else {
      this.reject(new Error("No record made"));
    }
  }

  onStop() {
    this.recordBtn.style.display = "";
    this.stopBtn.style.display = "none";
    this.stopBtn.disabled = false;
    this.saveBtn.disabled = false;
  }

  startRecording() {
    this.audio.pause();
    this.start = Date.now();
    this.updateTime();
    this.recordBtn.style.display = "none";
    this.stopBtn.style.display = "";
    this.saveBtn.disabled = true;
    this.stopBtn.focus();
    this.recorder.startRecording();
  }

  stopRecording() {
    clearTimeout(this.tid);
    this.tid = 0;
    this.stopBtn.disabled = true;
    this.recordBtn.focus();
    this.recorder.stopRecording();
  }

  updateTime() {
    // NOTE(Kagami): We can do this in `onaudioprocess` but that would
    // run too often and create unnecessary DOM updates.
    this.drawTime(Date.now() - this.start);
    this.tid = setTimeout(() => this.updateTime(), 300);
  }
}

let shown = false;

/**
 * Record a new voice message.
 *
 * @param {Object=} opts - Options
 * @param {string=} opts.wasmURL - URL of the module
 *                                 ("/static/js/vmsg.wasm" by default)
 * @param {string=} opts.shimURL - URL of the WebAssembly polyfill
 *                                 ("/static/js/wasm-polyfill.js" by default)
 * @param {number=} opts.pitch - Initial pitch shift ([-1, 1], 0 by default)
 * @return {Promise.<Blob>} A promise that contains recorded blob when fulfilled.
 */
function record(opts) {
  return new Promise((resolve, reject) => {
    if (shown) throw new Error("Record form is already opened");
    shown = true;
    new Form(opts, resolve, reject);
  // Use `.finally` once it's available in Safari and Edge.
  }).then(result => {
    shown = false;
    return result;
  }, err => {
    shown = false;
    throw err;
  });
}

/**
 * All available public items.
 */
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ Recorder, Form, record });

// Borrowed from and slightly modified:
// https://github.com/cwilso/Audio-Input-Effects/blob/master/js/jungle.js

// Copyright 2012, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

const delayTime = 0.100;
const fadeTime = 0.050;
const bufferTime = 0.100;

function createFadeBuffer(context, activeTime, fadeTime) {
  var length1 = activeTime * context.sampleRate;
  var length2 = (activeTime - 2*fadeTime) * context.sampleRate;
  var length = length1 + length2;
  var buffer = context.createBuffer(1, length, context.sampleRate);
  var p = buffer.getChannelData(0);

  var fadeLength = fadeTime * context.sampleRate;

  var fadeIndex1 = fadeLength;
  var fadeIndex2 = length1 - fadeLength;

  // 1st part of cycle
  for (var i = 0; i < length1; ++i) {
    var value;

    if (i < fadeIndex1) {
        value = Math.sqrt(i / fadeLength);
    } else if (i >= fadeIndex2) {
        value = Math.sqrt(1 - (i - fadeIndex2) / fadeLength);
    } else {
        value = 1;
    }

    p[i] = value;
  }

  // 2nd part
  for (var i = length1; i < length; ++i) {
    p[i] = 0;
  }

  return buffer;
}

function createDelayTimeBuffer(context, activeTime, fadeTime, shiftUp) {
  var length1 = activeTime * context.sampleRate;
  var length2 = (activeTime - 2*fadeTime) * context.sampleRate;
  var length = length1 + length2;
  var buffer = context.createBuffer(1, length, context.sampleRate);
  var p = buffer.getChannelData(0);

  // 1st part of cycle
  for (var i = 0; i < length1; ++i) {
    if (shiftUp)
      // This line does shift-up transpose
      p[i] = (length1-i)/length;
    else
      // This line does shift-down transpose
      p[i] = i / length1;
  }

  // 2nd part
  for (var i = length1; i < length; ++i) {
    p[i] = 0;
  }

  return buffer;
}

function Jungle(context) {
  this.context = context;
  // Create nodes for the input and output of this "module".
  var input = (context.createGain || context.createGainNode).call(context);
  var output = (context.createGain || context.createGainNode).call(context);
  this.input = input;
  this.output = output;

  // Delay modulation.
  var mod1 = context.createBufferSource();
  var mod2 = context.createBufferSource();
  var mod3 = context.createBufferSource();
  var mod4 = context.createBufferSource();
  this.shiftDownBuffer = createDelayTimeBuffer(context, bufferTime, fadeTime, false);
  this.shiftUpBuffer = createDelayTimeBuffer(context, bufferTime, fadeTime, true);
  mod1.buffer = this.shiftDownBuffer;
  mod2.buffer = this.shiftDownBuffer;
  mod3.buffer = this.shiftUpBuffer;
  mod4.buffer = this.shiftUpBuffer;
  mod1.loop = true;
  mod2.loop = true;
  mod3.loop = true;
  mod4.loop = true;

  // for switching between oct-up and oct-down
  var mod1Gain = (context.createGain || context.createGainNode).call(context);
  var mod2Gain = (context.createGain || context.createGainNode).call(context);
  var mod3Gain = (context.createGain || context.createGainNode).call(context);
  mod3Gain.gain.value = 0;
  var mod4Gain = (context.createGain || context.createGainNode).call(context);
  mod4Gain.gain.value = 0;

  mod1.connect(mod1Gain);
  mod2.connect(mod2Gain);
  mod3.connect(mod3Gain);
  mod4.connect(mod4Gain);

  // Delay amount for changing pitch.
  var modGain1 = (context.createGain || context.createGainNode).call(context);
  var modGain2 = (context.createGain || context.createGainNode).call(context);

  var delay1 = (context.createDelay || context.createDelayNode).call(context);
  var delay2 = (context.createDelay || context.createDelayNode).call(context);
  mod1Gain.connect(modGain1);
  mod2Gain.connect(modGain2);
  mod3Gain.connect(modGain1);
  mod4Gain.connect(modGain2);
  modGain1.connect(delay1.delayTime);
  modGain2.connect(delay2.delayTime);

  // Crossfading.
  var fade1 = context.createBufferSource();
  var fade2 = context.createBufferSource();
  var fadeBuffer = createFadeBuffer(context, bufferTime, fadeTime);
  fade1.buffer = fadeBuffer
  fade2.buffer = fadeBuffer;
  fade1.loop = true;
  fade2.loop = true;

  var mix1 = (context.createGain || context.createGainNode).call(context);
  var mix2 = (context.createGain || context.createGainNode).call(context);
  mix1.gain.value = 0;
  mix2.gain.value = 0;

  fade1.connect(mix1.gain);
  fade2.connect(mix2.gain);

  // Connect processing graph.
  input.connect(delay1);
  input.connect(delay2);
  delay1.connect(mix1);
  delay2.connect(mix2);
  mix1.connect(output);
  mix2.connect(output);

  // Start
  var t = context.currentTime + 0.050;
  var t2 = t + bufferTime - fadeTime;
  mod1.start(t);
  mod2.start(t2);
  mod3.start(t);
  mod4.start(t2);
  fade1.start(t);
  fade2.start(t2);

  this.mod1 = mod1;
  this.mod2 = mod2;
  this.mod1Gain = mod1Gain;
  this.mod2Gain = mod2Gain;
  this.mod3Gain = mod3Gain;
  this.mod4Gain = mod4Gain;
  this.modGain1 = modGain1;
  this.modGain2 = modGain2;
  this.fade1 = fade1;
  this.fade2 = fade2;
  this.mix1 = mix1;
  this.mix2 = mix2;
  this.delay1 = delay1;
  this.delay2 = delay2;

  this.setDelay(delayTime);
}

Jungle.prototype.setDelay = function(delayTime) {
  this.modGain1.gain.setTargetAtTime(0.5*delayTime, 0, 0.010);
  this.modGain2.gain.setTargetAtTime(0.5*delayTime, 0, 0.010);
};

Jungle.prototype.setPitchOffset = function(mult) {
  if (mult>0) { // pitch up
    this.mod1Gain.gain.value = 0;
    this.mod2Gain.gain.value = 0;
    this.mod3Gain.gain.value = 1;
    this.mod4Gain.gain.value = 1;
  } else { // pitch down
    this.mod1Gain.gain.value = 1;
    this.mod2Gain.gain.value = 1;
    this.mod3Gain.gain.value = 0;
    this.mod4Gain.gain.value = 0;
  }
  this.setDelay(delayTime*Math.abs(mult));
};

/***/ }),

/***/ "video.js":
/*!*************************************************************************************************!*\
  !*** external {"commonjs":"video.js","commonjs2":"video.js","amd":"video.js","root":"videojs"} ***!
  \*************************************************************************************************/
/***/ ((module) => {

"use strict";
module.exports = __WEBPACK_EXTERNAL_MODULE_video_js__;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/
/************************************************************************/
/******/
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__("./src/js/plugins/vmsg-plugin.js");
/******/
/******/ 	return __webpack_exports__;
/******/ })()
;
});


text:
namespace gfx {

// A Quad is defined by four corners, allowing it to have edges that are not
// axis-aligned, unlike a Rect.
class GEOMETRY_EXPORT QuadF {
 public:
  constexpr QuadF() = default;
  constexpr QuadF(const PointF& p1,
                  const PointF& p2,
                  const PointF& p3,
                  const PointF& p4)
      : p1_(p1), p2_(p2), p3_(p3), p4_(p4) {}

  constexpr explicit QuadF(const RectF& rect)
      : p1_(rect.x(), rect.y()),
        p2_(rect.right(), rect.y()),
        p3_(rect.right(), rect.bottom()),
        p4_(rect.x(), rect.bottom()) {}

  void operator=(const RectF& rect);

  void set_p1(const PointF& p) { p1_ = p; }
  void set_p2(const PointF& p) { p2_ = p; }
  void set_p3(const PointF& p) { p3_ = p; }
  void set_p4(const PointF& p) { p4_ = p; }

  constexpr const PointF& p1() const { return p1_; }
  constexpr const PointF& p2() const { return p2_; }
  constexpr const PointF& p3() const { return p3_; }
  constexpr const PointF& p4() const { return p4_; }

  // Returns true if the quad is an axis-aligned rectangle.
  bool IsRectilinear() const;

  // Returns true if the points of the quad are in counter-clockwise order. This
  // assumes that the quad is convex, and that no three points are collinear.
  bool IsCounterClockwise() const;

  // Returns true if the |point| is contained within the quad, or lies on on
  // edge of the quad. This assumes that the quad is convex.
  bool Contains(const PointF& point) const;

  // Returns true if the |quad| parameter is contained within |this| quad.
  // This method assumes |this| quad is convex. The |quad| parameter has no
  // restrictions.
  bool ContainsQuad(const QuadF& quad) const;

  // Returns a rectangle that bounds the four points of the quad. The points of
  // the quad may lie on the right/bottom edge of the resulting rectangle,
  // rather than being strictly inside it.
  RectF BoundingBox() const {
    float rl = std::min({p1_.x(), p2_.x(), p3_.x(), p4_.x()});
    float rr = std::max({p1_.x(), p2_.x(), p3_.x(), p4_.x()});
    float rt = std::min({p1_.y(), p2_.y(), p3_.y(), p4_.y()});
    float rb = std::max({p1_.y(), p2_.y(), p3_.y(), p4_.y()});
    return RectF(rl, rt, rr - rl, rb - rt);
  }

  // Realigns the corners in the quad by rotating them n corners to the right.
  void Realign(size_t times) {
    DCHECK_LE(times, 4u);
    for (size_t i = 0; i < times; ++i) {
      PointF temp = p1_;
      p1_ = p2_;
      p2_ = p3_;
      p3_ = p4_;
      p4_ = temp;
    }
  }

  // Add a vector to the quad, offseting each point in the quad by the vector.
  void operator+=(const Vector2dF& rhs);
  // Subtract a vector from the quad, offseting each point in the quad by the
  // inverse of the vector.
  void operator-=(const Vector2dF& rhs);

  // Scale each point in the quad by the |scale| factor.
  void Scale(float scale) { Scale(scale, scale); }

  // Scale each point in the quad by the scale factors along each axis.
  void Scale(float x_scale, float y_scale);

  // Tests whether any part of the rectangle intersects with this quad.
  // This only works for convex quads.
  // This intersection is edge-inclusive and will return true even if the
  // intersecting area is empty (i.e., the intersection is a line or a point).
  bool IntersectsRect(const RectF&) const;

  // Test whether any part of the circle/ellipse intersects with this quad.
  // Note that these two functions only work for convex quads.
  // These intersections are edge-inclusive and will return true even if the
  // intersecting area is empty (i.e., the intersection is a line or a point).
  bool IntersectsCircle(const PointF& center, float radius) const;
  bool IntersectsEllipse(const PointF& center, const SizeF& radii) const;

  // The center of the quad. If the quad is the result of a affine-transformed
  // rectangle this is the same as the original center transformed.
  PointF CenterPoint() const {
    return PointF((p1_.x() + p2_.x() + p3_.x() + p4_.x()) / 4.0,
                  (p1_.y() + p2_.y() + p3_.y() + p4_.y()) / 4.0);
  }

  // Returns a string representation of quad.
  std::string ToString() const;

 private:
  PointF p1_;
  PointF p2_;
  PointF p3_;
  PointF p4_;
};

inline bool operator==(const QuadF& lhs, const QuadF& rhs) {
  return
      lhs.p1() == rhs.p1() && lhs.p2() == rhs.p2() &&
      lhs.p3() == rhs.p3() && lhs.p4() == rhs.p4();
}

inline bool operator!=(const QuadF& lhs, const QuadF& rhs) {
  return !(lhs == rhs);
}

// Add a vector to a quad, offseting each point in the quad by the vector.
GEOMETRY_EXPORT QuadF operator+(const QuadF& lhs, const Vector2dF& rhs);
// Subtract a vector from a quad, offseting each point in the quad by the
// inverse of the vector.
GEOMETRY_EXPORT QuadF operator-(const QuadF& lhs, const Vector2dF& rhs);

// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const QuadF& quad, ::std::ostream* os);

}  // namespace gfx

#endif  // UI_GFX_GEOMETRY_QUAD_F_H_

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.solr;

import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.beans.Field;
import org.junit.Ignore;
import org.junit.Test;

@Ignore("Need refactoring in SolrComponentTestSupport, with new schema and solr-config from solr 5.2.1 and new Cloud Solr cluster instantiation")
public class SolrAddBeansTest extends SolrComponentTestSupport {

    public SolrAddBeansTest(SolrFixtures.TestServerType serverToTest) {
        super(serverToTest);
    }

    @Test
    public void testAddBeans() throws Exception {

        List<Item> beans = new ArrayList<>();

        //add bean1
        Item item1 = new Item();
        item1.id = TEST_ID;
        item1.categories =  new String[] {"aaa", "bbb", "ccc"};
        beans.add(item1);

        //add bean2
        Item item2 = new Item();
        item2.id = TEST_ID2;
        item2.categories =  new String[] {"aaa", "bbb", "ccc"};
        beans.add(item2);

        template.sendBodyAndHeader("direct:start", beans, SolrConstants.OPERATION, SolrConstants.OPERATION_ADD_BEANS);
        template.sendBodyAndHeader("direct:start", null, SolrConstants.OPERATION, SolrConstants.OPERATION_COMMIT);

        //verify
        assertEquals("wrong number of entries found", 1, executeSolrQuery("id:" + TEST_ID).getResults().getNumFound());
        assertEquals("wrong number of entries found", 1, executeSolrQuery("id:" + TEST_ID2).getResults().getNumFound());
        assertEquals("wrong number of entries found", 2, executeSolrQuery("*:*").getResults().getNumFound());
    }

    public class Item {
        @Field
        String id;

        @Field("cat")
        String[] categories;
    }
}


text:
DELETE FROM public.network_contact;
DELETE FROM public.network_endpoint;
DELETE FROM public.network_comment;
DELETE FROM public.network_machine_tag;
DELETE FROM public.network_tag;
DELETE FROM public.network_identifier;
DELETE FROM public.network;

DELETE FROM public.metadata;
DELETE FROM public.dataset_contact;
DELETE FROM public.dataset_endpoint;
DELETE FROM public.dataset_comment;
DELETE FROM public.dataset_machine_tag;
DELETE FROM public.dataset_tag;
DELETE FROM public.dataset_identifier;
DELETE FROM public.dataset;

DELETE FROM public.installation_contact;
DELETE FROM public.installation_endpoint;
DELETE FROM public.installation_comment;
DELETE FROM public.installation_machine_tag;
DELETE FROM public.installation_tag;
DELETE FROM public.installation_identifier;
DELETE FROM public.installation;

DELETE FROM public.organization_contact;
DELETE FROM public.organization_endpoint;
DELETE FROM public.organization_comment;
DELETE FROM public.organization_machine_tag;
DELETE FROM public.organization_tag;
DELETE FROM public.organization_identifier;
DELETE FROM public.organization;

DELETE FROM public.node_endpoint;
DELETE FROM public.node_comment;
DELETE FROM public.node_machine_tag;
DELETE FROM public.node_tag;
DELETE FROM public.node_identifier;
DELETE FROM public.node;

DELETE FROM public.contact;
DELETE FROM public.comment;
DELETE FROM public.tag;
DELETE FROM public.machine_tag;
DELETE FROM public.endpoint;
DELETE FROM public.identifier;

DELETE FROM public.gbif_doi;

DELETE FROM public.editor_rights;


text:
import logging
from flask import Blueprint, current_app, render_template
#from flask_login import login_required
from flask_security import login_required

app = Blueprint("auth", __name__, template_folder="templates")

@app.route("/")
@login_required
def profile():
    return render_template('User/profile.html')


text:
<!DOCTYPE html>

    <title>
        chengzhycn's blog</title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">

    <meta name="theme-color" content="#000000" />

    <meta http-equiv="window-target" content="_top" />

    <meta name="generator" content="Hugo 0.80.0 with theme pure" />
    <title>chengzhycn's blog</title>

    <link rel="stylesheet" href="https://chengzhycn.github.io/css/style.min.7dc20efbc53647d41aa9ddea0c48e59300223d084e66ea0cbe7c30bd88903acc.css">

    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="404 Page not found" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://chengzhycn.github.io/404.html" />

<meta itemprop="name" content="404 Page not found">
<meta itemprop="description" content="">
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="404 Page not found"/>
<meta name="twitter:description" content=""/>

chengzhycn

An Engineer.

          Beijing, China

    <form class="search-form sidebar-form">

            <input type="text" class="search-form-input form-control" placeholder="搜索" />

                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"></button>

                    <input type="text" class="ins-search-input" placeholder="想要查找什么..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close">×</button>

    </form>

        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          Toggle navigation

        </button>

                  Home

                  Archives

                  Categories

                  Tags

                  About

公告

Better Work, Better Life~

 分类

dns1

kubernetes1

network2

work2

 标签

dns1

kubernetes1

ops1

zone1

最新文章

                        Kubeadm安装集群

                        <time datetime="2021-01-17 22:12:37 +0800 CST" itemprop="datePublished">2021-01-17</time>

                        Dns Zone Files

                        <time datetime="2021-01-03 10:18:55 +0800 CST" itemprop="datePublished">2021-01-03</time>

                    404 Not Found

                 评论
		字数统计: 0字
		阅读时长: 0分

找不到页面啦~请换个姿势( ̄. ̄)

                返回首页

      本文链接:
      https://chengzhycn.github.io/404.html

      License:CC BY 4.0 CN

chengzhycnAn Engineer.

Better Work, Better Life~

    ©2021  -
    2021

        Theme by  xiaoheiAh base on pure.


text:
package de.javagl.common.ui;

import java.awt.Window;
import java.util.Arrays;
import java.util.function.Predicate;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

/**
 * Methods related to option panes
 */
public class JOptionPanes
{
    /**
     * Create a new input dialog that performs validation.
     *
     * @param parent The optional parent
     * @param title The title
     * @param mainComponent The main component that is shown in the
     * dialog. This must be a component that contains the text component.
     * @param textComponent The text component
     * @param validInputPredicate The predicate that says whether the
     * input is valid
     * @return JOptionPane.OK_OPTION if OK was pressed. Any
     * other value otherwise.
     */
    public static int showValidatedTextInputDialog(Window parent, String title,
        JComponent mainComponent, JTextComponent textComponent,
        Predicate<String> validInputPredicate)
    {
        JButton okButton = new JButton("Ok");

        String text = textComponent.getText();
        boolean valid = validInputPredicate.test(text);
        okButton.setEnabled(valid);

        JButton cancelButton = new JButton("Cancel");

        Object[] options = new Object[] { okButton, cancelButton };
        JOptionPane optionPane =
            new JOptionPane(mainComponent, JOptionPane.PLAIN_MESSAGE,
                JOptionPane.OK_CANCEL_OPTION, null, options, okButton);

        okButton.addActionListener(e -> optionPane.setValue(okButton));
        cancelButton.addActionListener(e -> optionPane.setValue(cancelButton));

        AncestorListener focussingAncestorListener = new AncestorListener()
        {
            @Override
            public void ancestorAdded(AncestorEvent event)
            {
                textComponent.requestFocus();
            }

            @Override
            public void ancestorRemoved(AncestorEvent event)
            {
                // Nothing to do here
            }

            @Override
            public void ancestorMoved(AncestorEvent event)
            {
                // Nothing to do here
            }
        };
        textComponent.addAncestorListener(focussingAncestorListener);

        DocumentListener documentListener = new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent e)
            {
                updateButtonState();
            }

            @Override
            public void removeUpdate(DocumentEvent e)
            {
                updateButtonState();
            }

            @Override
            public void changedUpdate(DocumentEvent e)
            {
                updateButtonState();
            }

            protected void updateButtonState()
            {
                String text = textComponent.getText();
                boolean valid = validInputPredicate.test(text);
                okButton.setEnabled(valid);
            }
        };
        Document document = textComponent.getDocument();
        document.addDocumentListener(documentListener);

        JDialog dialog = optionPane.createDialog(parent, title);
        dialog.pack();
        dialog.setResizable(true);
        dialog.setVisible(true);

        document.removeDocumentListener(documentListener);
        textComponent.removeAncestorListener(focussingAncestorListener);

        Object selectedValue = optionPane.getValue();
        if (selectedValue == null)
        {
            return JOptionPane.CLOSED_OPTION;
        }
        return Arrays.asList(options).indexOf(selectedValue);
    }

    /**
     * Private constructor to prevent instantiation
     */
    private JOptionPanes()
    {
        // Private constructor to prevent instantiation
    }
}


text:
*******
Autodoc
*******

Ansible Galaxy
==============

.. autoclass:: molecule.ansible_galaxy.AnsibleGalaxy
   :members:

Ansible Playbook
================

.. autoclass:: molecule.ansible_playbook.AnsiblePlaybook
   :members:

.. include:: command.rst

Config
======

.. autoclass:: molecule.config.Config
   :members:

.. autoclass:: molecule.config.ConfigV1
   :members:

.. include:: driver.rst

Molecule
========

.. autoclass:: molecule.core.Molecule
   :members:

State
=====

.. autoclass:: molecule.state.InvalidState
   :members:

.. autoclass:: molecule.state.State
   :members:

Util
====

.. automodule:: molecule.util
   :members:

.. include:: verifier.rst


text:
package ru.stqa.pft.mantis.tests;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.model.MailMessage;

import java.io.IOException;
import java.util.List;

import static org.testng.Assert.assertTrue;

/**
 * Created by Admin on 7/17/2016.
 */
public class ResetPasswordTests extends TestBase {

  @BeforeMethod
  public void startMailServer() {
    app.mail().start();
  }

  @Test
  public void testResetPassword() throws IOException {
    String userName = "Maria";
    String newPassword = "newPassword";
    String email = "maria@mail.ru";

    // Администратор входит в систему, переходит на страницу управления пользователями, выбирает заданного пользователя и нажимает кнопку Reset Password
    app.getDriver();
    app.registration().loginAsAdmin("administrator", "root");
    app.navigation().openManageUsersPage();
    app.registration().resetPassword(userName);

    // Отправляется письмо на адрес пользователя, получаем это письмо, извлекаем из него ссылку для смены пароля, переходим по этой ссылке и изменяем пароль.
    List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000);
    String confirmationLink = findConfirmationLink(mailMessages, email);
    app.registration().finish(confirmationLink, newPassword);

    // проверztv, что пользователь может войти в систему с новым паролем.
    assertTrue(app.newSession().login(userName, newPassword));
  }

  private String findConfirmationLink(List<MailMessage> mailMessages, String email) {
    MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
    VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
    return regex.getText(mailMessage.text);
  }

  @AfterMethod(alwaysRun = true)
  public void stopMailServer() {
    app.mail().stop();
  }

}


text:
package com.g11x.checklistapp;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.g11x.checklistapp.data.ChecklistItem;
import com.g11x.checklistapp.data.Database;
import com.g11x.checklistapp.language.Language;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ChecklistItemActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

  private static final int LOADER_ID = 9002;
  private ChecklistItem checklistItem;
  private Language language;
  private ContentObserver checklistContentObserver = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    setContentView(R.layout.activity_checklist_item);

    language = AppPreferences.getLanguageOverride(this);

    DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl(
        this.getIntent().getStringExtra("databaseRefUrl"));

    databaseRef.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
        checklistItem = dataSnapshot.getValue(ChecklistItem.class);
        createUI();
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {
        Log.e("", "Unable to fetch database item.");
      }
    });

    getSupportLoaderManager().initLoader(LOADER_ID, null, this);

    ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
    scrollView.setFadingEdgeLength(150);
  }

  private void createUI() {
    TextView name = (TextView) findViewById(R.id.name);
    name.setText(checklistItem.getName(language));

    TextView description = (TextView) findViewById(R.id.description);
    description.setText(checklistItem.getDescription(language));

    Button getDirections = (Button) findViewById(R.id.directions);
    getDirections.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        ChecklistItemActivity.this.onClickGetDirections();
      }
    });

    Button doneness = (Button) findViewById(R.id.doneness);
    if (checklistItem.isDone()) {
      doneness.setTextColor(ContextCompat.getColor(ChecklistItemActivity.this, R.color.primary));
      doneness.setPaintFlags(doneness.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
      doneness.setText(getResources().getString(R.string.complete));
      doneness.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_box_accent_24dp, 0, 0, 0);
    } else {
      doneness.setTextColor(Color.BLACK);
      doneness.setPaintFlags(doneness.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
      doneness.setText(getResources().getString(R.string.mark_as_done));
      doneness.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_box_outline_blank_black_24dp, 0, 0, 0);
    }
    doneness.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        ChecklistItemActivity.this.onClickIsDone();
      }
    });

    Button sendEmail = (Button) findViewById(R.id.send_email);
    if (checklistItem.getEmail() != null && !checklistItem.getEmail().equals("")) {
      sendEmail.setVisibility(View.VISIBLE);
      sendEmail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(Intent.ACTION_SENDTO);
          intent.setData(Uri.parse("mailto:"));
          intent.putExtra(Intent.EXTRA_EMAIL, checklistItem.getEmail());
          intent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.sent_from_rst_checklist_app));
          if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(Intent.createChooser(intent, "Send e-mail"));
          }
        }
      });
    } else {
      sendEmail.setVisibility(View.GONE);
    }

    Button call = (Button) findViewById(R.id.call);
    if (checklistItem.getPhone() != null && !checklistItem.getPhone().equals("")) {
      call.setVisibility(View.VISIBLE);
      call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(Intent.ACTION_DIAL);
          intent.setData(Uri.parse("tel:" + checklistItem.getPhone()));
          if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
          }
        }
      });
    } else {
      call.setVisibility(View.GONE);
    }
  }

  private void onClickIsDone() {
    ContentResolver contentResolver = getContentResolver();
    checklistItem.setDone(contentResolver, !checklistItem.isDone());
  }

  private void onClickGetDirections() {
    startActivity(new Intent(Intent.ACTION_VIEW, checklistItem.getDirections()));
  }

  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (checklistContentObserver != null) {
      getContentResolver().unregisterContentObserver(checklistContentObserver);
    }
    checklistContentObserver = new ContentObserver(new Handler()) {
      @Override
      public void onChange(boolean selfChange) {
        getSupportLoaderManager().restartLoader(LOADER_ID, null, ChecklistItemActivity.this);
        super.onChange(selfChange);
      }

      @Override
      public void onChange(boolean selfChange, Uri uri) {
        getSupportLoaderManager().restartLoader(LOADER_ID, null, ChecklistItemActivity.this);
        super.onChange(selfChange, uri);
      }
    };
    getContentResolver().registerContentObserver(Database.ChecklistItem.CONTENT_URI, true,
        checklistContentObserver);

    return new CursorLoader(ChecklistItemActivity.this,
        Database.ChecklistItem.CONTENT_URI,
        ChecklistItem.PROJECTION,
        null,
        null,
        null);
  }

  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    checklistItem.setDoneWithoutUpdatingContent(false);
    while (cursor.moveToNext()) {
      if (checklistItem.getHash().equals(cursor.getString(ChecklistItem.ITEM_HASH_COLUMN_INDEX))) {
        boolean isDone = cursor.getInt(ChecklistItem.DONE_COLUMN_INDEX) != 0;
        checklistItem.setDoneWithoutUpdatingContent(isDone);
      }
    }
    createUI();
  }

  @Override
  public void onLoaderReset(Loader<Cursor> loader) {
    // don't bother telling the adapter that data has changed, just leave it be with the stale
    // data.
  }

}


text:
package org.aludratest.eclipse.vde.internal.refactor;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.MoveParticipant;
import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;

public class RefactorMoveParticipant extends MoveParticipant {

	private UpdateDataClassRefactoring refactoring = new UpdateDataClassRefactoring();

	@Override
	public boolean initialize(RefactoringProcessor processor, Object element, RefactoringArguments arguments) {
		return refactoring.initialize(processor, element, arguments);
	}

	@Override
	public String getName() {
		return refactoring.getName();
	}

	@Override
	public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
			throws OperationCanceledException {
		return refactoring.checkConditions(pm, context);
	}

	@Override
	public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
		return refactoring.createChange(pm);
	}

	@Override
	public Change createPreChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
		return refactoring.createPreChange(pm);
	}

	@Override
	public TextChange getTextChange(Object element) {
		return refactoring.getTextChange(element);
	}

	@Override
	protected boolean initialize(Object element) {
		return refactoring.initialize(element);
	}

}


text:
.. sample documentation master file, created by
   sphinx-quickstart on Mon Apr 16 21:22:43 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

HPCBench Documentation
======================

.. module:: hpcbench

HPCBench is a Python package that allows you to specify and execute benchmarks. It provides:

* an API to describe how to execute benchmarks utilities and gather metrics.
* A way to describe benchmark campaigns in YAML format.
* command line utilities to execute your campaigns, and post-process generated metrics in
  various ways:

   * Merging metrics from different campaigns
   * Exporting metrics in CSV format
   * Exporting data to Elasticsearch
   * PDF report generation

HPCBench assumes that the various benchmark tools/binaries are managed elsewhere and does
not provide features for building and maintaining benchmark software.

NB: This Python package is still in pre-alpha stage, and not suitable for production.

Installation
============
.. highlight:: bash

**HPCBench** is in the `Python Package Index <http://pypi.python.org/pypi/hpcbench/>`_.

Installation with pip
---------------------

We recommend using `pip <http://pypi.python.org/pypi/pip>`_ to install hpcbench on all platforms::

  $ python -m pip install hpcbench

To upgrade HPCBench with pip::

  $ python -m pip install --upgrade hpcbench

Dependencies
------------

HPCBench supports both python 2.7 and 3.4+.

Overview
========

CLI
---

The main interface through which **HPCbench** is used is a set of command
line utilities:

* ben-sh: Execute a tests campaign on your workstation
* ben-csv: Extract metrics of an existing campaign in csv format
* ben-umb: Extract metrics of an existing campaign
* ben-elastic: Push campaign data to Elasticsearch
* ben-nett: Execute a tests campaign on a cluster
* ben-merge: Merge campaign output directories
* ben-tpl: Generate HPCBench plugin scaffolds,
  see :ref:`usage <ben-tpl-usage>` for more information on plugin generation.

**ben-sh** and **ben-nett** expect a YAML file describing the campaign to execute.
The structure of this YAML file is detailed in the :doc:`campaign file reference <campaign>`.

Campaign YAML description
-------------------------

.. toctree::
   :maxdepth: 2
   :numbered:

   campaign.rst
   standard_benchmark.rst

API
---

The purpose of the HPCBench API is to provide a consistent and unified layer:

* to execute, and parse results of existing benchmarks utilities (Linpack, IOR, ...)
* to use extracted metrics to build figures

Both system benchmarks (e.g. STREAM, linpack), as well as software benchmarks should be
implemented using this API. Most users parametrize benchmarks in the above-mentioned
campaign YAML file. More advanced users will want to implement their own benchmarks based
on the API.

For more information check the :doc:`module reference <modules>`

Getting Started
===============

As of now, only a few benchmarks are supported. This section assumes that
you have at least installed the ``sysbench`` utility on your workstation.

Launch a campaign on your workstation
-------------------------------------

Create your first campaign YAML file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Create a ``local-campaign.yaml`` file with the following content::

   benchmarks:
     '*':
       test:
         type: sysbench

Launch the benchmark on your workstation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Execute the following command::

   $ ben-sh local-campaign.yaml

This will create a ``hpcbench-<date>`` in the directory with the benchmark's results.
Although the user is not meant to be manually checking results inside the output directory
at this point take a look at ``hpcbench-<date>/<hostname>/*/test/metrics.json``. You will
find that this file contains the collected metrics data from sysbench. The raw logs and
stdout's can be found further down the directory tree.

**Note**: Do not manually edit files inside the output directory. HPCBench offers a number of
utilities to export and post-process the collected results.

Launch a campaign on a set of nodes
-----------------------------------

The YAML config file is getting a little more complex. For instance create
the following ``remote-campaign.yaml``::

   network:
     nodes:
       - localhost
   benchmarks:
     '*':
       test:
         type: sysbench

You can add computer nodes to the ``nodes`` section.

Launch the benchmark
~~~~~~~~~~~~~~~~~~~~

Use the ``ben-nett`` utility to execute the campaign on every nodes.
It uses SSH to submit jobs so you have to make sure you can access those
nodes without passphrase. For this you could use the ``ssh_config_file`` key in YAML to
specify a custom configuration (see) :doc:`campaign file reference <campaign>`)::

   $ ben-nett remote-campaign.yaml

.. _ben-tpl-usage:

How to create a new benchmark Python module?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is possible to create your own benchmark based on a tool that has not been so far supported
by HPCBench. This is done by generating an external plugin scaffold using ``ben-tpl`` and
implementing the benchmark execution and metrics parsing inside the generated classes.

Here is the basic workflow:

1. First create a default JSON file describing the Python module:
    ``ben-tpl benchmark -g config.json``
2. Update fields in ``config.json``
3. Generate the Python module template in the current directory:
    ``ben-tpl benchmark config.json``
4. Edit the ``benchmark.py`` file
5. When ready you can install the module, with ``pip`` for instance.

Development Guide
=================

Prerequisites
-------------

Docker
~~~~~~

`Elasticsearch <https://www.elastic.co/products/elasticsearch>`_ is required to execute
some of the unit-tests. The easiest way to accomplish this, is to use Docker containers.

Quick'n'dirty Docker installation::

   $ curl -fsSL get.docker.com -o get-docker.sh
   $ sh get-docker.sh
   $ curl -L https://github.com/docker/compose/releases/download/1.15.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
   $ chmod +x /usr/local/bin/docker-compose

Post-installation instructions to use Docker without root privileges (logout/login) required::

   $ sudo groupadd docker
   $ sudo usermod -aG docker $USER

Test your docker installation with::

    $ docker run --rm hello-world

Build instructions
------------------
.. highlight:: bash

Grab the source code::

  $ git clone https://github.com/BlueBrain/hpcbench.git
  $ cd hpcbench

We suggest you use a dedicated virtual environment. For that you can use
either `virtualenv <https://virtualenv.pypa.io/en/stable/>`_ package or
`pyenv <https://github.com/pyenv/pyenv>`_, which is even better.

With ``pyenv``::

  $ pyenv virtualenv hpcbench
  $ pyenv local hpcbench

Alternatively, with ``virtualenv``::

   $ virtualenv .env
   $ . .env/bin/activate

Then::

  $ pip install tox
  $ tox -e py27

``tox`` is configured to test HPCBench against different Python versions. To test against a
specific python version you can supply it the ``-e`` parameter::

  $ tox -e py27 --
  $ tox -e py36 --

The ``--tests`` parameter can be used to run only one specific unit test module or class::

  $ tox  -e py36 -- --tests tests/test_driver.py

Elasticsearch
~~~~~~~~~~~~~

To start an Elasticsearch container, you can use the
``misc/dc`` script wrapper on top of ``docker-compose``::

   $ misc/dc up -d

It will start an Elasticsearch container listening on port 9200 and a Kibana
instance listening on port 5612.

Let's now try to ping Elasticsearch::

   $ curl localhost:9200
   {
     "name" : "jQ-BcoF",
     "cluster_name" : "elasticsearch",
     "cluster_uuid" : "yGP7_Q2gSU2HmHpnQB-jzg",
     "version" : {
       "number" : "5.5.1",
       "build_hash" : "19c13d0",
       "build_date" : "2017-07-18T20:44:24.823Z",
       "build_snapshot" : false,
       "lucene_version" : "6.6.0"
     },
     "tagline" : "You Know, for Search"
   }

You can also access Kibana at http://localhost:5601
The ``Dev Tools`` is one of the most handy Elasticsearch client for humans.

Testing it all out
~~~~~~~~~~~~~~~~~~

Unit-tests assume that Elasticsearch is running on localhost.
You can define the ``UT_ELASTICSEARCH_HOST`` environment variable to specify
another location::

   $ ELASTICSEARCH_HOST=server01:9200 tox

How to integrate a new benchmark utility in the HPCBench repository?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. First make sure you can properly build the project and tests pass successfully.
   It may be tempting to skip this part, but please don't.
2. Create a dedicated Git branch.
3. Create a new Python module in ``hpcbench/benchmark`` directory named after the
   utility to integrate.
4. In this new module, implement ``hpcbench.api.Benchmark`` and
   ``hpcbench.MetricsExtractor`` classes.
5. Register the new module in ``setup.py`` ``[hpcbench.benchmarks]`` entrypoint
   so that it can be found by HPCBench.
6. Create a dedicated unit test class in `tests/benchmark/` directory.
   The purpose of this test is to make sure that:
   * your Benchmark class is properly defined, and usable by HPCBench.
   * your metric extractor is properly working, without having to launch the
     utility itself.
7. To properly test your metrics extractors, some outputs of the benchmark utility
   will be added to the repository. For every category of your benchmark, create a
   file title ``tests/benchmark/<test_module_name>.<category>.stdout`` with the
   benchmark utility's output. These files will be automatically used.
   Do not hesitate to take inspiration from the ``tests/benchmark/test_sysbench.py``
   test module.

8. Run the test-suites until it passes::

   $ tox

9. Submit a `pull-request <https://github.com/BlueBrain/hpcbench>`_

LICENSE
=======

This software is released under MIT License.

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
import os,shlex,sys,time,re,shutil
from waflib import ConfigSet,Utils,Options,Logs,Context,Build,Errors
WAF_CONFIG_LOG='config.log'
autoconfig=False
conf_template='''# project %(app)s configured on %(now)s by
# waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s)
# using %(args)s
#'''
class ConfigurationContext(Context.Context):
	'''configures the project'''
	cmd='configure'
	error_handlers=[]
	def __init__(self,**kw):
		super(ConfigurationContext,self).__init__(**kw)
		self.environ=dict(os.environ)
		self.all_envs={}
		self.top_dir=None
		self.out_dir=None
		self.tools=[]
		self.hash=0
		self.files=[]
		self.tool_cache=[]
		self.setenv('')
	def setenv(self,name,env=None):
		if name not in self.all_envs or env:
			if not env:
				env=ConfigSet.ConfigSet()
				self.prepare_env(env)
			else:
				env=env.derive()
			self.all_envs[name]=env
		self.variant=name
	def get_env(self):
		return self.all_envs[self.variant]
	def set_env(self,val):
		self.all_envs[self.variant]=val
	env=property(get_env,set_env)
	def init_dirs(self):
		top=self.top_dir
		if not top:
			top=Options.options.top
		if not top:
			top=getattr(Context.g_module,Context.TOP,None)
		if not top:
			top=self.path.abspath()
		top=os.path.abspath(top)
		self.srcnode=(os.path.isabs(top)and self.root or self.path).find_dir(top)
		assert(self.srcnode)
		out=self.out_dir
		if not out:
			out=Options.options.out
		if not out:
			out=getattr(Context.g_module,Context.OUT,None)
		if not out:
			out=Options.lockfile.replace('.lock-waf_%s_'%sys.platform,'').replace('.lock-waf','')
		out=os.path.realpath(out)
		self.bldnode=(os.path.isabs(out)and self.root or self.path).make_node(out)
		self.bldnode.mkdir()
		if not os.path.isdir(self.bldnode.abspath()):
			conf.fatal('Could not create the build directory %s'%self.bldnode.abspath())
	def execute(self):
		self.init_dirs()
		self.cachedir=self.bldnode.make_node(Build.CACHE_DIR)
		self.cachedir.mkdir()
		path=os.path.join(self.bldnode.abspath(),WAF_CONFIG_LOG)
		self.logger=Logs.make_logger(path,'cfg')
		app=getattr(Context.g_module,'APPNAME','')
		if app:
			ver=getattr(Context.g_module,'VERSION','')
			if ver:
				app="%s (%s)"%(app,ver)
		params={'now':time.ctime(),'pyver':sys.hexversion,'systype':sys.platform,'args':" ".join(sys.argv),'wafver':Context.WAFVERSION,'abi':Context.ABI,'app':app}
		self.to_log(conf_template%params)
		self.msg('Setting top to',self.srcnode.abspath())
		self.msg('Setting out to',self.bldnode.abspath())
		if id(self.srcnode)==id(self.bldnode):
			Logs.warn('Setting top == out')
		elif id(self.path)!=id(self.srcnode):
			if self.srcnode.is_child_of(self.path):
				Logs.warn('Are you certain that you do not want to set top="." ?')
		super(ConfigurationContext,self).execute()
		self.store()
		Context.top_dir=self.srcnode.abspath()
		Context.out_dir=self.bldnode.abspath()
		env=ConfigSet.ConfigSet()
		env.argv=sys.argv
		env.options=Options.options.__dict__
		env.config_cmd=self.cmd
		env.run_dir=Context.run_dir
		env.top_dir=Context.top_dir
		env.out_dir=Context.out_dir
		env.hash=self.hash
		env.files=self.files
		env.environ=dict(self.environ)
		if not self.env.NO_LOCK_IN_RUN and not getattr(Options.options,'no_lock_in_run'):
			env.store(os.path.join(Context.run_dir,Options.lockfile))
		if not self.env.NO_LOCK_IN_TOP and not getattr(Options.options,'no_lock_in_top'):
			env.store(os.path.join(Context.top_dir,Options.lockfile))
		if not self.env.NO_LOCK_IN_OUT and not getattr(Options.options,'no_lock_in_out'):
			env.store(os.path.join(Context.out_dir,Options.lockfile))
	def prepare_env(self,env):
		if not env.PREFIX:
			if Options.options.prefix or Utils.is_win32:
				env.PREFIX=Utils.sane_path(Options.options.prefix)
			else:
				env.PREFIX=''
		if not env.BINDIR:
			if Options.options.bindir:
				env.BINDIR=Utils.sane_path(Options.options.bindir)
			else:
				env.BINDIR=Utils.subst_vars('${PREFIX}/bin',env)
		if not env.LIBDIR:
			if Options.options.libdir:
				env.LIBDIR=Utils.sane_path(Options.options.libdir)
			else:
				env.LIBDIR=Utils.subst_vars('${PREFIX}/lib%s'%Utils.lib64(),env)
	def store(self):
		n=self.cachedir.make_node('build.config.py')
		n.write('version = 0x%x\ntools = %r\n'%(Context.HEXVERSION,self.tools))
		if not self.all_envs:
			self.fatal('nothing to store in the configuration context!')
		for key in self.all_envs:
			tmpenv=self.all_envs[key]
			tmpenv.store(os.path.join(self.cachedir.abspath(),key+Build.CACHE_SUFFIX))
	def load(self,input,tooldir=None,funs=None,with_sys_path=True,cache=False):
		tools=Utils.to_list(input)
		if tooldir:tooldir=Utils.to_list(tooldir)
		for tool in tools:
			if cache:
				mag=(tool,id(self.env),tooldir,funs)
				if mag in self.tool_cache:
					self.to_log('(tool %s is already loaded, skipping)'%tool)
					continue
				self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir,ctx=self,with_sys_path=with_sys_path)
			except ImportError as e:
				self.fatal('Could not load the Waf tool %r from %r\n%s'%(tool,sys.path,e))
			except Exception as e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(Utils.ex_stack())
				raise
			if funs is not None:
				self.eval_rules(funs)
			else:
				func=getattr(module,'configure',None)
				if func:
					if type(func)is type(Utils.readf):func(self)
					else:self.eval_rules(func)
			self.tools.append({'tool':tool,'tooldir':tooldir,'funs':funs})
	def post_recurse(self,node):
		super(ConfigurationContext,self).post_recurse(node)
		self.hash=Utils.h_list((self.hash,node.read('rb')))
		self.files.append(node.abspath())
	def eval_rules(self,rules):
		self.rules=Utils.to_list(rules)
		for x in self.rules:
			f=getattr(self,x)
			if not f:
				self.fatal('No such configuration function %r'%x)
			f()
def conf(f):
	def fun(*k,**kw):
		mandatory=True
		if'mandatory'in kw:
			mandatory=kw['mandatory']
			del kw['mandatory']
		try:
			return f(*k,**kw)
		except Errors.ConfigurationError:
			if mandatory:
				raise
	fun.__name__=f.__name__
	setattr(ConfigurationContext,f.__name__,fun)
	setattr(Build.BuildContext,f.__name__,fun)
	return f
@conf
def add_os_flags(self,var,dest=None,dup=False):
	try:
		flags=shlex.split(self.environ[var])
	except KeyError:
		return
	if dup or''.join(flags)not in''.join(Utils.to_list(self.env[dest or var])):
		self.env.append_value(dest or var,flags)
@conf
def cmd_to_list(self,cmd):
	if isinstance(cmd,str):
		if os.path.isfile(cmd):
			return[cmd]
		if os.sep=='/':
			return shlex.split(cmd)
		else:
			try:
				return shlex.split(cmd,posix=False)
			except TypeError:
				return shlex.split(cmd)
	return cmd
@conf
def check_waf_version(self,mini='1.8.99',maxi='2.0.0',**kw):
	self.start_msg('Checking for waf version in %s-%s'%(str(mini),str(maxi)),**kw)
	ver=Context.HEXVERSION
	if Utils.num2ver(mini)>ver:
		self.fatal('waf version should be at least %r (%r found)'%(Utils.num2ver(mini),ver))
	if Utils.num2ver(maxi)<ver:
		self.fatal('waf version should be at most %r (%r found)'%(Utils.num2ver(maxi),ver))
	self.end_msg('ok',**kw)
@conf
def find_file(self,filename,path_list=[]):
	for n in Utils.to_list(filename):
		for d in Utils.to_list(path_list):
			p=os.path.expanduser(os.path.join(d,n))
			if os.path.exists(p):
				return p
	self.fatal('Could not find %r'%filename)
@conf
def find_program(self,filename,**kw):
	exts=kw.get('exts',Utils.is_win32 and'.exe,.com,.bat,.cmd'or',.sh,.pl,.py')
	environ=kw.get('environ',getattr(self,'environ',os.environ))
	ret=''
	filename=Utils.to_list(filename)
	msg=kw.get('msg',', '.join(filename))
	var=kw.get('var','')
	if not var:
		var=re.sub(r'[-.]','_',filename[0].upper())
	path_list=kw.get('path_list','')
	if path_list:
		path_list=Utils.to_list(path_list)
	else:
		path_list=environ.get('PATH','').split(os.pathsep)
	if kw.get('value'):
		ret=self.cmd_to_list(kw['value'])
	elif var in environ:
		ret=self.cmd_to_list(environ[var])
	elif self.env[var]:
		ret=self.cmd_to_list(self.env[var])
	else:
		if not ret:
			ret=self.find_binary(filename,exts.split(','),path_list)
		if not ret and Utils.winreg:
			ret=Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER,filename)
		if not ret and Utils.winreg:
			ret=Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE,filename)
		ret=self.cmd_to_list(ret)
	if ret:
		if len(ret)==1:
			retmsg=ret[0]
		else:
			retmsg=ret
	else:
		retmsg=False
	self.msg('Checking for program %r'%msg,retmsg,**kw)
	if not kw.get('quiet'):
		self.to_log('find program=%r paths=%r var=%r -> %r'%(filename,path_list,var,ret))
	if not ret:
		self.fatal(kw.get('errmsg','')or'Could not find the program %r'%filename)
	interpreter=kw.get('interpreter')
	if interpreter is None:
		if not Utils.check_exe(ret[0],env=environ):
			self.fatal('Program %r is not executable'%ret)
		self.env[var]=ret
	else:
		self.env[var]=self.env[interpreter]+ret
	return ret
@conf
def find_binary(self,filenames,exts,paths):
	for f in filenames:
		for ext in exts:
			exe_name=f+ext
			if os.path.isabs(exe_name):
				if os.path.isfile(exe_name):
					return exe_name
			else:
				for path in paths:
					x=os.path.expanduser(os.path.join(path,exe_name))
					if os.path.isfile(x):
						return x
	return None
@conf
def run_build(self,*k,**kw):
	lst=[str(v)for(p,v)in kw.items()if p!='env']
	h=Utils.h_list(lst)
	dir=self.bldnode.abspath()+os.sep+(not Utils.is_win32 and'.'or'')+'conf_check_'+Utils.to_hex(h)
	try:
		os.makedirs(dir)
	except OSError:
		pass
	try:
		os.stat(dir)
	except OSError:
		self.fatal('cannot use the configuration test folder %r'%dir)
	cachemode=getattr(Options.options,'confcache',None)
	if cachemode==1:
		try:
			proj=ConfigSet.ConfigSet(os.path.join(dir,'cache_run_build'))
		except EnvironmentError:
			pass
		else:
			ret=proj['cache_run_build']
			if isinstance(ret,str)and ret.startswith('Test does not build'):
				self.fatal(ret)
			return ret
	bdir=os.path.join(dir,'testbuild')
	if not os.path.exists(bdir):
		os.makedirs(bdir)
	self.test_bld=bld=Context.create_context('build',top_dir=dir,out_dir=bdir)
	bld.init_dirs()
	bld.progress_bar=0
	bld.targets='*'
	bld.logger=self.logger
	bld.all_envs.update(self.all_envs)
	bld.env=kw['env']
	bld.kw=kw
	bld.conf=self
	kw['build_fun'](bld)
	ret=-1
	try:
		try:
			bld.compile()
		except Errors.WafError:
			ret='Test does not build: %s'%Utils.ex_stack()
			self.fatal(ret)
		else:
			ret=getattr(bld,'retval',0)
	finally:
		if cachemode==1:
			proj=ConfigSet.ConfigSet()
			proj['cache_run_build']=ret
			proj.store(os.path.join(dir,'cache_run_build'))
		else:
			shutil.rmtree(dir)
	return ret
@conf
def ret_msg(self,msg,args):
	if isinstance(msg,str):
		return msg
	return msg(args)
@conf
def test(self,*k,**kw):
	if not'env'in kw:
		kw['env']=self.env.derive()
	if kw.get('validate'):
		kw['validate'](kw)
	self.start_msg(kw['msg'],**kw)
	ret=None
	try:
		ret=self.run_build(*k,**kw)
	except self.errors.ConfigurationError:
		self.end_msg(kw['errmsg'],'YELLOW',**kw)
		if Logs.verbose>1:
			raise
		else:
			self.fatal('The configuration failed')
	else:
		kw['success']=ret
	if kw.get('post_check'):
		ret=kw['post_check'](kw)
	if ret:
		self.end_msg(kw['errmsg'],'YELLOW',**kw)
		self.fatal('The configuration failed %r'%ret)
	else:
		self.end_msg(self.ret_msg(kw['okmsg'],kw),**kw)
	return ret


text:
package com.grsu.config;

import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

/**
 * Created by dionp on 11.03.2017.
 */
public class SessionInitializer extends AbstractHttpSessionApplicationInitializer {
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
#include <assert.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#ifdef HAVE_STRUCT_SYSINFO_TOTALRAM
#include <sys/sysinfo.h>
#elif defined(HAVE_SWAPCTL) /* Solaris */
#include <sys/swap.h>
#endif

#include "intel_io.h"
#include "drmtest.h"
#include "igt_aux.h"

/**
 * intel_get_total_ram_mb:
 *
 * Returns:
 * The total amount of system RAM available in MB.
 */
uint64_t
intel_get_total_ram_mb(void)
{
	uint64_t retval;

#ifdef HAVE_STRUCT_SYSINFO_TOTALRAM /* Linux */
	struct sysinfo sysinf;
	int ret;

	ret = sysinfo(&sysinf);
	assert(ret == 0);

	retval = sysinf.totalram;
	retval *= sysinf.mem_unit;
#elif defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) /* Solaris */
	long pagesize, npages;

	pagesize = sysconf(_SC_PAGESIZE);
        npages = sysconf(_SC_PHYS_PAGES);

	retval = (uint64_t) pagesize * npages;
#else
#error "Unknown how to get RAM size for this OS"
#endif

	return retval / (1024*1024);
}

/**
 * intel_get_avail_ram_mb:
 *
 * Returns:
 * The amount of unused system RAM available in MB.
 */
uint64_t
intel_get_avail_ram_mb(void)
{
	uint64_t retval;

#ifdef HAVE_STRUCT_SYSINFO_TOTALRAM /* Linux */
	struct sysinfo sysinf;
	int ret;

	ret = sysinfo(&sysinf);
	assert(ret == 0);

	retval = sysinf.freeram;
	retval *= sysinf.mem_unit;
#elif defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) /* Solaris */
	long pagesize, npages;

	pagesize = sysconf(_SC_PAGESIZE);
        npages = sysconf(_SC_AVPHYS_PAGES);

	retval = (uint64_t) pagesize * npages;
#else
#error "Unknown how to get available RAM for this OS"
#endif

	return retval / (1024*1024);
}

/**
 * intel_get_total_swap_mb:
 *
 * Returns:
 * The total amount of swap space available in MB.
 */
uint64_t
intel_get_total_swap_mb(void)
{
	uint64_t retval;

#ifdef HAVE_STRUCT_SYSINFO_TOTALRAM /* Linux */
	struct sysinfo sysinf;
	int ret;

	ret = sysinfo(&sysinf);
	assert(ret == 0);

	retval = sysinf.freeswap;
	retval *= sysinf.mem_unit;
#elif defined(HAVE_SWAPCTL) /* Solaris */
	long pagesize = sysconf(_SC_PAGESIZE);
	uint64_t totalpages = 0;
	swaptbl_t *swt;
	char *buf;
	int n, i;

	if ((n = swapctl(SC_GETNSWP, NULL)) == -1) {
	    perror("swapctl: GETNSWP");
	    return 0;
	}
	if (n == 0) {
	    /* no error, but no swap devices either */
	    return 0;
	}

	swt = malloc(sizeof(struct swaptable) + (n * sizeof(swapent_t)));
	buf = malloc(n * MAXPATHLEN);
	if (!swt || !buf) {
	    perror("malloc");
	} else {
	    swt->swt_n = n;
	    for (i = 0 ; i < n; i++) {
		swt->swt_ent[i].ste_path = buf + (i * MAXPATHLEN);
	    }

	    if ((n = swapctl(SC_LIST, swt)) == -1) {
		perror("swapctl: LIST");
	    } else {
		for (i = 0; i < swt->swt_n; i++) {
		    totalpages += swt->swt_ent[i].ste_pages;
		}
	    }
	}
	free(swt);
	free(buf);

	retval = (uint64_t) pagesize * totalpages;
#else
#warning "Unknown how to get swap size for this OS"
	return 0;
#endif

	return retval / (1024*1024);
}

void
intel_purge_vm_caches(void)
{
	int fd;

	fd = open("/proc/sys/vm/drop_caches", O_RDWR);
	if (fd < 0)
		return;

	write(fd, "3\n", 2);
	close(fd);
}

/*
 * When testing a port to a new platform, create a standalone test binary
 * by running:
 * cc -o porttest intel_drm.c -I.. -DSTANDALONE_TEST `pkg-config --cflags libdrm`
 * and then running the resulting porttest program.
 */
#ifdef STANDALONE_TEST
void *mmio;

int main(int argc, char **argv)
{
    printf("Total RAM:  %" PRIu64 " Mb\n", intel_get_total_ram_mb());
    printf("Total Swap: %" PRIu64 " Mb\n", intel_get_total_swap_mb());

    return 0;
}
#endif /* STANDALONE_TEST */