text:
import { Laya } from "Laya";
import { Script3D } from "laya/d3/component/Script3D";
import { BaseCamera } from "laya/d3/core/BaseCamera";
import { Camera } from "laya/d3/core/Camera";
import { Vector3 } from "laya/d3/math/Vector3";
import { Event } from "laya/events/Event";
/**
 * 相机观测方向
 */
export enum IDE_RotateDirectFlags{
	Front,
	Right,
	Left,
	Back,
	Up,
	Down
}

/**
 * 类用来控制Editor中Camera的操作
 * @author miner
 */
export class CameraControlScript extends Script3D {

	//2*PI
    public static PI2 = Math.PI*2;
	// PI/2
    public static PIHALF = Math.PI/2;

	public static FRONTROTATE:Vector3 = new Vector3(0,CameraControlScript.PIHALF,0);
	public static RIGHTROTATE:Vector3 = new Vector3(CameraControlScript.PIHALF,CameraControlScript.PIHALF,0);
	public static BACKROTATE:Vector3 = new Vector3(Math.PI,CameraControlScript.PIHALF,0);
	public static LEFTROTATE:Vector3 = new Vector3(Math.PI+CameraControlScript.PIHALF,CameraControlScript.PIHALF,0);
	public static UPROTATE:Vector3 = new Vector3(0,0,0);
	public static DOWNROTATE:Vector3 = new Vector3(0,Math.PI,0);

	/**@private */
	private static tempVec3 = new Vector3();
	private static animatorTempVec3 = new Vector3();
	/**@private */
	private _lastMouseX: number;
	/**@private */
	private _lastMouseY: number;
	private _isMouseDown: boolean;
	private _camera: BaseCamera;
	private _rotateXDir:number = 1;

	//旋转中心点
	private _rotateTarget:Vector3 = new Vector3(0,0,0);
	//旋转角度
    private _currentRotate:Vector3 = new Vector3(0,CameraControlScript.PIHALF,0);
	//camera的位置
    private _currentPosition:Vector3 = new Vector3(0,0,0);
	//旋转半径
	private _radius:number = 0;
	//旋转动画长度,总帧数
	private _animatorSize = 10;
	//目前执行到动画的帧数
	private _animatorDo = 0;
	//动画步进值
	private _animatorStepX = 0;
	private _animatorStepY = 0;

	rotateSpeed:number = 1;
	wheelSpeed:number = 1;
	stepRadius:number = 5;
	LowWheelSpeed:number = 0.2;

	constructor() {
		super();

	}

	/**
	 * 同步相机位置通过Target radius currentRotate
	 */
	public static calByIcoXYZ(targetVec:Vector3,currentPosition:Vector3,radius:number,currentRotate:Vector3,camera:BaseCamera){
		currentRotate.x = (currentRotate.x+CameraControlScript.PI2)%(CameraControlScript.PI2);
		currentRotate.y = (currentRotate.y<-Math.PI)?currentRotate.y+CameraControlScript.PI2:(currentRotate.y>Math.PI?currentRotate.y-CameraControlScript.PI2:currentRotate.y);
		var xoyLength:number = Math.sin(currentRotate.y);
		currentPosition.setValue(Math.sin(currentRotate.x)*xoyLength,Math.cos(currentRotate.y),Math.cos(currentRotate.x)*xoyLength);
		Vector3.normalize(currentPosition,currentPosition);
		Vector3.scale(currentPosition,radius,currentPosition);
		Vector3.add(currentPosition,targetVec,currentPosition);
		camera.transform.position =currentPosition;
		CameraControlScript.tempVec3.setValue(0,1,0);
		camera.transform.lookAt(targetVec,CameraControlScript.tempVec3,true);
		camera.transform.rotationEuler.z =currentRotate.y>0?0:180;
		camera.transform.rotationEuler = camera.transform.rotationEuler;
		camera.transform.worldMatrix = camera.transform.worldMatrix;
	}

