text:
import {WhiteboardToolbar} from "./whiteboardToolbar";

/**
 * A white paperboard on which user can draw
 */
export class Whiteboard {
    private color = "#4E4E4E";
    private brush: Brush = Brush.Pencil;
    private brushSize: BrushSize = BrushSize.Medium;

    private canvas: HTMLCanvasElement = null;
    private parent: JQuery = null;
    private isDown = false;
    private canvasContext: CanvasRenderingContext2D = null;
    private toolbar: WhiteboardToolbar;
    private lastPoint: CanvasPointEvent;
    private canvasRect: ClientRect;

    constructor(private readOnly: boolean, containerId: string) {
        this.parent = $(containerId).first();
        this.canvas = <HTMLCanvasElement> this.parent.find(".whiteboard").first().get(0);
        if (!this.readOnly) {
            this.toolbar = new WhiteboardToolbar(this, this.parent);
        }
    }

    /**
     * Element must have is final position and parent when this method is called.
     * => It implies that animations are complete, add dom rendered
     */
    public show(displayThisDrawing ?: Blob): void {
        let self = this;
        if (this.canvas) {
            let offsetTop = this.canvas.offsetTop + this.parent.offset().top;
            let offsetLeft = this.canvas.offsetLeft + this.parent.offset().left;

            this.isDown = false;
            let jCanvas = $(this.canvas);
            this.canvasRect = this.canvas.getBoundingClientRect();
            jCanvas.attr("width", this.parent.width() + "px");
            jCanvas.attr("height", this.parent.height() + "px");
            if(displayThisDrawing) {
                let img = new Image();
                img.onload = function () {
                    self.canvasContext.drawImage(img,
                        0, 0, self.canvasRect.width, self.canvasRect.height);
                    self.canvasRect = self.canvas.getBoundingClientRect();
                };
                img.src = URL.createObjectURL(displayThisDrawing);
            }

            $(window).resize(function () {
                self.canvas.toBlob((blob) => {
                    let newWidth = self.parent.width();
                    let newHeight = self.parent.height();
                    jCanvas.attr("width", newWidth + "px");
                    jCanvas.attr("height", newHeight + "px");

                    let img = new Image();
                    img.onload = function () {
                        self.canvasContext.drawImage(img,
                            0, 0, self.canvasRect.width, self.canvasRect.height,
                            0, 0, newWidth, newHeight);
                        self.canvasRect = self.canvas.getBoundingClientRect();
                    };
                    if (blob) {
                        img.src = URL.createObjectURL(blob);
                    }
                });
            });
            this.canvasContext = this.canvas.getContext("2d");

            if(!this.readOnly) {
                jCanvas.on("touchstart", (e) => {
                    let touchEvent = <TouchEvent>e.originalEvent;
                    self.onDrawStart(touchEvent.touches[0].pageX - offsetLeft, touchEvent.touches[0].pageY - offsetTop);
                });
                jCanvas.on("touchmove", (e) => {
                    // ctx.moveTo(canvasX, canvasY);
                    let touchEvent = <TouchEvent>e.originalEvent;
                    self.onDrawMove(touchEvent.touches[0].pageX - offsetLeft, touchEvent.touches[0].pageY - offsetTop);
                });
                jCanvas.on("touchend", () => {
                    self.onDrawEnd();
                });

                //WIth mouse
                jCanvas.on("mousedown", (e) => {
                    self.onDrawStart(e.pageX - offsetLeft, e.pageY - offsetTop);
                });
                jCanvas.on("mousemove", (e) => {
                    self.onDrawMove(e.pageX - offsetLeft, e.pageY - offsetTop);
                });
                jCanvas.on("mouseup", () => {
                    self.onDrawEnd();
                });
                jCanvas.on("mouseout", () => {
                    self.onDrawEnd();
                });
            }
        }

        this.toolbar && this.toolbar.show();
    }

    public hide() {
        this.toolbar && this.toolbar.hide();
    }

    private onDrawStart(startX: number, startY: number) {
        this.isDown = true;
        this.lastPoint = new CanvasPointEvent(startX, startY, this.brush, this.color, this.brushSize, false);
    }

    private drawCanvas(point: CanvasPointEvent) {
        if (!point.dragging || !this.lastPoint) {
            return;
        }

        // Brush properties
        this.canvasContext.lineWidth = point.size.size;
        this.canvasContext.strokeStyle = point.color;
        this.canvasContext.lineJoin = "round";
        this.canvasContext.lineCap = "round";

        //Tool overwrite
        this.canvasContext.shadowBlur = 0;
        this.canvasContext.globalCompositeOperation = "source-over";
        let dist = Whiteboard.distanceBetween(this.lastPoint, point);
        let angle = Whiteboard.angleBetween(this.lastPoint, point);
        let lineWidth = point.size.size;

        for (let i = 0; i < dist; i += 4) {
            let x = this.lastPoint.x + (Math.sin(angle) * i);
            let y = this.lastPoint.y + (Math.cos(angle) * i);

            let radgrad;
            let rgb = Whiteboard.hexToRgb(point.color);

            // noinspection FallThroughInSwitchStatementJS
            switch (point.brush) {
                case Brush.Paintbrush :
                    radgrad = this.canvasContext.createRadialGradient(x, y, 0.1 * lineWidth, x, y, 0.8 * lineWidth);
                    radgrad.addColorStop(0, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0.2)');
                    radgrad.addColorStop(0.5, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0.05)');
                    radgrad.addColorStop(1, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0)');
                    this.canvasContext.fillStyle = radgrad;
                    this.canvasContext.fillRect(x - lineWidth, y - lineWidth, 2 * lineWidth, 2 * lineWidth);
                    break;
                case Brush.Chalk:
                    // this.canvasContext.globalCompositeOperation = "destination-over";
                    for (let i = 20; i--;) {
                        let offsetX = Whiteboard.getRandomInt(-lineWidth / 1.8, lineWidth / 1.8);
                        let offsetY = Whiteboard.getRandomInt(-lineWidth / 1.8, lineWidth / 1.8);
                        this.canvasContext.fillStyle = "#fff";
                        this.canvasContext.fillRect(point.x + offsetX, point.y + offsetY,
                            Whiteboard.getRandomInt(1, 3),
                            Whiteboard.getRandomInt(1, 3));
                    }

                    radgrad = this.canvasContext.createRadialGradient(x, y, 0.1 * lineWidth, x, y, 0.7 * lineWidth);
                    radgrad.addColorStop(0, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0.2)');
                    radgrad.addColorStop(0.85, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0.18)');
                    radgrad.addColorStop(1, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0)');
                    this.canvasContext.fillStyle = radgrad;
                    this.canvasContext.fillRect(x - lineWidth, y - lineWidth, 2 * lineWidth, 2 * lineWidth);
                    break;

                case Brush.Eraser :
                    this.canvasContext.globalCompositeOperation = "destination-out";
                    lineWidth = BrushSize.XLarge.size;
                default:
                    radgrad = this.canvasContext.createRadialGradient(x, y, 0, x, y, 0.5 * lineWidth);
                    radgrad.addColorStop(0, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',1)');
                    radgrad.addColorStop(0.85, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0.9)');
                    radgrad.addColorStop(1, 'rgba(' + rgb.red + ',' + rgb.green + ',' + rgb.blue + ',0)');
                    this.canvasContext.fillStyle = radgrad;
                    this.canvasContext.fillRect(x - lineWidth, y - lineWidth, 2 * lineWidth, 2 * lineWidth);
            }
        }
        this.lastPoint = point;

        // TODO tlu : support other brushes...
        // http://fabricjs.com/freedrawing
        // http://perfectionkills.com/exploring-canvas-drawing-techniques/
    }

