text:
package clui

import (
	term "github.com/nsf/termbox-go"
)

// ThumbPosition returns a scrollbar thumb position depending
// on currently active item(itemNo), total number of items
// (itemCount), and length/height of the scrollbar(length)
// including arrows. Returns position in interval of (1..lenght-2)
// or -1 if the thumb is not visible
func ThumbPosition(itemNo, itemCount, length int) int {
	length -= 2
	if itemNo < 0 {
		return -1
	}
	if itemNo >= itemCount-1 {
		return length - 1
	}

	if length < 4 {
		return 0
	}

	ydiff := int(float32(itemNo) / float32(itemCount-1.0) * float32(length-1))
	return ydiff
}

// ItemByThumbPosition calculates item number by scrollbar
// thumb position. Position - thumb position inside scrollbar,
// itemCount - total number of items, lenght - lenght or heigth
// of scrollbar. Return -1 if it is not possible to calculate:
// e.g, itemCount equals zero
func ItemByThumbPosition(position, itemCount, length int) int {
	length -= 2
	if position < 1 {
		return -1
	}
	if itemCount < 1 {
		return -1
	}
	if itemCount == 1 {
		return 0
	}

	newPos := int(float32(itemCount-1)*float32(position-1)/float32(length-1) + 0.9)

	if newPos < 0 {
		newPos = 0
	} else if newPos >= itemCount {
		newPos = itemCount - 1
	}

	return newPos
}

// ChildAt returns the children of parent control that is at absolute
// coordinates x, y. Returns nil if x, y are outside parent control and
// returns parent if no child is at x, y
func ChildAt(parent Control, x, y int) Control {
	px, py := parent.Pos()
	pw, ph := parent.Size()
	if px > x || py > y || px+pw <= x || py+ph <= y {
		return nil
	}

	if len(parent.Children()) == 0 {
		return parent
	}

	var ctrl Control
	ctrl = parent
	for _, child := range parent.Children() {
		if !child.Visible() {
			continue
		}

		check := ChildAt(child, x, y)
		if check != nil {
			ctrl = check
			break
		}
	}

	return ctrl
}

// DeactivateControls makes all children of parent inactive
func DeactivateControls(parent Control) {
	for _, ctrl := range parent.Children() {
		if ctrl.Active() {
			ctrl.SetActive(false)
			ctrl.ProcessEvent(Event{Type: EventActivate, X: 0})
		}

		DeactivateControls(ctrl)
	}
}

// ActivateControl makes control active and disables all other children of
// the parent. Returns true if control was found and activated
func ActivateControl(parent, control Control) bool {
	DeactivateControls(parent)
	res := false
	ctrl := FindChild(parent, control)
	if ctrl != nil {
		res = true
		if !ctrl.Active() {
			ctrl.ProcessEvent(Event{Type: EventActivate, X: 1})
			ctrl.SetActive(true)
		}
	}

	return res
}

// FindChild returns control if it is a child of the parent and nil otherwise
func FindChild(parent, control Control) Control {
	var res Control

	if parent == control {
		return parent
	}

	for _, ctrl := range parent.Children() {
		if ctrl == control {
			res = ctrl
			break
		}

		res = FindChild(ctrl, control)
		if res != nil {
			break
		}
	}

	return res
}

// IsMouseClickEvent returns if a user action can be treated as mouse click.
func IsMouseClickEvent(ev Event) bool {
	if ev.Type == EventClick {
		return true
	}
	if ev.Type == EventMouse && ev.Key == term.MouseLeft {
		return true
	}

	return false
}

// FindFirstControl returns the first child for that fn returns true.
// The function is used to find active or tab-stop control
func FindFirstControl(parent Control, fn func(Control) bool) Control {
	linear := getLinearControlList(parent, fn)
	if len(linear) == 0 {
		return nil
	}

	return linear[0]
}

// FindLastControl returns the first child for that fn returns true.
// The function is used by TAB processing method if a user goes backwards
// with TAB key - not supported now
func FindLastControl(parent Control, fn func(Control) bool) Control {
	linear := getLinearControlList(parent, fn)

	if len(linear) == 0 {
		return nil
	}

	return linear[len(linear)-1]
}

// ActiveControl returns the active child of the parent or nil if no child is
// active
func ActiveControl(parent Control) Control {
	fnActive := func(c Control) bool {
		return c.Active()
	}
	return FindFirstControl(parent, fnActive)
}

// FindFirstActiveControl returns the first active control of a parent
func FindFirstActiveControl(parent Control) Control {
	for _, curr := range getLinearControlList(parent, nil) {
		if curr.Active() {
			return curr
		}
	}
	return nil
}

func getLinearControlList(parent Control, fn func(Control) bool) []Control {
	result := []Control{}

	for _, curr := range parent.Children() {
		if fn != nil && fn(curr) {
			result = append(result, curr)
		}

		if len(curr.Children()) == 0 {
			continue
		}

		ch := getLinearControlList(curr, fn)
		if len(ch) != 0 {
			result = append(result, ch...)
		}
	}

	return result
}

// NextControl returns the next or previous child (depends on next parameter)
// that has tab-stop feature on. Used by library when processing TAB key
func NextControl(parent Control, curr Control, next bool) Control {
	fnTab := func(c Control) bool {
		isVisible := func() bool {
			ctrl := c.Parent()

			for ctrl != nil {
				if !ctrl.Visible() {
					return false
				}

				ctrl = ctrl.Parent()
			}

			return c.Visible()
		}

		return c.TabStop() && isVisible() && c.Enabled()
	}

	linear := getLinearControlList(parent, fnTab)

	if len(linear) == 0 {
		return nil
	}

	var pIndex, nIndex int

	for i, ch := range linear {
		if ch != curr {
			continue
		}

		pIndex = i - 1
		nIndex = i + 1
		break
	}

	if nIndex > len(linear)-1 {
		nIndex = 0
	}

	if pIndex < 0 {
		pIndex = len(linear) - 1
	}

	if next {
		return linear[nIndex]
	} else {
		return linear[pIndex]
	}
}

// SendEventToChild tries to find a child control that should recieve the evetn
// For mouse click events it looks for a control at coordinates of event,
// makes it active, and then sends the event to it.
// If it is not mouse click event then it looks for the first active child and
// sends the event to it if it is not nil
func SendEventToChild(parent Control, ev Event) bool {
	var child Control
	if IsMouseClickEvent(ev) {
		child = ChildAt(parent, ev.X, ev.Y)
		if child != nil && !child.Active() {
			ActivateControl(parent, child)
		}
	} else {
		child = ActiveControl(parent)
	}

	if child != nil && child != parent {
		ev.Target = child
		res := child.ProcessEvent(ev)

		if cparent := ClippedParent(child); cparent != nil && cparent != child {
			cparent.ProcessEvent(ev)
		}

		return res
	}

	return false
}

// CalcClipper calculates the clipper size based on the control's size, position
// and paddings
func CalcClipper(c Control) (int, int, int, int) {
	w, h := c.Size()
	x, y := c.Pos()
	px, py := c.Paddings()

	x = x + px
	y = y + py
	w = w - 2*px
	h = h - 2*py

	return x, y, w, h
}

// ClippedParent finds the first c parent with clipped flag
func ClippedParent(c Control) Control {
	var clipped Control

	ctrl := c.Parent()
	clipped = c

	for ctrl != nil {
		if ctrl.Clipped() {
			clipped = ctrl
			break
		}

		ctrl = ctrl.Parent()
	}

	return clipped
}

// ControlInRect returns true if c is within a given rect
func ControlInRect(c Control, x int, y int, w int, h int) bool {
	xx, yy := c.Pos()
	ww, hh := c.Size()

	return xx >= x && ww <= x+w && yy <= y+h &&
		yy+hh <= y+h && yy >= y && yy+h >= y
}


text:
import * as tf from '@tensorflow/tfjs-core';

import {BodyPixInput, BodyPixOutputStride, Padding} from './types';
import {Pose, TensorBuffer3D} from './types';
import {BodyPixInternalResolution} from './types';

function getSizeFromImageLikeElement(input: HTMLImageElement|
                                     HTMLCanvasElement|
                                     OffscreenCanvas): [number, number] {
  if ('offsetHeight' in input && input.offsetHeight !== 0
      && 'offsetWidth' in input && input.offsetWidth !== 0) {
    return [input.offsetHeight, input.offsetWidth];
  } else if (input.height != null && input.width != null) {
    return [input.height, input.width];
  } else {
    throw new Error(
        `HTMLImageElement must have height and width attributes set.`);
  }
}

function getSizeFromVideoElement(input: HTMLVideoElement): [number, number] {
  if (input.hasAttribute('height') && input.hasAttribute('width')) {
    // Prioritizes user specified height and width.
    // We can't test the .height and .width properties directly,
    // because they evaluate to 0 if unset.
    return [input.height, input.width];
  } else {
    return [input.videoHeight, input.videoWidth];
  }
}

export function getInputSize(input: BodyPixInput): [number, number] {
  if ((typeof (HTMLCanvasElement) !== 'undefined' &&
       input instanceof HTMLCanvasElement) ||
      (typeof (OffscreenCanvas) !== 'undefined' &&
          input instanceof OffscreenCanvas) ||
      (typeof (HTMLImageElement) !== 'undefined' &&
       input instanceof HTMLImageElement)) {
    return getSizeFromImageLikeElement(input);
  } else if (typeof (ImageData) !== 'undefined' && input instanceof ImageData) {
    return [input.height, input.width];
  } else if (
      typeof (HTMLVideoElement) !== 'undefined' &&
      input instanceof HTMLVideoElement) {
    return getSizeFromVideoElement(input);
  } else if (input instanceof tf.Tensor) {
    return [input.shape[0], input.shape[1]];
  } else {
    throw new Error(`error: Unknown input type: ${input}.`);
  }
}

function isValidInputResolution(
    resolution: number, outputStride: number): boolean {
  return (resolution - 1) % outputStride === 0;
}

export function toValidInputResolution(
    inputResolution: number, outputStride: BodyPixOutputStride): number {
  if (isValidInputResolution(inputResolution, outputStride)) {
    return inputResolution;
  }

  return Math.floor(inputResolution / outputStride) * outputStride + 1;
}

const INTERNAL_RESOLUTION_STRING_OPTIONS = {
  low: 'low',
  medium: 'medium',
  high: 'high',
  full: 'full'
};

const INTERNAL_RESOLUTION_PERCENTAGES = {
  [INTERNAL_RESOLUTION_STRING_OPTIONS.low]: 0.25,
  [INTERNAL_RESOLUTION_STRING_OPTIONS.medium]: 0.5,
  [INTERNAL_RESOLUTION_STRING_OPTIONS.high]: 0.75,
  [INTERNAL_RESOLUTION_STRING_OPTIONS.full]: 1.0
};

const MIN_INTERNAL_RESOLUTION = 0.1;
const MAX_INTERNAL_RESOLUTION = 2.0;

function toInternalResolutionPercentage(
    internalResolution: BodyPixInternalResolution): number {
  if (typeof internalResolution === 'string') {
    const result = INTERNAL_RESOLUTION_PERCENTAGES[internalResolution];

    tf.util.assert(
        typeof result === 'number',
        () => `string value of inputResolution must be one of ${
            Object.values(INTERNAL_RESOLUTION_STRING_OPTIONS)
                .join(',')} but was ${internalResolution}.`);
    return result;
  } else {
    tf.util.assert(
        typeof internalResolution === 'number' &&
            internalResolution <= MAX_INTERNAL_RESOLUTION &&
            internalResolution >= MIN_INTERNAL_RESOLUTION,
        () =>
            `inputResolution must be a string or number between ${
                MIN_INTERNAL_RESOLUTION} and ${MAX_INTERNAL_RESOLUTION}, but ` +
            `was ${internalResolution}`);

    return internalResolution;
  }
}

export function toInputResolutionHeightAndWidth(
    internalResolution: BodyPixInternalResolution,
    outputStride: BodyPixOutputStride,
    [inputHeight, inputWidth]: [number, number]): [number, number] {
  const internalResolutionPercentage =
      toInternalResolutionPercentage(internalResolution);

  return [
    toValidInputResolution(
        inputHeight * internalResolutionPercentage, outputStride),
    toValidInputResolution(
        inputWidth * internalResolutionPercentage, outputStride)
  ];
}

