text:
/**
 * Handle X events.
 */
package au.com.darkside.XServer;

import android.util.SparseArray;

import java.io.IOException;

/**
 * @author Matthew Kwan
 *
 * Handle X events.
 */
public class EventCode {
	public static final byte	KeyPress = 2;
	public static final byte	KeyRelease = 3;
	public static final byte	ButtonPress = 4;
	public static final byte	ButtonRelease = 5;
	public static final byte	MotionNotify = 6;
	public static final byte	EnterNotify = 7;
	public static final byte	LeaveNotify = 8;
	public static final byte	FocusIn = 9;
	public static final byte	FocusOut = 10;
	public static final byte	KeymapNotify = 11;
	public static final byte	Expose = 12;
	public static final byte	GraphicsExposure = 13;
	public static final byte	NoExposure = 14;
	public static final byte	VisibilityNotify = 15;
	public static final byte	CreateNotify = 16;
	public static final byte	DestroyNotify = 17;
	public static final byte	UnmapNotify = 18;
	public static final byte	MapNotify = 19;
	public static final byte	MapRequest = 20;
	public static final byte	ReparentNotify = 21;
	public static final byte	ConfigureNotify = 22;
	public static final byte	ConfigureRequest = 23;
	public static final byte	GravityNotify = 24;
	public static final byte	ResizeRequest = 25;
	public static final byte	CirculateNotify = 26;
	public static final byte	CirculateRequest = 27;
	public static final byte	PropertyNotify = 28;
	public static final byte	SelectionClear = 29;
	public static final byte	SelectionRequest = 30;
	public static final byte	SelectionNotify = 31;
	public static final byte	ColormapNotify = 32;
	public static final byte	ClientMessage = 33;
	public static final byte	MappingNotify = 34;

	public static final int		MaskKeyPress = 0x00000001;
	public static final int		MaskKeyRelease = 0x00000002;
	public static final int		MaskButtonPress = 0x00000004;
	public static final int		MaskButtonRelease = 0x00000008;
	public static final int		MaskEnterWindow = 0x00000010;
	public static final int		MaskLeaveWindow = 0x00000020;
	public static final int		MaskPointerMotion = 0x00000040;
	public static final int		MaskPointerMotionHint = 0x00000080;
	public static final int		MaskButton1Motion = 0x00000100;
	public static final int		MaskButton2Motion = 0x00000200;
	public static final int		MaskButton3Motion = 0x00000400;
	public static final int		MaskButton4Motion = 0x00000800;
	public static final int		MaskButton5Motion = 0x00001000;
	public static final int		MaskButtonMotion = 0x00002000;
	public static final int		MaskKeymapState = 0x00004000;
	public static final int		MaskExposure = 0x00008000;
	public static final int		MaskVisibilityChange = 0x00010000;
	public static final int		MaskStructureNotify = 0x00020000;
	public static final int		MaskResizeRedirect = 0x00040000;
	public static final int		MaskSubstructureNotify = 0x00080000;
	public static final int		MaskSubstructureRedirect = 0x00100000;
	public static final int		MaskFocusChange = 0x00200000;
	public static final int		MaskPropertyChange = 0x00400000;
	public static final int		MaskColormapChange = 0x00800000;
	public static final int		MaskOwnerGrabButton = 0x01000000;

	public static final int		MaskAllPointer = MaskButtonPress
		| MaskButtonRelease | MaskPointerMotion | MaskPointerMotionHint
		| MaskButton1Motion | MaskButton2Motion | MaskButton3Motion
		| MaskButton4Motion | MaskButton5Motion | MaskButtonMotion;

	private static final SparseArray<String> mCodes = new SparseArray<String>();

	/**
	 * Write an event header.
	 *
	 * @param client	The client to write to.
	 * @param code	The event code.
	 * @param arg	Optional first argument.
	 * @throws IOException
	 */
	private static void
	writeHeader (
		Client			client,
		byte			code,
		int				arg
	) throws IOException {
		InputOutput		io = client.getInputOutput ();

		io.writeByte ((byte) code);
		io.writeByte ((byte) arg);
		io.writeShort ((short) (client.getSequenceNumber () & 0xffff));
	}