	/**
	 * 根据位置计算观察角度
	 */
	private _caculateRotate(){
		Vector3.subtract(this._camera.transform.position,this._rotateTarget,CameraControlScript.tempVec3);
		Vector3.normalize(CameraControlScript.tempVec3,CameraControlScript.tempVec3);
		this._currentRotate.y = Math.acos(CameraControlScript.tempVec3.y);
		this._currentRotate.y = (this._currentRotate.y<-Math.PI)?this._currentRotate.y+CameraControlScript.PI2:(this._currentRotate.y>Math.PI?this._currentRotate.y-CameraControlScript.PI2:this._currentRotate.y);
		this._currentRotate.x = Math.atan(CameraControlScript.tempVec3.x/CameraControlScript.tempVec3.z);
		this._currentRotate.x = (this._currentRotate.x+CameraControlScript.PI2)%(CameraControlScript.PI2);
		this._camera.transform.rotationEuler.cloneTo(this._currentPosition);
		this._updateRotation(0,0,0);
	}

	//设置观测中点
	set currentTarget(value:Vector3){
		this._rotateTarget = value;
		this._caculateRotate();
	}

	get currentTarget():Vector3{
		return this._rotateTarget;
	}

	get currentRotate():Vector3{
		return this._currentRotate;
	}

	/**
	 * 无死角旋转方法
	 *
	 * @private
	 */
	private _updateRotation(offsetX:number,offsetY:number,elapsedTime:number): void {
		offsetX = offsetX/Laya.stage.width*CameraControlScript.PI2*this.rotateSpeed;
		offsetY = offsetY/Laya.stage.height*CameraControlScript.PI2*this.rotateSpeed;
		//上半球下半球x的旋转相反
		//计算
		// if(this._currentRotate.y<0)
		// 	this._currentRotate.x +=offsetX;
		// else
			this._currentRotate.x -=offsetX*this._rotateXDir;

		this._currentRotate.y -=offsetY;
		this._updateCameraByRotateValue()
	}

	//根据角度旋转相机,修改相机位置
	private _updateCameraByRotateValue(){
		CameraControlScript.calByIcoXYZ(this._rotateTarget,this._currentPosition,this.radius,this._currentRotate,this._camera);
	}

	/**
	 * 旋转动画
	 */
	doRotateAnimator(directEnum:IDE_RotateDirectFlags){
		var targetRotate:Vector3;
		switch(directEnum){
			case IDE_RotateDirectFlags.Front:
				targetRotate = CameraControlScript.FRONTROTATE;
				break;
			case IDE_RotateDirectFlags.Right:
				targetRotate = CameraControlScript.RIGHTROTATE;
				break;
			case IDE_RotateDirectFlags.Back:
				targetRotate = CameraControlScript.BACKROTATE;
				break;
			case IDE_RotateDirectFlags.Left:
				targetRotate = CameraControlScript.LEFTROTATE;
				break;
			case IDE_RotateDirectFlags.Up:
				targetRotate = CameraControlScript.UPROTATE;
				break;
			case IDE_RotateDirectFlags.Down:
				targetRotate = CameraControlScript.DOWNROTATE;
				break;
		}
		this._animatorStepX = (targetRotate.x-this._currentRotate.x)/this._animatorSize;
		this._animatorStepY = (targetRotate.y-this._currentRotate.y)/this._animatorSize;
		this._animatorDo = 0;
		Laya.timer.frameLoop(1,this,this.doRotatetwoon);

	}

	//旋转动画
	private doRotatetwoon(){
		if(this._animatorDo==this._animatorSize){
			Laya.timer.clear(this,this.doRotatetwoon);
			return;
		}
		this._currentRotate.x+=this._animatorStepX;
		this._currentRotate.y+=this._animatorStepY;
		this._updateCameraByRotateValue();
		this._animatorDo++;
	}

	/**
	 * @inheritDoc
	 */
	/*override*/  onAwake(): void {
		Laya.stage.on(Event.RIGHT_MOUSE_DOWN, this, this._mouseDown);
		Laya.stage.on(Event.RIGHT_MOUSE_UP, this, this._mouseUp);
		Laya.stage.on(Event.MOUSE_OUT, this, this._mouseUp);
		Laya.stage.on(Event.MOUSE_WHEEL,this,this._mouseWheel);
		this._camera = (<Camera>this.owner);
		CameraControlScript.tempVec3.setValue(0,0,0);
		this._radius = Vector3.distance( this._camera.transform.position,CameraControlScript.tempVec3);
		this._camera.transform.lookAt(this._rotateTarget,CameraControlScript.tempVec3,true);
		this._caculateRotate();
    }