    private static getRandomInt(min: number, max: number) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    private onDrawMove(moveX: number, moveY: number) {
        if (this.isDown) {
            let currentPoint = new CanvasPointEvent(moveX, moveY, this.brush, this.color, this.brushSize, true);
            this.drawCanvas(currentPoint);
        }
    }

    private onDrawEnd() {
        this.isDown = false;
        this.lastPoint = null;
    }

    private static distanceBetween(previousPoint: CanvasPointEvent, point: CanvasPointEvent): number {
        return Math.sqrt(Math.pow(point.x - previousPoint.x, 2) + Math.pow(point.y - previousPoint.y, 2));
    }

    private static angleBetween(previousPoint: CanvasPointEvent, point: CanvasPointEvent): number {
        return Math.atan2(point.x - previousPoint.x, point.y - previousPoint.y);
    }

    private static hexToRgb(colorHex: string): RGBColor {
        let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(colorHex);
        return result ? {
            red: parseInt(result[1], 16),
            green: parseInt(result[2], 16),
            blue: parseInt(result[3], 16)
        } : null;
    }

    changeColor(newColor: string) {
        this.color = newColor;
    }

    changeBrush(newBrush: string) {
        this.brush = Whiteboard.getBrushFrom(newBrush);
    }

    getBrush(): Brush {
        return this.brush;
    }

    getBrushName(): string {
        switch (this.brush) {
            case Brush.Chalk:
                return "chalk";
            case Brush.Paintbrush:
                return "paintbrush";
            case Brush.Eraser:
                return "eraser";
            default:
                return "pencil";
        }
    }

    // TODO tlu : move into a separate class
    private static getBrushFrom(newBrush: string): Brush {
        switch (newBrush) {
            case "chalk":
                return Brush.Chalk;
            case "paintbrush":
                return Brush.Paintbrush;
            case "eraser":
                return Brush.Eraser;
            default:
                return Brush.Pencil;
        }
    }

    getColor(): string {
        return this.color;
    }

    getBrushSize(): BrushSize {
        return this.brushSize;
    }

    setBrushSize(brushSize: BrushSize) {
        this.brushSize = brushSize;
        this.canvasContext.lineWidth = this.brushSize.size;
    }

    saveToBlob(cb: (drawingSaved: Blob) => void) {
        this.canvas.toBlob((blob) => {
            cb(blob);
        });
    }
}

class CanvasPointEvent {
    constructor(public x: number,
                public y: number,
                public brush: Brush,
                public color: string,
                public size: BrushSize,
                public dragging: boolean) {
    }
}

interface RGBColor {
    red: number,
    green: number,
    blue: number
}

export enum Brush {
    Pencil, Chalk, Paintbrush, Eraser
}

const BASE_LINE_WIDTH = 15;

export class BrushSize {
    public static Small = new BrushSize("0.5x", BASE_LINE_WIDTH / 2);
    public static Medium = new BrushSize("1x", BASE_LINE_WIDTH);
    public static Large = new BrushSize("2.5x", 2.5 * BASE_LINE_WIDTH);
    public static XLarge = new BrushSize("4x", 4 * BASE_LINE_WIDTH);

    private constructor(public label: string, public size: number) {
    }
}


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * Code Igniter Array Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		Rick Ellis
 * @link		http://www.codeigniter.com/user_guide/helpers/array_helper.html
 */

// ------------------------------------------------------------------------

/**
 * Element
 *
 * Lets you determine whether an array index is set and whether it has a value.
 * If the element is empty it returns FALSE (or whater you specify as the default value.)
 *
 * @access	public
 * @param	string
 * @param	array
 * @param	mixed
 * @return	mixed	depends on what the array contains
 */
function element($item, $array, $default = FALSE)
{
	if ( ! isset($array[$item]) OR $array[$item] == "")
	{
		return $default;
	}

	return $array[$item];
}

// ------------------------------------------------------------------------

/**
 * Random Element - Takes an array as input and returns a random element
 *
 * @access	public
 * @param	array
 * @return	mixed	depends on what the array contains
 */
function random_element($array)
{
	if ( ! is_array($array))
	{
		return $array;
	}
	return $array[array_rand($array)];
}

?>

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview Definition of the goog.ui.tree.TreeNode class.
 *
 *
 * This is a based on the webfx tree control. See file comment in
 * treecontrol.js.
 */

goog.provide('goog.ui.tree.TreeNode');

goog.forwardDeclare('goog.ui.tree.TreeControl');
goog.require('goog.ui.tree.BaseNode');
goog.requireType('goog.dom.DomHelper');
goog.requireType('goog.html.SafeHtml');  // circular

/**
 * A single node in the tree.
 * @param {string|!goog.html.SafeHtml} content The content of the node label.
 *     Strings are treated as plain-text and will be HTML escaped.
 * @param {Object=} opt_config The configuration for the tree. See
 *    goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config
 *    will be used.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
 * @constructor
 * @extends {goog.ui.tree.BaseNode}
 */
goog.ui.tree.TreeNode = function(content, opt_config, opt_domHelper) {
  'use strict';
  goog.ui.tree.BaseNode.call(this, content, opt_config, opt_domHelper);
};
goog.inherits(goog.ui.tree.TreeNode, goog.ui.tree.BaseNode);

/**
 * Returns the tree.
 * @return {?goog.ui.tree.TreeControl} The tree.
 * @override
 */
goog.ui.tree.TreeNode.prototype.getTree = function() {
  'use strict';
  if (this.tree) {
    return this.tree;
  }
  const parent = this.getParent();
  if (parent) {
    const tree = parent.getTree();
    if (tree) {
      this.setTreeInternal(tree);
      return tree;
    }
  }
  return null;
};

/**
 * Returns the source for the icon.
 * @return {string} Src for the icon.
 * @override
 */
goog.ui.tree.TreeNode.prototype.getCalculatedIconClass = function() {
  'use strict';
  const expanded = this.getExpanded();
  const expandedIconClass = this.getExpandedIconClass();
  if (expanded && expandedIconClass) {
    return expandedIconClass;
  }
  const iconClass = this.getIconClass();
  if (!expanded && iconClass) {
    return iconClass;
  }

  // fall back on default icons
  const config = this.getConfig();
  if (this.hasChildren()) {
    if (expanded && config.cssExpandedFolderIcon) {
      return config.cssTreeIcon + ' ' + config.cssExpandedFolderIcon;
    } else if (!expanded && config.cssCollapsedFolderIcon) {
      return config.cssTreeIcon + ' ' + config.cssCollapsedFolderIcon;
    }
  } else {
    if (config.cssFileIcon) {
      return config.cssTreeIcon + ' ' + config.cssFileIcon;
    }
  }
  return '';
};


text:
import clone from 'clone';
import equal from 'deep-equal';
import extend from 'extend';
import Delta, { AttributeMap } from 'quill-delta';
import { EmbedBlot, Scope, TextBlot } from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';

const debug = logger('quill:keyboard');

const SHORTKEY = /Mac/i.test(navigator.platform) ? 'metaKey' : 'ctrlKey';