export function toInputTensor(input: BodyPixInput) {
  // TODO: tf.browser.fromPixels types to support OffscreenCanvas
  // @ts-ignore
  return input instanceof tf.Tensor ? input : tf.browser.fromPixels(input);
}

export function resizeAndPadTo(
    imageTensor: tf.Tensor3D, [targetH, targetW]: [number, number],
    flipHorizontal = false): {
  resizedAndPadded: tf.Tensor3D,
  paddedBy: [[number, number], [number, number]]
} {
  const [height, width] = imageTensor.shape;

  const targetAspect = targetW / targetH;
  const aspect = width / height;

  let resizeW: number;
  let resizeH: number;
  let padL: number;
  let padR: number;
  let padT: number;
  let padB: number;

  if (aspect > targetAspect) {
    // resize to have the larger dimension match the shape.
    resizeW = targetW;
    resizeH = Math.ceil(resizeW / aspect);

    const padHeight = targetH - resizeH;
    padL = 0;
    padR = 0;
    padT = Math.floor(padHeight / 2);
    padB = targetH - (resizeH + padT);
  } else {
    resizeH = targetH;
    resizeW = Math.ceil(targetH * aspect);

    const padWidth = targetW - resizeW;
    padL = Math.floor(padWidth / 2);
    padR = targetW - (resizeW + padL);
    padT = 0;
    padB = 0;
  }

  const resizedAndPadded = tf.tidy(() => {
    // resize to have largest dimension match image
    let resized: tf.Tensor3D;
    if (flipHorizontal) {
      resized = tf.image.resizeBilinear(
          tf.reverse(imageTensor, 1), [resizeH, resizeW]);
    } else {
      resized = tf.image.resizeBilinear(imageTensor, [resizeH, resizeW]);
    }

    const padded = tf.pad3d(resized, [[padT, padB], [padL, padR], [0, 0]]);

    return padded;
  });

  return {resizedAndPadded, paddedBy: [[padT, padB], [padL, padR]]};
}

export function scaleAndCropToInputTensorShape(
    tensor: tf.Tensor3D,
    [inputTensorHeight, inputTensorWidth]: [number, number],
    [resizedAndPaddedHeight, resizedAndPaddedWidth]: [number, number],
    [[padT, padB], [padL, padR]]: [[number, number], [number, number]],
    applySigmoidActivation = false): tf.Tensor3D {
  return tf.tidy(() => {
    let inResizedAndPadded: tf.Tensor3D = tf.image.resizeBilinear(tensor,
        [resizedAndPaddedHeight, resizedAndPaddedWidth], true);

    if (applySigmoidActivation) {
      inResizedAndPadded = tf.sigmoid(inResizedAndPadded);
    }

    return removePaddingAndResizeBack(
        inResizedAndPadded, [inputTensorHeight, inputTensorWidth],
        [[padT, padB], [padL, padR]]);
  });
}

export function removePaddingAndResizeBack(
    resizedAndPadded: tf.Tensor3D,
    [originalHeight, originalWidth]: [number, number],
    [[padT, padB], [padL, padR]]: [[number, number], [number, number]]):
    tf.Tensor3D {
  return tf.tidy(() => {
    const batchedImage: tf.Tensor4D = tf.expandDims(resizedAndPadded);
    return tf.squeeze(tf.image
        .cropAndResize(
            batchedImage, [[
              padT / (originalHeight + padT + padB - 1.0),
              padL / (originalWidth + padL + padR - 1.0),
              (padT + originalHeight - 1.0) /
                  (originalHeight + padT + padB - 1.0),
              (padL + originalWidth - 1.0) / (originalWidth + padL + padR - 1.0)
            ]],
            [0], [originalHeight, originalWidth]), [0]);
  });
}

export function resize2d(
    tensor: tf.Tensor2D, resolution: [number, number],
    nearestNeighbor?: boolean): tf.Tensor2D {
  return tf.tidy(() => {
    const batchedImage: tf.Tensor4D = tf.expandDims(tensor, 2);
    return tf.squeeze(
        tf.image.resizeBilinear(batchedImage, resolution, nearestNeighbor));
  });
}

export function padAndResizeTo(
    input: BodyPixInput, [targetH, targetW]: [number, number]):
    {resized: tf.Tensor3D, padding: Padding} {
  const [height, width] = getInputSize(input);
  const targetAspect = targetW / targetH;
  const aspect = width / height;
  let [padT, padB, padL, padR] = [0, 0, 0, 0];
  if (aspect < targetAspect) {
    // pads the width
    padT = 0;
    padB = 0;
    padL = Math.round(0.5 * (targetAspect * height - width));
    padR = Math.round(0.5 * (targetAspect * height - width));
  } else {
    // pads the height
    padT = Math.round(0.5 * ((1.0 / targetAspect) * width - height));
    padB = Math.round(0.5 * ((1.0 / targetAspect) * width - height));
    padL = 0;
    padR = 0;
  }

  const resized: tf.Tensor3D = tf.tidy(() => {
    let imageTensor = toInputTensor(input);
    imageTensor = tf.pad3d(imageTensor, [[padT, padB], [padL, padR], [0, 0]]);

    return tf.image.resizeBilinear(imageTensor, [targetH, targetW]);
  });

  return {resized, padding: {top: padT, left: padL, right: padR, bottom: padB}};
}

export async function toTensorBuffers3D(tensors: tf.Tensor3D[]):
    Promise<TensorBuffer3D[]> {
  return Promise.all(tensors.map(tensor => tensor.buffer()));
}

export function scalePose(
    pose: Pose, scaleY: number, scaleX: number, offsetY = 0,
    offsetX = 0): Pose {
  return {
    score: pose.score,
    keypoints: pose.keypoints.map(({score, part, position}) => ({
                                    score,
                                    part,
                                    position: {
                                      x: position.x * scaleX + offsetX,
                                      y: position.y * scaleY + offsetY
                                    }
                                  }))
  };
}

export function scalePoses(
    poses: Pose[], scaleY: number, scaleX: number, offsetY = 0, offsetX = 0) {
  if (scaleX === 1 && scaleY === 1 && offsetY === 0 && offsetX === 0) {
    return poses;
  }
  return poses.map(pose => scalePose(pose, scaleY, scaleX, offsetY, offsetX));
}

export function flipPoseHorizontal(pose: Pose, imageWidth: number): Pose {
  return {
    score: pose.score,
    keypoints: pose.keypoints.map(
        ({score, part, position}) => ({
          score,
          part,
          position: {x: imageWidth - 1 - position.x, y: position.y}
        }))
  };
}

export function flipPosesHorizontal(poses: Pose[], imageWidth: number) {
  if (imageWidth <= 0) {
    return poses;
  }
  return poses.map(pose => flipPoseHorizontal(pose, imageWidth));
}

export function scaleAndFlipPoses(
    poses: Pose[], [height, width]: [number, number],
    [inputResolutionHeight, inputResolutionWidth]: [number, number],
    padding: Padding, flipHorizontal: boolean): Pose[] {
  const scaleY =
      (height + padding.top + padding.bottom) / (inputResolutionHeight);
  const scaleX =
      (width + padding.left + padding.right) / (inputResolutionWidth);

  const scaledPoses =
      scalePoses(poses, scaleY, scaleX, -padding.top, -padding.left);

  if (flipHorizontal) {
    return flipPosesHorizontal(scaledPoses, width);
  } else {
    return scaledPoses;
  }
}

redpajama_set_name: RedPajamaGithub


text:
/***************************************************************************

  memory.c

  Functions which handle the CPU memory and I/O port access.

  Caveats:

  * The install_mem/port_*_handler functions are only intended to be
    called at driver init time. Do not call them after this time.

  * If your driver executes an opcode which crosses a bank-switched
    boundary, it will pull the wrong data out of memory. Although not
    a common case, you may need to revert to memcpy to work around this.
    See machine/tnzs.c for an example.

***************************************************************************/

#include "driver.h"
#include "osd_cpu.h"

#define VERBOSE 0

/* #define MEM_DUMP */

#ifdef MEM_DUMP
static void mem_dump( void );
#endif

/* Convenience macros - not in cpuintrf.h because they shouldn't be used by everyone */
#define ADDRESS_BITS(index) 			(cpuintf[Machine->drv->cpu[index].cpu_type & ~CPU_FLAGS_MASK].address_bits)
#define ABITS1(index)					(cpuintf[Machine->drv->cpu[index].cpu_type & ~CPU_FLAGS_MASK].abits1)
#define ABITS2(index)					(cpuintf[Machine->drv->cpu[index].cpu_type & ~CPU_FLAGS_MASK].abits2)
#define ABITS3(index)					(0)
#define ABITSMIN(index) 				(cpuintf[Machine->drv->cpu[index].cpu_type & ~CPU_FLAGS_MASK].abitsmin)

unsigned char *OP_RAM;
unsigned char *OP_ROM;

/* change bases preserving opcode/data shift for encrypted games */
#define SET_OP_RAMROM(base) 				\
	OP_ROM = (base) + (OP_ROM - OP_RAM);	\
	OP_RAM = (base);

MHELE ophw; 			/* op-code hardware number */

struct ExtMemory ext_memory[MAX_EXT_MEMORY];

static unsigned char *ramptr[MAX_CPU],*romptr[MAX_CPU];

/* element shift bits, mask bits */
int mhshift[MAX_CPU][3], mhmask[MAX_CPU][3];

/* pointers to port structs */
/* ASG: port speedup */
static struct IOReadPort *readport[MAX_CPU];
static struct IOWritePort *writeport[MAX_CPU];
static int portmask[MAX_CPU];
static int readport_size[MAX_CPU];
static int writeport_size[MAX_CPU];
/* HJB 990210: removed 'static' for access by assembly CPU core memory handlers */
const struct IOReadPort *cur_readport;
const struct IOWritePort *cur_writeport;
int cur_portmask;

/* current hardware element map */
static MHELE *cur_mr_element[MAX_CPU];
static MHELE *cur_mw_element[MAX_CPU];

/* sub memory/port hardware element map */
/* HJB 990210: removed 'static' for access by assembly CPU core memory handlers */
MHELE readhardware[MH_ELEMAX << MH_SBITS];	/* mem/port read  */
MHELE writehardware[MH_ELEMAX << MH_SBITS]; /* mem/port write */

/* memory hardware handler */
/* HJB 990210: removed 'static' for access by assembly CPU core memory handlers */
mem_read_handler memoryreadhandler[MH_HARDMAX];
int memoryreadoffset[MH_HARDMAX];
mem_write_handler memorywritehandler[MH_HARDMAX];
int memorywriteoffset[MH_HARDMAX];

/* bank ram base address; RAM is bank 0 */
unsigned char *cpu_bankbase[HT_BANKMAX + 1];
static int bankreadoffset[HT_BANKMAX + 1];
static int bankwriteoffset[HT_BANKMAX + 1];

/* override OP base handler */
static opbase_handler setOPbasefunc[MAX_CPU];
static opbase_handler OPbasefunc;

/* current cpu current hardware element map point */
MHELE *cur_mrhard;
MHELE *cur_mwhard;

/* empty port handler structures */
static struct IOReadPort empty_readport[] =
{
	{ -1 }
};

static struct IOWritePort empty_writeport[] =
{
	{ -1 }
};

static void *install_port_read_handler_common(int cpu, int start, int end, mem_read_handler handler, int install_at_beginning);
static void *install_port_write_handler_common(int cpu, int start, int end, mem_write_handler handler, int install_at_beginning);

/***************************************************************************

  Memory read handling

***************************************************************************/

