text:
/*jslint browser: true, node: true */
/*global numeric, nifti */

"use strict";

/*** Imports ***/
var papaya = papaya || {};
papaya.volume = papaya.volume || {};
papaya.volume.nifti = papaya.volume.nifti || {};

/*** Constructor ***/
papaya.volume.nifti.HeaderNIFTI = papaya.volume.nifti.HeaderNIFTI || function () {
    this.nifti = null;
    this.isNIFTI2 = false;
    this.compressed = false;
    this.imageData = null;
};

/*** Static Pseudo-constants ***/

papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT = "XYZ-++";
papaya.volume.nifti.HeaderNIFTI.SPATIAL_UNITS_MASK = 0x07;
papaya.volume.nifti.HeaderNIFTI.TEMPORAL_UNITS_MASK = 0x38;

/*** Static Methods ***/

papaya.volume.nifti.HeaderNIFTI.isThisFormat = function (filename, data) {
    if (filename.indexOf(".nii") !== -1) {
        return true;
    }

    return nifti.isNIFTI(data[0]);
};

/*** Prototype Methods ***/

papaya.volume.nifti.HeaderNIFTI.prototype.readHeaderData = function (data, progressMeter, dialogHandler,
                                                                     onFinishedHeaderRead) {
    this.nifti = nifti.readHeader(data[0]);
    this.isNIFTI2 = nifti.isNIFTI2(data[0]);
    this.imageData = nifti.readImage(this.nifti, data[0]);
    onFinishedHeaderRead();
};

papaya.volume.nifti.HeaderNIFTI.prototype.readImageData = function (progressMeter, onFinishedImageRead) {
    onFinishedImageRead(this.imageData);
    this.imageData = null;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getImageDimensions = function () {
    var id = new papaya.volume.ImageDimensions(this.nifti.dims[1], this.nifti.dims[2], this.nifti.dims[3],
        this.nifti.dims[4]);
    id.dataOffsets[0] = this.nifti.vox_offset;
    id.dataLengths[0] = (id.getNumVoxelsSeries() * (this.nifti.numBitsPerVoxel / 8));

    return id;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getName = function () {
    return null;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getVoxelDimensions = function () {
    /*jslint bitwise: true */
    var vd;

    vd = new papaya.volume.VoxelDimensions(this.nifti.pixDims[1], this.nifti.pixDims[2], this.nifti.pixDims[3],
        this.nifti.pixDims[4]);

    vd.spatialUnit = (this.nifti.xyzt_units & papaya.volume.nifti.HeaderNIFTI.SPATIAL_UNITS_MASK);
    vd.temporalUnit = (this.nifti.xyzt_units & papaya.volume.nifti.HeaderNIFTI.TEMPORAL_UNITS_MASK);
    vd.flip = (this.nifti.pixDims[0] === -1);

    return vd;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getImageType = function () {
    var datatype = papaya.volume.ImageType.DATATYPE_UNKNOWN;

    if ((this.nifti.datatypeCode === nifti.NIFTI1.TYPE_UINT8) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_UINT16) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_UINT32) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_UINT64)) {
        datatype = papaya.volume.ImageType.DATATYPE_INTEGER_UNSIGNED;
    } else if ((this.nifti.datatypeCode === nifti.NIFTI1.TYPE_INT8) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_INT16) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_INT32) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_INT64)) {
        datatype = papaya.volume.ImageType.DATATYPE_INTEGER_SIGNED;
    } else if ((this.nifti.datatypeCode === nifti.NIFTI1.TYPE_FLOAT32) ||
        (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_FLOAT64)) {
        datatype = papaya.volume.ImageType.DATATYPE_FLOAT;
    } else if (this.nifti.datatypeCode === nifti.NIFTI1.TYPE_RGB24) {
        datatype = papaya.volume.ImageType.DATATYPE_RGB;
    }

    return new papaya.volume.ImageType(datatype, this.nifti.numBitsPerVoxel / 8, this.nifti.littleEndian,
        this.compressed);
};

papaya.volume.nifti.HeaderNIFTI.prototype.getOrientation = function () {
    var orientation = null;

    if ((this.nifti.qform_code > 0) && !this.qFormHasRotations()) {
        orientation = this.getOrientationQform();
    }

    if ((this.nifti.sform_code > this.nifti.qform_code) && !this.sFormHasRotations()) {
        orientation = this.getOrientationSform();
    }

    if (orientation === null) {
        orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
    }

    return new papaya.volume.Orientation(orientation);
};