class Keyboard extends Module {
  static match(evt, binding) {
    if (
      ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].some(key => {
        return !!binding[key] !== evt[key] && binding[key] !== null;
      })
    ) {
      return false;
    }
    return binding.key === evt.key || binding.key === evt.which;
  }

  constructor(quill, options) {
    super(quill, options);
    this.bindings = {};
    Object.keys(this.options.bindings).forEach(name => {
      if (this.options.bindings[name]) {
        this.addBinding(this.options.bindings[name]);
      }
    });
    this.addBinding({ key: 'Enter', shiftKey: null }, this.handleEnter);
    this.addBinding(
      { key: 'Enter', metaKey: null, ctrlKey: null, altKey: null },
      () => {},
    );
    if (/Firefox/i.test(navigator.userAgent)) {
      // Need to handle delete and backspace for Firefox in the general case #1171
      this.addBinding(
        { key: 'Backspace' },
        { collapsed: true },
        this.handleBackspace,
      );
      this.addBinding(
        { key: 'Delete' },
        { collapsed: true },
        this.handleDelete,
      );
    } else {
      this.addBinding(
        { key: 'Backspace' },
        { collapsed: true, prefix: /^.?$/ },
        this.handleBackspace,
      );
      this.addBinding(
        { key: 'Delete' },
        { collapsed: true, suffix: /^.?$/ },
        this.handleDelete,
      );
    }
    this.addBinding(
      { key: 'Backspace' },
      { collapsed: false },
      this.handleDeleteRange,
    );
    this.addBinding(
      { key: 'Delete' },
      { collapsed: false },
      this.handleDeleteRange,
    );
    this.addBinding(
      {
        key: 'Backspace',
        altKey: null,
        ctrlKey: null,
        metaKey: null,
        shiftKey: null,
      },
      { collapsed: true, offset: 0 },
      this.handleBackspace,
    );
    this.listen();
  }

  addBinding(keyBinding, context = {}, handler = {}) {
    const binding = normalize(keyBinding);
    if (binding == null) {
      debug.warn('Attempted to add invalid keyboard binding', binding);
      return;
    }
    if (typeof context === 'function') {
      context = { handler: context };
    }
    if (typeof handler === 'function') {
      handler = { handler };
    }
    const keys = Array.isArray(binding.key) ? binding.key : [binding.key];
    keys.forEach(key => {
      const singleBinding = extend({}, binding, { key }, context, handler);
      this.bindings[singleBinding.key] = this.bindings[singleBinding.key] || [];
      this.bindings[singleBinding.key].push(singleBinding);
    });
  }

  listen() {
    this.quill.root.addEventListener('keydown', evt => {
      if (evt.defaultPrevented) return;
      const bindings = (this.bindings[evt.key] || []).concat(
        this.bindings[evt.which] || [],
      );
      const matches = bindings.filter(binding => Keyboard.match(evt, binding));
      if (matches.length === 0) return;
      const range = this.quill.getSelection();
      if (range == null || !this.quill.hasFocus()) return;
      const [line, offset] = this.quill.getLine(range.index);
      const [leafStart, offsetStart] = this.quill.getLeaf(range.index);
      const [leafEnd, offsetEnd] =
        range.length === 0
          ? [leafStart, offsetStart]
          : this.quill.getLeaf(range.index + range.length);
      const prefixText =
        leafStart instanceof TextBlot
          ? leafStart.value().slice(0, offsetStart)
          : '';
      const suffixText =
        leafEnd instanceof TextBlot ? leafEnd.value().slice(offsetEnd) : '';
      const curContext = {
        collapsed: range.length === 0,
        empty: range.length === 0 && line.length() <= 1,
        format: this.quill.getFormat(range),
        line,
        offset,
        prefix: prefixText,
        suffix: suffixText,
        event: evt,
      };
      const prevented = matches.some(binding => {
        if (
          binding.collapsed != null &&
          binding.collapsed !== curContext.collapsed
        ) {
          return false;
        }
        if (binding.empty != null && binding.empty !== curContext.empty) {
          return false;
        }
        if (binding.offset != null && binding.offset !== curContext.offset) {
          return false;
        }
        if (Array.isArray(binding.format)) {
          // any format is present
          if (binding.format.every(name => curContext.format[name] == null)) {
            return false;
          }
        } else if (typeof binding.format === 'object') {
          // all formats must match
          if (
            !Object.keys(binding.format).every(name => {
              if (binding.format[name] === true)
                return curContext.format[name] != null;
              if (binding.format[name] === false)
                return curContext.format[name] == null;
              return equal(binding.format[name], curContext.format[name]);
            })
          ) {
            return false;
          }
        }
        if (binding.prefix != null && !binding.prefix.test(curContext.prefix)) {
          return false;
        }
        if (binding.suffix != null && !binding.suffix.test(curContext.suffix)) {
          return false;
        }
        return binding.handler.call(this, range, curContext, binding) !== true;
      });
      if (prevented) {
        evt.preventDefault();
      }
    });
  }

  handleBackspace(range, context) {
    // Check for astral symbols
    const length = /[\uD800-\uDBFF][\uDC00-\uDFFF]$/.test(context.prefix)
      ? 2
      : 1;
    if (range.index === 0 || this.quill.getLength() <= 1) return;
    let formats = {};
    const [line] = this.quill.getLine(range.index);
    let delta = new Delta().retain(range.index - length).delete(length);
    if (context.offset === 0) {
      // Always deleting newline here, length always 1
      const [prev] = this.quill.getLine(range.index - 1);
      if (prev) {
        const curFormats = line.formats();
        const prevFormats = this.quill.getFormat(range.index - 1, 1);
        formats = AttributeMap.diff(curFormats, prevFormats) || {};
        if (Object.keys(formats).length > 0) {
          // line.length() - 1 targets \n in line, another -1 for newline being deleted
          const formatDelta = new Delta()
            .retain(range.index + line.length() - 2)
            .retain(1, formats);
          delta = delta.compose(formatDelta);
        }
      }
    }
    this.quill.updateContents(delta, Quill.sources.USER);
    this.quill.focus();
  }

  handleDelete(range, context) {
    // Check for astral symbols
    const length = /^[\uD800-\uDBFF][\uDC00-\uDFFF]/.test(context.suffix)
      ? 2
      : 1;
    if (range.index >= this.quill.getLength() - length) return;
    let formats = {};
    const [line] = this.quill.getLine(range.index);
    let delta = new Delta().retain(range.index).delete(length);
    if (context.offset >= line.length() - 1) {
      const [next] = this.quill.getLine(range.index + 1);
      if (next) {
        const curFormats = line.formats();
        const nextFormats = this.quill.getFormat(range.index, 1);
        formats = AttributeMap.diff(curFormats, nextFormats) || {};
        if (Object.keys(formats).length > 0) {
          delta = delta.retain(next.length() - 1).retain(1, formats);
        }
      }
    }
    this.quill.updateContents(delta, Quill.sources.USER);
    this.quill.focus();
  }

  handleDeleteRange(range) {
    const lines = this.quill.getLines(range);
    let formats = {};
    if (lines.length > 1) {
      const firstFormats = lines[0].formats();
      const lastFormats = lines[lines.length - 1].formats();
      formats = AttributeMap.diff(lastFormats, firstFormats) || {};
    }
    this.quill.deleteText(range, Quill.sources.USER);
    if (Object.keys(formats).length > 0) {
      this.quill.formatLine(range.index, 1, formats, Quill.sources.USER);
    }
    this.quill.setSelection(range.index, Quill.sources.SILENT);
    this.quill.focus();
  }

  handleEnter(range, context) {
    const lineFormats = Object.keys(context.format).reduce(
      (formats, format) => {
        if (
          this.quill.scroll.query(format, Scope.BLOCK) &&
          !Array.isArray(context.format[format])
        ) {
          formats[format] = context.format[format];
        }
        return formats;
      },
      {},
    );
    const delta = new Delta()
      .retain(range.index)
      .delete(range.length)
      .insert('\n', lineFormats);
    this.quill.updateContents(delta, Quill.sources.USER);
    this.quill.setSelection(range.index + 1, Quill.sources.SILENT);
    this.quill.focus();

    Object.keys(context.format).forEach(name => {
      if (lineFormats[name] != null) return;
      if (Array.isArray(context.format[name])) return;
      if (name === 'code' || name === 'link') return;
      this.quill.format(name, context.format[name], Quill.sources.USER);
    });
  }
}