READ_HANDLER(mrh_ram)		{ return cpu_bankbase[0][offset]; }
READ_HANDLER(mrh_bank1) 	{ return cpu_bankbase[1][offset]; }
READ_HANDLER(mrh_bank2) 	{ return cpu_bankbase[2][offset]; }
READ_HANDLER(mrh_bank3) 	{ return cpu_bankbase[3][offset]; }
READ_HANDLER(mrh_bank4) 	{ return cpu_bankbase[4][offset]; }
READ_HANDLER(mrh_bank5) 	{ return cpu_bankbase[5][offset]; }
READ_HANDLER(mrh_bank6) 	{ return cpu_bankbase[6][offset]; }
READ_HANDLER(mrh_bank7) 	{ return cpu_bankbase[7][offset]; }
READ_HANDLER(mrh_bank8) 	{ return cpu_bankbase[8][offset]; }
READ_HANDLER(mrh_bank9) 	{ return cpu_bankbase[9][offset]; }
READ_HANDLER(mrh_bank10)	{ return cpu_bankbase[10][offset]; }
READ_HANDLER(mrh_bank11)	{ return cpu_bankbase[11][offset]; }
READ_HANDLER(mrh_bank12)	{ return cpu_bankbase[12][offset]; }
READ_HANDLER(mrh_bank13)	{ return cpu_bankbase[13][offset]; }
READ_HANDLER(mrh_bank14)	{ return cpu_bankbase[14][offset]; }
READ_HANDLER(mrh_bank15)	{ return cpu_bankbase[15][offset]; }
READ_HANDLER(mrh_bank16)	{ return cpu_bankbase[16][offset]; }
static mem_read_handler bank_read_handler[] =
{
	mrh_ram,   mrh_bank1,  mrh_bank2,  mrh_bank3,  mrh_bank4,  mrh_bank5,  mrh_bank6,  mrh_bank7,
	mrh_bank8, mrh_bank9,  mrh_bank10, mrh_bank11, mrh_bank12, mrh_bank13, mrh_bank14, mrh_bank15,
	mrh_bank16
};

READ_HANDLER(mrh_error)
{
	logerror("CPU #%d PC %04x: warning - read %02x from unmapped memory address %04x\n",cpu_getactivecpu(),cpu_get_pc(),cpu_bankbase[0][offset],offset);
	return cpu_bankbase[0][offset];
}

READ_HANDLER(mrh_error_sparse)
{
	logerror("CPU #%d PC %08x: warning - read unmapped memory address %08x\n",cpu_getactivecpu(),cpu_get_pc(),offset);
	return 0;
}

READ_HANDLER(mrh_error_sparse_bit)
{
	logerror("CPU #%d PC %08x: warning - read unmapped memory bit addr %08x (byte addr %08x)\n",cpu_getactivecpu(),cpu_get_pc(),offset<<3, offset);
	return 0;
}

READ_HANDLER(mrh_nop)
{
	return 0;
}

/***************************************************************************

  Memory write handling

***************************************************************************/

WRITE_HANDLER(mwh_ram)		{ cpu_bankbase[0][offset] = data;}
WRITE_HANDLER(mwh_bank1)	{ cpu_bankbase[1][offset] = data; }
WRITE_HANDLER(mwh_bank2)	{ cpu_bankbase[2][offset] = data; }
WRITE_HANDLER(mwh_bank3)	{ cpu_bankbase[3][offset] = data; }
WRITE_HANDLER(mwh_bank4)	{ cpu_bankbase[4][offset] = data; }
WRITE_HANDLER(mwh_bank5)	{ cpu_bankbase[5][offset] = data; }
WRITE_HANDLER(mwh_bank6)	{ cpu_bankbase[6][offset] = data; }
WRITE_HANDLER(mwh_bank7)	{ cpu_bankbase[7][offset] = data; }
WRITE_HANDLER(mwh_bank8)	{ cpu_bankbase[8][offset] = data; }
WRITE_HANDLER(mwh_bank9)	{ cpu_bankbase[9][offset] = data; }
WRITE_HANDLER(mwh_bank10)	{ cpu_bankbase[10][offset] = data; }
WRITE_HANDLER(mwh_bank11)	{ cpu_bankbase[11][offset] = data; }
WRITE_HANDLER(mwh_bank12)	{ cpu_bankbase[12][offset] = data; }
WRITE_HANDLER(mwh_bank13)	{ cpu_bankbase[13][offset] = data; }
WRITE_HANDLER(mwh_bank14)	{ cpu_bankbase[14][offset] = data; }
WRITE_HANDLER(mwh_bank15)	{ cpu_bankbase[15][offset] = data; }
WRITE_HANDLER(mwh_bank16)	{ cpu_bankbase[16][offset] = data; }
static mem_write_handler bank_write_handler[] =
{
	mwh_ram,   mwh_bank1,  mwh_bank2,  mwh_bank3,  mwh_bank4,  mwh_bank5,  mwh_bank6,  mwh_bank7,
	mwh_bank8, mwh_bank9,  mwh_bank10, mwh_bank11, mwh_bank12, mwh_bank13, mwh_bank14, mwh_bank15,
	mwh_bank16
};

WRITE_HANDLER(mwh_error)
{
	logerror("CPU #%d PC %04x: warning - write %02x to unmapped memory address %04x\n",cpu_getactivecpu(),cpu_get_pc(),data,offset);
	cpu_bankbase[0][offset] = data;
}

WRITE_HANDLER(mwh_error_sparse)
{
	logerror("CPU #%d PC %08x: warning - write %02x to unmapped memory address %08x\n",cpu_getactivecpu(),cpu_get_pc(),data,offset);
}

WRITE_HANDLER(mwh_error_sparse_bit)
{
	logerror("CPU #%d PC %08x: warning - write %02x to unmapped memory bit addr %08x\n",cpu_getactivecpu(),cpu_get_pc(),data,offset<<3);
}

WRITE_HANDLER(mwh_rom)
{
	logerror("CPU #%d PC %04x: warning - write %02x to ROM address %04x\n",cpu_getactivecpu(),cpu_get_pc(),data,offset);
}

WRITE_HANDLER(mwh_ramrom)
{
	cpu_bankbase[0][offset] = cpu_bankbase[0][offset + (OP_ROM - OP_RAM)] = data;
}

WRITE_HANDLER(mwh_nop)
{
}

/***************************************************************************

  Memory structure building

***************************************************************************/

/* return element offset */
static MHELE *get_element( MHELE *element , int ad , int elemask ,
						MHELE *subelement , int *ele_max )
{
	MHELE hw = element[ad];
	int i,ele;
	int banks = ( elemask / (1<<MH_SBITS) ) + 1;

	if( hw >= MH_HARDMAX ) return &subelement[(hw-MH_HARDMAX)<<MH_SBITS];

	/* create new element block */
	if( (*ele_max)+banks > MH_ELEMAX )
	{
		logerror("memory element size overflow\n");
		return 0;
	}
	/* get new element nunber */
	ele = *ele_max;
	(*ele_max)+=banks;
#ifdef MEM_DUMP
	logerror("create element %2d(%2d)\n",ele,banks);
#endif
	/* set link mark to current element */
	element[ad] = ele + MH_HARDMAX;
	/* get next subelement top */
	subelement	= &subelement[ele<<MH_SBITS];
	/* initialize new block */
	for( i = 0 ; i < (1<<MH_SBITS) ; i++ )
		subelement[i] = hw;

	return subelement;
}

static void set_element( int cpu , MHELE *celement , int sp , int ep , MHELE type , MHELE *subelement , int *ele_max )
{
	int i;
	int edepth = 0;
	int shift,mask;
	MHELE *eele = celement;
	MHELE *sele = celement;
	MHELE *ele;
	int ss,sb,eb,ee;

#ifdef MEM_DUMP
	logerror("set_element %8X-%8X = %2X\n",sp,ep,type);
#endif
	if( (unsigned int) sp > (unsigned int) ep ) return;
	do{
		mask  = mhmask[cpu][edepth];
		shift = mhshift[cpu][edepth];

		/* center element */
		ss = (unsigned int) sp >> shift;
		sb = (unsigned int) sp ? ((unsigned int) (sp-1) >> shift) + 1 : 0;
		eb = ((unsigned int) (ep+1) >> shift) - 1;
		ee = (unsigned int) ep >> shift;

		if( sb <= eb )
		{
			if( (sb|mask)==(eb|mask) )
			{
				/* same reason */
				ele = (sele ? sele : eele);
				for( i = sb ; i <= eb ; i++ ){
					ele[i & mask] = type;
				}
			}
			else
			{
				if( sele ) for( i = sb ; i <= (sb|mask) ; i++ )
					sele[i & mask] = type;
				if( eele ) for( i = eb&(~mask) ; i <= eb ; i++ )
					eele[i & mask] = type;
			}
		}

		edepth++;

		if( ss == sb ) sele = 0;
		else sele = get_element( sele , ss & mask , mhmask[cpu][edepth] ,
									subelement , ele_max );
		if( ee == eb ) eele = 0;
		else eele = get_element( eele , ee & mask , mhmask[cpu][edepth] ,
									subelement , ele_max );

	}while( sele || eele );
}

/* ASG 980121 -- allocate all the external memory */
static int memory_allocate_ext (void)
{
	struct ExtMemory *ext = ext_memory;
	int cpu;

	/* a change for MESS */
	if (Machine->gamedrv->rom == 0)  return 1;

	/* loop over all CPUs */
	for (cpu = 0; cpu < cpu_gettotalcpu (); cpu++)
	{
		const struct MemoryReadAddress *mra;
		const struct MemoryWriteAddress *mwa;

		int region = REGION_CPU1+cpu;
		int size = memory_region_length(region);

		/* now it's time to loop */
		while (1)
		{
			int lowest = 0x7fffffff, end, lastend;

			/* find the base of the lowest memory region that extends past the end */
			for (mra = Machine->drv->cpu[cpu].memory_read; mra->start != -1; mra++)
				if (mra->end >= size && mra->start < lowest) lowest = mra->start;
			for (mwa = Machine->drv->cpu[cpu].memory_write; mwa->start != -1; mwa++)
				if (mwa->end >= size && mwa->start < lowest) lowest = mwa->start;

			/* done if nothing found */
			if (lowest == 0x7fffffff)
				break;

			/* now loop until we find the end of this contiguous block of memory */
			lastend = -1;
			end = lowest;
			while (end != lastend)
			{
				lastend = end;

				/* find the base of the lowest memory region that extends past the end */
				for (mra = Machine->drv->cpu[cpu].memory_read; mra->start != -1; mra++)
					if (mra->start <= end && mra->end > end) end = mra->end + 1;
				for (mwa = Machine->drv->cpu[cpu].memory_write; mwa->start != -1; mwa++)
					if (mwa->start <= end && mwa->end > end) end = mwa->end + 1;
			}

			/* time to allocate */
			ext->start = lowest;
			ext->end = end - 1;
			ext->region = region;
			ext->data = (unsigned char *) malloc(end - lowest);

			/* if that fails, we're through */
			if (!ext->data)
				return 0;

			/* reset the memory */
			memset (ext->data, 0, end - lowest);
			size = ext->end + 1;
			ext++;
		}
	}

	return 1;
}

unsigned char *findmemorychunk(int cpu, int offset, int *chunkstart, int *chunkend)
{
	int region = REGION_CPU1+cpu;
	struct ExtMemory *ext;

	/* look in external memory first */
	for (ext = ext_memory; ext->data; ext++)
		if (ext->region == region && ext->start <= offset && ext->end >= offset)
		{
			*chunkstart = ext->start;
			*chunkend = ext->end;
			return ext->data;
		}

	/* return RAM */
	*chunkstart = 0;
	*chunkend = memory_region_length(region) - 1;
	return ramptr[cpu];
}

unsigned char *memory_find_base (int cpu, int offset)
{
	int region = REGION_CPU1+cpu;
	struct ExtMemory *ext;

	/* look in external memory first */
	for (ext = ext_memory; ext->data; ext++)
		if (ext->region == region && ext->start <= offset && ext->end >= offset)
			return ext->data + (offset - ext->start);

	return ramptr[cpu] + offset;
}

/* make these static so they can be used in a callback by game drivers */

static int rdelement_max = 0;
static int wrelement_max = 0;
static int rdhard_max = HT_USER;
static int wrhard_max = HT_USER;