	/**
	 * @inheritDoc
	 */
	/*override*/  onUpdate(): void {
		var elapsedTime: number = Laya.timer.delta;
		var offsetX: number = Laya.stage.mouseX - this._lastMouseX;
		var offsetY: number = Laya.stage.mouseY - this._lastMouseY;

		//是否满足旋转条件
		if (!isNaN(this._lastMouseX) && !isNaN(this._lastMouseY) && this._isMouseDown) {
			this._updateRotation(offsetX,offsetY,elapsedTime);
		}
		this._lastMouseX = Laya.stage.mouseX;
		this._lastMouseY = Laya.stage.mouseY;
	}

		/**
		 * @inheritDoc
		 */
		/*override*/  onDestroy(): void {
		Laya.stage.off(Event.RIGHT_MOUSE_DOWN, this, this._mouseDown);
		Laya.stage.off(Event.RIGHT_MOUSE_UP, this, this._mouseUp);
		Laya.stage.off(Event.MOUSE_OUT, this, this._mouseUp);
	}

	private _mouseDown(e: Event): void {
		this._lastMouseX = Laya.stage.mouseX;
		this._lastMouseY = Laya.stage.mouseY;
		this._isMouseDown = true;
		if(this._currentRotate.y<0)
			this._rotateXDir =-1;
		else
			this._rotateXDir =1;
	}

	private _mouseUp(e: Event): void {
		this._isMouseDown = false;
	}

	private _mouseWheel(e: Event) {

		if(this.radius<this.stepRadius)
		this.radius = this.radius - e.delta*this.LowWheelSpeed;
		else
		this.radius = this.radius - e.delta*this.wheelSpeed;
	}

	get radius(): number {
		return  this._radius;
	}

	set radius(value: number) {
		this._radius = Math.max(0.5, Math.min(500, value));
		this._updateRotation(0,0,0);
	}

	setRotateTarget(target:Vector3):void{

	}

	/**
	 * 向前移动。
	 * @param distance 移动距离。
	 */
	moveForward(distance: number): void {
	}

	/**
	 * 向右移动。
	 * @param distance 移动距离。
	 */
	moveRight(distance: number): void {
	}

	/**
	 * 向上移动。
	 * @param distance 移动距离。
	 */
	moveVertical(distance: number): void {
	}

}


text:
<?php
use yii\helpers\Html;

/**
 * @var \yii\web\View $this
 * @var backend\modules\user\models\LoginForm $model
 */
$this->title = 'Авторизация';
?>

    <?php echo Html::beginForm(Yii::$app->user->loginUrl, 'post', ['id' => 'loginForm']); ?>
        <div class="form-group field-loginform-username required
            <?php echo $model->getErrors('username') ? ' has-error' : ''; ?>">

                <?php
                echo Html::textInput('LoginForm[username]', $model->username, [
                    'class' => 'form-control',
                    'placeholder' => $model->getAttributeLabel('username')
                ]);
                ?>

            <?php if ($model->getErrors('username')) : ?>

                    <?php foreach ($model->getErrors('username') as $error) : ?>

                            <?php echo $error; ?>

                    <?php endforeach; ?>

            <?php endif; ?>

        <div class="form-group field-loginform-password required
            <?php echo $model->getErrors('password') ? ' has-error' : ''; ?>">

                <?php
                echo Html::passwordInput('LoginForm[password]', $model->password, [
                    'class' => 'form-control',
                    'placeholder' => $model->getAttributeLabel('password')
                ]);
                ?>

            <?php if ($model->getErrors('password')) : ?>

                    <?php foreach ($model->getErrors('password') as $error) : ?>

                            <?php echo $error; ?>

                    <?php endforeach; ?>

            <?php endif; ?>

                        <?php
                        echo Html::checkbox('запомнить меня', true, ['id' => 'remember-me']);
                        ?>

                            <?php echo $model->getAttributeLabel('rememberMe'); ?>

                <?php echo Html::submitButton('OK', ['class' => 'btn btn-success col-xs-12']); ?>

    <?php echo Html::endForm(); ?>