Keyboard.DEFAULTS = {
  bindings: {
    bold: makeFormatHandler('bold'),
    italic: makeFormatHandler('italic'),
    underline: makeFormatHandler('underline'),
    indent: {
      // highlight tab or tab at beginning of list, indent or blockquote
      key: 'Tab',
      format: ['blockquote', 'indent', 'list'],
      handler(range, context) {
        if (context.collapsed && context.offset !== 0) return true;
        this.quill.format('indent', '+1', Quill.sources.USER);
        return false;
      },
    },
    outdent: {
      key: 'Tab',
      shiftKey: true,
      format: ['blockquote', 'indent', 'list'],
      // highlight tab or tab at beginning of list, indent or blockquote
      handler(range, context) {
        if (context.collapsed && context.offset !== 0) return true;
        this.quill.format('indent', '-1', Quill.sources.USER);
        return false;
      },
    },
    'outdent backspace': {
      key: 'Backspace',
      collapsed: true,
      shiftKey: null,
      metaKey: null,
      ctrlKey: null,
      altKey: null,
      format: ['indent', 'list'],
      offset: 0,
      handler(range, context) {
        if (context.format.indent != null) {
          this.quill.format('indent', '-1', Quill.sources.USER);
        } else if (context.format.list != null) {
          this.quill.format('list', false, Quill.sources.USER);
        }
      },
    },
    'indent code-block': makeCodeBlockHandler(true),
    'outdent code-block': makeCodeBlockHandler(false),
    'remove tab': {
      key: 'Tab',
      shiftKey: true,
      collapsed: true,
      prefix: /\t$/,
      handler(range) {
        this.quill.deleteText(range.index - 1, 1, Quill.sources.USER);
      },
    },
    tab: {
      key: 'Tab',
      handler(range, context) {
        if (context.format.table) return true;
        this.quill.history.cutoff();
        const delta = new Delta()
          .retain(range.index)
          .delete(range.length)
          .insert('\t');
        this.quill.updateContents(delta, Quill.sources.USER);
        this.quill.history.cutoff();
        this.quill.setSelection(range.index + 1, Quill.sources.SILENT);
        return false;
      },
    },
    'blockquote empty enter': {
      key: 'Enter',
      collapsed: true,
      format: ['blockquote'],
      empty: true,
      handler() {
        this.quill.format('blockquote', false, Quill.sources.USER);
      },
    },
    'list empty enter': {
      key: 'Enter',
      collapsed: true,
      format: ['list'],
      empty: true,
      handler(range, context) {
        const formats = { list: false };
        if (context.format.indent) {
          formats.indent = false;
        }
        this.quill.formatLine(
          range.index,
          range.length,
          formats,
          Quill.sources.USER,
        );
      },
    },
    'checklist enter': {
      key: 'Enter',
      collapsed: true,
      format: { list: 'checked' },
      handler(range) {
        const [line, offset] = this.quill.getLine(range.index);
        const formats = extend({}, line.formats(), { list: 'checked' });
        const delta = new Delta()
          .retain(range.index)
          .insert('\n', formats)
          .retain(line.length() - offset - 1)
          .retain(1, { list: 'unchecked' });
        this.quill.updateContents(delta, Quill.sources.USER);
        this.quill.setSelection(range.index + 1, Quill.sources.SILENT);
        this.quill.scrollIntoView();
      },
    },
    'header enter': {
      key: 'Enter',
      collapsed: true,
      format: ['header'],
      suffix: /^$/,
      handler(range, context) {
        const [line, offset] = this.quill.getLine(range.index);
        const delta = new Delta()
          .retain(range.index)
          .insert('\n', context.format)
          .retain(line.length() - offset - 1)
          .retain(1, { header: null });
        this.quill.updateContents(delta, Quill.sources.USER);
        this.quill.setSelection(range.index + 1, Quill.sources.SILENT);
        this.quill.scrollIntoView();
      },
    },
    'table backspace': {
      key: 'Backspace',
      format: ['table'],
      collapsed: true,
      offset: 0,
      handler() {},
    },
    'table delete': {
      key: 'Delete',
      format: ['table'],
      collapsed: true,
      suffix: /^$/,
      handler() {},
    },
    'table enter': {
      key: 'Enter',
      shiftKey: null,
      format: ['table'],
      handler(range) {
        const module = this.quill.getModule('table');
        if (module) {
          const [table, row, cell, offset] = module.getTable(range);
          const shift = tableSide(table, row, cell, offset);
          if (shift == null) return;
          let index = table.offset();
          if (shift < 0) {
            const delta = new Delta().retain(index).insert('\n');
            this.quill.updateContents(delta, Quill.sources.USER);
            this.quill.setSelection(
              range.index + 1,
              range.length,
              Quill.sources.SILENT,
            );
          } else if (shift > 0) {
            index += table.length();
            const delta = new Delta().retain(index).insert('\n');
            this.quill.updateContents(delta, Quill.sources.USER);
            this.quill.setSelection(index, Quill.sources.USER);
          }
        }
      },
    },
    'table tab': {
      key: 'Tab',
      shiftKey: null,
      format: ['table'],
      handler(range, context) {
        const { event, line: cell } = context;
        const offset = cell.offset(this.quill.scroll);
        if (event.shiftKey) {
          this.quill.setSelection(offset - 1, Quill.sources.USER);
        } else {
          this.quill.setSelection(offset + cell.length(), Quill.sources.USER);
        }
      },
    },
    'list autofill': {
      key: ' ',
      shiftKey: null,
      collapsed: true,
      format: {
        list: false,
        'code-block': false,
        blockquote: false,
        header: false,
        table: false,
      },
      prefix: /^\s*?(\d+\.|-|\*|\[ ?\]|\[x\])$/,
      handler(range, context) {
        if (this.quill.scroll.query('list') == null) return true;
        const { length } = context.prefix;
        const [line, offset] = this.quill.getLine(range.index);
        if (offset > length) return true;
        let value;
        switch (context.prefix.trim()) {
          case '[]':
          case '[ ]':
            value = 'unchecked';
            break;
          case '[x]':
            value = 'checked';
            break;
          case '-':
          case '*':
            value = 'bullet';
            break;
          default:
            value = 'ordered';
        }
        this.quill.insertText(range.index, ' ', Quill.sources.USER);
        this.quill.history.cutoff();
        const delta = new Delta()
          .retain(range.index - offset)
          .delete(length + 1)
          .retain(line.length() - 2 - offset)
          .retain(1, { list: value });
        this.quill.updateContents(delta, Quill.sources.USER);
        this.quill.history.cutoff();
        this.quill.setSelection(range.index - length, Quill.sources.SILENT);
        return false;
      },
    },
    'code exit': {
      key: 'Enter',
      collapsed: true,
      format: ['code-block'],
      prefix: /^$/,
      suffix: /^\s*$/,
      handler(range) {
        const [line, offset] = this.quill.getLine(range.index);
        let numLines = 2;
        let cur = line;
        while (
          cur != null &&
          cur.length() <= 1 &&
          cur.formats()['code-block']
        ) {
          cur = cur.prev;
          numLines -= 1;
          // Requisite prev lines are empty
          if (numLines <= 0) {
            const delta = new Delta()
              .retain(range.index + line.length() - offset - 2)
              .retain(1, { 'code-block': null })
              .delete(1);
            this.quill.updateContents(delta, Quill.sources.USER);
            this.quill.setSelection(range.index - 1, Quill.sources.SILENT);
            return false;
          }
        }
        return true;
      },
    },
    'embed left': makeEmbedArrowHandler('ArrowLeft', false),
    'embed left shift': makeEmbedArrowHandler('ArrowLeft', true),
    'embed right': makeEmbedArrowHandler('ArrowRight', false),
    'embed right shift': makeEmbedArrowHandler('ArrowRight', true),
    'table down': makeTableArrowHandler(false),
    'table up': makeTableArrowHandler(true),
  },
};