	/**
	 * Send a key press event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param keycode	The code of the key that was pressed.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @throws IOException
	 */
	public static void
	sendKeyPress (
		Client			client,
		int				timestamp,
		int				keycode,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state
	) throws IOException {
		logKeyEvent(KeyPress, keycode, root, eventWindow, child, rootX, rootY,
					eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, KeyPress, keycode);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) 1);	// Same screen.
			io.writePadBytes (1);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a key release event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param keycode	The code of the key that was released.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @throws IOException
	 */
	public static void
	sendKeyRelease (
		Client			client,
		int				timestamp,
		int				keycode,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state
	) throws IOException {
		logKeyEvent(KeyRelease, keycode, root, eventWindow, child, rootX, rootY,
					eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, KeyRelease, keycode);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) 1);	// Same screen.
			io.writePadBytes (1);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a button press event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param button	The button that was pressed.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @throws IOException
	 */
	public static void
	sendButtonPress (
		Client			client,
		int				timestamp,
		int				button,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state
	) throws IOException {
		logButtonEvent(ButtonPress, button, root, eventWindow, child, rootX,
					   rootY, eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ButtonPress, button);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) 1);	// Same screen.
			io.writePadBytes (1);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a button release event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param button	The button that was released.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @throws IOException
	 */
	public static void
	sendButtonRelease (
		Client			client,
		int				timestamp,
		int				button,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state
	) throws IOException {
		logButtonEvent(ButtonRelease, button, root, eventWindow, child, rootX,
					   rootY, eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ButtonRelease, button);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) 1);	// Same screen.
			io.writePadBytes (1);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a motion notify event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param detail	0=Normal, 1=Hint.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @throws IOException
	 */
	public static void
	sendMotionNotify (
		Client			client,
		int				timestamp,
		int				detail,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state
	) throws IOException {
		logMotionEvent(MotionNotify, detail, root, eventWindow, child, rootX,
					   rootY, eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, MotionNotify, detail);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) 1);	// Same screen.
			io.writePadBytes (1);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send an enter notify event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param detail	0=Ancestor, 1=Virtual, 2=Inferior, 3=Nonlinear, 4=NonlinearVirtual.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @param mode	0=Normal, 1=Grab, 2=Ungrab.
	 * @param focus	Is the event window the focus window or an inferior of it?
	 * @throws IOException
	 */
	public static void
	sendEnterNotify (
		Client			client,
		int				timestamp,
		int				detail,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state,
		int				mode,
		boolean			focus
	) throws IOException {
		logMotionEvent(EnterNotify, detail, root, eventWindow, child, rootX,
					   rootY, eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, EnterNotify, detail);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) mode);	// Mode.
			io.writeByte ((byte) (focus ? 3 : 2));	// Same screen, focus.
		}
		io.flush ();
	}

	/**
	 * Send a leave notify event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param detail	0=Ancestor, 1=Virtual, 2=Inferior, 3=Nonlinear,
	 *												4=NonlinearVirtual.
	 * @param root	The root window of the event window.
	 * @param eventWindow	The window interested in the event.
	 * @param child	Child of event window, ancestor of source. Can be null.
	 * @param rootX	Pointer root X coordinate at the time of the event.
	 * @param rootY	Pointer root Y coordinate at the time of the event.
	 * @param eventX	Pointer X coordinate relative to event window.
	 * @param eventY	Pointer Y coordinate relative to event window.
	 * @param state	Bitmask of the buttons and modifier keys.
	 * @param mode	0=Normal, 1=Grab, 2=Ungrab.
	 * @param focus	Is the event window the focus window or an inferior of it?
	 * @throws IOException
	 */
	public static void
	sendLeaveNotify (
		Client			client,
		int				timestamp,
		int				detail,
		Window			root,
		Window			eventWindow,
		Window			child,
		int				rootX,
		int				rootY,
		int				eventX,
		int				eventY,
		int				state,
		int				mode,
		boolean			focus
	) throws IOException {
		logMotionEvent(LeaveNotify, detail, root, eventWindow, child, rootX,
					   rootY, eventX, eventY, state);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, LeaveNotify, detail);
			io.writeInt (timestamp);	// Time.
			io.writeInt (root.getId ());	// Root.
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (child == null ? 0 : child.getId ());	// Child.
			io.writeShort ((short) rootX);	// Root X.
			io.writeShort ((short) rootY);	// Root Y.
			io.writeShort ((short) eventX);	// Event X.
			io.writeShort ((short) eventY);	// Event Y.
			io.writeShort ((short) state);	// State.
			io.writeByte ((byte) mode);	// Mode.
			io.writeByte ((byte) (focus ? 3 : 2));	// Same screen, focus.
		}
		io.flush ();
	}

	/**
	 * Send a focus in event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param detail	0=Ancestor, 1=Virtual, 2=Inferior, 3=Nonlinear,
	 *					4=NonlinearVirtual, 5=Pointer, 6=PinterRoot, 7=None.
	 * @param eventWindow	The window interested in the event.
	 * @param mode	0=Normal, 1=Grab, 2=Ungrab, 3=WhileGrabbed.
	 * @throws IOException
	 */
	public static void
	sendFocusIn (
		Client			client,
		int				timestamp,
		int				detail,
		Window			eventWindow,
		int				mode
	) throws IOException {
        logFocusEvent(FocusIn, detail, eventWindow, mode);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, FocusIn, detail);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeByte ((byte) mode);	// Mode.
			io.writePadBytes (23);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a focus out event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Time in milliseconds since last server reset.
	 * @param detail	0=Ancestor, 1=Virtual, 2=Inferior, 3=Nonlinear,
	 *					4=NonlinearVirtual, 5=Pointer, 6=PinterRoot, 7=None.
	 * @param eventWindow	The window interested in the event.
	 * @param mode	0=Normal, 1=Grab, 2=Ungrab, 3=WhileGrabbed.
	 * @throws IOException
	 */
	public static void
	sendFocusOut (
		Client			client,
		int				timestamp,
		int				detail,
		Window			eventWindow,
		int				mode
	) throws IOException {
		logFocusEvent(FocusOut, detail, eventWindow, mode);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, FocusOut, detail);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeByte ((byte) mode);	// Mode.
			io.writePadBytes (23);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a keymap notify event.
	 *
	 * @param client	The client to write to.
	 * @param keys	A bit vector of the logical state of the keyboard.
	 * @throws IOException
	 */
	public static void
	sendKeymapNotify (
		Client			client,
		byte[]			keys
	) throws IOException {
		logKeymapNotify(keys);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			io.writeByte (KeymapNotify);
			io.writeBytes (keys, 0, 31);	// Keys.
		}
		io.flush ();
	}

	/**
	 * Send an expose event.
	 *
	 * @param client	The client to write to.
	 * @param window	The window where the exposure occurred.
	 * @param x	Left of the exposed rectangle.
	 * @param y	Top of the exposed rectangle.
	 * @param width	Width of the exposed rectangle.
	 * @param height	Height of the exposed rectangle.
	 * @param count	Number of rectangles remaining in the exposed region.
	 * @throws IOException
	 */
	public static void
	sendExpose (
		Client			client,
		Window			window,
		int				x,
		int				y,
		int				width,
		int				height,
		int				count
	) throws IOException {
		log(Expose);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, Expose, 0);
			io.writeInt (window.getId ());	// Event.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writeShort ((short) count);	// Count.
			io.writePadBytes (14);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a graphics exposure event.
	 *
	 * @param client	The client to write to.
	 * @param drawable	The drawable where the exposure occurred.
	 * @param majorOpcode	The graphics request that caused the event.
	 *						Either CopyArea or CopyPlane.
	 * @param x	Left of the exposed rectangle.
	 * @param y	Top of the exposed rectangle.
	 * @param width	Width of the exposed rectangle.
	 * @param height	Height of the exposed rectangle.
	 * @param count	Number of rectangles remaining in the exposed region.
	 * @throws IOException
	 */
	public static void
	sendGraphicsExposure (
		Client			client,
		Resource		drawable,
		byte			majorOpcode,
		int				x,
		int				y,
		int				width,
		int				height,
		int				count
	) throws IOException {
		log(GraphicsExposure);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, GraphicsExposure, 0);
			io.writeInt (drawable.getId ());	// Drawable.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writeShort ((short) 0);	// Minor opcode.
			io.writeShort ((short) count);	// Count.
			io.writeByte ((byte) majorOpcode);	// Major opcode.
			io.writePadBytes (11);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a no exposure event.
	 *
	 * @param client	The client to write to.
	 * @param drawable	The drawable where no exposure exposure occurred.
	 * @param majorOpcode	The graphics request that caused the event.
	 *						Either CopyArea or CopyPlane.
	 * @throws IOException
	 */
	public static void
	sendNoExposure (
		Client			client,
		Resource		drawable,
		byte			majorOpcode
	) throws IOException {
		log(NoExposure);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, NoExposure, 0);
			io.writeInt (drawable.getId ());	// Drawable.
			io.writeShort ((short) 0);	// Minor opcode.
			io.writeByte ((byte) majorOpcode);	// Major opcode.
			io.writePadBytes (21);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a visibility notify event.
	 *
	 * @param client	The client to write to.
	 * @param window	The window where the exposure occurred.
	 * @param state	0=Unobscured, 1=PartiallyObscured, 2=FullyObscured.
	 * @throws IOException
	 */
	public static void
	sendVisibilityNotify (
		Client			client,
		Window			window,
		int				state
	) throws IOException {
		log(VisibilityNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, VisibilityNotify, 0);
			io.writeInt (window.getId ());	// Event.
			io.writeByte ((byte) state);	// State.
			io.writePadBytes (23);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a create notify event.
	 *
	 * @param client	The client to write to.
	 * @param parent	The parent of the window that was created.
	 * @param window	The window that was created.
	 * @param x	X position of the created window.
	 * @param y	Y position of the created window.
	 * @param width	Width of the created window.
	 * @param height	Height of the created window.
	 * @param borderWidth	Border width of the created window.
	 * @param overrideRedirect	Does the created window use override redirect?
	 * @throws IOException
	 */
	public static void
	sendCreateNotify (
		Client			client,
		Window			parent,
		Window			window,
		int				x,
		int				y,
		int				width,
		int				height,
		int				borderWidth,
		boolean			overrideRedirect
	) throws IOException {
		log(CreateNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, CreateNotify, 0);
			io.writeInt (parent.getId ());	// Parent.
			io.writeInt (window.getId ());	// Window.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writeShort ((short) borderWidth);	// Border width.
			io.writeByte ((byte) (overrideRedirect ? 1 : 0));
			io.writePadBytes (9);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a destroy notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was destroyed.
	 * @throws IOException
	 */
	public static void
	sendDestroyNotify (
		Client			client,
		Window			eventWindow,
		Window			window
	) throws IOException {
		log(DestroyNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, DestroyNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writePadBytes (20);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send an unmap notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was unmapped.
	 * @param fromConfigure	True if event was caused by parent being resized.
	 * @throws IOException
	 */
	public static void
	sendUnmapNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		boolean			fromConfigure
	) throws IOException {
		log(UnmapNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, UnmapNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writeByte ((byte) (fromConfigure ? 1 : 0));	// From configure.
			io.writePadBytes (19);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a map notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was mapped.
	 * @param overrideRedirect	True if the window uses override redirect.
	 * @throws IOException
	 */
	public static void
	sendMapNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		boolean			overrideRedirect
	) throws IOException {
		log(MapNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, MapNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writeByte ((byte) (overrideRedirect ? 1 : 0));
			io.writePadBytes (19);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a map request event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was mapped.
	 * @throws IOException
	 */
	public static void
	sendMapRequest (
		Client			client,
		Window			eventWindow,
		Window			window
	) throws IOException {
		log(MapRequest);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, MapRequest, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writePadBytes (20);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a reparent notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that has been rerooted.
	 * @param parent	The window's new parent.
	 * @param x	X position of the window relative to the new parent.
	 * @param y	Y position of the window relative to the new parent.
	 * @param overrideRedirect	Does the window use override redirect?
	 * @throws IOException
	 */
	public static void
	sendReparentNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		Window			parent,
		int				x,
		int				y,
		boolean			overrideRedirect
	) throws IOException {
		log(ReparentNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ReparentNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writeInt (parent.getId ());	// Parent.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeByte ((byte) (overrideRedirect ? 1 : 0));
			io.writePadBytes (11);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a configure notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was changed.
	 * @param aboveSibling	The sibling window beneath it. May be null.
	 * @param x	X position of the window relative to its parent.
	 * @param y	Y position of the window relative to its parent.
	 * @param width	Width of the window.
	 * @param height	Height of the window.
	 * @param borderWidth	Border width of the window.
	 * @param overrideRedirect	Does the window use override redirect?
	 * @throws IOException
	 */
	public static void
	sendConfigureNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		Window			aboveSibling,
		int				x,
		int				y,
		int				width,
		int				height,
		int				borderWidth,
		boolean			overrideRedirect
	) throws IOException {
		log(ConfigureNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ConfigureNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writeInt (aboveSibling == null ? 0 : aboveSibling.getId ());
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writeShort ((short) borderWidth);	// Border width.
			io.writeByte ((byte) (overrideRedirect ? 1 : 0));
			io.writePadBytes (5);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a configure request event.
	 *
	 * @param client	The client to write to.
	 * @param stackMode	0=Above, 1=Below, 2=TopIf, 3=BottomIf, 4=Opposite
	 * @param parent	The parent of the window.
	 * @param window	The window that the ConfigureWindow was issued to.
	 * @param sibling	The sibling window beneath it. May be null.
	 * @param x	X position of the window.
	 * @param y	Y position of the window.
	 * @param width	Width of the window.
	 * @param height	Height of the window.
	 * @param borderWidth	Border width of the window.
	 * @param valueMask	Components specified in the ConfigureWindow request.
	 * @throws IOException
	 */
	public static void
	sendConfigureRequest (
		Client			client,
		int				stackMode,
		Window			parent,
		Window			window,
		Window			sibling,
		int				x,
		int				y,
		int				width,
		int				height,
		int				borderWidth,
		int				valueMask
	) throws IOException {
		log(ConfigureRequest);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ConfigureRequest, stackMode);
			io.writeInt (parent.getId ());	// Parent.
			io.writeInt (window.getId ());	// Window.
			io.writeInt (sibling == null ? 0 : sibling.getId ());	// Sibling.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writeShort ((short) borderWidth);	// Border width.
			io.writeShort ((short) valueMask);	// Value mask.
			io.writePadBytes (4);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a gravity notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was moved because parent changed size.
	 * @param x	X position of the window relative to the parent.
	 * @param y	Y position of the window relative to the parent.
	 * @throws IOException
	 */
	public static void
	sendGravityNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		int				x,
		int				y
	) throws IOException {
		log(GravityNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, GravityNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writeShort ((short) x);	// X.
			io.writeShort ((short) y);	// Y.
			io.writePadBytes (16);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a resize request event.
	 *
	 * @param client	The client to write to.
	 * @param window	A client is attempting to resize this window.
	 * @param width	Requested width of the window.
	 * @param height	Requested height of the window.
	 * @throws IOException
	 */
	public static void
	sendResizeRequest (
		Client			client,
		Window			window,
		int				width,
		int				height
	) throws IOException {
		log(ResizeRequest);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ResizeRequest, 0);
			io.writeInt (window.getId ());	// Window.
			io.writeShort ((short) width);	// Width.
			io.writeShort ((short) height);	// Height.
			io.writePadBytes (20);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a circulate notify event.
	 *
	 * @param client	The client to write to.
	 * @param eventWindow	The window where the event was generated.
	 * @param window	The window that was restacked.
	 * @param place	0=Top, 1=Bottom.
	 * @throws IOException
	 */
	public static void
	sendCirculateNotify (
		Client			client,
		Window			eventWindow,
		Window			window,
		int				place
	) throws IOException {
		log(CirculateNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, CirculateNotify, 0);
			io.writeInt (eventWindow.getId ());	// Event.
			io.writeInt (window.getId ());	// Window.
			io.writePadBytes (4);	// Unused.
			io.writeByte ((byte) place);	// Place.
			io.writePadBytes (15);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a circulate request event.
	 *
	 * @param client	The client to write to.
	 * @param parent	The parent of the window.
	 * @param window	The window that needs to be restacked.
	 * @param place	0=Top, 1=Bottom.
	 * @throws IOException
	 */
	public static void
	sendCirculateRequest (
		Client			client,
		Window			parent,
		Window			window,
		int				place
	) throws IOException {
		log(CirculateRequest);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, CirculateRequest, 0);
			io.writeInt (parent.getId ());	// Parent.
			io.writeInt (window.getId ());	// Window.
			io.writePadBytes (4);	// Unused.
			io.writeByte ((byte) place);	// Place.
			io.writePadBytes (15);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a property notify event.
	 *
	 * @param client	The client to write to.
	 * @param window	The window being changed
	 * @param atom	The property being changed.
	 * @param timestamp	Time in milliseconds when the property was changed.
	 * @param state	0=NewValue, 1=Deleted.
	 * @throws IOException
	 */
	public static void
	sendPropertyNotify (
		Client			client,
		Window			window,
		Atom			atom,
		int				timestamp,
		int				state
	) throws IOException {
		log(PropertyNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, PropertyNotify, 0);
			io.writeInt (window.getId ());	// Window.
			io.writeInt (atom.getId ());	// Atom.
			io.writeInt (timestamp);	// Time.
			io.writeByte ((byte) state);	// State.
			io.writePadBytes (15);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a selection clear event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Last-change time for the selection.
	 * @param window	Previous owner of the selection.
	 * @param atom	The selection.
	 * @throws IOException
	 */
	public static void
	sendSelectionClear (
		Client			client,
		int				timestamp,
		Window			window,
		Atom			atom
	) throws IOException {
		log(SelectionClear);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, SelectionClear, 0);
			io.writeInt (timestamp);	// Time.
			io.writeInt (window.getId ());	// Owner.
			io.writeInt (atom.getId ());	// Selection.
			io.writePadBytes (16);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a selection request event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Last-change time for the selection.
	 * @param owner	Current owner of the selection.
	 * @param requestor	Window requesting change of selection.
	 * @param selection	The selection whose owner changed.
	 * @param target	Target atom.
	 * @param property	Property atom. May be null.
	 * @throws IOException
	 */
	public static void
	sendSelectionRequest (
		Client			client,
		int				timestamp,
		Window			owner,
		Window			requestor,
		Atom			selection,
		Atom			target,
		Atom			property
	) throws IOException {
		log(SelectionRequest);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, SelectionRequest, 0);
			io.writeInt (timestamp);	// Time.
			io.writeInt (owner.getId ());	// Owner.
			io.writeInt (requestor.getId ());	// Requestor.
			io.writeInt (selection.getId ());	// Selection.
			io.writeInt (target.getId ());	// Target.
			io.writeInt (property == null ? 0 : property.getId ());
			io.writePadBytes (4);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a selection notify event.
	 *
	 * @param client	The client to write to.
	 * @param timestamp	Last-change time for the selection.
	 * @param requestor	Window requesting change of selection.
	 * @param selection	The selection whose owner changed.
	 * @param target	Target atom.
	 * @param property	Property atom. May be null.
	 * @throws IOException
	 */
	public static void
	sendSelectionNotify (
		Client			client,
		int				timestamp,
		Window			requestor,
		Atom			selection,
		Atom			target,
		Atom			property
	) throws IOException {
		log(SelectionNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, SelectionNotify, 0);
			io.writeInt (timestamp);	// Time.
			io.writeInt (requestor.getId ());	// Requestor.
			io.writeInt (selection.getId ());	// Selection.
			io.writeInt (target.getId ());	// Target.
			io.writeInt (property == null ? 0 : property.getId ());
			io.writePadBytes (8);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a colormap notify event.
	 *
	 * @param client	The client to write to.
	 * @param window	The window the colormap belongs to.
	 * @param cmap	The colormap. May be null.
	 * @param isNew	True=colormap changed, False=colormap un/installed.
	 * @param state	0=Uninstalled, 1=Installed.
	 * @throws IOException
	 */
	public static void
	sendColormapNotify (
		Client			client,
		Window			window,
		Colormap		cmap,
		boolean			isNew,
		int				state
	) throws IOException {
		log(ColormapNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, ColormapNotify, 0);
			io.writeInt (window.getId ());	// Window.
			io.writeInt (cmap == null ? 0 : cmap.getId ());	// Colormap.
			io.writeByte ((byte) (isNew ? 1 : 0));	// New.
			io.writeByte ((byte) state);	// State.
			io.writePadBytes (18);	// Unused.
		}
		io.flush ();
	}

	/**
	 * Send a mapping notify event.
	 *
	 * @param client	The client to write to.
	 * @param request	0=Modifier, 1=Keyboard, 2=Pointer.
	 * @param firstKeycode	Start of altered keycodes if request=Keyboard.
	 * @param count	Size of altered keycode range if request=Keyboard.
	 * @throws IOException
	 */
	public static void
	sendMappingNotify (
		Client			client,
		int				request,
		int				firstKeycode,
		int				count
	) throws IOException {
		log(MappingNotify);
		InputOutput		io = client.getInputOutput ();

		synchronized (io) {
			writeHeader (client, MappingNotify, 0);
			io.writeByte ((byte) request);	// Request.
			io.writeByte ((byte) firstKeycode);	// First keycode.
			io.writeByte ((byte) count);	// Count.
			io.writePadBytes (25);	// Unused.
		}
		io.flush ();
	}

	private static void log(int code, String info) {
		XServer.getLogger().info("event: code=%d (%s), %s",
								 code, mCodes.get(code), info);
	}

	private static void log(int code) {
		XServer.getLogger().info("event: code=%d (%s)", code, mCodes.get(code));
	}

	private static void log(int code, String subcodeName, int subcode,
							Window root, Window eventWindow, Window child,
							int rootX, int rootY, int eventX, int eventY,
							int state) {
		log(code,
			String.format("%s=%d, root=0x%x, eventWindow=0x%x, child=0x%x, rootX=%d, rootY=%d, eventX=%d, eventY=%d, state=%d",
						  subcodeName, subcode, root.getId(),
						  eventWindow.getId(),
						  child != null ? child.getId() : 0, rootX, rootY,
						  eventX, eventY, state));
	}

	private static void logButtonEvent(int code, int button, Window root,
									   Window eventWindow, Window child,
									   int rootX, int rootY, int eventX,
									   int eventY, int state) {
		log(code, "button", button, root, eventWindow, child, rootX, rootY,
			eventX, eventY, state);
	}

	private static void logMotionEvent(int code, int detail, Window root,
									   Window eventWindow, Window child,
									   int rootX, int rootY, int eventX,
									   int eventY, int state) {
		log(code, "detail", detail, root, eventWindow, child, rootX, rootY,
			eventX, eventY, state);
	}

	private static void logKeyEvent(int code, int keycode, Window root,
									Window eventWindow, Window child, int rootX,
									int rootY, int eventX, int eventY,
									int state) {
		log(code, "keycode", keycode, root, eventWindow, child, rootX, rootY,
			eventX, eventY, state);
	}

	private static void logFocusEvent(int code, int detail, Window eventWindow,
									  int mode) {
        String[] details = new String[] { "Ancestor", "Virtual", "Inferior",
										  "Nonlinear", "NonlinearVirtual",
										  "Pointer", "PointerRoot", "None" };
		String d = (0 <= detail) && (detail < details.length) ? details[detail]
															  : "invalid";
		String[] modes = new String[] { "Normal", "Grab", "Ungrab",
										"WhileGrabbed" };
		String m = (0 <= mode) && (mode < modes.length) ? modes[mode]
														: "invalid";
        log(code,
			String.format("detail=%d (%s), eventWindow=0x%x, mode=%d (%s)",
						  detail, d, eventWindow.getId(), mode, m));
	}

	private static void logKeymapNotify(byte[] keys) {
        StringBuffer buffer = new StringBuffer();
		String sep = "";
        for (int i = 0; i < keys.length; i++) {
			buffer.append(sep);
            buffer.append(String.format("0x%x", keys[i]));
			sep = " ";
		}

		log(KeymapNotify, buffer.toString());
	}

	static {
		mCodes.put(KeyPress, "KeyPress");
		mCodes.put(KeyRelease, "KeyRelease");
		mCodes.put(ButtonPress, "ButtonPress");
		mCodes.put(ButtonRelease, "ButtonRelease");
		mCodes.put(MotionNotify, "MotionNotify");
		mCodes.put(EnterNotify, "EnterNotify");
		mCodes.put(LeaveNotify, "LeaveNotify");
		mCodes.put(FocusIn, "FocusIn");
		mCodes.put(FocusOut, "FocusOut");
		mCodes.put(KeymapNotify, "KeymapNotify");
		mCodes.put(Expose, "Expose");
		mCodes.put(GraphicsExposure, "GraphicsExposure");
		mCodes.put(NoExposure, "NoExposure");
		mCodes.put(VisibilityNotify, "VisibilityNotify");
		mCodes.put(CreateNotify, "CreateNotify");
		mCodes.put(DestroyNotify, "DestroyNotify");
		mCodes.put(UnmapNotify, "UnmapNotify");
		mCodes.put(MapNotify, "MapNotify");
		mCodes.put(MapRequest, "MapRequest");
		mCodes.put(ReparentNotify, "ReparentNotify");
		mCodes.put(ConfigureNotify, "ConfigureNotify");
		mCodes.put(ConfigureRequest, "ConfigureRequest");
		mCodes.put(GravityNotify, "GravityNotify");
		mCodes.put(ResizeRequest, "ResizeRequest");
		mCodes.put(CirculateNotify, "CirculateNotify");
		mCodes.put(CirculateRequest, "CirculateRequest");
		mCodes.put(PropertyNotify, "PropertyNotify");
		mCodes.put(SelectionClear, "SelectionClear");
		mCodes.put(SelectionRequest, "SelectionRequest");
		mCodes.put(SelectionNotify, "SelectionNotify");
		mCodes.put(ColormapNotify, "ColormapNotify");
		mCodes.put(ClientMessage, "ClientMessage");
		mCodes.put(MappingNotify, "MappingNotify");
	}
}


text:
#import "NSObject.h"

@interface NSObject (AXAutoscrolling)
- (void)_accessibilityAutoscrollScrollToBottom;
- (void)_accessibilityAutoscrollScrollToTop;
- (void)_accessibilityDecreaseAutoscrollSpeed;
- (void)_accessibilityIncreaseAutoscrollSpeed;
- (void)_accessibilityPauseAutoscrolling;
- (void)_accessibilityAutoscrollInDirection:(int)arg1;
- (_Bool)_accessibilityIsAutoscrolling;
- (int)_accessibilityAvailableAutoscrollDirections;
- (id)_accessibilityAutoscrollTarget;
- (void)_accessibilitySetAutoscrollTarget:(id)arg1;
@end

redpajama_set_name: RedPajamaGithub


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Category.show_cover_in_menu'
        db.add_column('products_categories', 'show_cover_in_menu',
                      self.gf('django.db.models.fields.BooleanField')(default=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Category.show_cover_in_menu'
        db.delete_column('products_categories', 'show_cover_in_menu')

    models = {
        u'products.category': {
            'Meta': {'object_name': 'Category', 'db_table': "'products_categories'"},
            'cover': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_complementary': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_standalone': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
            'legacy_id': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['products.Category']"}),
            'position': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'show_cover_in_menu': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        u'products.photo': {
            'Meta': {'object_name': 'Photo', 'db_table': "'products_photos'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'is_main': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'legacy_hash': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
            'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'photos'", 'to': u"orm['products.Product']"})
        },
        u'products.product': {
            'Meta': {'object_name': 'Product', 'db_table': "'products_items'"},
            'categories': ('mptt.fields.TreeManyToManyField', [], {'related_name': "'products'", 'symmetrical': 'False', 'to': u"orm['products.Category']"}),
            'code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'dimensions': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}),
            'discount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
            'franchisee_discount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
            'franchisee_price': ('django.db.models.fields.DecimalField', [], {'db_index': 'True', 'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_new': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_retail': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_wholesale': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'pack_amount': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
            'price': ('django.db.models.fields.DecimalField', [], {'db_index': 'True', 'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
            'quantity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'sku': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '30', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now': 'True', 'blank': 'True'}),
            'weight': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'wholesale_discount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
            'wholesale_legacy_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
            'wholesale_price': ('django.db.models.fields.DecimalField', [], {'db_index': 'True', 'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'})
        }
    }

    complete_apps = ['products']


text:
package org.apache.solr.handler.tagger;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.analysis.charfilter.HTMLStripCharFilter;
import org.apache.lucene.analysis.core.WhitespaceTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.solr.common.SolrException;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.InputSource;

public class XmlInterpolationTest extends TaggerTestCase {

  private static DocumentBuilder xmlDocBuilder;

  @BeforeClass
  public static void beforeClass() throws Exception {
    DocumentBuilderFactory xmlDocBuilderFactory = DocumentBuilderFactory.newInstance();
    xmlDocBuilderFactory.setValidating(true);
    xmlDocBuilderFactory.setNamespaceAware(true);
    xmlDocBuilder = xmlDocBuilderFactory.newDocumentBuilder();

    initCore("solrconfig-tagger.xml", "schema-tagger.xml");
  }

  @AfterClass
  public static void cleanUpAfterClass() {
    xmlDocBuilder = null;
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    baseParams.set("field", "name_tagXml");
    baseParams.set("overlaps", "LONGEST_DOMINANT_RIGHT");
    baseParams.set("xmlOffsetAdjust", "true");
  }

  @Test
  public void test() throws Exception {
    buildNames("start end");

    assertXmlTag("<doc>before start  end after</doc>", true);
    assertXmlTag("<doc>before start
 end after</doc>", true);
    assertXmlTag("<doc>before start end after</doc>", true);
    assertXmlTag("<doc>before start end after</doc>", true);
    assertXmlTag("<doc>before start end after</doc>", true);
    assertXmlTag("<doc>before start end after</doc>", true); // adjacent tags
    assertXmlTag("<doc>before  start  end after</doc>", true);
    assertXmlTag("<doc>before  start    end   after</doc>", true);

    assertXmlTag("<doc>
before start
 end after</doc>", false);
    assertXmlTag("<doc>before start
end after
 </doc>", false);

    assertXmlTag("<doc>before start end after</doc>", true);
  }

  @Test(expected = SolrException.class)
  public void testInvalidXml() throws Exception {
    assertXmlTag("notXml", false);
  }

  @Test(expected = Exception.class)
  public void testValidatingXml() throws Exception {
    validateXml("foo");
  }

  protected void assertXmlTag(String docText, boolean expected) throws Exception {
    final SolrQueryRequest req = reqDoc(docText);
    try { // 5.4 and beyond we can use try-with-resources
      final SolrQueryResponse rsp = h.queryAndResponse(req.getParams().get("qt"), req);
      final TestTag[] testTags = pullTagsFromResponse(req, rsp);
      if (!expected) {
        assertEquals(0, testTags.length);
      } else {
        assertEquals(1, testTags.length);
        final TestTag tag = testTags[0];
        validateXml(insertAnchorAtOffsets(docText, tag.startOffset, tag.endOffset, tag.docName));
      }
    } finally {
      req.close();
    }
  }

  protected void validateXml(String xml) throws Exception {
    // the "parse" method also validates XML, will throw an exception if mis-formatted
    xmlDocBuilder.parse(new InputSource(new StringReader(xml)));
  }

  @Test
  public void testLuceneHtmlFilterBehavior() {
    String docText;

    // Close tag adjacent to start & end results in end offset including the close tag. LUCENE-5734
    docText = "<doc>start end</doc>";
    assertArrayEquals(
        tagExpect(docText, "start", "end"), analyzeTagOne(docText, "start", "end"));

    // Space after "end" means offset doesn't include
    docText = "<doc>start end </doc>";
    assertArrayEquals(tagExpect(docText, "start", "end"), analyzeTagOne(docText, "start", "end"));

    // Matches entity at end
    final String endStr = String.format(Locale.ROOT, "en&#x%02x;", (int) 'd');
    docText = "<doc>start " + endStr + "</doc>";
    assertArrayEquals(tagExpect(docText, "start", endStr), analyzeTagOne(docText, "start", "end"));
    // ... and at start
    final String startStr = String.format(Locale.ROOT, "&#x%02x;tart", (int) 's');
    docText = "<doc>" + startStr + " end</doc>";
    assertArrayEquals(tagExpect(docText, startStr, "end"), analyzeTagOne(docText, "start", "end"));

    // Test ignoring proc instructions & comments. Note: doesn't expand the entity to "start".
    docText =
        "<!DOCTYPE start [ "
            + "<!ENTITY start \"start\">"
            + "]><start><?start start ?><start/>&start;</start>";
    assertArrayEquals(new int[] {-1, -1}, analyzeTagOne(docText, "start", "start"));

    // Test entity behavior
    docText = " — – & &foo;   a b";
    assertArrayEquals(
        new String[] {"—", "–", "&", "&foo;", "\u00A0", "a", "b"}, analyzeReturnTokens(docText));

    // Observe offset adjustment of trailing entity to end tag
    docText = "foo bar";
    assertArrayEquals(tagExpect(docText, "foo", "foo"), analyzeTagOne(docText, "foo", "foo"));
  }

  private String insertAnchorAtOffsets(String docText, int startOffset, int endOffset, String id) {
    String insertStart = ""; // (normally we'd escape id)
    String insertEnd = "";
    return docText.substring(0, startOffset)
        + insertStart
        + docText.substring(startOffset, endOffset)
        + insertEnd
        + docText.substring(endOffset);
  }

  private int[] tagExpect(String docText, String start, String end) {
    return new int[] {docText.indexOf(start), docText.indexOf(end) + end.length()};
  }

  private int[] analyzeTagOne(String docText, String start, String end) {
    int[] result = {-1, -1};

    Reader filter = new HTMLStripCharFilter(new StringReader(docText));

    WhitespaceTokenizer ts = new WhitespaceTokenizer();
    final CharTermAttribute termAttribute = ts.addAttribute(CharTermAttribute.class);
    final OffsetAttribute offsetAttribute = ts.addAttribute(OffsetAttribute.class);
    try {
      ts.setReader(filter);
      ts.reset();
      while (ts.incrementToken()) {
        final String termString = termAttribute.toString();
        if (termString.equals(start)) result[0] = offsetAttribute.startOffset();
        if (termString.equals(end)) {
          result[1] = offsetAttribute.endOffset();
          return result;
        }
      }
      ts.end();
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      IOUtils.closeQuietly(ts);
    }
    return result;
  }

  private String[] analyzeReturnTokens(String docText) {
    List<String> result = new ArrayList<>();

    Reader filter =
        new HTMLStripCharFilter(new StringReader(docText), Collections.singleton("unescaped"));
    WhitespaceTokenizer ts = new WhitespaceTokenizer();
    final CharTermAttribute termAttribute = ts.addAttribute(CharTermAttribute.class);
    try {
      ts.setReader(filter);
      ts.reset();
      while (ts.incrementToken()) {
        result.add(termAttribute.toString());
      }
      ts.end();
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      IOUtils.closeQuietly(ts);
    }
    return result.toArray(new String[result.size()]);
  }
}


text:
#include <aws/glue/model/GetCrawlersResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetCrawlersResult::GetCrawlersResult()
{
}

GetCrawlersResult::GetCrawlersResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetCrawlersResult& GetCrawlersResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Crawlers"))
  {
    Aws::Utils::Array<JsonView> crawlersJsonList = jsonValue.GetArray("Crawlers");
    for(unsigned crawlersIndex = 0; crawlersIndex < crawlersJsonList.GetLength(); ++crawlersIndex)
    {
      m_crawlers.push_back(crawlersJsonList[crawlersIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  return *this;
}


text:
post_title: Uninstall
menu_order: 30
feature_maturity: preview
enterprise: 'no'
---

Uninstalling a cluster is straightforward. Replace `app-id` with the name of the Cassandra instance to be uninstalled. If you have only one instance and are using the default package name (`cassandra`), you can omit `--app-id=<app-id>` in the command below.

```
$ dcos package uninstall --app-id=<app-id> cassandra
```

Then, use the [framework cleaner script](https://docs.mesosphere.com/1.9/deploying-services/uninstall/#framework-cleaner) to remove your Cassandra instance from Zookeeper and destroy all data associated with it. The script requires several arguments. The default values are:

- `framework_role` is `cassandra-role`.
- `framework_principal` is `cassandra-principal`.
- `zk_path` is `dcos-service-<service-name>`.

These values may vary if you customized them during installation.


text:
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

package simsigGatewayInterface;
import strampáil.ClientInterface;
import strampáil.Notifier;
import strampáil.Printer;
import java.util.HashMap;

// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

/**
 * A STOMP client designed to interface with the a
 * SimSig
 *
 * Interface Gateway.
 *
 * @author Mark David Pokorny
 * @version Dé Máirt, 3ú Bealtaine 2016
 * @since Déardaoin, 21ú Aibreán 2016
 */
public class SimSigClient implements Notifier
{

// ------------------------------------------ SimSigClient Class ---------------

  private ClientInterface clientInterface;
  private Harness harness;
  private boolean connected;

// ------------------------------------------ SimSigClient Class ---------------

  /**
   * Creates a SimSig client that listens for and parses SimSig messages from
   * the SimSig server.
   */
  public SimSigClient(
    String address, int port, int debug, String stompHostName, Harness harness)
  {

    this.harness = harness;
    connected = false;
    clientInterface = new ClientInterface(address, port, debug, this);

    if (clientInterface.handshake())
    {
      if (clientInterface.connect(stompHostName))
      {
        clientInterface.subscribe("/topic/TD_ALL_SIG_AREA", true);
        connected = true;
      } // End if
    } // End if

    harness.connected(connected);

  } // End 'SimSigClient(String, int, int, String, Harness)' Constructor

// ------------------------------------------ SimSigClient Class ---------------

  /**
   * Shuts down this SimSigClient and the underlying interface.
   */
  public void close()
  {
    if (connected)
    {
      // SimSig loader 4.5.9 doesn't send a RECEIPT for UNSUBSCRIBE (it should!)
      clientInterface.unsubscribe(false);
      // SimSig loader 4.5.9 complains about an access violation when
      // receiving a DISCONNECT frame. Not much can be done about it at the mo.
      clientInterface.disconnect();
      clientInterface.close();
    } // End if
  } // End 'close()' Method

// ------------------------------------------ SimSigClient Class ---------------

  /**
   * Parses SimSig messages when received by the {@link ClientInterface}.
   */
  public void alert()
  {
    String message = clientInterface.retrieveMessage();
    if (message != null)
      harness.transferMessage(parseMessage(message));
  } // End 'alert()' method

// ------------------------------------------ SimSigClient Class ---------------

  private static SimSigMessage parseMessage(String message)
  {

    MessageType type;
    HashMap<String, String> parameters;

    if (message.startsWith("{\"") && message.endsWith("\"}}"))
    {

      int headerFinalIndex = message.indexOf("\"", 2);
      String messageType = message.substring(2, headerFinalIndex);

      if (messageType.equals("CA_MSG") ||
          messageType.equals("CB_MSG") ||
          messageType.equals("CC_MSG"))
        type = MessageType.TD;
      else if (messageType.equals("SG_MSG"))
        type = MessageType.SIGNAL;
      else
      {
        Printer.printError(
          "Unable to understand SimSig message type: " + messageType);
        return null;
      }

      Printer.printInfo(type.name() + " message received.");

      if (message.startsWith("\":{\"", headerFinalIndex))
        parameters = parseParameters(message.substring(headerFinalIndex + 4));
      else
      {
        Printer.printError("Invalid SimSig message syntax.");
        return null;
      }

    } // End if
    else
    {
      Printer.printError("'" + message + "' is not valid JSON syntax.");
      return null;
    } // End else

    return new SimSigMessage(type, parameters.get("area_id"), parameters);

  } // End 'parseMessage(String)' Method

// ------------------------------------------ SimSigClient Class ---------------

  private static HashMap<String, String> parseParameters(String message)
  {

    HashMap<String, String> parameters = new HashMap<String, String>();
    String key, value;
    int keyEnd = 0;
    int valueEnd = 0;
    while (true)
    {
      keyEnd = message.indexOf("\"", valueEnd);
      key = message.substring(valueEnd, keyEnd);

      if (message.startsWith("\":\"", keyEnd))
      {
        keyEnd += 3;
        valueEnd = message.indexOf("\"", keyEnd);
        value = message.substring(keyEnd, valueEnd);

        parameters.put(key, value);
        Printer.printDebug(key + ":" + value);

        if (message.startsWith("\",\"", valueEnd))
        {
          valueEnd += 3;
          continue;
        } // End if
        else if (message.startsWith("\"}}", valueEnd))
          return parameters;
        else
        {
          Printer.printError("1: Invalid JSON syntax detected.");
          return null;
        } // End else

      }
      else
      {
        Printer.printError("2: Invalid JSON syntax detected.");
        return null;
      } // End else

    } // End while

  } // End 'parseHeaders(String)' Method

// ------------------------------------------ SimSigClient Class ---------------

} // End 'SimSigClient' Class

// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


text:
package org.apache.nifi.nar;

import org.apache.nifi.annotation.behavior.RequiresInstanceClassLoading;
import org.apache.nifi.authentication.LoginIdentityProvider;
import org.apache.nifi.authorization.AccessPolicyProvider;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.authorization.UserGroupProvider;
import org.apache.nifi.bundle.Bundle;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.components.ConfigurableComponent;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.state.StateProvider;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.controller.repository.ContentRepository;
import org.apache.nifi.controller.repository.FlowFileRepository;
import org.apache.nifi.controller.repository.FlowFileSwapManager;
import org.apache.nifi.controller.status.history.ComponentStatusRepository;
import org.apache.nifi.flowfile.FlowFilePrioritizer;
import org.apache.nifi.init.ConfigurableComponentInitializer;
import org.apache.nifi.init.ConfigurableComponentInitializerFactory;
import org.apache.nifi.processor.Processor;
import org.apache.nifi.provenance.ProvenanceRepository;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.reporting.ReportingTask;
import org.apache.nifi.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Scans through the classpath to load all FlowFileProcessors, FlowFileComparators, and ReportingTasks using the service provider API and running through all classloaders (root, NARs).
 *
 * @ThreadSafe - is immutable
 */
@SuppressWarnings("rawtypes")
public class ExtensionManager {

    private static final Logger logger = LoggerFactory.getLogger(ExtensionManager.class);

    // Maps a service definition (interface) to those classes that implement the interface
    private static final Map<Class, Set<Class>> definitionMap = new HashMap<>();

    private static final Map<String, List<Bundle>> classNameBundleLookup = new HashMap<>();
    private static final Map<BundleCoordinate, Bundle> bundleCoordinateBundleLookup = new HashMap<>();
    private static final Map<ClassLoader, Bundle> classLoaderBundleLookup = new HashMap<>();
    private static final Map<String, ConfigurableComponent> tempComponentLookup = new HashMap<>();

    private static final Map<String, Class<?>> requiresInstanceClassLoading = new HashMap<>();
    private static final Map<String, InstanceClassLoader> instanceClassloaderLookup = new ConcurrentHashMap<>();

    static {
        definitionMap.put(Processor.class, new HashSet<>());
        definitionMap.put(FlowFilePrioritizer.class, new HashSet<>());
        definitionMap.put(ReportingTask.class, new HashSet<>());
        definitionMap.put(ControllerService.class, new HashSet<>());
        definitionMap.put(Authorizer.class, new HashSet<>());
        definitionMap.put(UserGroupProvider.class, new HashSet<>());
        definitionMap.put(AccessPolicyProvider.class, new HashSet<>());
        definitionMap.put(LoginIdentityProvider.class, new HashSet<>());
        definitionMap.put(ProvenanceRepository.class, new HashSet<>());
        definitionMap.put(ComponentStatusRepository.class, new HashSet<>());
        definitionMap.put(FlowFileRepository.class, new HashSet<>());
        definitionMap.put(FlowFileSwapManager.class, new HashSet<>());
        definitionMap.put(ContentRepository.class, new HashSet<>());
        definitionMap.put(StateProvider.class, new HashSet<>());
    }

    /**
     * Loads all FlowFileProcessor, FlowFileComparator, ReportingTask class types that can be found on the bootstrap classloader and by creating classloaders for all NARs found within the classpath.
     * @param narBundles the bundles to scan through in search of extensions
     */
    public static void discoverExtensions(final Bundle systemBundle, final Set<Bundle> narBundles) {
        // get the current context class loader
        ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();

        // load the system bundle first so that any extensions found in JARs directly in lib will be registered as
        // being from the system bundle and not from all the other NARs
        loadExtensions(systemBundle);
        bundleCoordinateBundleLookup.put(systemBundle.getBundleDetails().getCoordinate(), systemBundle);

        // consider each nar class loader
        for (final Bundle bundle : narBundles) {
            // Must set the context class loader to the nar classloader itself
            // so that static initialization techniques that depend on the context class loader will work properly
            final ClassLoader ncl = bundle.getClassLoader();
            Thread.currentThread().setContextClassLoader(ncl);
            loadExtensions(bundle);

            // Create a look-up from coordinate to bundle
            bundleCoordinateBundleLookup.put(bundle.getBundleDetails().getCoordinate(), bundle);
        }

        // restore the current context class loader if appropriate
        if (currentContextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
        }
    }

    /**
     * Loads extensions from the specified bundle.
     *
     * @param bundle from which to load extensions
     */
    @SuppressWarnings("unchecked")
    private static void loadExtensions(final Bundle bundle) {
        for (final Map.Entry<Class, Set<Class>> entry : definitionMap.entrySet()) {
            final boolean isControllerService = ControllerService.class.equals(entry.getKey());
            final boolean isProcessor = Processor.class.equals(entry.getKey());
            final boolean isReportingTask = ReportingTask.class.equals(entry.getKey());

            final ServiceLoader<?> serviceLoader = ServiceLoader.load(entry.getKey(), bundle.getClassLoader());
            for (final Object o : serviceLoader) {
                // create a cache of temp ConfigurableComponent instances, the initialize here has to happen before the checks below
                if ((isControllerService || isProcessor || isReportingTask) && o instanceof ConfigurableComponent) {
                    final ConfigurableComponent configurableComponent = (ConfigurableComponent) o;
                    initializeTempComponent(configurableComponent);

                    final String cacheKey = getClassBundleKey(o.getClass().getCanonicalName(), bundle.getBundleDetails().getCoordinate());
                    tempComponentLookup.put(cacheKey, (ConfigurableComponent)o);
                }

                // only consider extensions discovered directly in this bundle
                boolean registerExtension = bundle.getClassLoader().equals(o.getClass().getClassLoader());

                if (registerExtension) {
                    final Class extensionType = o.getClass();
                    if (isControllerService && !checkControllerServiceEligibility(extensionType)) {
                        registerExtension = false;
                        logger.error(String.format(
                                "Skipping Controller Service %s because it is bundled with its supporting APIs and requires instance class loading.", extensionType.getName()));
                    }

                    final boolean canReferenceControllerService = (isControllerService || isProcessor || isReportingTask) && o instanceof ConfigurableComponent;
                    if (canReferenceControllerService && !checkControllerServiceReferenceEligibility((ConfigurableComponent) o, bundle.getClassLoader())) {
                        registerExtension = false;
                        logger.error(String.format(
                                "Skipping component %s because it is bundled with its referenced Controller Service APIs and requires instance class loading.", extensionType.getName()));
                    }

                    if (registerExtension) {
                        registerServiceClass(o.getClass(), classNameBundleLookup, bundle, entry.getValue());
                    }
                }

            }

            classLoaderBundleLookup.put(bundle.getClassLoader(), bundle);
        }
    }

    private static void initializeTempComponent(final ConfigurableComponent configurableComponent) {
        ConfigurableComponentInitializer initializer = null;
        try {
            initializer = ConfigurableComponentInitializerFactory.createComponentInitializer(configurableComponent.getClass());
            initializer.initialize(configurableComponent);
        } catch (final InitializationException e) {
            logger.warn(String.format("Unable to initialize component %s due to %s", configurableComponent.getClass().getName(), e.getMessage()));
        }
    }

    private static boolean checkControllerServiceReferenceEligibility(final ConfigurableComponent component, final ClassLoader classLoader) {
        // if the extension does not require instance classloading, its eligible
        final boolean requiresInstanceClassLoading = component.getClass().isAnnotationPresent(RequiresInstanceClassLoading.class);

        final Set<Class> cobundledApis = new HashSet<>();
        try (final NarCloseable closeable = NarCloseable.withComponentNarLoader(component.getClass().getClassLoader())) {
            final List<PropertyDescriptor> descriptors = component.getPropertyDescriptors();
            if (descriptors != null && !descriptors.isEmpty()) {
                for (final PropertyDescriptor descriptor : descriptors) {
                    final Class<? extends ControllerService> serviceApi = descriptor.getControllerServiceDefinition();
                    if (serviceApi != null && classLoader.equals(serviceApi.getClassLoader())) {
                        cobundledApis.add(serviceApi);
                    }
                }
            }
        }

        if (!cobundledApis.isEmpty()) {
            logger.warn(String.format(
                    "Component %s is bundled with its referenced Controller Service APIs %s. The service APIs should not be bundled with component implementations that reference it.",
                    component.getClass().getName(), StringUtils.join(cobundledApis.stream().map(cls -> cls.getName()).collect(Collectors.toSet()), ", ")));
        }

        // the component is eligible when it does not require instance classloading or when the supporting APIs are bundled in a parent NAR
        return requiresInstanceClassLoading == false || cobundledApis.isEmpty();
    }

    private static boolean checkControllerServiceEligibility(Class extensionType) {
        final Class originalExtensionType = extensionType;
        final ClassLoader originalExtensionClassLoader = extensionType.getClassLoader();

        // if the extension does not require instance classloading, its eligible
        final boolean requiresInstanceClassLoading = extensionType.isAnnotationPresent(RequiresInstanceClassLoading.class);

        final Set<Class> cobundledApis = new HashSet<>();
        while (extensionType != null) {
            for (final Class i : extensionType.getInterfaces()) {
                if (originalExtensionClassLoader.equals(i.getClassLoader())) {
                    cobundledApis.add(i);
                }
            }

            extensionType = extensionType.getSuperclass();
        }

        if (!cobundledApis.isEmpty()) {
            logger.warn(String.format("Controller Service %s is bundled with its supporting APIs %s. The service APIs should not be bundled with the implementations.",
                    originalExtensionType.getName(), StringUtils.join(cobundledApis.stream().map(cls -> cls.getName()).collect(Collectors.toSet()), ", ")));
        }

        // the service is eligible when it does not require instance classloading or when the supporting APIs are bundled in a parent NAR
        return requiresInstanceClassLoading == false || cobundledApis.isEmpty();
    }

    /**
     * Registers extension for the specified type from the specified Bundle.
     *
     * @param type the extension type
     * @param classNameBundleMap mapping of classname to Bundle
     * @param bundle the Bundle being mapped to
     * @param classes to map to this classloader but which come from its ancestors
     */
    private static void registerServiceClass(final Class<?> type, final Map<String, List<Bundle>> classNameBundleMap, final Bundle bundle, final Set<Class> classes) {
        final String className = type.getName();

        // get the bundles that have already been registered for the class name
        List<Bundle> registeredBundles = classNameBundleMap.get(className);

        if (registeredBundles == null) {
            registeredBundles = new ArrayList<>();
            classNameBundleMap.put(className, registeredBundles);
        }

        boolean alreadyRegistered = false;
        for (final Bundle registeredBundle : registeredBundles) {
            final BundleCoordinate registeredCoordinate = registeredBundle.getBundleDetails().getCoordinate();

            // if the incoming bundle has the same coordinate as one of the registered bundles then consider it already registered
            if (registeredCoordinate.equals(bundle.getBundleDetails().getCoordinate())) {
                alreadyRegistered = true;
                break;
            }

            // if the type wasn't loaded from an ancestor, and the type isn't a processor, cs, or reporting task, then
            // fail registration because we don't support multiple versions of any other types
            if (!multipleVersionsAllowed(type)) {
                throw new IllegalStateException("Attempt was made to load " + className + " from "
                        + bundle.getBundleDetails().getCoordinate().getCoordinate()
                        + " but that class name is already loaded/registered from " + registeredBundle.getBundleDetails().getCoordinate()
                        + " and multiple versions are not supported for this type"
                );
            }
        }

        // if none of the above was true then register the new bundle
        if (!alreadyRegistered) {
            registeredBundles.add(bundle);
            classes.add(type);

            if (type.isAnnotationPresent(RequiresInstanceClassLoading.class)) {
                final String cacheKey = getClassBundleKey(className, bundle.getBundleDetails().getCoordinate());
                requiresInstanceClassLoading.put(cacheKey, type);
            }
        }

    }

    /**
     * @param type a Class that we found from a service loader
     * @return true if the given class is a processor, controller service, or reporting task
     */
    private static boolean multipleVersionsAllowed(Class<?> type) {
        return Processor.class.isAssignableFrom(type) || ControllerService.class.isAssignableFrom(type) || ReportingTask.class.isAssignableFrom(type);
    }

    /**
     * Determines the effective ClassLoader for the instance of the given type.
     *
     * @param classType the type of class to lookup the ClassLoader for
     * @param instanceIdentifier the identifier of the specific instance of the classType to look up the ClassLoader for
     * @param bundle the bundle where the classType exists
     * @param additionalUrls additional URLs to add to the instance class loader
     * @return the ClassLoader for the given instance of the given type, or null if the type is not a detected extension type
     */
    public static InstanceClassLoader createInstanceClassLoader(final String classType, final String instanceIdentifier, final Bundle bundle, final Set<URL> additionalUrls) {
        if (StringUtils.isEmpty(classType)) {
            throw new IllegalArgumentException("Class-Type is required");
        }

        if (StringUtils.isEmpty(instanceIdentifier)) {
            throw new IllegalArgumentException("Instance Identifier is required");
        }

        if (bundle == null) {
            throw new IllegalArgumentException("Bundle is required");
        }

        // If the class is annotated with @RequiresInstanceClassLoading and the registered ClassLoader is a URLClassLoader
        // then make a new InstanceClassLoader that is a full copy of the NAR Class Loader, otherwise create an empty
        // InstanceClassLoader that has the NAR ClassLoader as a parent

        InstanceClassLoader instanceClassLoader;
        final ClassLoader bundleClassLoader = bundle.getClassLoader();
        final String key = getClassBundleKey(classType, bundle.getBundleDetails().getCoordinate());

        if (requiresInstanceClassLoading.containsKey(key) && bundleClassLoader instanceof NarClassLoader) {
            final Class<?> type = requiresInstanceClassLoading.get(key);
            final RequiresInstanceClassLoading requiresInstanceClassLoading = type.getAnnotation(RequiresInstanceClassLoading.class);

            final NarClassLoader narBundleClassLoader = (NarClassLoader) bundleClassLoader;
            logger.debug("Including ClassLoader resources from {} for component {}", new Object[] {bundle.getBundleDetails(), instanceIdentifier});

            final Set<URL> instanceUrls = new LinkedHashSet<>();
            for (final URL url : narBundleClassLoader.getURLs()) {
                instanceUrls.add(url);
            }

            ClassLoader ancestorClassLoader = narBundleClassLoader.getParent();

            if (requiresInstanceClassLoading.cloneAncestorResources()) {
                final ConfigurableComponent component = getTempComponent(classType, bundle.getBundleDetails().getCoordinate());
                final Set<BundleCoordinate> reachableApiBundles = findReachableApiBundles(component);

                while (ancestorClassLoader != null && ancestorClassLoader instanceof NarClassLoader) {
                    final Bundle ancestorNarBundle = classLoaderBundleLookup.get(ancestorClassLoader);

                    // stop including ancestor resources when we reach one of the APIs, or when we hit the Jetty NAR
                    if (ancestorNarBundle == null || reachableApiBundles.contains(ancestorNarBundle.getBundleDetails().getCoordinate())
                            || ancestorNarBundle.getBundleDetails().getCoordinate().getId().equals(NarClassLoaders.JETTY_NAR_ID)) {
                        break;
                    }

                    final NarClassLoader ancestorNarClassLoader = (NarClassLoader) ancestorClassLoader;
                    for (final URL url : ancestorNarClassLoader.getURLs()) {
                        instanceUrls.add(url);
                    }
                    ancestorClassLoader = ancestorNarClassLoader.getParent();
                }
            }

            instanceClassLoader = new InstanceClassLoader(instanceIdentifier, classType, instanceUrls, additionalUrls, ancestorClassLoader);
        } else {
            instanceClassLoader = new InstanceClassLoader(instanceIdentifier, classType, Collections.emptySet(), additionalUrls, bundleClassLoader);
        }

        if (logger.isTraceEnabled()) {
            for (URL url : instanceClassLoader.getURLs()) {
                logger.trace("URL resource {} for {}...", new Object[]{url.toExternalForm(), instanceIdentifier});
            }
        }

        instanceClassloaderLookup.put(instanceIdentifier, instanceClassLoader);
        return instanceClassLoader;
    }

    /**
     * Find the bundle coordinates for any service APIs that are referenced by this component and not part of the same bundle.
     *
     * @param component the component being instantiated
     */
    protected static Set<BundleCoordinate> findReachableApiBundles(final ConfigurableComponent component) {
        final Set<BundleCoordinate> reachableApiBundles = new HashSet<>();

        try (final NarCloseable closeable = NarCloseable.withComponentNarLoader(component.getClass().getClassLoader())) {
            final List<PropertyDescriptor> descriptors = component.getPropertyDescriptors();
            if (descriptors != null && !descriptors.isEmpty()) {
                for (final PropertyDescriptor descriptor : descriptors) {
                    final Class<? extends ControllerService> serviceApi = descriptor.getControllerServiceDefinition();
                    if (serviceApi != null && !component.getClass().getClassLoader().equals(serviceApi.getClassLoader())) {
                        final Bundle apiBundle = classLoaderBundleLookup.get(serviceApi.getClassLoader());
                        reachableApiBundles.add(apiBundle.getBundleDetails().getCoordinate());
                    }
                }
            }
        }

        return reachableApiBundles;
    }

    /**
     * Retrieves the InstanceClassLoader for the component with the given identifier.
     *
     * @param instanceIdentifier the identifier of a component
     * @return the instance class loader for the component
     */
    public static InstanceClassLoader getInstanceClassLoader(final String instanceIdentifier) {
        return instanceClassloaderLookup.get(instanceIdentifier);
    }

    /**
     * Removes the InstanceClassLoader for a given component.
     *
     * @param instanceIdentifier the of a component
     */
    public static InstanceClassLoader removeInstanceClassLoader(final String instanceIdentifier) {
        if (instanceIdentifier == null) {
            return null;
        }

        final InstanceClassLoader classLoader = instanceClassloaderLookup.remove(instanceIdentifier);
        closeURLClassLoader(instanceIdentifier, classLoader);
        return classLoader;
    }

    /**
     * Closes the given ClassLoader if it is an instance of URLClassLoader.
     *
     * @param instanceIdentifier the instance id the class loader corresponds to
     * @param classLoader the class loader to close
     */
    public static void closeURLClassLoader(final String instanceIdentifier, final ClassLoader classLoader) {
        if (classLoader != null && (classLoader instanceof URLClassLoader)) {
            final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            try {
                urlClassLoader.close();
            } catch (IOException e) {
                logger.warn("Unable to close URLClassLoader for " + instanceIdentifier);
            }
        }
    }

    /**
     * Retrieves the bundles that have a class with the given name.
     *
     * @param classType the class name of an extension
     * @return the list of bundles that contain an extension with the given class name
     */
    public static List<Bundle> getBundles(final String classType) {
        if (classType == null) {
            throw new IllegalArgumentException("Class type cannot be null");
        }
        final List<Bundle> bundles = classNameBundleLookup.get(classType);
        return bundles == null ? Collections.emptyList() : new ArrayList<>(bundles);
    }

    /**
     * Retrieves the bundle with the given coordinate.
     *
     * @param bundleCoordinate a coordinate to look up
     * @return the bundle with the given coordinate, or null if none exists
     */
    public static Bundle getBundle(final BundleCoordinate bundleCoordinate) {
        if (bundleCoordinate == null) {
            throw new IllegalArgumentException("BundleCoordinate cannot be null");
        }
        return bundleCoordinateBundleLookup.get(bundleCoordinate);
    }

    /**
     * Retrieves the bundle for the given class loader.
     *
     * @param classLoader the class loader to look up the bundle for
     * @return the bundle for the given class loader
     */
    public static Bundle getBundle(final ClassLoader classLoader) {
        if (classLoader == null) {
            throw new IllegalArgumentException("ClassLoader cannot be null");
        }
        return classLoaderBundleLookup.get(classLoader);
    }

    public static Set<Class> getExtensions(final Class<?> definition) {
        if (definition == null) {
            throw new IllegalArgumentException("Class cannot be null");
        }
        final Set<Class> extensions = definitionMap.get(definition);
        return (extensions == null) ? Collections.<Class>emptySet() : extensions;
    }

    public static ConfigurableComponent getTempComponent(final String classType, final BundleCoordinate bundleCoordinate) {
        if (classType == null) {
            throw new IllegalArgumentException("Class type cannot be null");
        }

        if (bundleCoordinate == null) {
            throw new IllegalArgumentException("Bundle Coordinate cannot be null");
        }

        return tempComponentLookup.get(getClassBundleKey(classType, bundleCoordinate));
    }

    private static String getClassBundleKey(final String classType, final BundleCoordinate bundleCoordinate) {
        return classType + "_" + bundleCoordinate.getCoordinate();
    }

    public static void logClassLoaderMapping() {
        final StringBuilder builder = new StringBuilder();

        builder.append("Extension Type Mapping to Bundle:");
        for (final Map.Entry<Class, Set<Class>> entry : definitionMap.entrySet()) {
            builder.append("\n\t=== ").append(entry.getKey().getSimpleName()).append(" Type ===");

            for (final Class type : entry.getValue()) {
                final List<Bundle> bundles = classNameBundleLookup.containsKey(type.getName())
                        ? classNameBundleLookup.get(type.getName()) : Collections.emptyList();

                builder.append("\n\t").append(type.getName());

                for (final Bundle bundle : bundles) {
                    final String coordinate = bundle.getBundleDetails().getCoordinate().getCoordinate();
                    final String workingDir = bundle.getBundleDetails().getWorkingDirectory().getPath();
                    builder.append("\n\t\t").append(coordinate).append(" || ").append(workingDir);
                }
            }

            builder.append("\n\t=== End ").append(entry.getKey().getSimpleName()).append(" types ===");
        }

        logger.info(builder.toString());
    }
}


text:
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.sleep_delay = 5
Delayed::Worker.max_attempts = 4
Delayed::Worker.max_run_time = 30.minutes
Delayed::Worker.delay_jobs = !Rails.env.test?

# Delayed job requires some attributes to be accessible - make sure they are
Delayed::Worker.backend = :active_record
Delayed::Job.attr_accessible :priority, :payload_object, :handler, :run_at, :failed_at


text:
//
//  ViewController.m
//  AutoLayout代码
//
//  Created by iqeggandroid on 15/4/6.
//  Copyright (c) 2015年 iqeggandroid. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *blueView = [[UIView alloc] init];
    blueView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:blueView];

    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:redView];

    /*
     Item == first item 需要设置约束的控件
     attribute == 需要设置的约束
     relateBy == relation 等于
     toItem == second item 被参照的控件
     attribure == 需要设置的约束
     multiplier == multiplier 乘以
     constant == constant  加上
     */
    // 1添加蓝色View距离父控件左边的距离固定为20 x
    blueView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *blueLeftLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:20];
    // 2添加蓝色View距离父控件右边的距离固定为20 宽度
    NSLayoutConstraint *blueRightLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:-20];
    // 3添加蓝色View距离父控件上边的距离固定为20 y
    NSLayoutConstraint *blueTopLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
    // 4添加蓝色View的高度50 高
    NSLayoutConstraint *blueHeightLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:50];
    [self.view addConstraints:@[blueLeftLc,blueRightLc,blueTopLc]];
    [blueView addConstraint:blueHeightLc];

    // 设置红色控件
    redView.translatesAutoresizingMaskIntoConstraints = NO;
    // 红色的高度和蓝色的高度一样
    NSLayoutConstraint *redHeightLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
    // 红色的右边和蓝色的右边对其
    NSLayoutConstraint *redRightLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0];
    // 红色的顶部等于蓝色的底部+20
    NSLayoutConstraint *redTopLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20];
    // 红色的宽度等于蓝色的宽度*0.5
    NSLayoutConstraint *redWidthLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];
    [self.view addConstraints:@[redHeightLc,redRightLc,redTopLc,redWidthLc]];

}

@end


text:
import {Scope} from "./Scope";

/**
 * Represents a {Scope} that makes a binding of a service only have a single instance in memory
 */
export class TransientScope extends Scope
{

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="com.shopizer.core.cache"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" />

     <cache name="com.shopizer.OBJECT_CACHE"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="1200"
           timeToLiveSeconds="1200"
           memoryStoreEvictionPolicy="LFU" />

     <cache name="store" maxElementsInMemory="1000" eternal="false"
    	overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

     <cache name="countriesMap" maxElementsInMemory="500" eternal="false"
    	overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

     <cache name="countrByCode" maxElementsInMemory="300" eternal="false"
    	overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

     <cache name="zoneByCode" maxElementsInMemory="800" eternal="false"
    	overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

     <cache name="languageByCode" maxElementsInMemory="50" eternal="false"
    	overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

</ehcache>