/* return = FALSE:can't allocate element memory */
int memory_init(void)
{
	int i, cpu;
	const struct MemoryReadAddress *memoryread;
	const struct MemoryWriteAddress *memorywrite;
	const struct MemoryReadAddress *mra;
	const struct MemoryWriteAddress *mwa;
	const struct IOReadPort *ioread;
	const struct IOWritePort *iowrite;
	int abits1,abits2,abits3,abitsmin;
	rdelement_max = 0;
	wrelement_max = 0;
	rdhard_max = HT_USER;
	wrhard_max = HT_USER;

	for( cpu = 0 ; cpu < MAX_CPU ; cpu++ )
		cur_mr_element[cpu] = cur_mw_element[cpu] = 0;

	ophw = 0xff;

	/* ASG 980121 -- allocate external memory */
	if (!memory_allocate_ext ())
		return 0;

	for( cpu = 0 ; cpu < cpu_gettotalcpu() ; cpu++ )
	{
		const struct MemoryReadAddress *_mra;
		const struct MemoryWriteAddress *_mwa;

		setOPbasefunc[cpu] = NULL;

		ramptr[cpu] = romptr[cpu] = memory_region(REGION_CPU1+cpu);

		/* initialize the memory base pointers for memory hooks */
		_mra = Machine->drv->cpu[cpu].memory_read;
		if (_mra)
		{
			while (_mra->start != -1)
			{
//				if (_mra->base) *_mra->base = memory_find_base (cpu, _mra->start);
//				if (_mra->size) *_mra->size = _mra->end - _mra->start + 1;
				_mra++;
			}
		}
		_mwa = Machine->drv->cpu[cpu].memory_write;
		if (_mwa)
		{
			while (_mwa->start != -1)
			{
				if (_mwa->base) *_mwa->base = memory_find_base (cpu, _mwa->start);
				if (_mwa->size) *_mwa->size = _mwa->end - _mwa->start + 1;
				_mwa++;
			}
		}

		/* initialize port structures */
		readport_size[cpu] = 0;
		writeport_size[cpu] = 0;
		readport[cpu] = 0;
		writeport[cpu] = 0;

		/* install port handlers - at least an empty one */
		ioread = Machine->drv->cpu[cpu].port_read;
		if (ioread == 0)  ioread = empty_readport;

		while (1)
		{
			if (install_port_read_handler_common(cpu, ioread->start, ioread->end, ioread->handler, 0) == 0)
			{
				memory_shutdown();
				return 0;
			}

			if (ioread->start == -1)  break;

			ioread++;
		}

		iowrite = Machine->drv->cpu[cpu].port_write;
		if (iowrite == 0)  iowrite = empty_writeport;

		while (1)
		{
			if (install_port_write_handler_common(cpu, iowrite->start, iowrite->end, iowrite->handler, 0) == 0)
			{
				memory_shutdown();
				return 0;
			}

			if (iowrite->start == -1)  break;

			iowrite++;
		}

		portmask[cpu] = 0xffff;
#if (HAS_Z80)
		if ((Machine->drv->cpu[cpu].cpu_type & ~CPU_FLAGS_MASK) == CPU_Z80 &&
			(Machine->drv->cpu[cpu].cpu_type & CPU_16BIT_PORT) == 0)
			portmask[cpu] = 0xff;
#endif
#if (HAS_DRZ80)
		if ((Machine->drv->cpu[cpu].cpu_type & ~CPU_FLAGS_MASK) == CPU_DRZ80 &&
			(Machine->drv->cpu[cpu].cpu_type & CPU_16BIT_PORT) == 0)
			portmask[cpu] = 0xff;
#endif
	}

	/* initialize global handler */
	for( i = 0 ; i < MH_HARDMAX ; i++ ){
		memoryreadoffset[i] = 0;
		memorywriteoffset[i] = 0;
	}
	/* bank memory */
	for (i = 1; i <= MAX_BANKS; i++)
	{
		memoryreadhandler[i] = bank_read_handler[i];
		memorywritehandler[i] = bank_write_handler[i];
	}
	/* non map memory */
	memoryreadhandler[HT_NON] = mrh_error;
	memorywritehandler[HT_NON] = mwh_error;
	/* NOP memory */
	memoryreadhandler[HT_NOP] = mrh_nop;
	memorywritehandler[HT_NOP] = mwh_nop;
	/* RAMROM memory */
	memorywritehandler[HT_RAMROM] = mwh_ramrom;
	/* ROM memory */
	memorywritehandler[HT_ROM] = mwh_rom;

	/* if any CPU is 21-bit or more, we change the error handlers to be more benign */
	for (cpu = 0; cpu < cpu_gettotalcpu(); cpu++)
		if (ADDRESS_BITS (cpu) >= 21)
		{
			memoryreadhandler[HT_NON] = mrh_error_sparse;
			memorywritehandler[HT_NON] = mwh_error_sparse;
#if (HAS_TMS34010)
			if ((Machine->drv->cpu[cpu].cpu_type & ~CPU_FLAGS_MASK)==CPU_TMS34010)
			{
				memoryreadhandler[HT_NON] = mrh_error_sparse_bit;
				memorywritehandler[HT_NON] = mwh_error_sparse_bit;
			}
#endif
		}

	for( cpu = 0 ; cpu < cpu_gettotalcpu() ; cpu++ )
	{
		/* cpu selection */
		abits1 = ABITS1 (cpu);
		abits2 = ABITS2 (cpu);
		abits3 = ABITS3 (cpu);
		abitsmin = ABITSMIN (cpu);

		/* element shifter , mask set */
		mhshift[cpu][0] = (abits2+abits3);
		mhshift[cpu][1] = abits3;			/* 2nd */
		mhshift[cpu][2] = 0;				/* 3rd (used by set_element)*/
		mhmask[cpu][0]	= MHMASK(abits1);		/*1st(used by set_element)*/
		mhmask[cpu][1]	= MHMASK(abits2);		/*2nd*/
		mhmask[cpu][2]	= MHMASK(abits3);		/*3rd*/

		/* allocate current element */
		if( (cur_mr_element[cpu] = (MHELE *)malloc(sizeof(MHELE)<<abits1)) == 0 )
		{
			memory_shutdown();
			return 0;
		}
		if( (cur_mw_element[cpu] = (MHELE *)malloc(sizeof(MHELE)<<abits1)) == 0 )
		{
			memory_shutdown();
			return 0;
		}

		/* initialize current element table */
		for( i = 0 ; i < (1<<abits1) ; i++ )
		{
			cur_mr_element[cpu][i] = HT_NON;	/* no map memory */
			cur_mw_element[cpu][i] = HT_NON;	/* no map memory */
		}

		memoryread = Machine->drv->cpu[cpu].memory_read;
		memorywrite = Machine->drv->cpu[cpu].memory_write;

		/* memory read handler build */
		if (memoryread)
		{
			mra = memoryread;
			while (mra->start != -1) mra++;
			mra--;

			while (mra >= memoryread)
			{
				install_mem_read_handler (cpu, mra->start, mra->end, mra->handler);
				mra--;
			}
		}

		/* memory write handler build */
		if (memorywrite)
		{
			mwa = memorywrite;
			while (mwa->start != -1) mwa++;
			mwa--;

			while (mwa >= memorywrite)
			{
				install_mem_write_handler (cpu, mwa->start, mwa->end, mwa->handler);
				mwa--;
			}
		}
	}

	logerror("used read  elements %d/%d , functions %d/%d\n"
			,rdelement_max,MH_ELEMAX , rdhard_max,MH_HARDMAX );
	logerror("used write elements %d/%d , functions %d/%d\n"
			,wrelement_max,MH_ELEMAX , wrhard_max,MH_HARDMAX );

#ifdef MEM_DUMP
	mem_dump();
#endif
	return 1;	/* ok */
}

void memory_set_opcode_base(int cpu,unsigned char *base)
{
	romptr[cpu] = base;
}

void memorycontextswap(int activecpu)
{
	cpu_bankbase[0] = ramptr[activecpu];

	cur_mrhard = cur_mr_element[activecpu];
	cur_mwhard = cur_mw_element[activecpu];

	/* ASG: port speedup */
	cur_readport = readport[activecpu];
	cur_writeport = writeport[activecpu];
	cur_portmask = portmask[activecpu];

	OPbasefunc = setOPbasefunc[activecpu];

	/* op code memory pointer */
	ophw = HT_RAM;
	OP_RAM = cpu_bankbase[0];
	OP_ROM = romptr[activecpu];
}

void memory_shutdown(void)
{
	struct ExtMemory *ext;
	int cpu;

	for( cpu = 0 ; cpu < MAX_CPU ; cpu++ )
	{
		if( cur_mr_element[cpu] != 0 )
		{
			free( cur_mr_element[cpu] );
			cur_mr_element[cpu] = 0;
		}
		if( cur_mw_element[cpu] != 0 )
		{
			free( cur_mw_element[cpu] );
			cur_mw_element[cpu] = 0;
		}

		if (readport[cpu] != 0)
		{
			free(readport[cpu]);
			readport[cpu] = 0;
		}

		if (writeport[cpu] != 0)
		{
			free(writeport[cpu]);
			writeport[cpu] = 0;
		}
	}

	/* ASG 980121 -- free all the external memory */
	for (ext = ext_memory; ext->data; ext++)
		free(ext->data);
	memset (ext_memory, 0, sizeof (ext_memory));
}

/***************************************************************************

  Perform a memory read. This function is called by the CPU emulation.

***************************************************************************/

/* use these constants to define which type of memory handler to build */
#define TYPE_8BIT					0		/* 8-bit aligned */
#define TYPE_16BIT_BE				1		/* 16-bit aligned, big-endian */
#define TYPE_16BIT_LE				2		/* 16-bit aligned, little-endian */

#define CAN_BE_MISALIGNED			0		/* word/dwords can be read on non-16-bit boundaries */
#define ALWAYS_ALIGNED				1		/* word/dwords are always read on 16-bit boundaries */

#ifndef MAME_MEMINLINE
#include "memory_read.h"
#endif

/***************************************************************************

  Perform a memory write. This function is called by the CPU emulation.

***************************************************************************/

#ifndef MAME_MEMINLINE
#include "memory_write.h"
#endif

/***************************************************************************

  Opcode base changers. This function is called by the CPU emulation.

***************************************************************************/

/* generic opcode base changer */
#define SETOPBASE(name,abits,shift) 													\
void name(int pc)																		\
{																						\
	MHELE hw;																			\
																						\
	pc = (UINT32)pc >> shift;															\
																						\
	/* allow overrides */																\
	if (OPbasefunc) 																	\
	{																					\
		pc = OPbasefunc(pc);															\
		if (pc == -1)																	\
			return; 																	\
	}																					\
																						\
	/* perform the lookup */															\
	hw = cur_mrhard[(UINT32)pc >> (ABITS2_##abits + ABITS_MIN_##abits)];				\
	if (hw >= MH_HARDMAX)																\
	{																					\
		hw -= MH_HARDMAX;																\
		hw = readhardware[(hw << MH_SBITS) + (((UINT32)pc >> ABITS_MIN_##abits) & MHMASK(ABITS2_##abits))]; \
	}																					\
	ophw = hw;																			\
																						\
	/* RAM or banked memory */															\
	if (hw <= HT_BANKMAX)																\
	{																					\
		SET_OP_RAMROM(cpu_bankbase[hw] - memoryreadoffset[hw])							\
		return; 																		\
	}																					\
																						\
	/* do not support on callback memory region */										\
	logerror("CPU #%d PC %04x: warning - op-code execute on mapped i/o\n",              \
				cpu_getactivecpu(),cpu_get_pc());										\
}

/* the handlers we need to generate */
SETOPBASE(cpu_setOPbase16,	  16,	 0)
SETOPBASE(cpu_setOPbase16bew, 16BEW, 0)
SETOPBASE(cpu_setOPbase16lew, 16LEW, 0)
SETOPBASE(cpu_setOPbase20,	  20,	 0)
SETOPBASE(cpu_setOPbase21,	  21,	 0)
SETOPBASE(cpu_setOPbase24,	  24,	 0)
SETOPBASE(cpu_setOPbase24bew, 24BEW, 0)
SETOPBASE(cpu_setOPbase29,	  29,	 3)
SETOPBASE(cpu_setOPbase32,	  32,	 0)
SETOPBASE(cpu_setOPbase32lew, 32LEW, 0)

/***************************************************************************

  Perform an I/O port read. This function is called by the CPU emulation.

***************************************************************************/
int cpu_readport(int port)
{
	const struct IOReadPort *iorp = cur_readport;

	port &= cur_portmask;

	/* search the handlers. The order is as follows: first the dynamically installed
	   handlers are searched, followed by the static ones in whatever order they were
	   specified in the driver */
	while (iorp->start != -1)
	{
		if (port >= iorp->start && port <= iorp->end)
		{
			mem_read_handler handler = iorp->handler;

			if (handler == IORP_NOP) return 0;
			else return (*handler)(port - iorp->start);
		}

		iorp++;
	}

	logerror("CPU #%d PC %04x: warning - read unmapped I/O port %02x\n",cpu_getactivecpu(),cpu_get_pc(),port);
	return 0;
}

/***************************************************************************

  Perform an I/O port write. This function is called by the CPU emulation.

***************************************************************************/
void cpu_writeport(int port, int value)
{
	const struct IOWritePort *iowp = cur_writeport;

	port &= cur_portmask;

	/* search the handlers. The order is as follows: first the dynamically installed
	   handlers are searched, followed by the static ones in whatever order they were
	   specified in the driver */
	while (iowp->start != -1)
	{
		if (port >= iowp->start && port <= iowp->end)
		{
			mem_write_handler handler = iowp->handler;

			if (handler == IOWP_NOP) return;
			else (*handler)(port - iowp->start,value);

			return;
		}

		iowp++;
	}

	logerror("CPU #%d PC %04x: warning - write %02x to unmapped I/O port %02x\n",cpu_getactivecpu(),cpu_get_pc(),value,port);
}

/* set readmemory handler for bank memory  */
void cpu_setbankhandler_r(int bank, mem_read_handler handler)
{
	int offset = 0;
	MHELE hardware;

	if ((((FPTR)handler)== ((FPTR)MRA_RAM)) || (((FPTR)handler)==((FPTR)MRA_ROM)))
	{
		handler = mrh_ram;
	}
	else if ((((FPTR)handler)==((FPTR)MRA_BANK1)) || (((FPTR)handler)==((FPTR)MRA_BANK2)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK3)) || (((FPTR)handler)==((FPTR)MRA_BANK4)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK5)) || (((FPTR)handler)==((FPTR)MRA_BANK6)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK7)) || (((FPTR)handler)==((FPTR)MRA_BANK8)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK9)) || (((FPTR)handler)==((FPTR)MRA_BANK10)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK11)) || (((FPTR)handler)==((FPTR)MRA_BANK12)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK13)) || (((FPTR)handler)==((FPTR)MRA_BANK14)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK15)) || (((FPTR)handler)==((FPTR)MRA_BANK16)))
	{
		hardware = (int)MWA_BANK1 - (int)handler + 1;
		handler = bank_read_handler[hardware];
		offset = bankreadoffset[hardware];
	}
	else if (((FPTR)handler)==((FPTR)MRA_NOP))
	{
		handler = mrh_nop;
	}
	else
	{
		offset = bankreadoffset[bank];
	}
	memoryreadoffset[bank] = offset;
	memoryreadhandler[bank] = handler;
}