function makeCodeBlockHandler(indent) {
  return {
    key: 'Tab',
    shiftKey: !indent,
    format: { 'code-block': true },
    handler(range) {
      const CodeBlock = this.quill.scroll.query('code-block');
      const lines =
        range.length === 0
          ? this.quill.getLines(range.index, 1)
          : this.quill.getLines(range);
      let { index, length } = range;
      lines.forEach((line, i) => {
        if (indent) {
          line.insertAt(0, CodeBlock.TAB);
          if (i === 0) {
            index += CodeBlock.TAB.length;
          } else {
            length += CodeBlock.TAB.length;
          }
        } else if (line.domNode.textContent.startsWith(CodeBlock.TAB)) {
          line.deleteAt(0, CodeBlock.TAB.length);
          if (i === 0) {
            index -= CodeBlock.TAB.length;
          } else {
            length -= CodeBlock.TAB.length;
          }
        }
      });
      this.quill.update(Quill.sources.USER);
      this.quill.setSelection(index, length, Quill.sources.SILENT);
    },
  };
}

function makeEmbedArrowHandler(key, shiftKey) {
  const where = key === 'ArrowLeft' ? 'prefix' : 'suffix';
  return {
    key,
    shiftKey,
    altKey: null,
    [where]: /^$/,
    handler(range) {
      let { index } = range;
      if (key === 'ArrowRight') {
        index += range.length + 1;
      }
      const [leaf] = this.quill.getLeaf(index);
      if (!(leaf instanceof EmbedBlot)) return true;
      if (key === 'ArrowLeft') {
        if (shiftKey) {
          this.quill.setSelection(
            range.index - 1,
            range.length + 1,
            Quill.sources.USER,
          );
        } else {
          this.quill.setSelection(range.index - 1, Quill.sources.USER);
        }
      } else if (shiftKey) {
        this.quill.setSelection(
          range.index,
          range.length + 1,
          Quill.sources.USER,
        );
      } else {
        this.quill.setSelection(
          range.index + range.length + 1,
          Quill.sources.USER,
        );
      }
      return false;
    },
  };
}

function makeFormatHandler(format) {
  return {
    key: format[0],
    shortKey: true,
    handler(range, context) {
      this.quill.format(format, !context.format[format], Quill.sources.USER);
    },
  };
}

function makeTableArrowHandler(up) {
  return {
    key: up ? 'ArrowUp' : 'ArrowDown',
    collapsed: true,
    format: ['table'],
    handler(range, context) {
      // TODO move to table module
      const key = up ? 'prev' : 'next';
      const cell = context.line;
      const targetRow = cell.parent[key];
      if (targetRow != null) {
        if (targetRow.statics.blotName === 'table-row') {
          let targetCell = targetRow.children.head;
          let cur = cell;
          while (cur.prev != null) {
            cur = cur.prev;
            targetCell = targetCell.next;
          }
          const index =
            targetCell.offset(this.quill.scroll) +
            Math.min(context.offset, targetCell.length() - 1);
          this.quill.setSelection(index, 0, Quill.sources.USER);
        }
      } else {
        const targetLine = cell.table()[key];
        if (targetLine != null) {
          if (up) {
            this.quill.setSelection(
              targetLine.offset(this.quill.scroll) + targetLine.length() - 1,
              0,
              Quill.sources.USER,
            );
          } else {
            this.quill.setSelection(
              targetLine.offset(this.quill.scroll),
              0,
              Quill.sources.USER,
            );
          }
        }
      }
      return false;
    },
  };
}

function normalize(binding) {
  if (typeof binding === 'string' || typeof binding === 'number') {
    binding = { key: binding };
  } else if (typeof binding === 'object') {
    binding = clone(binding, false);
  } else {
    return null;
  }
  if (binding.shortKey) {
    binding[SHORTKEY] = binding.shortKey;
    delete binding.shortKey;
  }
  return binding;
}

function tableSide(table, row, cell, offset) {
  if (row.prev == null && row.next == null) {
    if (cell.prev == null && cell.next == null) {
      return offset === 0 ? -1 : 1;
    }
    return cell.prev == null ? -1 : 1;
  }
  if (row.prev == null) {
    return -1;
  }
  if (row.next == null) {
    return 1;
  }
  return null;
}

export { Keyboard as default, SHORTKEY, normalize };


text:
module Google
  class Translator < Google::Translate
  end
end


text:
<!DOCTYPE html>
<link rel="help" href="https://drafts.csswg.org/css-grid-1/#algo-overview">
<meta name="assert" content="An element with an aspect-ratio resolves its percentage against the definite row.">
<link rel="match" href="../../reference/ref-filled-green-100px-square-only.html">

Test passes if there is a filled green square.


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _CONF_VIRTUAL_MEM_H_
#define _CONF_VIRTUAL_MEM_H_

//! Size of Virtual Memory on internal RAM (unit 512B)
#define VMEM_NB_SECTOR   32 // 16KB

#endif // _CONF_VIRTUAL_MEM_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septoria tenella var. europaea Gonz. Frag.

### Remarks
null


text:
module Crypt
  module ECB
    def padded_last_block(last_block)
      block = last_block || ''
      buffer = block.split('')
      remainingMessageBytes = buffer.length
      remainingMessageBytes.upto(block_size()-1) { buffer << 0.chr }
      return buffer.join('')
    end

    def unpadded_last_block(last_block)
      block = last_block || ''
      chars = block.split('')
      buffer = []
      chars.each do |c|
        if c != 0
          buffer << c
        else
          break
        end
      end
      return buffer.join('')
    end

    def encrypt_stream(plainStream, cryptStream)
      while ((block = plainStream.read(block_size())) && (block.length == block_size()))
        cryptStream.write(encrypt_block(block))
      end
      cryptStream.write(encrypt_block(padded_last_block(block)))
    end

    def decrypt_stream(cryptStream, plainStream)
      while (block = cryptStream.read(block_size()))
        plainText = decrypt_block(block)
        plainStream.write(plainText) unless cryptStream.eof?
      end
      plainStream.write(unpadded_last_block(plainText))
    end

    def carefully_open_file(filename, mode)
      begin
        aFile = File.new(filename, mode)
      rescue
        puts "Sorry. There was a problem opening the file <#{filename}>."
        aFile.close() unless aFile.nil?
        raise
      end
      return(aFile)
    end

    def encrypt_file(plainFilename, cryptFilename)
      plainFile = carefully_open_file(plainFilename, 'rb')
      cryptFile = carefully_open_file(cryptFilename, 'wb+')
      encrypt_stream(plainFile, cryptFile)
      plainFile.close unless plainFile.closed?
      cryptFile.close unless cryptFile.closed?
    end

    def decrypt_file(cryptFilename, plainFilename)
      cryptFile = carefully_open_file(cryptFilename, 'rb')
      plainFile = carefully_open_file(plainFilename, 'wb+')
      decrypt_stream(cryptFile, plainFile)
      cryptFile.close unless cryptFile.closed?
      plainFile.close unless plainFile.closed?
    end

    def encrypt_string(plainText)
      plainStream = StringIO.new(plainText)
      cryptStream = StringIO.new('')
      encrypt_stream(plainStream, cryptStream)
      cryptText = cryptStream.string
      return(cryptText)
    end

    def decrypt_string(cryptText)
      cryptStream = StringIO.new(cryptText)
      plainStream = StringIO.new('')
      decrypt_stream(cryptStream, plainStream)
      plainText = plainStream.string
      return(plainText)
    end
  end