papaya.volume.nifti.HeaderNIFTI.prototype.getOrientationQform = function () {
    var orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT,
        qFormMatParams = this.nifti.convertNiftiQFormToNiftiSForm(this.nifti.quatern_b, this.nifti.quatern_c,
            this.nifti.quatern_d, this.nifti.qoffset_x, this.nifti.qoffset_y, this.nifti.qoffset_z,
            this.nifti.pixDims[1], this.nifti.pixDims[2], this.nifti.pixDims[3], this.nifti.pixDims[0]);

    if (this.nifti.qform_code > 0) {
        orientation = this.nifti.convertNiftiSFormToNEMA(qFormMatParams);

        if (!papaya.volume.Orientation.isValidOrientationString(orientation)) {
            orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
        }
    } else {
        orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
    }

    return orientation;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getOrientationSform = function () {
    var orientation = this.nifti.convertNiftiSFormToNEMA(this.nifti.affine);

    if (!papaya.volume.Orientation.isValidOrientationString(orientation)) {
        orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
    }

    return orientation;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getQformMatCopy = function () {
    return this.nifti.getQformMat().clone();
};

papaya.volume.nifti.HeaderNIFTI.prototype.getSformMatCopy = function () {
    return this.nifti.affine.clone();
};

papaya.volume.nifti.HeaderNIFTI.prototype.getOrigin = function (forceQ, forceS) {
    var origin = new papaya.core.Coordinate(0, 0, 0),
        qFormMatParams,
        affineQform,
        affineQformInverse,
        affineSformInverse,
        orientation,
        someOffsets,
        xyz, sense,
        xIndex, yIndex, zIndex,
        xFlip, yFlip, zFlip;

    if ((this.nifti.qform_code > 0) && !forceS) {
        if (this.qFormHasRotations()) {
            affineQform = this.nifti.getQformMat();
            affineQformInverse = numeric.inv(affineQform);
            origin.setCoordinate(affineQformInverse[0][3], affineQformInverse[1][3], affineQformInverse[2][3]);
        } else {
            qFormMatParams = this.nifti.convertNiftiQFormToNiftiSForm(this.nifti.quatern_b, this.nifti.quatern_c,
                this.nifti.quatern_d, this.nifti.qoffset_x, this.nifti.qoffset_y, this.nifti.qoffset_z,
                this.nifti.pixDims[1], this.nifti.pixDims[2], this.nifti.pixDims[3], this.nifti.pixDims[0]);

            orientation = this.nifti.convertNiftiSFormToNEMA(qFormMatParams);

            if (!papaya.volume.Orientation.isValidOrientationString(orientation)) {
                orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
            }

            xyz = orientation.substring(0, 3).toUpperCase();
            sense = orientation.substring(3);
            xIndex = xyz.indexOf('X');
            yIndex = xyz.indexOf('Y');
            zIndex = xyz.indexOf('Z');
            xFlip = (sense.charAt(xIndex) === '+');
            yFlip = (sense.charAt(yIndex) === '+');
            zFlip = (sense.charAt(zIndex) === '+');

            someOffsets = new Array(3);
            someOffsets[0] = ((this.nifti.qoffset_x / this.nifti.pixDims[xIndex + 1])) * (xFlip ? -1 : 1);
            someOffsets[1] = ((this.nifti.qoffset_y / this.nifti.pixDims[yIndex + 1])) * (yFlip ? -1 : 1);
            someOffsets[2] = ((this.nifti.qoffset_z / this.nifti.pixDims[zIndex + 1])) * (zFlip ? -1 : 1);

            origin.setCoordinate(someOffsets[0], someOffsets[1], someOffsets[2], true);
        }
    } else if ((this.nifti.sform_code > 0) && !forceQ) {
        if (this.sFormHasRotations()) {
            affineSformInverse = numeric.inv(this.nifti.affine);
            origin.setCoordinate(affineSformInverse[0][3], affineSformInverse[1][3], affineSformInverse[2][3]);
        } else {
            orientation = this.nifti.convertNiftiSFormToNEMA(this.nifti.affine);

            if (!papaya.volume.Orientation.isValidOrientationString(orientation)) {
                orientation = papaya.volume.nifti.HeaderNIFTI.ORIENTATION_DEFAULT;
            }

            xyz = orientation.substring(0, 3).toUpperCase();
            sense = orientation.substring(3);
            xIndex = xyz.indexOf('X');
            yIndex = xyz.indexOf('Y');
            zIndex = xyz.indexOf('Z');
            xFlip = (sense.charAt(xIndex) === '+');
            yFlip = (sense.charAt(yIndex) === '+');
            zFlip = (sense.charAt(zIndex) === '+');

            someOffsets = new Array(3);
            someOffsets[0] = ((this.nifti.affine[0][3] / this.nifti.pixDims[xIndex + 1])) * (xFlip ? -1 : 1);
            someOffsets[1] = ((this.nifti.affine[1][3] / this.nifti.pixDims[yIndex + 1])) * (yFlip ? -1 : 1);
            someOffsets[2] = ((this.nifti.affine[2][3] / this.nifti.pixDims[zIndex + 1])) * (zFlip ? -1 : 1);

            origin.setCoordinate(someOffsets[0], someOffsets[1], someOffsets[2], true);
        }
    }

    if (origin.isAllZeros()) {
        origin.setCoordinate(this.nifti.dims[1] / 2.0, this.nifti.dims[2] / 2.0, this.nifti.dims[3] / 2.0);
    }

    return origin;
};

papaya.volume.nifti.HeaderNIFTI.prototype.qFormHasRotations = function () {
    return papaya.volume.Transform.hasRotations(this.getQformMatCopy());
};

papaya.volume.nifti.HeaderNIFTI.prototype.sFormHasRotations = function () {
    return papaya.volume.Transform.hasRotations(this.getSformMatCopy());
};

papaya.volume.nifti.HeaderNIFTI.prototype.getImageRange = function () {
    var ir = new papaya.volume.ImageRange(this.nifti.cal_min, this.nifti.cal_max),
        slope = this.nifti.scl_slope,
        imageDimensions = this.getImageDimensions();

    if (slope === 0) {
        slope = 1;
    }

    ir.setGlobalDataScale(slope, this.nifti.scl_inter, imageDimensions.slices * imageDimensions.timepoints);
    ir.validateDataScale();

    return ir;
};

papaya.volume.nifti.HeaderNIFTI.prototype.hasError = function () {
    return false;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getImageDescription = function () {
    return new papaya.volume.ImageDescription(this.nifti.description);
};

papaya.volume.nifti.HeaderNIFTI.prototype.getOrientationCertainty = function () {
    var certainty, origin;

    certainty = papaya.volume.Header.ORIENTATION_CERTAINTY_UNKNOWN;

    if ((this.nifti.qform_code > 0) || (this.nifti.sform_code > 0)) {
        certainty = papaya.volume.Header.ORIENTATION_CERTAINTY_LOW;

        origin = this.getOrigin();
        if ((origin !== null) && !origin.isAllZeros()) {
            certainty = papaya.volume.Header.ORIENTATION_CERTAINTY_HIGH;
        }
    }

    return certainty;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getBestTransform = function () {
    if ((this.nifti.qform_code > 0) && (this.nifti.qform_code > this.nifti.sform_code) && this.qFormHasRotations()) {
        return this.getQformMatCopy();
    }

    if ((this.nifti.sform_code > 0) && (this.nifti.sform_code >= this.nifti.qform_code) && this.sFormHasRotations()) {
        return this.getSformMatCopy();
    }

    return null;
};

papaya.volume.nifti.HeaderNIFTI.prototype.getBestTransformOrigin = function () {
    if ((this.nifti.qform_code > 0) && (this.nifti.qform_code > this.nifti.sform_code) && this.qFormHasRotations()) {
        return this.getOrigin(true, false);
    }

    if ((this.nifti.sform_code > 0) && (this.nifti.sform_code >= this.nifti.qform_code) && this.sFormHasRotations()) {
        return this.getOrigin(false, true);
    }

    return null;
};

papaya.volume.nifti.HeaderNIFTI.prototype.toString = function () {
    var fmt = papaya.utilities.StringUtils.formatNumber,
        string = "";

    if (this.isNIFTI2) {
        string += ("Datatype" + " = " +  this.nifti.datatypeCode + " (" + this.nifti.getDatatypeCodeString(this.nifti.datatypeCode) + ")
");
        string += ("Bits Per Voxel" + " = " + this.nifti.numBitsPerVoxel + "
");
        string += ("Image Dimensions" + " (1-8): " +
        this.nifti.dims[0] + ", " +
        this.nifti.dims[1] + ", " +
        this.nifti.dims[2] + ", " +
        this.nifti.dims[3] + ", " +
        this.nifti.dims[4] + ", " +
        this.nifti.dims[5] + ", " +
        this.nifti.dims[6] + ", " +
        this.nifti.dims[7] + "
");

        string += ("Intent Parameters (1-3): " +
            this.nifti.intent_p1 + ", " +
            this.nifti.intent_p2 + ", " +
            this.nifti.intent_p3) + "
";

        string += ("Voxel Dimensions (1-8): " +
        fmt(this.nifti.pixDims[0]) + ", " +
        fmt(this.nifti.pixDims[1]) + ", " +
        fmt(this.nifti.pixDims[2]) + ", " +
        fmt(this.nifti.pixDims[3]) + ", " +
        fmt(this.nifti.pixDims[4]) + ", " +
        fmt(this.nifti.pixDims[5]) + ", " +
        fmt(this.nifti.pixDims[6]) + ", " +
        fmt(this.nifti.pixDims[7]) + "
");

        string += ("Image Offset" + " = " + this.nifti.vox_offset + "
");
        string += ("Data Scale:  Slope" + " = " + this.nifti.scl_slope + "  Intercept" + " = " + this.nifti.scl_inter+ "
");
        string += ("Display Range:  Max" + " = " + this.nifti.cal_max + "  Min" + " = " + this.nifti.cal_min + "
");
        string += ("Slice Duration" + " = " + this.nifti.slice_duration + "
");
        string += ("Time Axis Shift" + " = " + this.nifti.toffset + "
");
        string += ("Slice Start" + " = " + this.nifti.slice_start + "
");
        string += ("Slice End" + " = " + this.nifti.slice_end + "
");
        string += ("Description: \"" + this.nifti.description + "\"
");
        string += ("Auxiliary File: \"" + this.nifti.aux_file + "\"
");
        string += ("Q-Form Code" + " = " + this.nifti.qform_code + " (" + this.nifti.getTransformCodeString(this.nifti.qform_code) + ")
");
        string += ("S-Form Code" + " = " + this.nifti.sform_code + " (" + this.nifti.getTransformCodeString(this.nifti.sform_code) + ")
");
        string += ("Quaternion Parameters:  " +
        "b = " + fmt(this.nifti.quatern_b) + "  " +
        "c = " + fmt(this.nifti.quatern_c) + "  " +
        "d = " + fmt(this.nifti.quatern_d) + "
");

        string += ("Quaternion Offsets:  " +
        "x = " + this.nifti.qoffset_x + "  " +
        "y = " + this.nifti.qoffset_y + "  " +
        "z = " + this.nifti.qoffset_z + "
");

        string += ("S-Form Parameters X: " +
        fmt(this.nifti.affine[0][0]) + ", " +
        fmt(this.nifti.affine[0][1]) + ", " +
        fmt(this.nifti.affine[0][2]) + ", " +
        fmt(this.nifti.affine[0][3]) + "
");

        string += ("S-Form Parameters Y: " +
        fmt(this.nifti.affine[1][0]) + ", " +
        fmt(this.nifti.affine[1][1]) + ", " +
        fmt(this.nifti.affine[1][2]) + ", " +
        fmt(this.nifti.affine[1][3]) + "
");

        string += ("S-Form Parameters Z: " +
        fmt(this.nifti.affine[2][0]) + ", " +
        fmt(this.nifti.affine[2][1]) + ", " +
        fmt(this.nifti.affine[2][2]) + ", " +
        fmt(this.nifti.affine[2][3]) + "
");

        string += ("Slice Code" + " = " + this.nifti.slice_code + "
");
        string += ("Units Code" + " = " + this.nifti.xyzt_units + " (" + this.nifti.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.nifti.xyzt_units) + ", " + this.nifti.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.nifti.xyzt_units) + ")
");
        string += ("Intent Code " + " = " + this.nifti.intent_code + "
");
        string += ("Intent Name: \"" + this.nifti.intent_name + "\"
");

        string += ("Dim Info " + " = " + this.nifti.dim_info + "
");
    } else {
        string += ("Dim Info" + " = " + this.nifti.dim_info + "
");

        string += ("Image Dimensions" + " (1-8): " + this.nifti.dims[0] + ", " + this.nifti.dims[1] + ", " +
        this.nifti.dims[2] + ", " + this.nifti.dims[3] + ", " + this.nifti.dims[4] + ", " + this.nifti.dims[5] + ", " +
        this.nifti.dims[6] + ", " + this.nifti.dims[7] + "
");
        string += ("Intent Parameters" + " (1-3): " + this.nifti.intent_p1 + ", " + this.nifti.intent_p2 + ", " +
            this.nifti.intent_p3) + "
";
        string += ("Intent Code" + " = " + this.nifti.intent_code + "
");
        string += ("Datatype" + " = " + this.nifti.datatypeCode + " (" + this.nifti.getDatatypeCodeString(this.nifti.datatypeCode) + ")
");
        string += ("Bits Per Voxel" + " = " + this.nifti.numBitsPerVoxel + "
");
        string += ("Slice Start" + " = " + this.nifti.slice_start + "
");
        string += ("Voxel Dimensions" + " (1-8): " + fmt(this.nifti.pixDims[0]) + ", " + fmt(this.nifti.pixDims[1]) + ", " +
        fmt(this.nifti.pixDims[2]) + ", " + fmt(this.nifti.pixDims[3]) + ", " + fmt(this.nifti.pixDims[4]) + ", " +
        fmt(this.nifti.pixDims[5]) + ", " + fmt(this.nifti.pixDims[6]) + ", " + fmt(this.nifti.pixDims[7]) + "
");
        string += ("Image Offset" + " = " + this.nifti.vox_offset + "
");
        string += ("Data Scale" + ":  Slope = " + this.nifti.scl_slope + "  Intercept = " + this.nifti.scl_inter + "
");
        string += ("Slice End" + " = " + this.nifti.slice_end + "
");
        string += ("Slice Code" + " = " + this.nifti.slice_code + "
");
        string += ("Units Code" + " = " + this.nifti.xyzt_units + " (" + this.nifti.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.nifti.xyzt_units) + ", " + this.nifti.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.nifti.xyzt_units) + ")
");
        string += ("Display Range" + ":  Max" + " = " + this.nifti.cal_max + "  Min" + " = " + this.nifti.cal_min + "
");
        string += ("Slice Duration" + " = " + this.nifti.slice_duration + "
");
        string += ("Time Axis Shift" + " = " + this.nifti.toffset + "
");
        string += ("Description" + ": \"" + this.nifti.description + "\"
");
        string += ("Auxiliary File" + ": \"" + this.nifti.aux_file + "\"
");
        string += ("Q-Form Code" + " = " + this.nifti.qform_code + " (" + this.nifti.getTransformCodeString(this.nifti.qform_code) + ")
");
        string += ("S-Form Code" + " = " + this.nifti.sform_code + " (" + this.nifti.getTransformCodeString(this.nifti.sform_code) + ")
");
        string += ("Quaternion Parameters" + ":  b" + " = " + fmt(this.nifti.quatern_b) +
        "  c" + " = " +
        fmt(this.nifti.quatern_c) +
        "  d" + " = " + fmt(this.nifti.quatern_d) + "
");
        string += ("Quaternion Offsets" + ":  x" + " = " + this.nifti.qoffset_x + "  y" + " = " +
        this.nifti.qoffset_y + "  z" + " = " +
        this.nifti.qoffset_z + "
");
        string += ("S-Form Parameters X" + ": " + fmt(this.nifti.affine[0][0]) + ", " + fmt(this.nifti.affine[0][1]) + ", " +
        fmt(this.nifti.affine[0][2]) + ", " + fmt(this.nifti.affine[0][3]) + "
");
        string += ("S-Form Parameters Y" + ": " + fmt(this.nifti.affine[1][0]) + ", " + fmt(this.nifti.affine[1][1]) + ", " +
        fmt(this.nifti.affine[1][2]) + ", " + fmt(this.nifti.affine[1][3]) + "
");
        string += ("S-Form Parameters Z" + ": " + fmt(this.nifti.affine[2][0]) + ", " + fmt(this.nifti.affine[2][1]) + ", " +
        fmt(this.nifti.affine[2][2]) + ", " + fmt(this.nifti.affine[2][3]) + "
");
        string += ("Intent Name" + ": \"" + this.nifti.intent_name + "\"
");
    }

    return string;
};


text:
(function(ga, Handlebars) {
	'use strict';
	Handlebars.registerHelper('number', function(n) {
		return ga.formatter.number(n);
	});
	Handlebars.registerHelper('currency', function(n) {
		return ga.formatter.number(n) + ' €';
	});
	Handlebars.registerHelper('financeValue', function(n) {
		if (n === '-' || n === null || n === undefined) {
			return 'nichts vorhanden';
		}
		if (n === '.') {
			return 'unbekannt oder geheimzuhalten';
		}
		return ga.formatter.number(n) + ' €';
	});

	Handlebars.registerHelper('eachProperty', function(context, options) {
		var result = "";
		for ( var key in context) {
			result = result + options.fn({
				'key': key,
				'value': context[key]
			});
		}
		return result;
	});
})(ga, Handlebars);

redpajama_set_name: RedPajamaGithub


text:
import telnetlib
import time
import sys
import getpass
import socket

#define variables for telnet connections
TELNET_PORT = 23
TELNET_TIMEOUT = 6

#create a function that defines the IP address of router, user,pass and connection.

def send_command(remote_conn, cmd):
    cmd = cmd.rstrip()
    remote_conn.write(cmd + '\n')
    time.sleep(1)
    return remote_conn.read_very_eager()

def login(remote_conn, username, password):
    output = remote_conn.read_until("sername:", TELNET_TIMEOUT)
    remote_conn.write(username + '\n')
    output += remote_conn.read_until("ssword:", TELNET_TIMEOUT)
    remote_conn.write(password + '\n')
    return output

def no_paging(remote_conn, paging_cmd='terminal length 0'):
    return send_command(remote_conn, paging_cmd)

def telnet_connect(ip_addr):
    try:
        return telnetlib.Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
    except socket.timeout:
        sys.exit("Connection Timeout-Out")

def main():
    ip_addr = raw_input("Enter IP Address: ")
    ip_addr = ip_addr.strip()
    username = 'pyclass'
    password = getpass.getpass()

    remote_conn = telnet_connect(ip_addr)
    output = login(remote_conn, username, password)
    time.sleep(1)
    remote_conn.read_very_eager()
    no_paging(remote_conn)

    output = send_command(remote_conn, 'show ip int brief')

    print "\n\n"
    print output

    remote_conn.close()

if __name__=="__main__":
    main()


text:
fn f(x:isize) {
    static child: isize = x + 1;
    //~^ ERROR attempt to use a non-constant value in a constant
    //~| ERROR unresolved name `x`
}

fn main() {}


text:
#ifndef SRS_KERNEL_UTILITY_HPP
#define SRS_KERNEL_UTILITY_HPP

/*
#include <srs_kernel_utility.hpp>
*/

#include <srs_core.hpp>

#include <string>

class SrsStream;

// compare
#define srs_min(a, b) (((a) < (b))? (a) : (b))
#define srs_max(a, b) (((a) < (b))? (b) : (a))

// get current system time in ms, use cache to avoid performance problem
extern int64_t srs_get_system_time_ms();
extern int64_t srs_get_system_startup_time_ms();
// the deamon st-thread will update it.
extern int64_t srs_update_system_time_ms();

// dns resolve utility, return the resolved ip address.
extern std::string srs_dns_resolve(std::string host);

// whether system is little endian
extern bool srs_is_little_endian();

// replace old_str to new_str of str
extern std::string srs_string_replace(std::string str, std::string old_str, std::string new_str);
// trim char in trim_chars of str
extern std::string srs_string_trim_end(std::string str, std::string trim_chars);
// trim char in trim_chars of str
extern std::string srs_string_trim_start(std::string str, std::string trim_chars);
// remove char in remove_chars of str
extern std::string srs_string_remove(std::string str, std::string remove_chars);
// whether string end with
extern bool srs_string_ends_with(std::string str, std::string flag);

// create dir recursively
extern int srs_create_dir_recursively(std::string dir);

// whether path exists.
extern bool srs_path_exists(std::string path);

/**
* whether stream starts with the avc NALU in "AnnexB"
* from H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
* start code must be "N[00] 00 00 01" where N>=0
* @param pnb_start_code output the size of start code, must >=3.
*       NULL to ignore.
*/
extern bool srs_avc_startswith_annexb(SrsStream* stream, int* pnb_start_code = NULL);

/**
* whether stream starts with the aac ADTS
* from aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 75, 1.A.2.2 ADTS.
* start code must be '1111 1111 1111'B, that is 0xFFF
*/
extern bool srs_aac_startswith_adts(SrsStream* stream);

/**
* cacl the crc32 of bytes in buf.
*/
extern u_int32_t srs_crc32(const void* buf, int size);

/**
* Decode a base64-encoded string.
*
* @param out      buffer for decoded data
* @param in       null-terminated input string
* @param out_size size in bytes of the out buffer, must be at
*                 least 3/4 of the length of in
* @return         number of bytes written, or a negative value in case of
*                 invalid input
*/
extern int srs_av_base64_decode(u_int8_t* out, const char* in, int out_size);

/**
* Encode data to base64 and null-terminate.
*
* @param out      buffer for encoded data
* @param out_size size in bytes of the out buffer (including the
*                 null terminator), must be at least AV_BASE64_SIZE(in_size)
* @param in       input buffer containing the data to encode
* @param in_size  size in bytes of the in buffer
* @return         out or NULL in case of error
*/
extern char* srs_av_base64_encode(char* out, int out_size, const u_int8_t* in, int in_size);

/**
 * Calculate the output size needed to base64-encode x bytes to a
 * null-terminated string.
 */
#define SRS_AV_BASE64_SIZE(x)  (((x)+2) / 3 * 4 + 1)

/**
* convert hex string to data.
* for example, p=config='139056E5A0'
* output hex to data={0x13, 0x90, 0x56, 0xe5, 0xa0}
*/
extern int ff_hex_to_data(u_int8_t* data, const char* p);

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

    <ViewFlipper
        android:id="@+id/viewFlipper"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_margin="2dp"
        android:background="@color/dark_gray">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/et_position"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginRight="6dp"
                android:layout_weight="1"
                android:gravity="left|center_vertical"
                android:hint="请输入 position"
                android:imeOptions="actionSearch"
                android:inputType="number"
                android:lines="1"
                android:maxLines="1"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:textColor="@color/white"
                android:textColorHint="@color/white"
                android:textSize="16sp" />

            <Button
                android:id="@+id/btn_search"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="8dp"
                android:background="@drawable/shape_round_blue"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:text="跳转"
                android:textColor="@color/white"
                android:textSize="16sp" />
        </LinearLayout>

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">

            <RadioGroup
                android:id="@+id/rg_tab"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="horizontal" />
                android:orientation="horizontal" />
        </HorizontalScrollView>
    </ViewFlipper>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
package edu.snu.csne.csne2543.exceptions;

/**
 * Simple class demonstrating an exception
 *
 * @author Brent Eskridge
 */
public class DivideByZero
{
    public static void main( String[] args )
    {
        divide( 5, 0 );
    }

    public static int divide( int numerator, int denominator )
    {
        int result = 0;

        try
        {
            result = numerator / denominator;
        }
        catch( ArithmeticException ae )
        {
            System.err.println( "Oops!" );
            System.err.println( ae );
            ae.printStackTrace();
        }

        System.out.println( "Done: result=["
                + result
                + "]" );

        return result;
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>UJ XRD Portal</title>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <script type="text/javascript" src="<?php echo base_url('/js/home/home.js'); ?>"></script>

    <script type="text/javascript" src="<?php echo base_url('/js/validator.min.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo base_url('/js/jquery.md5.js'); ?>"></script>

    <link href="<?php echo base_url('/css/home/home.css'); ?>" rel="stylesheet"></link>

</head>
<body>


text:
import { LightningElement, api } from "lwc";

export default class SettingsRowInput extends LightningElement {
    @api title;
    @api description;
    @api inputId;
    @api label; // optional
    @api helpText;
    @api value;
    @api placeholder;
    @api options;
    @api disabled;
    @api type;
    @api variant = "label-hidden";

    // overide label to use title

    handleInputChange(event) {
        let eventDetail = {};
        let typeLowercased = this.type.toLowerCase();

        switch (typeLowercased) {
            case "toggle":
                eventDetail = {
                    // event.detail.value is undefined for a toggle
                    value: event.detail.checked,
                };
                break;

            default:
                eventDetail = {
                    value: event.detail.value,
                };
        }

        const settingsInputChange = new CustomEvent("settingsinputchange", { detail: eventDetail });
        this.dispatchEvent(settingsInputChange);
    }

    @api
    resetValue() {
        let typeLowercased = this.type.toLowerCase();

        switch (typeLowercased) {
            case "toggle":
                this.template.querySelector("lightning-input").checked = this.value;
                break;
            case "text":
                this.template.querySelector("lightning-input").value = this.value;
                break;
            case "combobox":
                this.template.querySelector("lightning-combobox").value = this.value;
                break;
        }
    }

    get checked() {
        if (this.type === "toggle") {
            return this.value;
        }
        return undefined;
    }

    get isCombobox() {
        return this.type === "combobox";
    }

    get isInput() {
        return this.type !== "combobox";
    }

    get comboboxStyling() {
        return "slds-size_3-of-3 ";
    }

    get inputStyling() {
        switch (this.type) {
            case "text":
                return "slds-size_3-of-3 slds-p-bottom_large";

            default:
                return undefined;
        }
    }

    get inputLabel() {
        if (!this.label) {
            return this.title;
        }
        return this.label;
    }
}


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

<title>The GNU C Library: Scanning Directory Content</title>

<meta name="description" content="The GNU C Library: Scanning Directory Content">
<meta name="keywords" content="The GNU C Library: Scanning Directory Content">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Accessing-Directories.html#Accessing-Directories" rel="up" title="Accessing Directories">
<link href="Simple-Directory-Lister-Mark-II.html#Simple-Directory-Lister-Mark-II" rel="next" title="Simple Directory Lister Mark II">
<link href="Random-Access-Directory.html#Random-Access-Directory" rel="prev" title="Random Access Directory">

Next: Simple Directory Lister Mark II, Previous: Random Access Directory, Up: Accessing Directories   [Contents][Index]

14.2.6 Scanning the Content of a Directory

A higher-level interface to the directory handling functions is the
scandir function.  With its help one can select a subset of the
entries in a directory, possibly sort them and get a list of names as
the result.

Function: int scandir (const char *<var>dir</var>, struct dirent ***<var>namelist</var>, int (*<var>selector</var>) (const struct dirent *), int (*<var>cmp</var>) (const struct dirent **, const struct dirent **))

Preliminary:
| MT-Safe
| AS-Unsafe heap
| AC-Unsafe mem fd
| See POSIX Safety Concepts.

The scandir function scans the contents of the directory selected
by <var>dir</var>.  The result in *<var>namelist</var> is an array of pointers to
structure of type struct dirent which describe all selected
directory entries and which is allocated using malloc.  Instead
of always getting all directory entries returned, the user supplied
function <var>selector</var> can be used to decide which entries are in the
result.  Only the entries for which <var>selector</var> returns a non-zero
value are selected.

Finally the entries in *<var>namelist</var> are sorted using the
user-supplied function <var>cmp</var>.  The arguments passed to the <var>cmp</var>
function are of type struct dirent **, therefore one cannot
directly use the strcmp or strcoll functions; instead see
the functions alphasort and versionsort below.

The return value of the function is the number of entries placed in
*<var>namelist</var>.  If it is -1 an error occurred (either the
directory could not be opened for reading or the malloc call failed) and
the global variable errno contains more information on the error.

As described above the fourth argument to the scandir function
must be a pointer to a sorting function.  For the convenience of the
programmer the GNU C Library contains implementations of functions which
are very helpful for this purpose.

Function: int alphasort (const struct dirent **<var>a</var>, const struct dirent **<var>b</var>)

Preliminary:
| MT-Safe locale
| AS-Unsafe heap
| AC-Unsafe mem
| See POSIX Safety Concepts.

The alphasort function behaves like the strcoll function
(see String/Array Comparison).  The difference is that the arguments
are not string pointers but instead they are of type
struct dirent **.

The return value of alphasort is less than, equal to, or greater
than zero depending on the order of the two entries <var>a</var> and <var>b</var>.

Function: int versionsort (const struct dirent **<var>a</var>, const struct dirent **<var>b</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

The versionsort function is like alphasort except that it
uses the strverscmp function internally.

If the filesystem supports large files we cannot use the scandir
anymore since the dirent structure might not able to contain all
the information.  The LFS provides the new type struct dirent64.  To use this we need a new function.

Function: int scandir64 (const char *<var>dir</var>, struct dirent64 ***<var>namelist</var>, int (*<var>selector</var>) (const struct dirent64 *), int (*<var>cmp</var>) (const struct dirent64 **, const struct dirent64 **))

Preliminary:
| MT-Safe
| AS-Unsafe heap
| AC-Unsafe mem fd
| See POSIX Safety Concepts.

The scandir64 function works like the scandir function
except that the directory entries it returns are described by elements
of type struct dirent64.  The function pointed to by
<var>selector</var> is again used to select the desired entries, except that
<var>selector</var> now must point to a function which takes a
struct dirent64 * parameter.

Similarly the <var>cmp</var> function should expect its two arguments to be
of type struct dirent64 **.

As <var>cmp</var> is now a function of a different type, the functions
alphasort and versionsort cannot be supplied for that
argument.  Instead we provide the two replacement functions below.

Function: int alphasort64 (const struct dirent64 **<var>a</var>, const struct dirent **<var>b</var>)

Preliminary:
| MT-Safe locale
| AS-Unsafe heap
| AC-Unsafe mem
| See POSIX Safety Concepts.

The alphasort64 function behaves like the strcoll function
(see String/Array Comparison).  The difference is that the arguments
are not string pointers but instead they are of type
struct dirent64 **.

Return value of alphasort64 is less than, equal to, or greater
than zero depending on the order of the two entries <var>a</var> and <var>b</var>.

Function: int versionsort64 (const struct dirent64 **<var>a</var>, const struct dirent64 **<var>b</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

The versionsort64 function is like alphasort64, excepted that it
uses the strverscmp function internally.

It is important not to mix the use of scandir and the 64-bit
comparison functions or vice versa.  There are systems on which this
works but on others it will fail miserably.

Next: Simple Directory Lister Mark II, Previous: Random Access Directory, Up: Accessing Directories   [Contents][Index]


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NuGetGallery.FunctionTests.Helpers;
using NuGet;
using NuGetGallery.FunctionalTests.TestBase;

namespace NuGetGallery.FunctionalTests
{
    [TestClass]
    public class NuGetCoreTests : GalleryTestBase
    {
        [Description("Downloads a package from the server and validates that the file is present in the local disk"), TestMethod]
        [Priority(0)]
        public void DownloadPackageWithNuGetCoreTest()
        {
            string packageId = Constants.TestPackageId; //try to down load a pre-defined test package.
            AssertAndValidationHelper.DownloadPackageAndVerify(packageId);
        }

    }
}


text:
// -*- Mode: C++; -*-
//                            Package   : omniORB
// poacurrentimpl.h           Created on: 2001/06/01
//                            Author    : Duncan Grisby (dpg1)
//
//    Copyright (C) 2001 AT&T Research Cambridge
//
//    This file is part of the omniORB library.
//
//    The omniORB library is free software; you can redistribute it and/or
//    modify it under the terms of the GNU Library General Public
//    License as published by the Free Software Foundation; either
//    version 2 of the License, or (at your option) any later version.
//
//    This library is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//    Library General Public License for more details.
//
//    You should have received a copy of the GNU Library General Public
//    License along with this library; if not, write to the Free
//    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//    02111-1307, USA
//
//
// Description:
//    Internal implementation of PortableServer::Current
//

/*
  $Log: poacurrentimpl.h,v $
  Revision 1.1.4.2  2006/07/02 22:52:05  dgrisby
  Store self thread in task objects to avoid calls to self(), speeding
  up Current. Other minor performance tweaks.

  Revision 1.1.4.1  2003/03/23 21:03:43  dgrisby
  Start of omniORB 4.1.x development branch.

  Revision 1.1.2.4  2001/08/17 17:12:34  sll
  Modularise ORB configuration parameters.

  Revision 1.1.2.3  2001/08/01 10:08:20  dpg1
  Main thread policy.

  Revision 1.1.2.2  2001/06/11 11:38:17  dpg1
  Failed to initialise refcount in Current object.

  Revision 1.1.2.1  2001/06/07 16:24:09  dpg1
  PortableServer::Current support.

*/

#include <omnithread.h>
#include <omniORB4/callDescriptor.h>
#include <omniCurrent.h>

OMNI_NAMESPACE_BEGIN(omni)

class omniOrbPOACurrent : public PortableServer::Current
{
public:
  omniOrbPOACurrent(CORBA::Boolean is_nil = 0)
    : OMNIORB_BASE_CTOR(PortableServer::)Current(is_nil), pd_refCount(1)
  {}
  virtual ~omniOrbPOACurrent();

  PortableServer::POA_ptr    get_POA();
  PortableServer::ObjectId*  get_object_id();
  CORBA::Object_ptr          get_reference();
  PortableServer::Servant    get_servant();

  static PortableServer::Current_ptr theCurrent();
  // Returns a reference to the POA Current, initialising it if
  // necessary.
  //  This function is thread-safe.
  //  Does not throw any exceptions.

  static omniObjRef*             real_get_reference(omniCallDescriptor*);
  static PortableServer::Servant real_get_servant  (omniCallDescriptor*);
  // Static functions to do the work of get_reference() and
  // get_servant() given a call descriptor. Used by POA functions
  // which don't have access to an omniOrbPOACurrent instance.

  ////////////////////////////
  // Override CORBA::Object //
  ////////////////////////////
  virtual void* _ptrToObjRef(const char* repoId);
  virtual void _NP_incrRefCount();
  virtual void _NP_decrRefCount();

private:
  int pd_refCount;
};

class poaCurrentStackInsert {
public:
  inline poaCurrentStackInsert(omniCallDescriptor* desc,
			       omni_thread* self = 0)
    : pd_dummy(0)
  {
    if (desc && _OMNI_NS(orbParameters)::supportCurrent) {
      if (!self) {
	self = omni_thread::self();

	if (!self) {
	  pd_dummy = 1;
	  self     = omni_thread::create_dummy();
	}
      }
      pd_current = omniCurrent::get(self);
      pd_old_cd  = pd_current->callDescriptor();
      pd_current->setCallDescriptor(desc);
    }
    else
      pd_current = 0;
  }
  inline ~poaCurrentStackInsert()
  {
    if (pd_current) {
      pd_current->setCallDescriptor(pd_old_cd);
      if (pd_dummy)
	omni_thread::release_dummy();
    }
  }
private:
  omniCurrent*        pd_current;
  omniCallDescriptor* pd_old_cd;
  CORBA::Boolean      pd_dummy;
};

OMNI_NAMESPACE_END(omni)


text:
package com.microsoft.azure.management.appservice.implementation;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.GroupableResourcesImpl;
import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter;
import com.microsoft.azure.management.appservice.WebApp;
import com.microsoft.azure.management.appservice.WebApps;
import rx.Completable;

/**
 * The implementation for {@link WebApps}.
 */
@LangDefinition(ContainerName = "/Microsoft.Azure.Management.AppService.Fluent")
class WebAppsImpl
        extends GroupableResourcesImpl<
        WebApp,
        WebAppImpl,
        SiteInner,
        WebAppsInner,
        AppServiceManager>
        implements WebApps {

    private final PagedListConverter<SiteInner, WebApp> converter;
    private final WebSiteManagementClientImpl serviceClient;

    WebAppsImpl(final WebAppsInner innerCollection, AppServiceManager manager, WebSiteManagementClientImpl serviceClient) {
        super(innerCollection, manager);
        this.serviceClient = serviceClient;

        converter = new PagedListConverter<SiteInner, WebApp>() {
            @Override
            public WebApp typeConvert(SiteInner siteInner) {
                siteInner.withSiteConfig(innerCollection.getConfiguration(siteInner.resourceGroup(), siteInner.name()));
                WebAppImpl impl = wrapModel(siteInner);
                return impl.cacheAppSettingsAndConnectionStrings().toBlocking().single();
            }
        };
    }

    @Override
    public PagedList<WebApp> listByGroup(String resourceGroupName) {
        return wrapList(innerCollection.listByResourceGroup(resourceGroupName));
    }

    @Override
    public WebApp getByGroup(String groupName, String name) {
        SiteInner siteInner = innerCollection.get(groupName, name);
        if (siteInner == null) {
            return null;
        }
        siteInner.withSiteConfig(innerCollection.getConfiguration(groupName, name));
        return wrapModel(siteInner).cacheAppSettingsAndConnectionStrings().toBlocking().single();
    }

    @Override
    protected WebAppImpl wrapModel(String name) {
        return new WebAppImpl(name, new SiteInner(), null, innerCollection, super.myManager, serviceClient);
    }

    @Override
    protected WebAppImpl wrapModel(SiteInner inner) {
        if (inner == null) {
            return null;
        }
        SiteConfigInner configInner = inner.siteConfig();
        return new WebAppImpl(inner.name(), inner, configInner, innerCollection, super.myManager, serviceClient);
    }

    protected PagedList<WebApp> wrapList(PagedList<SiteInner> pagedList) {
        return converter.convert(pagedList);
    }

    @Override
    public WebAppImpl define(String name) {
        return wrapModel(name);
    }

    @Override
    public Completable deleteByGroupAsync(String groupName, String name) {
        return innerCollection.deleteAsync(groupName, name).toCompletable();
    }
}


text:
require 'sass-rails'
require 'bourbon'
require "modicon"
require 'coffee-rails'
require 'underscore-rails'
require "haml-rails"
require "redcarpet"

module Showboat
  class Engine < ::Rails::Engine
    isolate_namespace Showboat
  end
end


text:
using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Globalization;
public class servidorRobo : MonoBehaviour {
	private Socket cliente;
	private TcpListener server = new TcpListener(IPAddress.Any, 12598);
	// Use this for initialization
	void Start () {
		server.Start(); // inicia o servidor
	}
	void Update () {
		int tamanho = 0; //tamanho da mensagem recebida
		if (server.Pending()){
			cliente = server.AcceptSocket(); //aceita conexao
			cliente.Blocking = false;
			byte[] mensagem = new byte[1024];
			string strMessage = "";
			while(!strMessage.Contains (";")){
				try{tamanho = cliente.Receive (mensagem);
					strMessage = strMessage +
						System.Text.Encoding.UTF8.GetString(mensagem);
				}catch(System.Exception e){}
			}
			string comando = strMessage.Split (';')[0];
			byte[] envioBuffer = new byte[4];
			envioBuffer[0] = (byte)'a';
			envioBuffer[1] = (byte)'c'; // mensagem a ser enviada ao cliente
			envioBuffer[2] = (byte)'k';
			envioBuffer[3] = 10;
			Servo_Motor_Rotacao [] servos =
				GameObject.FindObjectsOfType<Servo_Motor_Rotacao>();
			if(strMessage.Contains("distancia")){
				Sensor_Infra_Vermelho sensorIV =
					GameObject.FindObjectOfType<Sensor_Infra_Vermelho>();
				float distancia = sensorIV.GetDistancia();
				envioBuffer[0] = (byte)distancia;
				envioBuffer[1] = 10;
			}
			else for(int i = 0; i < servos.Length; i++)
			{
				if(strMessage.Contains("frente")){
					servos[i].velocidade = 150;
					servos[i].direcao_rotacao = 1-i;
				}else if(strMessage.Contains("tras")){
					servos[i].velocidade = 150;
					servos[i].direcao_rotacao = i;
				}else if(strMessage.Contains("direita")){
					servos[i].velocidade = 150;
					servos[i].direcao_rotacao = 0;
				}else if(strMessage.Contains("esquerda")){
					servos[i].velocidade = 150;
					servos[i].direcao_rotacao = 1;
				}else if(strMessage.Contains("parar")){
					servos[i].velocidade = 0;
				}
			}
			cliente.Send(envioBuffer);
		}
	}
}


text:
package main

import (
	"fmt"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestExecPyHelper(t *testing.T) {
	ijson := execPyHelper("test_sum", "", "1", "2")
	s := ijson.(float64)
	if s != 3 {
		t.Error(fmt.Sprintf("unexpected sum %v", s))
	}
}

func TestFileNameWithoutExtension(t *testing.T) {
	f := FileNameWithoutExtension
	assert.Equal(t, f("base.txt"), "base")
	assert.Equal(t, f("s/base.txt"), "base")
	assert.Equal(t, f("s/base.sub.txt"), "base.sub")
	assert.Equal(t, f("/whatever/base.sub..txt"), "base.sub.")
}


text:
avl_node_t*
find_smallest_child(avl_node_t* node)
{
    if (node->left == NULL)
        return node;
    return find_smallest_child(node->left);
}

avl_node_t*
find_biggest_child(avl_node_t* node)
{
    if (node->right == NULL)
        return node;
    return find_biggest_child(node->right);
}

void
avl_free_node(avl_node_t* node)
{
    free(node->data);
    free(node);
}

static void
rec_debug_node(avl_node_t* node, unsigned int level,
               char const* label, display_fcn_t display_fcn)
{
    if (node == NULL)
        return ;
    printf("%s\t", label);
    for (unsigned int i = 0; i <= level; ++i)
        printf("-");
    printf("\theight: %d\tbalance: %d\tdata: ", node->height, avl_balance(node));
    display_fcn(node->data);
    printf("\n");
    rec_debug_node(node->left, level + 1, "LEFT", display_fcn);
    rec_debug_node(node->right, level + 1, "RIGHT", display_fcn);
}

void
avl_debug(avl_node_t* root, display_fcn_t display_fcn)
{
    printf("--- START DEBUG ---\n");
    rec_debug_node(root, 0, "ROOT", display_fcn);
    printf("--- END   DEBUG ---\n");
}


text:
#import "NSObject.h"

@class NSString;

@interface SKUIStoreNotes : NSObject
{
    NSString *_standardNotes;
}

@property(retain, nonatomic) NSString *standardNotes; // @synthesize standardNotes=_standardNotes;
- (void).cxx_destruct;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Huang-Ming Chang's design and research">

    <title>HUANG-MING CHANG</title>

    <link rel="canonical" href="http://hmch17.github.io//design/2013/08/01/archesense-archeboard/">

    <link rel="stylesheet" href=" /css/bootstrap.min.css ">

    <link rel="stylesheet" href=" /css/clean-blog.min.css ">

    <link rel="stylesheet" href=" /css/syntax.css ">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Lato:300,400,700,900&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>

                HUANG-MING CHANG
                UX Researcher / Designer / Engineer

                    Design

                    Research

                    Experience

ArcheSense & ArcheBoard

Eindhoven University of Technology

                    Co-designer

                        Leonid Ivonin

                    Year
                    2013

Emotion

Moodboard

Physiological signals

UX/UI

Research

Adobe Flash AIR

Mobile

In this joint PhD project, we applied the methods in Affective Computing, using physiological signal data as an objective observation for investigating media experience. In the first two years of our PhD project (2011-2012), we conducted several experiences to build reliable computational model of emotions. In the year of 2013, we developed two applications - ArcheSense and ArcheBoard - that can be applied in practice for design and evaluation of media experience.

For more information about the theoretical part and experimental findings about this project, see the research section at here.

Emotion recognition and Visualization

The essense of ArcheSense and ArcheBoard is applications for emotion recognition and visualization. ArcheSense is a mobile application installed on Android tablet (e.g. NEXUS 7) that can be connected Shimmer bio-sensors using bluetooth. With the computational model we gained from our experiment, ArcheSense can be used to recognize users' real-time emotional states.

How ArcheSense and ArcheBoard fit into design practice

While ArcheSense is for detecting emotional states, it requires another applicaiton for visualizing and representing emotional experiences to make the whole concept complete. In the context of user experience design, it has been very challenging for designers to investigate the true experience that users have in mind. While most researchers use qualitative research methods like interview, we took a rather direct approach by using physiological measurement. In order for designers to benefit from information provided by the users' unconscious thoughts, we built ArcheBoard to visualize users' emotional experiences as Mood Boards.

Implementation

Using ArcheSense and ArcheBoard

Traditional mood board is limited to a static visualization, which is difficult to capture the changes of emotions over time. ArcheSense and ArcheBoard supports dynamic visualization in order to rebuild the experience for a specific moment. In order to use these applications, it is necessary to record the experience for reference. This video serves as the timeline of the representation. Next, for composing mood boards, ArcheBoard requires several sets of affective images, depending on the emotions you intend to measure. Finally, ArcheSense needs to be deployed to the user's body to monitor his or her emotional states. Feed all the above data to ArcheBoard and it will render a series of dynamic mood boards along with the timeline.

A walkthrough to set up ArcheBoard

Various Context of Use

ArcheBoard can be used for different purposes. Mood board mode is developed for design inspiration. Thus designers can use ArcheBoard as a tool for generate new mood boards in order to invoke more ideas. Annotation mode is for investigating the changes of user experience over time. Researchers can use ArcheBoard to take notes and look into the quantitative data.

Mood board mode is for design inspirations

Annotation mode is for user experience research.

Demo video of ArcheBoard for a study on an advertisement.

                        Next Project →

Copyright © HUANG-MING CHANG 2017


text:
package com.github.jsonldjava.core;

import java.util.Map;

public class JsonLdError extends Exception {

    Map<String, Object> details;
    private Error type;

    public JsonLdError(Error type, Object detail) {
        // TODO: pretty toString (e.g. print whole json objects)
        super(detail == null ? "" : detail.toString());
        this.type = type;
    }

    public JsonLdError(Error type) {
        super("");
        this.type = type;
    }

    public enum Error {
        LOADING_DOCUMENT_FAILED("loading document failed"), LIST_OF_LISTS("list of lists"), INVALID_INDEX_VALUE(
                "invalid @index value"), CONFLICTING_INDEXES("conflicting indexes"), INVALID_ID_VALUE(
                        "invalid @id value"), INVALID_LOCAL_CONTEXT("invalid local context"), MULTIPLE_CONTEXT_LINK_HEADERS(
                                "multiple context link headers"), LOADING_REMOTE_CONTEXT_FAILED(
                                        "loading remote context failed"), INVALID_REMOTE_CONTEXT("invalid remote context"), RECURSIVE_CONTEXT_INCLUSION(
                                                "recursive context inclusion"), INVALID_BASE_IRI("invalid base IRI"), INVALID_VOCAB_MAPPING(
                                                        "invalid vocab mapping"), INVALID_DEFAULT_LANGUAGE("invalid default language"), KEYWORD_REDEFINITION(
                                                                "keyword redefinition"), INVALID_TERM_DEFINITION("invalid term definition"), INVALID_REVERSE_PROPERTY(
                                                                        "invalid reverse property"), INVALID_IRI_MAPPING("invalid IRI mapping"), CYCLIC_IRI_MAPPING(
                                                                                "cyclic IRI mapping"), INVALID_KEYWORD_ALIAS("invalid keyword alias"), INVALID_TYPE_MAPPING(
                                                                                "invalid type mapping"), INVALID_LANGUAGE_MAPPING("invalid language mapping"), COLLIDING_KEYWORDS(
                                                                                "colliding keywords"), INVALID_CONTAINER_MAPPING("invalid container mapping"), INVALID_TYPE_VALUE(
                                                                                "invalid type value"), INVALID_VALUE_OBJECT("invalid value object"), INVALID_VALUE_OBJECT_VALUE(
                                                                                "invalid value object value"), INVALID_LANGUAGE_TAGGED_STRING(
                                                                                "invalid language-tagged string"), INVALID_LANGUAGE_TAGGED_VALUE(
                                                                                "invalid language-tagged value"), INVALID_TYPED_VALUE("invalid typed value"), INVALID_SET_OR_LIST_OBJECT(
                                                                                "invalid set or list object"), INVALID_LANGUAGE_MAP_VALUE(
                                                                                "invalid language map value"), COMPACTION_TO_LIST_OF_LISTS(
                                                                                "compaction to list of lists"), INVALID_REVERSE_PROPERTY_MAP(
                                                                                "invalid reverse property map"), INVALID_REVERSE_VALUE("invalid @reverse value"), INVALID_REVERSE_PROPERTY_VALUE(
                                                                                "invalid reverse property value"),

                                                                                // non spec related errors
                                                                                SYNTAX_ERROR("syntax error"), NOT_IMPLEMENTED("not implemnted"), UNKNOWN_FORMAT(
                                                                                "unknown format"), INVALID_INPUT("invalid input"), PARSE_ERROR("parse error"), UNKNOWN_ERROR(
                                                                                "unknown error");

        private final String error;

        private Error(String error) {
            this.error = error;
        }

        @Override
        public String toString() {
            return error;
        }
    }

    public JsonLdError setType(Error error) {
        this.type = error;
        return this;
    };

    public Error getType() {
        return type;
    }

    public Map<String, Object> getDetails() {
        return details;
    }

    @Override
    public String getMessage() {
        final String msg = super.getMessage();
        if (msg != null && !"".equals(msg)) {
            return type.toString() + ": " + msg;
        }
        return type.toString();
    }
}


text:
package buildutil_test

import (
	"fmt"
	"go/build"
	"path/filepath"
	"runtime"
	"strings"
	"testing"

	"golang.org/x/tools/go/buildutil"
)

func testContainingPackageCaseFold(file, want string) error {
	bp, err := buildutil.ContainingPackage(&build.Default, ".", file)
	if err != nil {
		return err
	}
	if got := bp.ImportPath; got != want {
		return fmt.Errorf("ContainingPackage(%q) = %s, want %s", file, got, want)
	}
	return nil
}

func TestContainingPackageCaseFold(t *testing.T) {
	path := filepath.Join(runtime.GOROOT(), `src\fmt\print.go`)
	err := testContainingPackageCaseFold(path, "fmt")
	if err != nil {
		t.Error(err)
	}
	vol := filepath.VolumeName(path)
	if len(vol) != 2 || vol[1] != ':' {
		t.Fatalf("GOROOT path has unexpected volume name: %v", vol)
	}
	rest := path[len(vol):]
	err = testContainingPackageCaseFold(strings.ToUpper(vol)+rest, "fmt")
	if err != nil {
		t.Error(err)
	}
	err = testContainingPackageCaseFold(strings.ToLower(vol)+rest, "fmt")
	if err != nil {
		t.Error(err)
	}
}


text:
module Betengineapi
  VERSION = "0.0.1"
end


text:
unless User.find_by(email: 'admin@foo.de')
  user_data = {
    firstname:             'admin',
    lastname:              'root',
    email:                 'admin@foo.de',
    password:              'demo',
    password_confirmation: 'demo',
  }
  User.create(user_data)
end

unless Kind.count > 0
  Kind.create({ name: 'Lebensmittel' })
  Kind.create({ name: 'Wohnung' })
  Kind.create({ name: 'Gehalt' })
  Kind.create({ name: 'Auto' })
end


text:
//
//  GTLStorageObject.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Cloud Storage JSON API (storage/v1)
// Description:
//   Lets you store and retrieve potentially-large, immutable data objects.
// Documentation:
//   https://developers.google.com/storage/docs/json_api/
// Classes:
//   GTLStorageObject (0 custom class methods, 26 custom properties)
//   GTLStorageObjectCustomerEncryption (0 custom class methods, 2 custom properties)
//   GTLStorageObjectMetadata (0 custom class methods, 0 custom properties)
//   GTLStorageObjectOwner (0 custom class methods, 2 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLStorageObjectAccessControl;
@class GTLStorageObjectCustomerEncryption;
@class GTLStorageObjectMetadata;
@class GTLStorageObjectOwner;

// ----------------------------------------------------------------------------
//
//   GTLStorageObject
//

// An object.

@interface GTLStorageObject : GTLObject

// Access controls on the object.
@property (nonatomic, retain) NSArray *acl;  // of GTLStorageObjectAccessControl

// The name of the bucket containing this object.
@property (nonatomic, copy) NSString *bucket;

// Cache-Control directive for the object data.
@property (nonatomic, copy) NSString *cacheControl;

// Number of underlying components that make up this object. Components are
// accumulated by compose operations.
@property (nonatomic, retain) NSNumber *componentCount;  // intValue

// Content-Disposition of the object data.
@property (nonatomic, copy) NSString *contentDisposition;

// Content-Encoding of the object data.
@property (nonatomic, copy) NSString *contentEncoding;

// Content-Language of the object data.
@property (nonatomic, copy) NSString *contentLanguage;

// Content-Type of the object data.
@property (nonatomic, copy) NSString *contentType;

// CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64
// in big-endian byte order. For more information about using the CRC32c
// checksum, see Hashes and ETags: Best Practices.
@property (nonatomic, copy) NSString *crc32c;

// Metadata of customer-supplied encryption key, if the object is encrypted by
// such a key.
@property (nonatomic, retain) GTLStorageObjectCustomerEncryption *customerEncryption;

// HTTP 1.1 Entity tag for the object.
@property (nonatomic, copy) NSString *ETag;

// The content generation of this object. Used for object versioning.
@property (nonatomic, retain) NSNumber *generation;  // longLongValue

// The ID of the object.
// identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
@property (nonatomic, copy) NSString *identifier;

// The kind of item this is. For objects, this is always storage#object.
@property (nonatomic, copy) NSString *kind;

// MD5 hash of the data; encoded using base64. For more information about using
// the MD5 hash, see Hashes and ETags: Best Practices.
@property (nonatomic, copy) NSString *md5Hash;

// Media download link.
@property (nonatomic, copy) NSString *mediaLink;

// User-provided metadata, in key/value pairs.
@property (nonatomic, retain) GTLStorageObjectMetadata *metadata;

// The version of the metadata for this object at this generation. Used for
// preconditions and for detecting changes in metadata. A metageneration number
// is only meaningful in the context of a particular generation of a particular
// object.
@property (nonatomic, retain) NSNumber *metageneration;  // longLongValue

// The name of this object. Required if not specified by URL parameter.
@property (nonatomic, copy) NSString *name;

// The owner of the object. This will always be the uploader of the object.
@property (nonatomic, retain) GTLStorageObjectOwner *owner;

// The link to this object.
@property (nonatomic, copy) NSString *selfLink;

// Content-Length of the data in bytes.
@property (nonatomic, retain) NSNumber *size;  // unsignedLongLongValue

// Storage class of the object.
@property (nonatomic, copy) NSString *storageClass;

// The creation time of the object in RFC 3339 format.
@property (nonatomic, retain) GTLDateTime *timeCreated;

// The deletion time of the object in RFC 3339 format. Will be returned if and
// only if this version of the object has been deleted.
@property (nonatomic, retain) GTLDateTime *timeDeleted;

// The modification time of the object metadata in RFC 3339 format.
@property (nonatomic, retain) GTLDateTime *updated;

@end

// ----------------------------------------------------------------------------
//
//   GTLStorageObjectCustomerEncryption
//

@interface GTLStorageObjectCustomerEncryption : GTLObject

// The encryption algorithm.
@property (nonatomic, copy) NSString *encryptionAlgorithm;

// SHA256 hash value of the encryption key.
@property (nonatomic, copy) NSString *keySha256;

@end

// ----------------------------------------------------------------------------
//
//   GTLStorageObjectMetadata
//

@interface GTLStorageObjectMetadata : GTLObject
// This object is documented as having more properties that are NSString. Use
// -additionalJSONKeys and -additionalPropertyForName: to get the list of
// properties and then fetch them; or -additionalProperties to fetch them all at
// once.
@end

// ----------------------------------------------------------------------------
//
//   GTLStorageObjectOwner
//

@interface GTLStorageObjectOwner : GTLObject

// The entity, in the form user-userId.
@property (nonatomic, copy) NSString *entity;

// The ID for the entity.
@property (nonatomic, copy) NSString *entityId;

@end


text:
namespace Plantr_v2.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class errorValidationForSoulCreate : DbMigration
    {
        public override void Up()
        {
            AlterColumn("dbo.Souls", "FirstName", c => c.String(nullable: false));
            AlterColumn("dbo.Souls", "LastName", c => c.String(nullable: false));
            AlterColumn("dbo.Souls", "Address", c => c.String(nullable: false));
            AlterColumn("dbo.Souls", "City", c => c.String(nullable: false));
        }

        public override void Down()
        {
            AlterColumn("dbo.Souls", "City", c => c.String());
            AlterColumn("dbo.Souls", "Address", c => c.String());
            AlterColumn("dbo.Souls", "LastName", c => c.String());
            AlterColumn("dbo.Souls", "FirstName", c => c.String());
        }
    }
}


text:
package com.evolveum.midpoint.prism;

import com.evolveum.midpoint.util.exception.SchemaException;

/**
 * @author Radovan Semancik
 *
 */
@FunctionalInterface
public interface Revivable {

	void revive(PrismContext prismContext) throws SchemaException;

}


text:
/* $Id$ */

package org.apache.fop.render.ps;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.util.Map;

import org.w3c.dom.Document;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.xmlgraphics.image.loader.ImageException;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.image.loader.ImageProcessingHints;
import org.apache.xmlgraphics.image.loader.ImageSessionContext;
import org.apache.xmlgraphics.ps.PSGenerator;
import org.apache.xmlgraphics.ps.PSResource;

import org.apache.fop.fonts.EmbeddingMode;
import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontTriplet;
import org.apache.fop.fonts.LazyFont;
import org.apache.fop.fonts.MultiByteFont;
import org.apache.fop.fonts.SingleByteFont;
import org.apache.fop.fonts.Typeface;
import org.apache.fop.render.RenderingContext;
import org.apache.fop.render.intermediate.AbstractIFPainter;
import org.apache.fop.render.intermediate.BorderPainter;
import org.apache.fop.render.intermediate.GraphicsPainter;
import org.apache.fop.render.intermediate.IFException;
import org.apache.fop.render.intermediate.IFState;
import org.apache.fop.traits.BorderProps;
import org.apache.fop.traits.RuleStyle;
import org.apache.fop.util.CharUtilities;
import org.apache.fop.util.HexEncoder;

/**
 * IFPainter implementation that produces PostScript.
 */
public class PSPainter extends AbstractIFPainter<PSDocumentHandler> {

    /** logging instance */
    private static Log log = LogFactory.getLog(PSPainter.class);

    private final GraphicsPainter graphicsPainter;

    private BorderPainter borderPainter;

    private boolean inTextMode;

    /**
     * Default constructor.
     * @param documentHandler the parent document handler
     */
    public PSPainter(PSDocumentHandler documentHandler) {
        this(documentHandler, IFState.create());
    }

    protected PSPainter(PSDocumentHandler documentHandler, IFState state) {
        super(documentHandler);
        this.graphicsPainter = new PSGraphicsPainter(getGenerator());
        this.borderPainter = new BorderPainter(graphicsPainter);
        this.state = state;
    }

    private PSGenerator getGenerator() {
        return getDocumentHandler().getGenerator();
    }

    /** {@inheritDoc} */
    public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
            throws IFException {
        try {
            PSGenerator generator = getGenerator();
            saveGraphicsState();
            generator.concatMatrix(toPoints(transform));
        } catch (IOException ioe) {
            throw new IFException("I/O error in startViewport()", ioe);
        }
        if (clipRect != null) {
            clipRect(clipRect);
        }
    }

    /** {@inheritDoc} */
    public void endViewport() throws IFException {
        try {
            restoreGraphicsState();
        } catch (IOException ioe) {
            throw new IFException("I/O error in endViewport()", ioe);
        }
    }

    /** {@inheritDoc} */
    public void startGroup(AffineTransform transform, String layer) throws IFException {
        try {
            PSGenerator generator = getGenerator();
            saveGraphicsState();
            generator.concatMatrix(toPoints(transform));
        } catch (IOException ioe) {
            throw new IFException("I/O error in startGroup()", ioe);
        }
    }

    /** {@inheritDoc} */
    public void endGroup() throws IFException {
        try {
            restoreGraphicsState();
        } catch (IOException ioe) {
            throw new IFException("I/O error in endGroup()", ioe);
        }
    }

    /** {@inheritDoc} */
    protected Map createDefaultImageProcessingHints(ImageSessionContext sessionContext) {
        Map hints = super.createDefaultImageProcessingHints(sessionContext);

        //PostScript doesn't support alpha channels
        hints.put(ImageProcessingHints.TRANSPARENCY_INTENT,
                ImageProcessingHints.TRANSPARENCY_INTENT_IGNORE);
        //TODO We might want to support image masks in the future.
        return hints;
    }

    /** {@inheritDoc} */
    protected RenderingContext createRenderingContext() {
        PSRenderingContext psContext = new PSRenderingContext(
                getUserAgent(), getGenerator(), getFontInfo());
        return psContext;
    }

    /** {@inheritDoc} */
    protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect)
            throws ImageException, IOException {
        if (!getDocumentHandler().getPSUtil().isOptimizeResources()
                || PSImageUtils.isImageInlined(info,
                        (PSRenderingContext)createRenderingContext())) {
            super.drawImageUsingImageHandler(info, rect);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Image " + info + " is embedded as a form later");
            }
            //Don't load image at this time, just put a form placeholder in the stream
            PSResource form = getDocumentHandler().getFormForImage(info.getOriginalURI());
            PSImageUtils.drawForm(form, info, rect, getGenerator());
        }
    }

    /** {@inheritDoc} */
    public void drawImage(String uri, Rectangle rect) throws IFException {
        try {
            endTextObject();
        } catch (IOException ioe) {
            throw new IFException("I/O error in drawImage()", ioe);
        }
        drawImageUsingURI(uri, rect);
    }

    /** {@inheritDoc} */
    public void drawImage(Document doc, Rectangle rect) throws IFException {
        try {
            endTextObject();
        } catch (IOException ioe) {
            throw new IFException("I/O error in drawImage()", ioe);
        }
        drawImageUsingDocument(doc, rect);
    }

    /** {@inheritDoc} */
    public void clipRect(Rectangle rect) throws IFException {
        try {
            PSGenerator generator = getGenerator();
            endTextObject();
            generator.defineRect(rect.x / 1000.0, rect.y / 1000.0,
                    rect.width / 1000.0, rect.height / 1000.0);
            generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath"));
        } catch (IOException ioe) {
            throw new IFException("I/O error in clipRect()", ioe);
        }
    }

    /** {@inheritDoc} */
    public void clipBackground(Rectangle rect,
            BorderProps bpsBefore, BorderProps bpsAfter,
            BorderProps bpsStart, BorderProps bpsEnd) throws IFException {

        try {
            borderPainter.clipBackground(rect,
                    bpsBefore,  bpsAfter, bpsStart,  bpsEnd);
        } catch (IOException ioe) {
            throw new IFException("I/O error while clipping background", ioe);
        }

    }

    /** {@inheritDoc} */
    public void fillRect(Rectangle rect, Paint fill) throws IFException {
        if (fill == null) {
            return;
        }
        if (rect.width != 0 && rect.height != 0) {
            try {
                endTextObject();
                PSGenerator generator = getGenerator();
                if (fill != null) {
                    if (fill instanceof Color) {
                        generator.useColor((Color)fill);
                    } else {
                        throw new UnsupportedOperationException("Non-Color paints NYI");
                    }
                }
                generator.defineRect(rect.x / 1000.0, rect.y / 1000.0,
                        rect.width / 1000.0, rect.height / 1000.0);
                generator.writeln(generator.mapCommand("fill"));
            } catch (IOException ioe) {
                throw new IFException("I/O error in fillRect()", ioe);
            }
        }
    }

    /** {@inheritDoc} */
    public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom,
            BorderProps left, BorderProps right, Color innerBackgroundColor) throws IFException {
        if (top != null || bottom != null || left != null || right != null) {
            try {
                endTextObject();
                if (getDocumentHandler().getPSUtil().getRenderingMode() == PSRenderingMode.SIZE
                    && hasOnlySolidBorders(top, bottom, left, right)) {
                    super.drawBorderRect(rect, top, bottom, left, right, innerBackgroundColor);
                } else {
                    this.borderPainter.drawBorders(rect, top, bottom, left, right, innerBackgroundColor);
                }
            } catch (IOException ioe) {
                throw new IFException("I/O error in drawBorderRect()", ioe);
            }
        }
    }

    /** {@inheritDoc} */
    public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
                throws IFException {
        try {
            endTextObject();
            this.graphicsPainter.drawLine(start, end, width, color, style);
        } catch (IOException ioe) {
            throw new IFException("I/O error in drawLine()", ioe);
        }
    }

    private Typeface getTypeface(String fontName) {
        if (fontName == null) {
            throw new NullPointerException("fontName must not be null");
        }
        Typeface tf = getFontInfo().getFonts().get(fontName);
        if (tf instanceof LazyFont) {
            tf = ((LazyFont)tf).getRealFont();
        }
        return tf;
    }

    /**
     * Saves the graphics state of the rendering engine.
     * @throws IOException if an I/O error occurs
     */
    protected void saveGraphicsState() throws IOException {
        endTextObject();
        getGenerator().saveGraphicsState();
    }

    /**
     * Restores the last graphics state of the rendering engine.
     * @throws IOException if an I/O error occurs
     */
    protected void restoreGraphicsState() throws IOException {
        endTextObject();
        getGenerator().restoreGraphicsState();
    }

    /**
     * Indicates the beginning of a text object.
     * @throws IOException if an I/O error occurs
     */
    protected void beginTextObject() throws IOException {
        if (!inTextMode) {
            PSGenerator generator = getGenerator();
            generator.saveGraphicsState();
            generator.writeln("BT");
            inTextMode = true;
        }
    }

    /**
     * Indicates the end of a text object.
     * @throws IOException if an I/O error occurs
     */
    protected void endTextObject() throws IOException {
        if (inTextMode) {
            inTextMode = false;
            PSGenerator generator = getGenerator();
            generator.writeln("ET");
            generator.restoreGraphicsState();
        }
    }

    private String formatMptAsPt(PSGenerator gen, int value) {
        return gen.formatDouble(value / 1000.0);
    }

    /* Disabled: performance experiment (incomplete)

    private static final String ZEROS = "0.00";

    private String formatMptAsPt1(int value) {
        String s = Integer.toString(value);
        int len = s.length();
        StringBuffer sb = new StringBuffer();
        if (len < 4) {
            sb.append(ZEROS.substring(0, 5 - len));
            sb.append(s);
        } else {
            int dec = len - 3;
            sb.append(s.substring(0, dec));
            sb.append('.');
            sb.append(s.substring(dec));
        }
        return sb.toString();
    }*/

    /** {@inheritDoc} */
    public void drawText(int x, int y, int letterSpacing, int wordSpacing,
            int[][] dp, String text) throws IFException {
        try {
            //Do not draw text if font-size is 0 as it creates an invalid PostScript file
            if (state.getFontSize() == 0) {
                return;
            }
            PSGenerator generator = getGenerator();
            generator.useColor(state.getTextColor());
            beginTextObject();
            FontTriplet triplet = new FontTriplet(
                    state.getFontFamily(), state.getFontStyle(), state.getFontWeight());
            //TODO Ignored: state.getFontVariant()
            //TODO Opportunity for font caching if font state is more heavily used
            String fontKey = getFontKey(triplet);
            int sizeMillipoints = state.getFontSize();

            // This assumes that *all* CIDFonts use a /ToUnicode mapping
            Typeface tf = getTypeface(fontKey);
            SingleByteFont singleByteFont = null;
            if (tf instanceof SingleByteFont) {
                singleByteFont = (SingleByteFont)tf;
            }
            Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints);

            PSFontResource res = getDocumentHandler().getPSResourceForFontKey(fontKey);
            boolean otf = tf instanceof MultiByteFont && ((MultiByteFont)tf).isOTFFile();
            useFont(fontKey, sizeMillipoints, otf);

            if (dp != null && dp[0] != null) {
                x += dp[0][0];
                y -= dp[0][1];
            }
            generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x)
                    + " " + formatMptAsPt(generator, y) + " Tm");

            int textLen = text.length();
            int start = 0;
            if (singleByteFont != null) {
                //Analyze string and split up in order to paint in different sub-fonts/encodings
                int currentEncoding = -1;
                for (int i = 0; i < textLen; i++) {
                    char c = text.charAt(i);
                    char mapped = tf.mapChar(c);
                    int encoding = mapped / 256;
                    if (currentEncoding != encoding) {
                        if (i > 0) {
                            writeText(text, start, i - start,
                                    letterSpacing, wordSpacing, dp, font, tf, false);
                        }
                        if (encoding == 0) {
                            useFont(fontKey, sizeMillipoints, false);
                        } else {
                            useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints, false);
                        }
                        currentEncoding = encoding;
                        start = i;
                    }
                }
            } else {
                if (tf instanceof MultiByteFont && ((MultiByteFont)tf).isOTFFile()) {
                    //Analyze string and split up in order to paint in different sub-fonts/encodings
                    int curEncoding = 0;
                    for (int i = start; i < textLen; i++) {
                        char orgChar = text.charAt(i);

                        MultiByteFont mbFont = (MultiByteFont)tf;
                        mbFont.mapChar(orgChar);
                        int origGlyphIdx = mbFont.findGlyphIndex(orgChar);
                        int newGlyphIdx = mbFont.getUsedGlyphs().get(origGlyphIdx);
                        int encoding = newGlyphIdx / 256;
                        if (encoding != curEncoding) {
                            if (i != 0) {
                                writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf,
                                        true);
                                start = i;
                            }
                            generator.writeln("/" + res.getName() + "." + encoding + " "
                                    + generator.formatDouble(sizeMillipoints / 1000f) + " F");
                            curEncoding = encoding;
                        }
                    }
                } else {
                    useFont(fontKey, sizeMillipoints, false);
                }
            }
            writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf,
                    tf instanceof MultiByteFont);
        } catch (IOException ioe) {
            throw new IFException("I/O error in drawText()", ioe);
        }
    }

    private void writeText(String text, int start, int len,
            int letterSpacing, int wordSpacing, int[][] dp,
            Font font, Typeface tf, boolean multiByte) throws IOException {
        PSGenerator generator = getGenerator();
        int end = start + len;
        int initialSize = len;
        initialSize += initialSize / 2;

        boolean hasLetterSpacing = (letterSpacing != 0);
        boolean needTJ = false;

        int lineStart = 0;
        StringBuffer accText = new StringBuffer(initialSize);
        StringBuffer sb = new StringBuffer(initialSize);
        boolean isOTF = multiByte && ((MultiByteFont)tf).isOTFFile();
        for (int i = start; i < end; i++) {
            char orgChar = text.charAt(i);
            char ch;
            int cw;
            int xGlyphAdjust = 0;
            int yGlyphAdjust = 0;

            if (CharUtilities.isFixedWidthSpace(orgChar)) {
                //Fixed width space are rendered as spaces so copy/paste works in a reader
                ch = font.mapChar(CharUtilities.SPACE);
                cw = font.getCharWidth(orgChar);
                xGlyphAdjust = font.getCharWidth(ch) - cw;
            } else {
                if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
                    xGlyphAdjust -= wordSpacing;
                }
                ch = font.mapChar(orgChar);
                cw = font.getCharWidth(orgChar); // this is never used?
            }

            if (dp != null && i < dp.length && dp[i] != null) {
                // get x advancement adjust
                xGlyphAdjust -= dp[i][2] - dp[i][0];
                yGlyphAdjust += dp[i][3] - dp[i][1];
            }
            if (dp != null && i < dp.length - 1 && dp[i + 1] != null) {
                // get x placement adjust for next glyph
                xGlyphAdjust -= dp[i + 1][0];
                yGlyphAdjust += dp[i + 1][1];
            }
            if (!multiByte || isOTF) {
                char codepoint = (char)(ch % 256);
                if (isOTF) {
                    codepoint -= (((MultiByteFont)tf).getEmbeddingMode() == EmbeddingMode.FULL) ? 0 : 1;
                    accText.append(HexEncoder.encode(codepoint, 2));
                } else {
                    PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text
                }
            } else {
                accText.append(HexEncoder.encode(ch));
            }
            if (xGlyphAdjust != 0 || yGlyphAdjust != 0) {
                needTJ = true;
                if (sb.length() == 0) {
                    sb.append('['); //Need to start TJ
                }
                if (accText.length() > 0) {
                    if ((sb.length() - lineStart + accText.length()) > 200) {
                        sb.append(PSGenerator.LF);
                        lineStart = sb.length();
                    }
                    lineStart = writePostScriptString(sb, accText, multiByte, lineStart);
                    sb.append(' ');
                    accText.setLength(0); //reset accumulated text
                }
                if (yGlyphAdjust == 0) {
                    sb.append(Integer.toString(xGlyphAdjust)).append(' ');
                } else {
                    sb.append('[');
                    sb.append(Integer.toString(yGlyphAdjust)).append(' ');
                    sb.append(Integer.toString(xGlyphAdjust)).append(']').append(' ');
                }
            }
        }
        if (needTJ) {
            if (accText.length() > 0) {
                if ((sb.length() - lineStart + accText.length()) > 200) {
                    sb.append(PSGenerator.LF);
                }
                writePostScriptString(sb, accText, multiByte);
            }
            if (hasLetterSpacing) {
                sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ");
            } else {
                sb.append("] TJ");
            }
        } else {
            writePostScriptString(sb, accText, multiByte);
            if (hasLetterSpacing) {
                StringBuffer spb = new StringBuffer();
                spb.append(formatMptAsPt(generator, letterSpacing))
                    .append(" 0 ");
                sb.insert(0, spb.toString());
                sb.append(" " + generator.mapCommand("ashow"));
            } else {
                sb.append(" " + generator.mapCommand("show"));
            }
        }
        generator.writeln(sb.toString());
    }

    private void writePostScriptString(StringBuffer buffer, StringBuffer string,
            boolean multiByte) {
        writePostScriptString(buffer, string, multiByte, 0);
    }

    private int writePostScriptString(StringBuffer buffer, StringBuffer string, boolean multiByte,
            int lineStart) {
        buffer.append(multiByte ? '<' : '(');
        int l = string.length();
        int index = 0;
        int maxCol = 200;
        buffer.append(string.substring(index, Math.min(index + maxCol, l)));
        index += maxCol;
        while (index < l) {
            if (!multiByte) {
                buffer.append('\\');
            }
            buffer.append(PSGenerator.LF);
            lineStart = buffer.length();
            buffer.append(string.substring(index, Math.min(index + maxCol, l)));
            index += maxCol;
        }
        buffer.append(multiByte ? '>' : ')');
        return lineStart;
    }

    private void useFont(String key, int size, boolean otf) throws IOException {
        PSFontResource res = getDocumentHandler().getPSResourceForFontKey(key);
        PSGenerator generator = getGenerator();
        if (otf) {
            String name = "/" + res.getName() + ".0";
            generator.getCurrentState().useFont(name, size);
            generator.writeln(name + ' ' + generator.formatDouble(size / 1000f) + " F");
        } else {
            generator.useFont("/" + res.getName(), size / 1000f);
        }
        res.notifyResourceUsageOnPage(generator.getResourceTracker());
    }
}


text:
@implementation SSUISingleImagePickerPreviewViewController {
  SSUIButton *_confirmButton;
}
@dynamic delegate;

- (void)initSubviews {
  [super initSubviews];
  _confirmButton = [[SSUIButton alloc] init];
  _confirmButton.outsideEdge = UIEdgeInsetsMake(-6, -6, -6, -6);
  [_confirmButton setTitleColor:self.toolBarTintColor forState:UIControlStateNormal];
  [_confirmButton setTitle:@"使用" forState:UIControlStateNormal];
  [_confirmButton addTarget:self action:@selector(handleConfirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
  [_confirmButton sizeToFit];
  [self.topToolBarView addSubview:_confirmButton];
}

- (void)setDownloadStatus:(SSUIAssetDownloadStatus)downloadStatus {
  [super setDownloadStatus:downloadStatus];
  switch (downloadStatus) {
    case SSUIAssetDownloadStatusSucceed:
      _confirmButton.hidden = NO;
      break;

    case SSUIAssetDownloadStatusDownloading:
      _confirmButton.hidden = YES;
      break;

    case SSUIAssetDownloadStatusCanceled:
      _confirmButton.hidden = NO;
      break;

    case SSUIAssetDownloadStatusFailed:
      _confirmButton.hidden = YES;
      break;

    default:
      break;
  }
}

- (void)viewDidLoad {
  [super viewDidLoad];
}

- (void)viewDidLayoutSubviews {
  [super viewDidLayoutSubviews];
  _confirmButton.frame = CGRectSetXY(_confirmButton.frame,
                                     CGRectGetWidth(self.topToolBarView.frame) - CGRectGetWidth(_confirmButton.frame) - 10,
                                     CGRectGetMinY(self.backButton.frame) + CGFloatGetCenter(CGRectGetHeight(self.backButton.frame),
                                                                                CGRectGetHeight(_confirmButton.frame)));
}

- (void)handleConfirmButtonClick:(id)sender {
  [self.navigationController dismissViewControllerAnimated:YES completion:^(void) {
    if (self.delegate && [self.delegate respondsToSelector:@selector(imagePickerPreviewViewController:didSelectImageWithImagesAsset:)]) {
      SSUIAsset *imageAsset = [self.imagesAssetArray objectAtIndex:self.imagePreviewView.currentImageIndex];
      [self.delegate imagePickerPreviewViewController:self didSelectImageWithImagesAsset:imageAsset];
    }
  }];
}
@end


text:
package org.fusesource.hawtdb.util.list;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Provides a list of LinkedNode objects.
 *
 * @author Hiram Chirino
 */
public class LinkedNodeList<T extends LinkedNode<T>> implements Iterable<T> {

    protected volatile T head;
    protected volatile int size;

    public LinkedNodeList() {
    }

    public boolean isEmpty() {
        return head == null;
    }

    public void addLast(T node) {
        node.linkToTail(this);
    }

    public void addFirst(T node) {
        node.linkToHead(this);
    }

    public T getHead() {
        return head;
    }

    public T getTail() {
        if( head==null ) {
            return null;
        }
        return head.prev;
    }

    public void clear() {
        while (head != null) {
            head.unlink();
        }
    }

    public void addLast(LinkedNodeList<T> list) {
        if (list.isEmpty()) {
            return;
        }
        if (head == null) {
            head = list.head;
            reparent(list);
        } else {
            getTail().linkAfter(list);
        }
    }

    public void addFirst(LinkedNodeList<T> list) {
        if (list.isEmpty()) {
            return;
        }
        if (head == null) {
            reparent(list);
            head = list.head;
            list.head = null;
        } else {
            getHead().linkBefore(list);
        }
    }

    public T reparent(LinkedNodeList<T> list) {
        size += list.size;
        T n = list.head;
        do {
            n.list = this;
            n = n.next;
        } while (n != list.head);
        list.head = null;
        list.size = 0;
        return n;
    }

    /**
     * Move the head to the tail and returns the new head node.
     *
     * @return
     */
    public T rotate() {
    	if( head ==null )
    		return null;
        return head = head.getNextCircular();
    }

    /**
     * Move the head to the tail and returns the new head node.
     *
     * @return
     */
    public void rotateTo(T head) {
    	assert head!=null: "Cannot rotate to a null head";
    	assert head.list == this : "Cannot rotate to a node not linked to this list";
        this.head = head;
    }

    public int size() {
        return size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        boolean first=true;
        T cur = getHead();
        while( cur!=null ) {
            if( !first ) {
                sb.append(", ");
            }
            sb.append(cur);
            first=false;
            cur = cur.getNext();
        }
        sb.append("]");
        return sb.toString();
    }

    /**
     * Copies the nodes of the LinkedNodeList to an ArrayList.
     * @return
     */
    public ArrayList<T> toArrayList() {
    	ArrayList<T> rc = new ArrayList<T>(size);
    	T cur = head;
    	while( cur!=null ) {
    		rc.add(cur);
    		cur = cur.getNext();
    	}
    	return rc;
    }

    /**
     * Copies the nodes of the LinkedNodeList to the specified array.
     * @return the passed array.
     */
    public T[] toArray(T[] array) {
        int pos = 0;
    	ArrayList<T> rc = new ArrayList<T>(size);
    	T cur = head;
    	while( cur!=null ) {
    		array[pos] = cur;
            pos ++;
    		cur = cur.getNext();
    	}
        return array;
    }

    /**
     * Copies the nodes of the LinkedNodeList to an ArrayList in reverse order.
     * @return
     */
    public ArrayList<T> toArrayListReversed() {
        ArrayList<T> rc = new ArrayList<T>(size);
        if( head != null ) {
            T cur = getTail();;
            while( cur!=null ) {
                rc.add(cur);
                cur = cur.getPrevious();
            }
        }
        return rc;
    }

    public Iterator<T> iterator() {
        return new Iterator<T>() {
            T next = getHead();
            private T last;

            public boolean hasNext() {
                return next!=null;
            }

            public T next() {
                last = next;
                next = last.getNext();
                return last;
            }

            public void remove() {
                if( last==null ) {
                    throw new IllegalStateException();
                }
                last.unlink();
                last=null;
            }
        };
    }
}


text:
@implementation CUStop

@synthesize stopID, stopName, code, coordinate;
@synthesize score;

- (id)initWithDictionary:(id)dic {
	if (self = [super init]) {
		self.stopID = [dic objectForKey:@"stop_id"];
		self.stopName = [dic objectForKey:@"stop_name"];
		self.code = [dic objectForKey:@"code"];
		NSArray *points = [dic objectForKey:@"stop_points"];
		if ([points count] > 0) {
			NSDictionary *point = [points objectAtIndex:0];
			coordinate.latitude = [[point objectForKey:@"stop_lat"] doubleValue];
			coordinate.longitude = [[point objectForKey:@"stop_lon"] doubleValue];
		}
	}
	return self;
}

- (id)dictionary {
	NSMutableDictionary *dic = [NSMutableDictionary dictionary];
	if (stopID)
		[dic setObject:stopID forKey:@"stop_id"];
	if (stopName)
		[dic setObject:stopName forKey:@"stop_name"];
	if (code)
		[dic setObject:code forKey:@"code"];
	NSDictionary *point = [NSDictionary dictionaryWithObjectsAndKeys:
						   [NSNumber numberWithDouble:coordinate.latitude], @"stop_lat",
						   [NSNumber numberWithDouble:coordinate.longitude], @"stop_lon",
						   nil];
	[dic setObject:[NSArray arrayWithObject:point] forKey:@"stop_points"];
	return dic;
}

- (NSString*)title {
	return stopName;
}

- (NSString*)subtitle {
	return code;
}

- (void)dealloc {
	[stopID release];
	[stopName release];
	[code release];
	[super dealloc];
}

@end