/* set writememory handler for bank memory	*/
void cpu_setbankhandler_w(int bank, mem_write_handler handler)
{
	int offset = 0;
	MHELE hardware;

	if (((FPTR)handler)==((FPTR)MWA_RAM))
	{
		handler = mwh_ram;
	}
	else if ((((FPTR)handler)==((FPTR)MWA_BANK1)) || (((FPTR)handler)==((FPTR)MWA_BANK2)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK3)) || (((FPTR)handler)==((FPTR)MWA_BANK4)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK5)) || (((FPTR)handler)==((FPTR)MWA_BANK6)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK7)) || (((FPTR)handler)==((FPTR)MWA_BANK8)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK9)) || (((FPTR)handler)==((FPTR)MWA_BANK10)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK11)) || (((FPTR)handler)==((FPTR)MWA_BANK12)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK13)) || (((FPTR)handler)==((FPTR)MWA_BANK14)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK15)) || (((FPTR)handler)==((FPTR)MWA_BANK16)))
	{
		hardware = (int)MWA_BANK1 - (int)handler + 1;
		handler = bank_write_handler[hardware];
		offset = bankwriteoffset[hardware];
	}
	else if (((FPTR)handler)==((FPTR)MWA_NOP))
	{
		handler = mwh_nop;
	}
	else if (((FPTR)handler)==((FPTR)(FPTR)MWA_RAMROM))
	{
		handler = mwh_ramrom;
	}
	else if (((FPTR)handler)==((FPTR)MWA_ROM))
	{
		handler = mwh_rom;
	}
	else
	{
		offset = bankwriteoffset[bank];
	}
	memorywriteoffset[bank] = offset;
	memorywritehandler[bank] = handler;
}

/* cpu change op-code memory base */
void cpu_setOPbaseoverride (int cpu,opbase_handler function)
{
	setOPbasefunc[cpu] = function;
	if (cpu == cpu_getactivecpu())
		OPbasefunc = function;
}

void *install_mem_read_handler(int cpu, int start, int end, mem_read_handler handler)
{
	MHELE hardware = 0;
	int abitsmin;
	int i, hw_set;
#if VERBOSE
	logerror("Install new memory read handler:\n");
	logerror("             cpu: %d\n", cpu);
	logerror("           start: 0x%08x\n", start);
	logerror("             end: 0x%08x\n", end);
#ifdef __LP64__
	logerror(" handler address: 0x%016lx\n", (unsigned long) handler);
#else
	logerror(" handler address: 0x%08x\n", (unsigned int) handler);
#endif
#endif
	abitsmin = ABITSMIN (cpu);

	/* see if this function is already registered */
	hw_set = 0;
	for ( i = 0 ; i < MH_HARDMAX ; i++)
	{
		/* record it if it matches */
		if (( memoryreadhandler[i] == handler ) &&
			(  memoryreadoffset[i] == start))
		{
#if VERBOSE
			logerror("handler match - use old one\n");
#endif
			hardware = i;
			hw_set = 1;
		}
	}
	if ((((FPTR)handler)==((FPTR)MRA_RAM)) || (((FPTR)handler)==((FPTR)MRA_ROM)))
	{
		hardware = HT_RAM;	/* special case ram read */
		hw_set = 1;
	}
	if ((((FPTR)handler)==((FPTR)MRA_BANK1)) || (((FPTR)handler)==((FPTR)MRA_BANK2)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK3)) || (((FPTR)handler)==((FPTR)MRA_BANK4)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK5)) || (((FPTR)handler)==((FPTR)MRA_BANK6)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK7)) || (((FPTR)handler)==((FPTR)MRA_BANK8)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK9)) || (((FPTR)handler)==((FPTR)MRA_BANK10)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK11)) || (((FPTR)handler)==((FPTR)MRA_BANK12)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK13)) || (((FPTR)handler)==((FPTR)MRA_BANK14)) ||
		(((FPTR)handler)==((FPTR)MRA_BANK15)) || (((FPTR)handler)==((FPTR)MRA_BANK16)))
	{
		hardware = (int)MRA_BANK1 - (int)handler + 1;
		memoryreadoffset[hardware] = bankreadoffset[hardware] = start;
		cpu_bankbase[hardware] = memory_find_base(cpu, start);
		hw_set = 1;
	}
	else if (((FPTR)handler)==((FPTR)MRA_NOP))
	{
		hardware = HT_NOP;
		hw_set = 1;
	}
	if (!hw_set)  /* no match */
	{
		/* create newer hardware handler */
		if( rdhard_max == MH_HARDMAX )
		{
			logerror("read memory hardware pattern over !\n");
			logerror("Failed to install new memory handler.\n");
			return memory_find_base(cpu, start);
		}
		else
		{
			/* register hardware function */
			hardware = rdhard_max++;
			memoryreadhandler[hardware] = handler;
			memoryreadoffset[hardware] = start;
		}
	}
	/* set hardware element table entry */
	set_element( cpu , cur_mr_element[cpu] ,
		(((unsigned int) start) >> abitsmin) ,
		(((unsigned int) end) >> abitsmin) ,
		hardware , readhardware , &rdelement_max );
#if VERBOSE
	logerror("Done installing new memory handler.\n");
	logerror("used read  elements %d/%d , functions %d/%d\n"
			,rdelement_max,MH_ELEMAX , rdhard_max,MH_HARDMAX );
#endif
	return memory_find_base(cpu, start);
}

void *install_mem_write_handler(int cpu, int start, int end, mem_write_handler handler)
{
	MHELE hardware = 0;
	int abitsmin;
	int i, hw_set;
#if VERBOSE
	logerror("Install new memory write handler:\n");
	logerror("             cpu: %d\n", cpu);
	logerror("           start: 0x%08x\n", start);
	logerror("             end: 0x%08x\n", end);
#ifdef __LP64__
	logerror(" handler address: 0x%016lx\n", (unsigned long) handler);
#else
	logerror(" handler address: 0x%08x\n", (unsigned int) handler);
#endif
#endif
	abitsmin = ABITSMIN (cpu);

	/* see if this function is already registered */
	hw_set = 0;
	for ( i = 0 ; i < MH_HARDMAX ; i++)
	{
		/* record it if it matches */
		if (( memorywritehandler[i] == handler ) &&
			(  memorywriteoffset[i] == start))
		{
#if VERBOSE
			logerror("handler match - use old one\n");
#endif
			hardware = i;
			hw_set = 1;
		}
	}

	if (((FPTR)handler)==((FPTR)MWA_RAM))
	{
		hardware = HT_RAM;	/* special case ram write */
		hw_set = 1;
	}
	else if ((((FPTR)handler)==((FPTR)MWA_BANK1)) || (((FPTR)handler)==((FPTR)MWA_BANK2)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK3)) ||	(((FPTR)handler)==((FPTR)MWA_BANK4)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK5)) ||	(((FPTR)handler)==((FPTR)MWA_BANK6)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK7)) ||	(((FPTR)handler)==((FPTR)MWA_BANK8)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK9)) ||	(((FPTR)handler)==((FPTR)MWA_BANK10)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK11)) || (((FPTR)handler)==((FPTR)MWA_BANK12)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK13)) || (((FPTR)handler)==((FPTR)MWA_BANK14)) ||
		(((FPTR)handler)==((FPTR)MWA_BANK15)) || (((FPTR)handler)==((FPTR)MWA_BANK16)))
	{
		hardware = (int)MWA_BANK1 - (int)handler + 1;
		memorywriteoffset[hardware] = bankwriteoffset[hardware] = start;
		cpu_bankbase[hardware] = memory_find_base(cpu, start);
		hw_set = 1;
	}
	else if (((FPTR)handler)==((FPTR)MWA_NOP))
	{
		hardware = HT_NOP;
		hw_set = 1;
	}
	else if (((FPTR)handler)==((FPTR)MWA_RAMROM))
	{
		hardware = HT_RAMROM;
		hw_set = 1;
	}
	else if (((FPTR)handler)==((FPTR)MWA_ROM))
	{
		hardware = HT_ROM;
		hw_set = 1;
	}
	if (!hw_set)  /* no match */
	{
		/* create newer hardware handler */
		if( wrhard_max == MH_HARDMAX )
		{
			logerror("write memory hardware pattern over !\n");
			logerror("Failed to install new memory handler.\n");

			return memory_find_base(cpu, start);
		}
		else
		{
			/* register hardware function */
			hardware = wrhard_max++;
			memorywritehandler[hardware] = handler;
			memorywriteoffset[hardware] = start;
		}
	}
	/* set hardware element table entry */
	set_element( cpu , cur_mw_element[cpu] ,
		(((unsigned int) start) >> abitsmin) ,
		(((unsigned int) end) >> abitsmin) ,
		hardware , writehardware , &wrelement_max );
#if VERBOSE
	logerror("Done installing new memory handler.\n");
	logerror("used write elements %d/%d , functions %d/%d\n"
			,wrelement_max,MH_ELEMAX , wrhard_max,MH_HARDMAX );
#endif
	return memory_find_base(cpu, start);
}

void *install_port_read_handler(int cpu, int start, int end, mem_read_handler handler)
{
	return install_port_read_handler_common(cpu, start, end, handler, 1);
}

void *install_port_write_handler(int cpu, int start, int end, mem_write_handler handler)
{
	return install_port_write_handler_common(cpu, start, end, handler, 1);
}

static void *install_port_read_handler_common(int cpu, int start, int end,
											  mem_read_handler handler, int install_at_beginning)
{
	int i, oldsize;

	oldsize = readport_size[cpu];
	readport_size[cpu] += sizeof(struct IOReadPort);

	if (readport[cpu] == 0)
	{
		readport[cpu] = (IOReadPort *) malloc(readport_size[cpu]);
	}
	else
	{
		readport[cpu] = (IOReadPort *) realloc(readport[cpu], readport_size[cpu]);
	}

	if (readport[cpu] == 0)  return 0;

	if (install_at_beginning)
	{
		/* can't do a single memcpy because it doesn't handle overlapping regions correctly??? */
		for (i = oldsize / sizeof(struct IOReadPort); i >= 1; i--)
		{
			memcpy(&readport[cpu][i], &readport[cpu][i - 1], sizeof(struct IOReadPort));
		}

		i = 0;
	}
	else
	{
		i = oldsize / sizeof(struct IOReadPort);
	}

#ifdef MEM_DUMP
	logerror("Installing port read handler: cpu %d  slot %X  start %X  end %X\n", cpu, i, start, end);
#endif

	readport[cpu][i].start = start;
	readport[cpu][i].end = end;
	readport[cpu][i].handler = handler;

	return readport[cpu];
}