end

module Crypt
  class Blowfish
    include Crypt::ECB
  end
end


text:
{% if page.category != 'pt-br' %}

Please enable JavaScript to view the comments powered by Disqus.
{% endif %}


text:
import { Injectable } from '@angular/core';
import { DetailedItem } from '../detailed-item';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DetailedSelectedService {

  _items = new BehaviorSubject<DetailedItem[]>([]);
  items  = this._items.asObservable();

  get (): DetailedItem[] {
    return this._items.getValue();
  }

  updateSelected (items: DetailedItem[]) {
    this._items.next(items);
  }

  structureSelectedItems (items: DetailedItem[]) {
    const structuredSelectedMap  = {};
    const structuredSelectedKeys = [];
    items.forEach((item) => {
      const lastInPath = item.path[item.path.length - 1];
      let key;
      if (item.name === lastInPath) {
        key = item.path.slice(0, -1)
                  .join(' > ');
      } else {
        key = item.path.join(' > ');
      }

      if (structuredSelectedKeys.indexOf(key) === -1) {
        structuredSelectedKeys.push(key);
      }

      structuredSelectedMap[key] = structuredSelectedMap[key] || [];

      structuredSelectedMap[key].push(item);
    });

    return {
      keys: structuredSelectedKeys,
      map:  structuredSelectedMap
    };
  }
}


text:
package com.venky.swf.db.annotations.column;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface UNIQUE_KEY {
	public String value() default "K1" ;
	public boolean allowMultipleRecordsWithNull() default true;
	public boolean exportable() default true;
}


text:
package gov.va.cpe.clio;

import gov.va.cpe.vpr.pom.IGenericPOMObjectDAO;
import gov.va.cpe.vpr.queryeng.query.QueryDef;
import gov.va.cpe.vpr.sync.vista.IVistaVprObjectDao;
import gov.va.hmp.jsonc.JsonCCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static gov.va.hmp.web.servlet.view.ModelAndViewFactory.contentNegotiatingModelAndView;

@Controller
@RequestMapping("/clio/**")
public class ClioController {
    @Autowired
    IGenericPOMObjectDAO jdsDao;

    @Autowired
    IVistaVprObjectDao vprObjectDao;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView categories(
            @RequestParam(required = false) String termType,
            HttpServletRequest request) throws IOException {
        QueryDef qry = new QueryDef("clioterminology");
        qry.setForPatientObject(false);
        if (termType != null && !termType.equals("")) {
            qry.where("termType").is(termType);
        }
        return contentNegotiatingModelAndView(JsonCCollection.create(request, jdsDao.findAllByQuery(ClioTerminology.class, qry, null)));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="achievements_all">

    </string-array>

    <string-array name="achievements_online">

    </string-array>

    <string-array name="achievements_offline">

    </string-array>

    <string-array name="leaderboards_all">

    </string-array>

    <string-array name="leaderboards_online">

    </string-array>

    <string-array name="leaderboards_offline">

    </string-array>

</resources>


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# Acceleration

Содержит данные полученные от акселерометра на определенный момент времени.

## Параметры

*   **x**: величина ускорение по оси x. (в м/с ^ 2) *(Число)*
*   **y**: величина ускорение по оси y. (в м/с ^ 2) *(Число)*
*   **z**: величина ускорение по оси z. (в м/с ^ 2) *(Число)*
*   **timestamp**: временая метка в миллисекундах. *(DOMTimeStamp)*

## Описание

Объект `Acceleration` заполняется и возвращает любой из методов `Acceleration` API. Значения величин ускорение включают эффект гравитации (9,81 м/с ^ 2), так что когда устройство находится горизонтально экраном вверх, возвращаемые значения *x*, *y*, и *z* должны быть ``, `` и `9,81`.

## Поддерживаемые платформы

*   Android
*   BlackBerry WebWorks (OS 5.0 или выше)
*   iOS
*   Tizen
*   Windows Phone 7 и 8
*   Windows 8

## Краткий пример

    function onSuccess(acceleration) {
        alert('Acceleration X: ' + acceleration.x + '\n' +
              'Acceleration Y: ' + acceleration.y + '\n' +
              'Acceleration Z: ' + acceleration.z + '\n' +
              'Timestamp: '      + acceleration.timestamp + '\n');
    };

    function onError() {
        alert('onError!');
    };

    navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);

## Развернутый пример

    <!DOCTYPE html>

        <title>Acceleration Example</title>

Example

getCurrentAcceleration


text:
<core-loading [hideUntil]="commentsLoaded">
    <div (click)="openComments()" *ngIf="commentsCount >= 0">
        {{ 'core.commentscount' | translate : {'$a': commentsCount} }}
    </div>
    <div *ngIf="commentsCount < 0">
        {{ 'core.commentsnotworking' | translate }}
    </div>
</core-loading>


text:
package com.deleidos.rtws.webapp.tenantapi.parse;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.deleidos.rtws.commons.model.dimension.CacheInitPolicy;
import com.deleidos.rtws.commons.model.dimension.DimensionColumn;
import com.deleidos.rtws.commons.model.dimension.DimensionColumnRole;
import com.deleidos.rtws.commons.model.dimension.DimensionTable;
import com.deleidos.rtws.commons.model.dimension.MissPolicy;

public class DimensionCacheParser {
	private static final String TABLE_CONFIG_ID_KEY = "tableConfigId";
	private static final String TABLE_SCHEMA_KEY = "tableSchema";
	private static final String TABLE_NAME_KEY = "tableName";
	private static final String SURROGATE_KEY_SEQ_NAME_KEY = "surrogateKeySeqName";
	private static final String MISS_POLICY_KEY = "missPolicy";
	private static final String CACHE_INIT_POLICY_KEY = "cacheInitPolicy";
	private static final String CACHE_MAX_RECORDS_KEY = "cacheMaxRecords";

	private static final String COLUMN_CONFIGS_KEY = "columnConfigs";
	private static final String COLUMN_CONFIG_ID_KEY = "columnConfigId";
	private static final String DB_COLUMN_NAME_KEY = "dbColumnName";
	private static final String DIMENSION_ROLE_KEY = "dimensionRole";
	private static final String CACHE_FIELD_KEY = "cacheField";
	private static final String CACHE_FIELD_NAME_KEY = "name";
	private static final String CACHE_FIELD_TYPE_KEY = "type";
	private static final String CACHE_FIELD_DEFAULT_VALUE_KEY = "defaultValue";
	private static final String CACHE_FIELD_FORMAT_MASK_KEY = "formatMask";