redpajama_set_name: RedPajamaGithub


text:
"""Converts Pascal VOC data to TFRecords file format with Example protos.

The raw Pascal VOC data set is expected to reside in JPEG files located in the
directory 'JPEGImages'. Similarly, bounding box annotations are supposed to be
stored in the 'Annotation directory'

This TensorFlow script converts the training and evaluation data into
a sharded data set consisting of 1024 and 128 TFRecord files, respectively.

Each validation TFRecord file contains ~500 records. Each training TFREcord
file contains ~1000 records. Each record within the TFRecord file is a
serialized Example proto. The Example proto contains the following fields:

    image/encoded: string containing JPEG encoded image in RGB colorspace
    image/height: integer, image height in pixels
    image/width: integer, image width in pixels
    image/channels: integer, specifying the number of channels, always 3
    image/format: string, specifying the format, always'JPEG'

    image/object/bbox/xmin: list of float specifying the 0+ human annotated
        bounding boxes
    image/object/bbox/xmax: list of float specifying the 0+ human annotated
        bounding boxes
    image/object/bbox/ymin: list of float specifying the 0+ human annotated
        bounding boxes
    image/object/bbox/ymax: list of float specifying the 0+ human annotated
        bounding boxes
    image/object/bbox/label: list of integer specifying the classification index.
    image/object/bbox/label_text: list of string descriptions.

Note that the length of xmin is identical to the length of xmax, ymin and ymax
for each example.
"""
import os
import sys
import random

import numpy as np
import tensorflow as tf

import xml.etree.ElementTree as ET

from datasets.dataset_utils import int64_feature, float_feature, bytes_feature
from datasets.pascalvoc_common import VOC_LABELS

# Original dataset organisation.
DIRECTORY_ANNOTATIONS = 'Annotations/'
DIRECTORY_IMAGES = 'JPEGImages/'

# TFRecords convertion parameters.
RANDOM_SEED = 4242
SAMPLES_PER_FILES = 200

def _process_image(directory, name):
    """Process a image and annotation file.

    Args:
      filename: string, path to an image file e.g., '/path/to/example.JPG'.
      coder: instance of ImageCoder to provide TensorFlow image coding utils.
    Returns:
      image_buffer: string, JPEG encoding of RGB image.
      height: integer, image height in pixels.
      width: integer, image width in pixels.
    """
    # Read the image file.
    filename = directory + DIRECTORY_IMAGES + name + '.jpg'
    image_data = tf.gfile.FastGFile(filename, 'r').read()

    # Read the XML annotation file.
    filename = os.path.join(directory, DIRECTORY_ANNOTATIONS, name + '.xml')
    tree = ET.parse(filename)
    root = tree.getroot()

    # Image shape.
    size = root.find('size')
    shape = [int(size.find('height').text),
             int(size.find('width').text),
             int(size.find('depth').text)]
    # Find annotations.
    bboxes = []
    labels = []
    labels_text = []
    difficult = []
    truncated = []
    for obj in root.findall('object'):
        label = obj.find('name').text
        labels.append(int(VOC_LABELS[label][0]))
        labels_text.append(label.encode('ascii'))

        if obj.find('difficult'):
            difficult.append(int(obj.find('difficult').text))
        else:
            difficult.append(0)
        if obj.find('truncated'):
            truncated.append(int(obj.find('truncated').text))
        else:
            truncated.append(0)

        bbox = obj.find('bndbox')
        bboxes.append((float(bbox.find('ymin').text) / shape[0],
                       float(bbox.find('xmin').text) / shape[1],
                       float(bbox.find('ymax').text) / shape[0],
                       float(bbox.find('xmax').text) / shape[1]
                       ))
    return image_data, shape, bboxes, labels, labels_text, difficult, truncated