static void *install_port_write_handler_common(int cpu, int start, int end,
											   mem_write_handler handler, int install_at_beginning)
{
	int i, oldsize;

	oldsize = writeport_size[cpu];
	writeport_size[cpu] += sizeof(struct IOWritePort);

	if (writeport[cpu] == 0)
	{
		writeport[cpu] = (IOWritePort *) malloc(writeport_size[cpu]);
	}
	else
	{
		writeport[cpu] = (IOWritePort *) realloc(writeport[cpu], writeport_size[cpu]);
	}

	if (writeport[cpu] == 0)  return 0;

	if (install_at_beginning)
	{
		/* can't do a single memcpy because it doesn't handle overlapping regions correctly??? */
		for (i = oldsize / sizeof(struct IOWritePort); i >= 1; i--)
		{
			memcpy(&writeport[cpu][i], &writeport[cpu][i - 1], sizeof(struct IOWritePort));
		}

		i = 0;
	}
	else
	{
		i = oldsize / sizeof(struct IOWritePort);
	}

#ifdef MEM_DUMP
	logerror("Installing port write handler: cpu %d  slot %X  start %X  end %X\n", cpu, i, start, end);
#endif

	writeport[cpu][i].start = start;
	writeport[cpu][i].end = end;
	writeport[cpu][i].handler = handler;

	return writeport[cpu];
}

#ifdef MEM_DUMP
static void mem_dump( void )
{
	extern int totalcpu;
	int cpu;
	int naddr,addr;
	MHELE nhw,hw;

	FILE *temp = fopen ("memdump.log", "w");

	if (!temp) return;

	for( cpu = 0 ; cpu < 1 ; cpu++ )
	{
		fprintf(temp,"cpu %d read memory \n",cpu);
		addr = 0;
		naddr = 0;
		nhw = 0xff;
		while( (addr >> mhshift[cpu][0]) <= mhmask[cpu][0] ){
			hw = cur_mr_element[cpu][addr >> mhshift[cpu][0]];
			if( hw >= MH_HARDMAX )
			{	/* 2nd element link */
				hw = readhardware[((hw-MH_HARDMAX)<<MH_SBITS) + ((addr>>mhshift[cpu][1]) & mhmask[cpu][1])];
				if( hw >= MH_HARDMAX )
					hw = readhardware[((hw-MH_HARDMAX)<<MH_SBITS) + (addr & mhmask[cpu][2])];
			}
			if( nhw != hw )
			{
				if( addr )
	fprintf(temp,"  %08x(%08x) - %08x = %02x\n",naddr,memoryreadoffset[nhw],addr-1,nhw);
				nhw = hw;
				naddr = addr;
			}
			addr++;
		}
		fprintf(temp,"  %08x(%08x) - %08x = %02x\n",naddr,memoryreadoffset[nhw],addr-1,nhw);

		fprintf(temp,"cpu %d write memory \n",cpu);
		naddr = 0;
		addr = 0;
		nhw = 0xff;
		while( (addr >> mhshift[cpu][0]) <= mhmask[cpu][0] ){
			hw = cur_mw_element[cpu][addr >> mhshift[cpu][0]];
			if( hw >= MH_HARDMAX )
			{	/* 2nd element link */
				hw = writehardware[((hw-MH_HARDMAX)<<MH_SBITS) + ((addr>>mhshift[cpu][1]) & mhmask[cpu][1])];
				if( hw >= MH_HARDMAX )
					hw = writehardware[((hw-MH_HARDMAX)<<MH_SBITS) + (addr & mhmask[cpu][2])];
			}
			if( nhw != hw )
			{
				if( addr )
	fprintf(temp,"  %08x(%08x) - %08x = %02x\n",naddr,memorywriteoffset[nhw],addr-1,nhw);
				nhw = hw;
				naddr = addr;
			}
			addr++;
		}
	fprintf(temp,"  %08x(%08x) - %08x = %02x\n",naddr,memorywriteoffset[nhw],addr-1,nhw);
	}
	fclose(temp);
}
#endif


text:
<?php

function checkImageExists($connEx, $imagePath, $debug) {
    // returns TRUE if the image is already in table
    $imagePathA = mysqli_real_escape_string($connEx, $imagePath);
    $sql = "SELECT * FROM photo_index.indexMaster WHERE pathName = '" . $imagePathA . "'";
    if ($debug) echo "In checkImageExists, sql: $sql \n";
    $result = $connEx->query($sql);

    if ($result->num_rows > 0) {
        echo " - already exists" . PHP_EOL;
        return TRUE;
    } else {
        echo " - new entry" . PHP_EOL;
        return FALSE;
    }
}

?>


text:
package org.gradle.api.plugins.quality;

import org.gradle.api.Project;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.model.ReplacedBy;
import org.gradle.api.resources.TextResource;
import org.gradle.util.SingleMessageLogger;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Configuration options for the Checkstyle plugin.
 *
 * @see CheckstylePlugin
 */
public class CheckstyleExtension extends CodeQualityExtension {

    private final Project project;

    private TextResource config;
    private Map<String, Object> configProperties = new LinkedHashMap<String, Object>();
    private int maxErrors;
    private int maxWarnings = Integer.MAX_VALUE;
    private boolean showViolations = true;
    private final DirectoryProperty configDirectory;

    public CheckstyleExtension(Project project) {
        this.project = project;
        this.configDirectory = project.getObjects().directoryProperty();
    }

    /**
     * The Checkstyle configuration file to use.
     */
    public File getConfigFile() {
        return getConfig().asFile();
    }

    /**
     * The Checkstyle configuration file to use.
     */
    public void setConfigFile(File configFile) {
        setConfig(project.getResources().getText().fromFile(configFile));
    }

    /**
     * The Checkstyle configuration to use. Replaces the {@code configFile} property.
     *
     * @since 2.2
     */
    public TextResource getConfig() {
        return config;
    }

    /**
     * The Checkstyle configuration to use. Replaces the {@code configFile} property.
     *
     * @since 2.2
     */
    public void setConfig(TextResource config) {
        this.config = config;
    }

    /**
     * The properties available for use in the configuration file. These are substituted into the configuration file.
     */
    public Map<String, Object> getConfigProperties() {
        return configProperties;
    }

    /**
     * The properties available for use in the configuration file. These are substituted into the configuration file.
     */
    public void setConfigProperties(Map<String, Object> configProperties) {
        this.configProperties = configProperties;
    }

    /**
     * Path to other Checkstyle configuration files. By default, this path is {@code $rootProject.projectDir/config/checkstyle}
     *

     * This path will be exposed as the variable {@code config_loc} in Checkstyle's configuration files.
     *

     * @return path to other Checkstyle configuration files
     * @since 4.0
     *
     */
    @Deprecated
    @ReplacedBy("configDirectory")
    public File getConfigDir() {
        SingleMessageLogger.nagUserOfReplacedMethod("CheckstyleExtension.getConfigDir()", "Use CheckstyleExtension.getConfigDirectory() instead");
        return configDirectory.get().getAsFile();
    }

    /**
     * Path to other Checkstyle configuration files. By default, this path is {@code $rootProject.projectDir/config/checkstyle}
     *

     * This path will be exposed as the variable {@code config_loc} in Checkstyle's configuration files.
     *

     * @since 4.0
     */
    @Deprecated
    public void setConfigDir(File configDir) {
        SingleMessageLogger.nagUserOfReplacedMethod("CheckstyleExtension.setConfigDir()", "Use CheckstyleExtension.getConfigDirectory().set() instead");
        this.configDirectory.set(configDir);
    }

    /**
     * Path to other Checkstyle configuration files. By default, this path is {@code $rootProject.projectDir/config/checkstyle}
     *

     * This path will be exposed as the variable {@code config_loc} in Checkstyle's configuration files.
     *

     * @return path to other Checkstyle configuration files
     * @since 4.7
     */
    public DirectoryProperty getConfigDirectory() {
        return configDirectory;
    }

    /**
     * The maximum number of errors that are tolerated before breaking the build
     * or setting the failure property. Defaults to <tt>0</tt>.
     *

     * Example: maxErrors = 42
     *
     * @since 3.4
     * @return the maximum number of errors allowed
     */
    public int getMaxErrors() {
        return maxErrors;
    }

    /**
     * Set the maximum number of errors that are tolerated before breaking the build.
     *
     * @since 3.4
     * @param maxErrors number of errors allowed
     */
    public void setMaxErrors(int maxErrors) {
        this.maxErrors = maxErrors;
    }

    /**
     * The maximum number of warnings that are tolerated before breaking the build
     * or setting the failure property. Defaults to <tt>Integer.MAX_VALUE</tt>.
     *

     * Example: maxWarnings = 1000
     *
     * @since 3.4
     * @return the maximum number of warnings allowed
     */
    public int getMaxWarnings() {
        return maxWarnings;
    }

    /**
     * Set the maximum number of warnings that are tolerated before breaking the build.
     *
     * @since 3.4
     * @param maxWarnings number of warnings allowed
     */
    public void setMaxWarnings(int maxWarnings) {
        this.maxWarnings = maxWarnings;
    }

    /**
     * Whether rule violations are to be displayed on the console. Defaults to <tt>true</tt>.
     *
     * Example: showViolations = false
     */
    public boolean isShowViolations() {
        return showViolations;
    }

    /**
     * Whether rule violations are to be displayed on the console. Defaults to <tt>true</tt>.
     *
     * Example: showViolations = false
     */
    public void setShowViolations(boolean showViolations) {
        this.showViolations = showViolations;
    }
}


text:
package org.eigenbase.dmv;

import java.util.*;

import javax.jmi.reflect.*;

import org.eigenbase.jmi.*;

/**
 * DmvResponse represents the result of a DMV query.
 *
 * @author John Sichi
 * @version $Id$
 */
public class DmvResponse
{
    //~ Instance fields --------------------------------------------------------

    private final Collection<RefObject> searchResult;

    private final JmiDependencyGraph transformationResult;

    //~ Constructors -----------------------------------------------------------

    public DmvResponse(
        Collection<RefObject> searchResult,
        JmiDependencyGraph transformationResult)
    {
        this.searchResult = searchResult;
        this.transformationResult = transformationResult;
    }

    //~ Methods ----------------------------------------------------------------

    public Collection<RefObject> getSearchResult()
    {
        return searchResult;
    }

    public JmiDependencyGraph getTransformationResult()
    {
        return transformationResult;
    }
}

// End DmvResponse.java


text:
package com.spit.spirit17.HelperClasses;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.spit.spirit17.R;

/**
 * Created by Tejas on 04/01/2017.
 */

public class CustomPagerAdapter extends PagerAdapter {

    private Context mContext;
    private LayoutInflater mLayoutInflater;

    private int[] mResources = {
            R.drawable.viewpager_1
    };

    public CustomPagerAdapter(android.content.Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mResources.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.viewpager_image);
        imageView.setImageResource(mResources[position]);
        container.addView(itemView);
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }

}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Utility functions to be used in trusted code.
 */

import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js';

import {WallpaperImage, WallpaperLayout} from '../trusted/personalization_app.mojom-webui.js';

export function isWallpaperImage(obj: any): obj is WallpaperImage {
  return typeof obj?.assetId === 'bigint';
}

export function isFilePath(obj: any): obj is FilePath {
  return typeof obj?.path === 'string' && obj.path;
}

/**
 * Convert a string layout value to the corresponding enum.
 */
export function getWallpaperLayoutEnum(layout: string): WallpaperLayout {
  switch (layout) {
    case 'FILL':
      return WallpaperLayout.kCenterCropped;
    case 'CENTER':  // fall through
    default:
      return WallpaperLayout.kCenter;
  }
}

/**
 * Checks if argument is a string with non-zero length.
 */
export function isNonEmptyString(maybeString: unknown): maybeString is string {
  return typeof maybeString === 'string' && maybeString.length > 0;
}