	public static DimensionTable parseCacheConfigJson(String cacheConfigJson) throws ParseException
	{
		DimensionTable result = null;

		JSONObject json = null;
		try
		{
			json = JSONObject.fromObject(cacheConfigJson);
		}
		catch(JSONException jsonException)
		{
			throw new ParseException("Invalid JSON Format", -1);
		}

		result = new DimensionTable();

		result.setId(parseOptLong(json, TABLE_CONFIG_ID_KEY));

		String schema = parseOptString(json, TABLE_SCHEMA_KEY);
		String tableName = parseOptString(json, TABLE_NAME_KEY);
		if(StringUtils.isNotBlank(schema) || StringUtils.isNotBlank(tableName))
		{
			String fqTableName = (schema == null ? "" : schema.trim());
			if(StringUtils.isNotBlank(tableName))
			{
				if(fqTableName.length() > 0)
				{
					fqTableName += ".";
				}
				fqTableName += tableName.trim();
			}
			result.setName(fqTableName);
		}

		result.setSurrogateKeySeqName(parseOptString(json, SURROGATE_KEY_SEQ_NAME_KEY));

		result.setMissPolicy(parseOptEnum(MissPolicy.class, json, MISS_POLICY_KEY));

		result.setDefaultCacheInitPolicy(parseOptEnum(CacheInitPolicy.class, json, CACHE_INIT_POLICY_KEY));

		result.setDefaultCacheMaxRecords(parseOptLong(json, CACHE_MAX_RECORDS_KEY));

		JSONArray columnConfigs = json.optJSONArray(COLUMN_CONFIGS_KEY);
		if(columnConfigs != null && columnConfigs.size() > 0)
		{
			List<DimensionColumn> tmpColumns = new ArrayList<DimensionColumn>();

			JSONObject currColumnConfig = null;
			for(int index=0; index < columnConfigs.size(); index++)
			{
				currColumnConfig = columnConfigs.optJSONObject(index);
				if(currColumnConfig != null)
				{
					tmpColumns.add(parseCacheColumnConfig(currColumnConfig));
				}
				else
				{
					throw new ParseException("Invalid Column Config Provided", -1);
				}
			}

			result.setColumns(tmpColumns);
		}

		return result;
	}

	public static DimensionColumn parseCacheColumnConfig(JSONObject cacheColumnConfig) throws ParseException
	{
		DimensionColumn result = null;

		if(cacheColumnConfig != null)
		{

			result = new DimensionColumn();

			result.setId(parseOptLong(cacheColumnConfig, COLUMN_CONFIG_ID_KEY));
			result.setName(parseOptString(cacheColumnConfig, DB_COLUMN_NAME_KEY));
			result.setRole(parseOptEnum(DimensionColumnRole.class, cacheColumnConfig, DIMENSION_ROLE_KEY));

			JSONObject fieldConfig = cacheColumnConfig.optJSONObject(CACHE_FIELD_KEY);
			if(fieldConfig != null)
			{
				result.setMappingFieldName(parseOptString(fieldConfig, CACHE_FIELD_NAME_KEY));
				result.setMappingFieldType(parseOptString(fieldConfig, CACHE_FIELD_TYPE_KEY));
				result.setDefaultValue(parseOptString(fieldConfig, CACHE_FIELD_DEFAULT_VALUE_KEY));
				result.setFormatMask(parseOptString(fieldConfig, CACHE_FIELD_FORMAT_MASK_KEY));
			}
		}

		return result;
	}

	/**
	 * Inspects the provided object for the specified key and returns null if not found or the
	 * value if it's available.  This is in contrast to the poor json-lib impl of
	 * optStr which returns 'null' ... making it impossible to detect the abscense of a value.
	 */
	private static String parseOptString(JSONObject jsonObject, String key) throws ParseException
	{
		String result = null;

		if(jsonObject.containsKey(key))
		{
			try
			{
				Object obj = jsonObject.get(key);
				if(obj != null && (obj instanceof String))
				{
					result = (String)obj;
				}
			}
			catch(JSONException e)
			{
				throw new ParseException("Invalid String for '" + key + "'", -1);
			}
		}

		return result;
	}

	/**
	 * Inspects the provided object for the specified key and returns null if not found or the
	 * value if it's available.  This is in contrast to the poor json-lib impl of
	 * optLong which returns -1 for the null case ... making it impossible to detect the abscense of a value.
	 */
	private static Long parseOptLong(JSONObject jsonObject, String key) throws ParseException
	{
		Long result = null;

		if(jsonObject.containsKey(key))
		{
			try
			{
				result = new Long(jsonObject.getLong(key));
			}
			catch(JSONException e)
			{
				throw new ParseException("Invalid Long for '" + key + "'", -1);
			}
		}

		return result;
	}

	private static <T extends Enum<T>> T parseOptEnum(Class<T> enumClazz, JSONObject jsonObject, String key) throws ParseException
	{
		T result = null;

		String enumText = parseOptString(jsonObject, key);
		if(enumText != null)
		{
			if(StringUtils.isNotBlank(enumText))
			{
				String toCompare = enumText.trim();

				T[] enumConstants = enumClazz.getEnumConstants();
				if(enumConstants != null)
				{
					for(int index=0; index < enumConstants.length; index++)
					{
						if(toCompare.equalsIgnoreCase(enumConstants[index].name()))
						{
							result = enumConstants[index];
							break;
						}
					}
				}
			}

			if(result == null)
			{
				throw new ParseException("Invalid Enum value specified for '" + enumClazz.getName() + "'", -1);
			}
		}

		return result;
	}
}


text:
export { default as DataAdapter } from './data_adapter';
export { default as ContainerDebugAdapter } from './container_debug_adapter';


text:
package com.polydes.datastruct.data.core;

public class HaxeObjectDefinition
{
	public String haxeClass;
	public HaxeField[] fields;
	public String haxereaderExpression;
	public boolean showLabels;

	public HaxeObjectDefinition(String haxeClass, HaxeField[] fields)
	{
		this.haxeClass = haxeClass;
		this.fields = fields;

		haxereaderExpression = null;
	}
}


text:
<?php
/**
 *
 * @access private
 *
 */
class DataConnection {

	public function readOnly(){
		$pdo = new PDO(NATURAL_PDO_DSN_READ, NATURAL_PDO_USER_READ, NATURAL_PDO_PASS_READ);
		$db = new NotORM($pdo);
		//debug mode on
		//Comment the following line to disable debugging
		//$db->debug = true;
		return $db;
	}

	public function readWrite(){
		$pdo = new PDO(NATURAL_PDO_DSN_WRITE, NATURAL_PDO_USER_WRITE, NATURAL_PDO_PASS_WRITE);
		$db = new NotORM($pdo);
		//debug mode on
		//Comment the following line to disable debugging
		//$db->debug - true;
		return $db;
	}

}
?>


text:
from .ninepatch import NinePatch
from .icons import add_fontawesome, FONT_NAME
from .pyglet_utils import my_path
from pyglet.resource import Loader

try:
	import json
except ImportError:
	try:
		import simplejson as json
	except ImportError:
		import sys
		print('\nsimplui requires json support. upgrade to python 2.6 or install the simplejson module.\n')
		sys.exit(0)

class BaseTheme(dict):
	def __init__(self, arg, image):
		for k, v in arg.items():
			if isinstance(v, dict):
				temp = {}