def _convert_to_example(image_data, labels, labels_text, bboxes, shape,
                        difficult, truncated):
    """Build an Example proto for an image example.

    Args:
      image_data: string, JPEG encoding of RGB image;
      labels: list of integers, identifier for the ground truth;
      labels_text: list of strings, human-readable labels;
      bboxes: list of bounding boxes; each box is a list of integers;
          specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong
          to the same label as the image label.
      shape: 3 integers, image shapes in pixels.
    Returns:
      Example proto
    """
    xmin = []
    ymin = []
    xmax = []
    ymax = []
    for b in bboxes:
        assert len(b) == 4
        # pylint: disable=expression-not-assigned
        [l.append(point) for l, point in zip([ymin, xmin, ymax, xmax], b)]
        # pylint: enable=expression-not-assigned

    image_format = b'JPEG'
    example = tf.train.Example(features=tf.train.Features(feature={
            'image/height': int64_feature(shape[0]),
            'image/width': int64_feature(shape[1]),
            'image/channels': int64_feature(shape[2]),
            'image/shape': int64_feature(shape),
            'image/object/bbox/xmin': float_feature(xmin),
            'image/object/bbox/xmax': float_feature(xmax),
            'image/object/bbox/ymin': float_feature(ymin),
            'image/object/bbox/ymax': float_feature(ymax),
            'image/object/bbox/label': int64_feature(labels),
            'image/object/bbox/label_text': bytes_feature(labels_text),
            'image/object/bbox/difficult': int64_feature(difficult),
            'image/object/bbox/truncated': int64_feature(truncated),
            'image/format': bytes_feature(image_format),
            'image/encoded': bytes_feature(image_data)}))
    return example

def _add_to_tfrecord(dataset_dir, name, tfrecord_writer):
    """Loads data from image and annotations files and add them to a TFRecord.

    Args:
      dataset_dir: Dataset directory;
      name: Image name to add to the TFRecord;
      tfrecord_writer: The TFRecord writer to use for writing.
    """
    image_data, shape, bboxes, labels, labels_text, difficult, truncated = \
        _process_image(dataset_dir, name)
    example = _convert_to_example(image_data, labels, labels_text,
                                  bboxes, shape, difficult, truncated)
    tfrecord_writer.write(example.SerializeToString())

def _get_output_filename(output_dir, name, idx):
    return '%s/%s_%03d.tfrecord' % (output_dir, name, idx)

def run(dataset_dir, output_dir, name='voc_train', shuffling=False):
    """Runs the conversion operation.

    Args:
      dataset_dir: The dataset directory where the dataset is stored.
      output_dir: Output directory.
    """
    if not tf.gfile.Exists(dataset_dir):
        tf.gfile.MakeDirs(dataset_dir)

    # Dataset filenames, and shuffling.
    path = os.path.join(dataset_dir, DIRECTORY_ANNOTATIONS)
    filenames = sorted(os.listdir(path))
    if shuffling:
        random.seed(RANDOM_SEED)
        random.shuffle(filenames)

    # Process dataset files.
    i = 0
    fidx = 0
    while i < len(filenames):
        # Open new TFRecord file.
        tf_filename = _get_output_filename(output_dir, name, fidx)
        with tf.python_io.TFRecordWriter(tf_filename) as tfrecord_writer:
            j = 0
            while i < len(filenames) and j < SAMPLES_PER_FILES:
                sys.stdout.write('\r>> Converting image %d/%d' % (i+1, len(filenames)))
                sys.stdout.flush()

                filename = filenames[i]
                img_name = filename[:-4]
                _add_to_tfrecord(dataset_dir, img_name, tfrecord_writer)
                i += 1
                j += 1
            fidx += 1

    # Finally, write the labels file:
    # labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
    # dataset_utils.write_label_file(labels_to_class_names, dataset_dir)
    print('\nFinished converting the Pascal VOC dataset!')

if __name__ == '__main__':
    dataset_dir = '/home/dst/data/VOCdevkit/VOC2007'
    output_dir = '/home/dst/SSD/voc2007tf'

    run(dataset_dir, output_dir)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>P-Index</title>
<meta name="date" content="2015-04-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E G I M O P R S T

P

Parser - Class in test.calc

Класс @param Parser предназначен для обработки текстовой строки