text:
package org.springframework.boot.loader.archive;

import org.springframework.boot.loader.util.AsciiBytes;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.jar.Manifest;

/**
 * An archive that can be launched by the {@link org.springframework.boot.loader.Launcher}.
 *
 * @author Phillip Webb
 * @see JarFileArchive
 */
public abstract class Archive {

	/**
	 * Returns a URL that can be used to load the archive.
	 * @return the archive URL
	 * @throws java.net.MalformedURLException
	 */
	public abstract URL getUrl() throws MalformedURLException;

	/**
	 * Obtain the main class that should be used to launch the application. By default
	 * this method uses a {@code Start-Class} manifest entry.
	 * @return the main class
	 * @throws Exception
	 */
	public String getMainClass() throws Exception {
		Manifest manifest = getManifest();
		String mainClass = null;
		if (manifest != null) {
			mainClass = manifest.getMainAttributes().getValue("Start-Class");
		}
		if (mainClass == null) {
			throw new IllegalStateException(
					"No 'Start-Class' manifest entry specified in " + this);
		}
		return mainClass;
	}

	@Override
	public String toString() {
		try {
			return getUrl().toString();
		}
		catch (Exception ex) {
			return "archive";
		}
	}

	/**
	 * Returns the manifest of the archive.
	 * @return the manifest
	 * @throws java.io.IOException
	 */
	public abstract Manifest getManifest() throws IOException;

	/**
	 * Returns all entries from the archive.
	 * @return the archive entries
	 */
	public abstract Collection<Entry> getEntries();

	/**
	 * Returns nested {@link Archive}s for entries that match the specified filter.
	 * @param filter the filter used to limit entries
	 * @return nested archives
	 * @throws java.io.IOException
	 */
	public abstract List<Archive> getNestedArchives(EntryFilter filter)
			throws IOException;

	/**
	 * Returns a filtered version of the archive.
	 * @param filter the filter to apply
	 * @return a filter archive
	 * @throws java.io.IOException
	 */
	public abstract Archive getFilteredArchive(EntryRenameFilter filter)
			throws IOException;

	/**
	 * Represents a single entry in the archive.
	 */
	public static interface Entry {

		/**
		 * Returns {@code true} if the entry represents a directory.
		 * @return if the entry is a directory
		 */
		boolean isDirectory();

		/**
		 * Returns the name of the entry
		 * @return the name of the entry
		 */
		AsciiBytes getName();

	}

	/**
	 * Strategy interface to filter {@link Entry Entries}.
	 */
	public static interface EntryFilter {

		/**
		 * Apply the jar entry filter.
		 * @param entry the entry to filter
		 * @return {@code true} if the filter matches
		 */
		boolean matches(Entry entry);

	}

	/**
	 * Strategy interface to filter or rename {@link Entry Entries}.
	 */
	public static interface EntryRenameFilter {

		/**
		 * Apply the jar entry filter.
		 * @param entryName the current entry name. This may be different that the
		 * original entry name if a previous filter has been applied
		 * @param entry the entry to filter
		 * @return the new name of the entry or {@code null} if the entry should not be
		 * included.
		 */
		AsciiBytes apply(AsciiBytes entryName, Entry entry);

	}

}