				for k2, v2 in v.items():
					if k2.startswith('image'):
						temp[k2] = NinePatch( image.get_region(*v2) )
					else:
						temp[k2] = v2

				self[k] = temp
			else:
				self[k] = v

		self['image'] = image

		if FONT_NAME == self.get('icon', None):
			add_fontawesome()

class Theme(BaseTheme):
	def __init__(self, path):
		loader = Loader(path=path)

		with open(path +'theme.json') as theme_file:
			info = json.loads( theme_file.read() )
			image = loader.texture( info['image'] )
			BaseTheme.__init__(self, info, image)

def pywidget_theme():
	return Theme(my_path("pywidget"))

def macos_theme():
	return Theme(my_path("macos"))


text:
package org.drools.metric.phreak;

import org.drools.core.common.ReteEvaluator;
import org.drools.core.common.TupleSets;
import org.drools.core.phreak.PhreakReactiveFromNode;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.LeftTupleSink;
import org.drools.core.reteoo.ReactiveFromNode;
import org.drools.core.reteoo.ReactiveFromNode.ReactiveFromMemory;
import org.drools.metric.util.MetricLogUtils;

public class PhreakReactiveFromNodeMetric extends PhreakReactiveFromNode {

    @Override
    public void doNode(ReactiveFromNode fromNode,
                       ReactiveFromMemory fm,
                       LeftTupleSink sink,
                       ReteEvaluator reteEvaluator,
                       TupleSets<LeftTuple> srcLeftTuples,
                       TupleSets<LeftTuple> trgLeftTuples,
                       TupleSets<LeftTuple> stagedLeftTuples) {

        try {
            MetricLogUtils.getInstance().startMetrics(fromNode);

            super.doNode(fromNode, fm, sink, reteEvaluator, srcLeftTuples, trgLeftTuples, stagedLeftTuples);

        } finally {
            MetricLogUtils.getInstance().logAndEndMetrics();
        }
    }
}


text:
package org.apache.druid.indexing.kinesis;

import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.name.Names;
import org.apache.druid.common.aws.AWSCredentialsConfig;
import org.apache.druid.guice.JsonConfigProvider;
import org.apache.druid.indexing.kinesis.supervisor.KinesisSupervisorSpec;
import org.apache.druid.indexing.kinesis.supervisor.KinesisSupervisorTuningConfig;
import org.apache.druid.initialization.DruidModule;

import java.util.List;

public class KinesisIndexingServiceModule implements DruidModule
{
  public static final String AWS_SCOPE = "kinesis";
  static final String PROPERTY_BASE = "druid.kinesis";

  @Override
  public List<? extends Module> getJacksonModules()
  {
    return ImmutableList.of(
        new SimpleModule(getClass().getSimpleName())
            .registerSubtypes(
                new NamedType(KinesisIndexTask.class, "index_kinesis"),
                new NamedType(KinesisDataSourceMetadata.class, "kinesis"),
                new NamedType(KinesisIndexTaskIOConfig.class, "kinesis"),
                new NamedType(KinesisSupervisorTuningConfig.class, "kinesis"),
                new NamedType(KinesisSupervisorSpec.class, "kinesis"),
                new NamedType(KinesisSamplerSpec.class, "kinesis")
            )
    );
  }

  @Override
  public void configure(Binder binder)
  {
    JsonConfigProvider.bind(binder, PROPERTY_BASE, AWSCredentialsConfig.class, Names.named(AWS_SCOPE));
  }
}


text:
mqtt_publish::mqtt_publish(const fixed_header& fh, shan::util::streambuf_ptr sb_ptr)
: fixed_header(fh) {
	// flags
	_dup = ((_flags & MASK_DUP) != 0);
	_qos = ((_flags & MASK_QOS) >> 1);
	_retain = ((_flags & MASK_RETAIN) != 0);
	if ((_qos == 0) && _dup)
		throw mqtt_error("malformed packet received. (publish packet with qos = 0 and dup = 1)");
	if (_qos == QOS_INVALID)
		throw mqtt_error("malformed packet received. (publish packet with qos = 3)");

	std::size_t variable_header_len = 0;

	// topic name
	_topic_name = decode_string(sb_ptr);
	if (_topic_name.empty())
		throw mqtt_error("malformed packet received. (empty topic name)");

	if (_topic_name[0] == '$')
		throw mqtt_error("malformed packet received. (clients can not publish to topics starting with $)");

	for (auto ch : _topic_name) {
		if ((ch == '#') || (ch == '+')) // is_wildcard(ch))
			throw mqtt_error("malformed packet received. (the topic of the PUBLISH has a wildcard.)");
	}
	variable_header_len += (_topic_name.length() + 2);

	// packet id
	if ((_qos == QOS_AT_LEAST_ONCE) || (_qos == QOS_EXACTLY_ONCE)) {
		_packet_id = sb_ptr->read_uint16();
		variable_header_len += 2;
	}

	// payload
	std::size_t payload_len = _remaining_length - variable_header_len;
	if (sb_ptr->in_size() < payload_len)
		throw mqtt_error("malformed packet received. (not enough data - PUBLISH payload.)");
	_payload.resize(payload_len);
	sb_ptr->read(&_payload[0], payload_len);
}

mqtt_publish::mqtt_publish(bool dup, uint8_t qos, bool retain, std::string topic_name, uint16_t packet_id, const std::vector<uint8_t>& payload)
: fixed_header(PUBLISH, 0, 0) {
	// flags
	_dup = dup;
	_qos = qos;
	_retain = retain;

	uint8_t flags = 0;
	if (dup)
		flags = 0x08;

	if (qos == QOS_INVALID)
		throw mqtt_error("try to cretae malformed packet. (PUBLISH QoS is 3)");
	flags |= (qos << 1);

	if (retain)
		flags |= 0x01;

	_flags |= flags;

	// topic name
	if (_topic_name.length() > 0xffff)
		throw mqtt_error("try to cretae malformed packet. (PUBLISH topic name is too long)");
	_topic_name = topic_name;
	_remaining_length = static_cast<uint32_t>(_topic_name.length()) + 2;

	// packet id
	if ((_qos == QOS_AT_LEAST_ONCE) || (_qos == QOS_EXACTLY_ONCE)) {
		_packet_id = packet_id;
		_remaining_length += 2;
	}

	// payload
	if (payload.size() + _remaining_length > 0x0fffffff)
		throw mqtt_error("try to cretae malformed packet. (PUBLISH payload is too long)");
	_payload = payload; // copy assignment.
	_remaining_length += static_cast<uint32_t>(_payload.size());
}

void mqtt_publish::serialize(shan::util::streambuf_ptr sb_ptr) const {
	fixed_header::serialize(sb_ptr);

	encode_string(_topic_name, sb_ptr);

	if ((_qos == QOS_AT_LEAST_ONCE) || (_qos == QOS_EXACTLY_ONCE))
		sb_ptr->write_uint16(_packet_id);

	sb_ptr->write(&_payload[0], _payload.size());
}

std::ostream& mqtt_publish::str(std::ostream& os) const {
	fixed_header::str(os);

	os << ((_dup) ? " D:1" : " D:0")
	   << " QoS:" << static_cast<int>(_qos)
	   << ((_retain) ? " R:1" : " R:0")
	<< " TN:" << _topic_name;

	if (_qos > 0)
		os << " PID:" << _packet_id;

	return os;
}