Parser() - Constructor for class test.calc.Parser

A C D E G I M O P R S T

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.intellij.execution.rmi.ssl;

import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.util.Base64;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrivateKeyReader {
  public static final String P1_BEGIN_MARKER = "-----BEGIN RSA PRIVATE KEY";
  public static final String P1_END_MARKER = "-----END RSA PRIVATE KEY";

  public static final String P8_BEGIN_MARKER = "-----BEGIN PRIVATE KEY";
  public static final String P8_END_MARKER = "-----END PRIVATE KEY";

  private static final Map<String, PrivateKey> keyCache = Collections.synchronizedMap(new HashMap<String, PrivateKey>());

  @NotNull private final String myFileName;

  public PrivateKeyReader(@NotNull String fileName) {
    myFileName = fileName;
  }

  public PrivateKey getPrivateKey() throws IOException {
    PrivateKey key = keyCache.get(myFileName);
    if (key != null) return key;
    key = read(myFileName);
    keyCache.put(myFileName, key);
    return key;
  }

  private static PrivateKey read(String fileName) throws IOException {
    KeyFactory factory;
    try {
      factory = KeyFactory.getInstance("RSA");
    }
    catch (NoSuchAlgorithmException e) {
      throw new IOException("JCE error: " + e.getMessage());
    }

    List<String> lines = FileUtilRt.loadLines(fileName, "UTF-8");
    for (int i = 0; i < lines.size(); i++) {
      String line = lines.get(i);
      if (line.contains(P1_BEGIN_MARKER)) {
        List<String> strings = lines.subList(i + 1, lines.size());
        byte[] keyBytes = readKeyMaterial(P1_END_MARKER, strings);
        RSAPrivateCrtKeySpec keySpec = getRSAKeySpec(keyBytes);

        try {
          return factory.generatePrivate(keySpec);
        }
        catch (InvalidKeySpecException e) {
          throw new IOException("Invalid PKCS#1 PEM file: " + e.getMessage());
        }
      }

      if (line.contains(P8_BEGIN_MARKER)) {
        List<String> strings = lines.subList(i + 1, lines.size());
        byte[] keyBytes = readKeyMaterial(P8_END_MARKER, strings);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

        try {
          return factory.generatePrivate(keySpec);
        }
        catch (InvalidKeySpecException e) {
          throw new IOException("Invalid PKCS#8 PEM file: " + e.getMessage());
        }
      }
    }

    throw new IOException("Invalid PEM file: no begin marker");
  }

  private static byte[] readKeyMaterial(String endMarker, List<String> strings) throws IOException {
    StringBuilder buf = new StringBuilder();
    for (String line : strings) {
      if (line.contains(endMarker)) {
        return Base64.decode(buf.toString());
      }
      buf.append(line.trim());
    }
    throw new IOException("Invalid PEM file: No end marker");
  }

  /**
   * Convert PKCS#1 encoded private key into RSAPrivateCrtKeySpec.
   *

   *
The ASN.1 syntax for the private key with CRT is
   *

   *

   * --
   * -- Representation of RSA private key with information for the CRT algorithm.
   * --
   * RSAPrivateKey ::= SEQUENCE {
   *   version           Version,
   *   modulus           INTEGER,  -- n
   *   publicExponent    INTEGER,  -- e
   *   privateExponent   INTEGER,  -- d
   *   prime1            INTEGER,  -- p
   *   prime2            INTEGER,  -- q
   *   exponent1         INTEGER,  -- d mod (p-1)
   *   exponent2         INTEGER,  -- d mod (q-1)
   *   coefficient       INTEGER,  -- (inverse of q) mod p
   *   otherPrimeInfos   OtherPrimeInfos OPTIONAL
   * }
   *

   *
   * @param keyBytes PKCS#1 encoded key
   * @return KeySpec
   * @throws IOException
   */
  private static RSAPrivateCrtKeySpec getRSAKeySpec(byte[] keyBytes) throws IOException {
    DerParser parser = new DerParser(keyBytes);

    Asn1Object sequence = parser.read();
    if (sequence.getType() != DerParser.SEQUENCE) {
      throw new IOException("Invalid DER: not a sequence");
    }

    // Parse inside the sequence
    parser = sequence.getParser();

    parser.read(); // Skip version
    BigInteger modulus = parser.read().getInteger();
    BigInteger publicExp = parser.read().getInteger();
    BigInteger privateExp = parser.read().getInteger();
    BigInteger prime1 = parser.read().getInteger();
    BigInteger prime2 = parser.read().getInteger();
    BigInteger exp1 = parser.read().getInteger();
    BigInteger exp2 = parser.read().getInteger();
    BigInteger crtCoef = parser.read().getInteger();

    return new RSAPrivateCrtKeySpec(
      modulus, publicExp, privateExp, prime1, prime2,
      exp1, exp2, crtCoef);
  }
}