text:
pg.modal = function() {

	var notice = function(msg, type) {
		var $fader = jQuery('
');
		var $container = jQuery('
');
		var $header = jQuery('
Notice
');
		var $okButton = jQuery('<button class="okButton adminButton">Ok</button>');
		if(type === 'error') {
			$header.text('Error');
		}
		var $message = jQuery('
'+msg+'
');

		$fader.append($container);
		$container.append($header);
		$container.append($message);
		$container.append($okButton);

		$fader.appendTo(jQuery('body'));
		$container.css({
			'margin-top': -container.outerHeight()*0.5+'px'
		});

		$okButton.click(function() {
			$fader.remove();
		});
	};

	var floater = function(id, title, html, width, top) {
		if(jQuery('#'+id).length > 0) return;

		var $container = jQuery('
');
		var $header = jQuery('');
		var $body = jQuery('
');
		var $title = jQuery('
'+title+'
');
		var $closeButton = jQuery('<button class="closeButton" title="Close">×</button>');
		var $message = jQuery(html);

		$header.append($title,$closeButton);
		$body.append($message);
		$container.append($header, $body);
		$container.appendTo(jQuery('body'));

		$container.draggable({
			containment: "parent",
			handle: "header"
		});
		$container.css({
			'width': width,
			'left': jQuery('body').width()*0.5 - $container.width()*0.5 + 40,
			'top': top

		});

		$closeButton.click(function() {
			$container.remove();
		});

	};

	var confirm = function(msg, title, callback) {
		var $fader = jQuery('
');
		var $container = jQuery('
');
		var $header = jQuery('
'+title+'
');
		var $message = jQuery('
'+msg+'
');

		var $yesButton = jQuery('<button class="yesButton adminButton">Yes</button>');
		var $noButton = jQuery('<button class="noButton adminButton">No</button>');

		$fader.append($container);
		$container.append($header);
		$container.append($message);
		$container.append($yesButton);
		$container.append($noButton);

		$fader.appendTo(jQuery('body'));
		$container.css({
			'margin-top': -container.outerHeight()*0.5+'px'
		});

		$yesButton.click(function() {
			callback();
			$fader.remove();
		});

		$noButton.click(function() {
			$fader.remove();
		});
	};

	var form = function(html, title, callback) {
		var $fader = jQuery('
');
		var $container = jQuery('
');
		var $header = jQuery('
'+title+'
');
		var $content = jQuery(html);

		var saveButton = jQuery('<button class="saveButton adminButton">Save</button>');
		var cancelButton = jQuery('<button class="cancelButton adminButton">Cancel</button>');

		$fader.append($container);
		$container.append($header);
		$container.append($content);
		$container.append(saveButton);
		$container.append(cancelButton);

		$fader.appendTo(jQuery('body'));
		$container.css({
			'margin-top': -container.outerHeight()*0.5+'px'
		});

		saveButton.click(function() {
			callback(html);
			$fader.remove();
		});

		cancelButton.click(function() {
			try{resetContentEditingState();}catch(e) {}
			$fader.remove();
		});

		setTimeout(function() {
			$container.css({
				'margin-top': -container.outerHeight()*0.5+'px'
			});
		}, 10);
	};

	return {
		notice:notice,
		floater:floater,
		confirm:confirm,
		form:form
	};
}();


text:
Plotting a Call Graph
=====================

Usage
-----

Using Windows 8.1 ``http.sys``. Before ``MS15-034``.

.. code:: python

    draw_call_graph(sark.Function(name="_UlpParseRange@32").ea, to=True, distance=4)

.. figure:: ../media/examples/httpsys8_1_callgraph.png
   :alt:

Code
----

.. code:: python

    import sark
    import networkx as nx

    def draw_call_graph(ea, distance=2, to=False):
        # First, get the IDB graph (caching it might be a good idea
        # as this operation can be time consuming on large IDBs)
        idb_graph = sark.graph.get_idb_graph()

        # Get the address of the function to use in the graph
        func_ea = sark.Function(ea).ea

        # Create the call graph
        if to:
            # If we want the calls to our function, we need to reverse
            # the graph
            idb_graph = idb_graph.reverse()

        # Use NetworkX to limit the IDB graph
        call_graph = nx.ego_graph(idb_graph, func_ea, distance)

        # Paint the root node red
        call_graph.node[func_ea][sark.ui.NXGraph.BG_COLOR] = 0x80

        if to:
            # If we reversed it before, we need to reverse it again
            # to make the links point the right way
            call_graph = call_graph.reverse()

        # Create an NXGraph viewer
        viewer = sark.ui.NXGraph(call_graph, handler=sark.ui.AddressNodeHandler())

        # Show the graph
        viewer.Show()


text:
How can you use Chrome's DevTools inspector to help you format or position elements?
Chrome's devtools is a powerful DOM inspector with a great visual representation of what is going on in a webpage. You can highlight individual elements and edit them within devtools. You can change margins, positiong, and a variety of different aspects that change the appearance of the elements.
How can you resize elements on the DOM using CSS?
You can input size values in percentages, em, and px. It is a versatile tool for sizing the elements as needed per webpage.
What are the differences between Absolute, Fixed, Static, and Relative positioning? Which did you find easiest to use? Which was most difficult?
Static is the default for all page elements. It means elements flow as they normally would. Absolute is a powerful type of positioning that places any element on any part of the webpage exactly as intended without interference from other elements. Fixed allows elements to stay the same relative to the viewport - meaning if a user scrolls, that element will stay in the same location in the new view. Relative can be a difficult positioning tool. Relative elements require other relative elements to be utilized properly.
What are the differences between Margin, Border, and Padding?
Padding = a transparent area around the content. Border = a border that goes around the content / padding. Margin = The transparent area around the border.
What was your impression of this challenge overall? (love, hate, and why?)
Was annoying at times. I felt like it should have been an easier exercise, but was made difficult for no good reason.

![1](imgs/1.png)
![2](imgs/2.png)
![3](imgs/3.png)
![4](imgs/4.png)
![5](imgs/5.png)
![6](imgs/6.png)
![7](imgs/7.png)
![8](imgs/8.png)
![9](imgs/9.png)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Pure Bootstrap Datepicker</title>
    <link href="components/bootstrap/docs/assets/css/bootstrap.css" rel="stylesheet">
    <link href="../css/datepicker.css" rel="stylesheet">

    <link href="components/google-code-prettify/src/prettify.css" rel="stylesheet">
    <link href="docs.css" rel="stylesheet">
    <link rel="stylesheet" href="components/font-awesome/css/font-awesome.min.css">

          Pure Bootstrap Datepicker

Docs and examples

Dark theme

Watch on GitHub

Pure Bootstrap Datepicker bootstrap-datepicker.js

About

Add datepicker picker to field or to any other element.

can be used as a component

formats: dd, d, mm, m, yyyy, yy

separators: -, /, .

Download v1.0.1

Download Development

 Examples

 Using bootstrap-datepicker.js

 Options

 Markup

 Methods

 Events

 Keyboard support

 I18N

 Sandbox

Examples

Attached to a field with the format specified via options.

<input type="text" id="dp1">

$('#dp1').datepicker();

Attached to a field with the format specified via data tag.

<input type="text" value="02/16/13" data-date-format="mm/dd/yy" id="dp2">

$('#dp2').datepicker();

As component.

<div class="input-append date" id="dp3" data-date-format="dd-mm-yyyy">
    <input class="span2" size="16" type="text" value="12-02-2013" readonly><a class="btn"><i class="icon-calendar"></i></a>
</div>

$('#dp3').datepicker();

Attached to non-field element, using events to work with the date values.

<a href="#" class="btn small" id="dp4" data-date-format="yyyy-mm-dd" data-date="2013-02-20">Change</a>

$('#dp4').datepicker()
    .on('changeDate', function(e){
        var y = e.date.getFullYear(),
            _m = e.date.getMonth() + 1,
            m = (_m > 9 ? _m : '0'+_m),
            _d = e.date.getDate(),
            d = (_d > 9 ? _d : '0'+_d);
        $(this).text(y + '-' + m + '-' + d);
    });

Inline/embedded picker

<div id="dp5" data-date="12-02-2013" data-date-format="dd-mm-yyyy"></div>

$('#dp5').datepicker();

Using bootstrap-datepicker.js

Call the datepicker via javascript:

$('.datepicker').datepicker()

Options

                  Name
                  Type
                  Default
                  Description

                  format
                  string
                  'mm/dd/yyyy'
                  The date format, combination of d, dd, D, DD, m, mm, M, MM, yy, yyyy.

                  weekStart
                  number
                  0
                  Day of the week start. 0 (Sunday) to 6 (Saturday)

                  calendarWeeks
                  boolean
                  false
                  Whether or not to show week numbers to the left of week rows.

                  startDate
                  date
                  -Infinity
                  The earliest date that may be selected; all earlier dates will be disabled.

                  endDate
                  date
                  Infinity
                  The latest date that may be selected; all later dates will be disabled.

                  daysOfWeekDisabled
                  string, array
                  []
                  Days of the week that should be disabled. Values are 0 (Sunday) to 6 (Saturday). Multiple values should be comma-separated. Example: disable weekends: '0,6' or [0,6].

                  autoclose
                  boolean
                  false
                  Whether or not to close the datepicker immediately when a date is selected.

                  startView
                  number, string
                  0, 'month'
                  The view that the datepicker should show when it is opened.  Accepts values of 0 or 'month' for month view (the default), 1 or 'year' for the 12-month overview, and 2 or 'decade' for the 10-year overview.  Useful for date-of-birth datepickers.

                  minViewMode
                  number, string
                  0, 'days'
                  Set a limit for the view mode.  Accepts: 'days' or 0, 'months' or 1, and 'years' or 2.  Gives the ability to pick only a month or an year.  The day is set to the 1st for 'months', and the month is set to January for 'years'.

                  todayBtn
                  boolean, "linked"
                  false
                  If true or "linked", displays a "Today" button at the bottom of the datepicker to select the current date.  If true, the "Today" button will only move the current date into view; if "linked", the current date will also be selected.

                  todayHighlight
                  boolean
                  false
                  If true, highlights the current date.

                  keyboardNavigation
                  boolean
                  true
                  Whether or not to allow date navigation by arrow keys.

                  language
                  string
                  "en"
                  The IETF code (eg  "en" for English, "pt-BR" for Brazilian Portuguese) of the language to use for month and day names.  These will also be used as the input's value (and subsequently sent to the server in the case of form submissions).  If a full code (eg "de-DE") is supplied the picker will first check for an "de-DE" language and if not found will fallback and check for a "de" language.  If an unknown language code is given, English will be used.  See I18N below.

                  forceParse
                  boolean
                  true
                  Whether or not to force parsing of the input value when the picker is closed.  That is, when an invalid date is left in the input field by the user, the picker will forcibly parse that value, and set the input's value to the new, valid date, conforming to the given format.

Markup data-attributes

Any option can be specified as a data-attribute by taking the option name, replacing each uppercase letter with a corresponding lowercase letter prepended by a dash, and prepending the whole name with data-date-.  For example, autoclose would become data-date-autoclose and daysOfWeekDisabled would become data-date-days-of-week-disabled.

Format a component.

<div class="input-append date" id="datepicker" data-date-format="dd-mm-yyyy">
  <input type="text" value="12-02-2013"><span class="add-on"><i class="icon-th"></i></span>
</div>

Format inline.

<div data-date="12-02-2012" data-date-format="dd-mm-yyyy"></div>

Methods

                  Method
                  Args
                  Type
                  ?
                  Description

                  .datepicker(options)

                  Initializes an datepicker.

                  remove

                  Remove the datepicker.  Removes attached events, internal attached objects, and added HTML elements.

                  show

                  Show the datepicker.

                  hide

                  Hide the datepicker.

                  update
                  date
                  string
                  ✖
                  Update the datepicker with the current input value or given date as argument. In second case input will be updated as well.

                  setStartDate
                  date
                  string
                  ✖
                  Sets a new lower date limit on the datepicker.  Omit date (or provide an otherwise falsey value) to unset the limit.

                  setEndDate
                  date
                  string
                  ✖
                  Sets a new upper date limit on the datepicker.  Omit date (or provide an otherwise falsey value) to unset the limit.

                  setDaysOfWeekDisabled
                  dates
                  string, array
                  ✖
                  Sets the days of week that should be disabled.  Omit dates (or provide an otherwise falsey value) to unset the disabled days.

Events

Datepicker class exposes a few events for manipulating the dates.

                  Event
                  Description

                  show
                  Fired immediately when the date picker is displayed.

                  hide
                  Fired immediately when the date picker is hidden.

                  changeDate

                    Fired when the date is changed.

$('.datepicker').datepicker()
    .on('changeDate', function(e){
        alert(e.date.toString());
    });

                  changeYear
                  Fired when the view year is changed from decade view.

                  changeMonth
                  Fired when the view month is changed from year view.

Keyboard support

The datepicker includes some keyboard navigation:

up, down, left, right arrow keys

By themselves, left/right will move backward/forward one day, up/down will move back/forward one week.

With the shift key, up/left will move backward one month, down/right will move forward one month.

With the ctrl key, up/left will move backward one year, down/right will move forward oone year.

Shift+ctrl behaves the same as ctrl -- that is, it does not change both month and year simultaneously, only the year.

escape

The escape key can be used to hide and re-show the datepicker; this is necessary if the user wants to manually edit the value.

enter

When the picker is visible, enter will simply hide it. When the picker is not visible, enter will have normal effects -- submitting the current form, etc.

I18N

The plugin supports i18n for the month and weekday names and the
                weekStart
                option. The default is English ('en'); other available translations are avilable in the
                js/locales/
                directory, simply include your desired locale after the plugin. To add more languages, simply add a key to
                $.fn.datepicker.dates
                , before calling
                .datepicker()
                . Example:

$.fn.datepicker.dates['en'] = {
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
};

If your browser (or those of your users) is displaying characters wrong, chances are the browser is loading the javascript file with a non-unicode encoding.  Simply add charset="UTF-8" to your script tag:

<script type="text/javascript" src="bootstrap-datepicker.XX.js" charset="UTF-8"></script>

$('.datepicker').datepicker({
    language: 'XX' // as defined in bootstrap-datepicker.XX.js
});

Sandbox αlphα

Use the form below to tweak the options; results and code appear in realtime below.

As you change options, your address bar will update to reflect the current configuration (requires a browser with history.replaceState support).  This url can be used to link to the sandbox with the given configuration pre-loaded.

            <form class="form-inline sandbox-form">

                Type:

                  <input name="markup" value="input" type="radio" checked>
                  Text input

                  <input name="markup" value="component" type="radio">
                  Component

                  <input name="markup" value="embedded" type="radio">
                  Embedded / inline

                Options:

                Format
                  <input class="span2" id="format" name="format" type="text" placeholder="mm/dd/yyyy">
                Week start
                  <input class="span1" id="weekStart" name="weekStart" type="text" placeholder="0">
                Start date
                  <input class="span2" id="startDate" name="startDate" type="text" placeholder="-Infinity">
                End date
                  <input class="span2" id="endDate" name="endDate" type="text" placeholder="+Infinity">
                Start view
                  <select class="span2" id="startView" name="startView">
                    <option value="0">0 / month</option>
                    <option value="1">1 / year</option>
                    <option value="2">2 / decade</option>
                  </select>

                Min view mode
                  <select class="span2" id="minViewMode" name="minViewMode">
                    <option value="0">0 / days</option>
                    <option value="1">1 / months</option>
                    <option value="2">2 / years</option>
                  </select>

                Today button
                  <select class="span2" id="todayBtn" name="todayBtn">
                    <option value="false">disabled</option>
                    <option value="true">enabled (unlinked)</option>
                    <option value="linked">linked</option>
                  </select>

                Language
                  <select class="span1" id="language" name="language">
                    <option value="en">en</option>
                  </select>

                Days of week disabled:
                  <input type="checkbox" name="daysOfWeekDisabled" value="0"> 0
                  <input type="checkbox" name="daysOfWeekDisabled" value="1"> 1
                  <input type="checkbox" name="daysOfWeekDisabled" value="2"> 2
                  <input type="checkbox" name="daysOfWeekDisabled" value="3"> 3
                  <input type="checkbox" name="daysOfWeekDisabled" value="4"> 4
                  <input type="checkbox" name="daysOfWeekDisabled" value="5"> 5
                  <input type="checkbox" name="daysOfWeekDisabled" value="6"> 6

                  <input id="calendarWeeks" name="calendarWeeks" type="checkbox">
                  Calendar weeks

                  <input id="autoclose" name="autoclose" type="checkbox">
                  Autoclose

                  <input id="todayHighlight" name="todayHighlight" type="checkbox">
                  Today highlight

                  <input id="keyboardNavigation" name="keyboardNavigation" type="checkbox" checked>
                  Keyboard navigation

                  <input id="forceParse" name="forceParse" type="checkbox" checked>
                  Force parse

                <button class="btn btn-danger" type="reset">Reset to defaults</button>

            </form>

bootstrap-datepicker was started by Stefan Petre; improvements by @eternicode and various contributors.

Andrew Rowls 2012-2013


text:
package org.g_node.nix;

import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.annotation.*;
import org.g_node.nix.internal.None;
import org.g_node.nix.internal.VectorUtils;
import org.g_node.nix.base.ImplContainer;
import org.g_node.nix.internal.BuildLibs;

import java.util.List;

/**
 *
SetDimension

 * Dimension descriptor for a dimension that represents just a list or set of values.
 *

 * The SetDimension is used in cases where data is given as a set or list. This can be just a collection of values but
 * also a list of recorded signals or a stack of images. Optionally an array of labels, one for each index of this
 * dimension, can be specified.
 *
 * @see Dimension
 * @see RangeDimension
 * @see SampledDimension
 */

@Properties(value = {
        @Platform(include = {"<nix/Dimensions.hpp>"}),
        @Platform(value = "linux", link = BuildLibs.NIX_1, preload = BuildLibs.HDF5_7),
        @Platform(value = "windows",
                link = BuildLibs.NIX,
                preload = {BuildLibs.HDF5, BuildLibs.MSVCP120, BuildLibs.MSVCR120, BuildLibs.SZIP, BuildLibs.ZLIB})})
@Namespace("nix")
public class SetDimension<T extends SetDimension> extends ImplContainer implements Comparable<T> {
    static {
        Loader.load();
    }

    //--------------------------------------------------
    // Constructors
    //--------------------------------------------------

    /**
     * Constructor that creates an uninitialized SetDimension.
     *

     * Calling any method on an uninitialized dimension will throw a {@link java.lang.RuntimeException}.
     */
    public SetDimension() {
        allocate();
    }

    private native void allocate();

    //--------------------------------------------------
    // Base class methods
    //--------------------------------------------------

    public native
    @Cast("bool")
    boolean isNone();

    //--------------------------------------------------
    // Methods concerning SetDimension
    //--------------------------------------------------

    /**
     * The actual dimension that is described by the dimension descriptor.
     *

     * The index of the dimension entity representing the dimension of the actual
     * data that is defined by this descriptor.
     *
     * @return The dimension index of the dimension.
     */
    public native
    @Name("index")
    @Cast("size_t")
    long getIndex();

    /**
     * The type of the dimension.
     *

     * This field indicates whether the dimension is a SampledDimension, SetDimension or
     * RangeDimension.
     *
     * @return The dimension type. Constants specified in {@link DataType}
     * @see DataType
     */
    public native
    @Name("dimensionType")
    @ByVal
    @Cast("nix::DimensionType")
    int getDimensionType();

    private native
    @ByVal
    VectorUtils.StringVector labels();

    /**
     * Get the labels of the range dimension.
     *

     * The labels serve as names for each index of the data at the respective
     * dimension.
     *
     * @return The labels of the dimension as a list of strings.
     */
    public List<String> getLabels() {
        return labels().getStrings();
    }

    private native void labels(@Const @ByRef VectorUtils.StringVector labels);

    private native void labels(@Const @ByVal None t);

    /**
     * Set the labels for the dimension.
     *
     * @param labels A list containing all new labels. If <tt>null</tt> removes the labels from the dimension.
     */
    public void setLabels(List<String> labels) {
        if (labels != null) {
            labels(new VectorUtils.StringVector(labels));
        } else {
            labels(new None());
        }
    }

    //--------------------------------------------------
    // Overrides
    //--------------------------------------------------

    @Override
    public int compareTo(T dimension) {
        if (this == dimension) {
            return 0;
        }
        return (int) (this.getIndex() - dimension.getIndex());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 1: 461 (1922)

#### Original name
Verrucaria emergens J. Steiner

### Remarks
null


text:
<?php
// http://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f
// http://stackoverflow.com/questions/4320081/clear-php-cli-output

function replaceOut($str)
{
    $numNewLines = substr_count($str, "\n");
    echo chr(27) . "[0G"; // Set cursor to first column
    echo $str;
    echo chr(27) . "[" . $numNewLines ."A"; // Set cursor up x lines
}

function redraw($c) {
    replaceOut("First Ln\nTime: " . time() . "\nThird Ln" . ord($c));

}

/*
while (true) {
    sleep(1);
}
*/

redraw('');

system("stty -icanon");
while ($c = fread(STDIN, 1)) {
    redraw($c);
}


text:
object SomeObject {
  def someMethod: String = ""
  /*start*/SomeObject.someMethod(1)/*end*/
}
//Int