/**
 * A bare-minimum ASN.1 DER decoder, just having enough functions to
 * decode PKCS#1 private keys. Especially, it doesn't handle explicitly
 * tagged types with an outer tag.
 *

 *
This parser can only handle one layer. To parse nested constructs,
 * get a new parser for each layer using {@code Asn1Object.getParser()}.
 *

 *
There are many DER decoders in JRE but using them will tie this
 * program to a specific JCE/JVM.
 *
 * @author zhang
 */
class DerParser {

  // Classes
  public final static int UNIVERSAL = 0x00;
  public final static int APPLICATION = 0x40;
  public final static int CONTEXT = 0x80;
  public final static int PRIVATE = 0xC0;

  // Constructed Flag
  public final static int CONSTRUCTED = 0x20;

  // Tag and data types
  public final static int ANY = 0x00;
  public final static int BOOLEAN = 0x01;
  public final static int INTEGER = 0x02;
  public final static int BIT_STRING = 0x03;
  public final static int OCTET_STRING = 0x04;
  public final static int NULL = 0x05;
  public final static int REAL = 0x09;
  public final static int ENUMERATED = 0x0a;

  public final static int SEQUENCE = 0x10;
  public final static int SET = 0x11;

  public final static int NUMERIC_STRING = 0x12;
  public final static int PRINTABLE_STRING = 0x13;
  public final static int VIDEOTEX_STRING = 0x15;
  public final static int IA5_STRING = 0x16;
  public final static int GRAPHIC_STRING = 0x19;
  public final static int ISO646_STRING = 0x1A;
  public final static int GENERAL_STRING = 0x1B;

  public final static int UTF8_STRING = 0x0C;
  public final static int UNIVERSAL_STRING = 0x1C;
  public final static int BMP_STRING = 0x1E;

  public final static int UTC_TIME = 0x17;

  protected InputStream in;

  /**
   * Create a new DER decoder from an input stream.
   *
   * @param in The DER encoded stream
   */
  public DerParser(InputStream in) throws IOException {
    this.in = in;
  }

  /**
   * Create a new DER decoder from a byte array.
   *
   * @param bytes The encoded bytes
   * @throws IOException
   */
  public DerParser(byte[] bytes) throws IOException {
    this(new ByteArrayInputStream(bytes));
  }

  /**
   * Read next object. If it's constructed, the value holds
   * encoded content and it should be parsed by a new
   * parser from {@code Asn1Object.getParser}.
   *
   * @return A object
   * @throws IOException
   */
  public Asn1Object read() throws IOException {
    int tag = in.read();

    if (tag == -1) {
      throw new IOException("Invalid DER: stream too short, missing tag");
    }

    int length = getLength();

    byte[] value = new byte[length];
    int n = in.read(value);
    if (n < length) {
      throw new IOException("Invalid DER: stream too short, missing value");
    }

    return new Asn1Object(tag, length, value);
  }

  /**
   * Decode the length of the field. Can only support length
   * encoding up to 4 octets.
   *

   *
In BER/DER encoding, length can be encoded in 2 forms,
   *

   *
Short form. One octet. Bit 8 has value "0" and bits 7-1
   * give the length.
   *
Long form. Two to 127 octets (only 4 is supported here).
   * Bit 8 of first octet has value "1" and bits 7-1 give the
   * number of additional length octets. Second and following
   * octets give the length, base 256, most significant digit first.
   *

   *
   * @return The length as integer
   * @throws IOException
   */
  private int getLength() throws IOException {

    int i = in.read();
    if (i == -1) {
      throw new IOException("Invalid DER: length missing");
    }

    // A single byte short length
    if ((i & ~0x7F) == 0) {
      return i;
    }

    int num = i & 0x7F;

    // We can't handle length longer than 4 bytes
    if (i >= 0xFF || num > 4) {
      throw new IOException("Invalid DER: length field too big ("
                            + i + ")");
    }

    byte[] bytes = new byte[num];
    int n = in.read(bytes);
    if (n < num) {
      throw new IOException("Invalid DER: length too short");
    }

    return new BigInteger(1, bytes).intValue();
  }
}

/**
 * An ASN.1 TLV. The object is not parsed. It can
 * only handle integers and strings.
 *
 * @author zhang
 */
class Asn1Object {

  protected final int type;
  protected final int length;
  protected final byte[] value;
  protected final int tag;

  /**
   * Construct a ASN.1 TLV. The TLV could be either a
   * constructed or primitive entity.
   *

   *
The first byte in DER encoding is made of following fields,
   *

   * -------------------------------------------------
   * |Bit 8|Bit 7|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1|
   * -------------------------------------------------
   * |  Class    | CF  |     +      Type             |
   * -------------------------------------------------
   *

   *

   *
Class: Universal, Application, Context or Private
   *
CF: Constructed flag. If 1, the field is constructed.
   *
Type: This is actually called tag in ASN.1. It
   * indicates data type (Integer, String) or a construct
   * (sequence, choice, set).
   *

   *
   * @param tag    Tag or Identifier
   * @param length Length of the field
   * @param value  Encoded octet string for the field.
   */
  public Asn1Object(int tag, int length, byte[] value) {
    this.tag = tag;
    this.type = tag & 0x1F;
    this.length = length;
    this.value = value;
  }

  public int getType() {
    return type;
  }

  public int getLength() {
    return length;
  }

  public byte[] getValue() {
    return value;
  }

  public boolean isConstructed() {
    return (tag & DerParser.CONSTRUCTED) == DerParser.CONSTRUCTED;
  }

  /**
   * For constructed field, return a parser for its content.
   *
   * @return A parser for the construct.
   * @throws IOException
   */
  public DerParser getParser() throws IOException {
    if (!isConstructed()) {
      throw new IOException("Invalid DER: can't parse primitive entity");
    }

    return new DerParser(value);
  }

  /**
   * Get the value as integer
   *
   * @return BigInteger
   * @throws IOException
   */
  public BigInteger getInteger() throws IOException {
    if (type != DerParser.INTEGER) {
      throw new IOException("Invalid DER: object is not integer");
    }

    return new BigInteger(value);
  }

  /**
   * Get value as string. Most strings are treated
   * as Latin-1.
   *
   * @return Java string
   * @throws IOException
   */
  public String getString() throws IOException {

    String encoding;

    switch (type) {

      // Not all are Latin-1 but it's the closest thing
      case DerParser.NUMERIC_STRING:
      case DerParser.PRINTABLE_STRING:
      case DerParser.VIDEOTEX_STRING:
      case DerParser.IA5_STRING:
      case DerParser.GRAPHIC_STRING:
      case DerParser.ISO646_STRING:
      case DerParser.GENERAL_STRING:
        encoding = "ISO-8859-1";
        break;

      case DerParser.BMP_STRING:
        encoding = "UTF-16BE";
        break;

      case DerParser.UTF8_STRING:
        encoding = "UTF-8";
        break;

      case DerParser.UNIVERSAL_STRING:
        throw new IOException("Invalid DER: can't handle UCS-4 string");

      default:
        throw new IOException("Invalid DER: object is not a string");
    }

    return new String(value, encoding);
  }
}


text:
const long long DownloadPriority::LOWEST  = 10;
const long long DownloadPriority::LOWER   = 100;
const long long DownloadPriority::MEDIUM  = 1000;
const long long DownloadPriority::HIGHER  = 10000;
const long long DownloadPriority::HIGHEST = 100000;