text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="/releases/4.3.0/css/style.css" rel="stylesheet" />

<title>apply ';' MACRO (';' LIST)*</title>
<meta name="generator" content="Jekyll v3.8.5" />
<meta property="og:title" content="apply ';' MACRO (';' LIST)*" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="The apply macro takes the name of a macro and invokes this macro with each element of the given list as an argument. It is useful when the arguments to the macro are in a comma separated list. args = com.example.foo, 3.12, HIGHEST ${apply;repo;${args}}" />
<meta property="og:description" content="The apply macro takes the name of a macro and invokes this macro with each element of the given list as an argument. It is useful when the arguments to the macro are in a comma separated list. args = com.example.foo, 3.12, HIGHEST ${apply;repo;${args}}" />

			Intro
			Headers
			Instructions
			Macros
			Commands

<button class="dropbtn">4.3.0</button>

Introduction

How to install bnd

Guided Tour

Guided Tour Workspace & Projects

Concepts

Best practices

Build

Project Setup

Generating JARs

Versioning

Baselining

Service Components

Metatype

Contracts

Bundle Annotations

Accessor Properties

SPI Annotations

Resolving Dependencies

Launching

Startlevels

Testing

Testing with Launchpad

Packaging Applications

JPMS Libraries

Wrapping Libraries to OSGi Bundles

Generating Documentation

Commands

For Developers

Tools bound to bnd

Headers

Instruction Reference

Instruction Index

Macro Reference

Macro Index

Plugins

Settings

Errors

Warnings

Frequently Asked Questions

 apply ';' MACRO (';' LIST)*

The apply macro takes the name of a macro and invokes this macro with each element of the given list as an argument. It is useful when the arguments to the macro are in a comma separated list.

args = com.example.foo, 3.12, HIGHEST
${apply;repo;${args}}

This will be expanded to:

${repo;com.example.foo;3.12;HIGHEST}

Which will provide the path to the artifact

GitHub


text:
layout: page
title: Final project
date: 2016-06-08 22:22:22
permalink: mec560-final-project
---

## DUE DATE: DEC 15, 2016 (NO LATE SUBMISSIONS ACCEPTED)

### MEC 560: Advanced Control Systems

Choose a system of your choice and apply linear/nonlinear control techniques you learned in MEC 560 to design a controller to perform a specific task. Submit a 5-6 page report with your with. Any statement showing significant gap in knowledge will be heavily penalized.

Your report should be organized as follows,

1. Problem statement
2. Approach
3. Mathematical model of the system you are designing control for.
    - Clearly identfy controllers, sensors, any constraints you may face.
4. System analysis
    - Controllability
    - Observability
    - Stability of the unactuated system
5. Controller synthesis
    - Identify the control scheme you are using
    - Apply Lyapunov method to show that the controller is stable
    - Clearly identify parameters of your controller
6. Observer synthesis
    - Design kalman filter (EKF for nonlinear filter)
    - Include discussion of if you can use observer with your controller model
    - If linear system, verify separation principle.
7. Simulation experiments
    - Test model under atleast 4 different environmental conditions
    - Test model under parametric uncertainities
    - Identify conditions under which your controller will fail to achieve success on the desired task.
8. Additional Notes
    - Include any additional findings.
9. Course feedback
    - How much time did you spend on this project?
    - If you were to redo the project, what would you do differently.
    - Give 2 changes you would like the instructor to incorporate in future classes?
    - What are the two most important things you learned from the instructor.
10. Self-assessment
    - What grade do you expect to get on the project?
    - What grade do you expect to get on the course.
    - Identify 2 areas that you need to improve on.
    - Identify 2 most interesting concepts you learned in this course?

redpajama_set_name: RedPajamaGithub


text: <!DOCTYPE html>


text:
package edu.utah.further.core.util.aop;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Marks a method or a class a utility processor. Useful for AOP.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne {@code <oren.livne@utah.edu>}
 * @version May 26, 2010
 */
@Target(
{ TYPE, METHOD })
@Retention(RUNTIME)
@Inherited
@Documented
public @interface SomeAnnotation
{
	// ========================= CONSTANTS ===============================

	/**
	 * Must be a constant expression.
	 */
	static final String CLASS_NAME = "edu.utah.further.core.util.aop.SomeAnnotation";
}


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # This module will let you pause/unpause Pingdom alerts
      class Pingdom < Base
        # @return [:running, :paused] Define whether or not the check should be running or paused.
        attribute :state
        validates :state, presence: true, expression_inclusion: {:in=>[:running, :paused], :message=>"%{value} needs to be :running, :paused"}

        # @return [Integer] Pingdom ID of the check.
        attribute :checkid
        validates :checkid, presence: true, type: Integer

        # @return [String] Pingdom user ID.
        attribute :uid
        validates :uid, presence: true, type: String

        # @return [String] Pingdom user password.
        attribute :passwd
        validates :passwd, presence: true, type: String

        # @return [String] Pingdom API key.
        attribute :key
        validates :key, presence: true, type: String
      end
    end
  end
end


text:
import { Extent } from '../../extent';
import { DeclutterGroups } from '../canvas';
import VectorContext from '../VectorContext';
import { SerializableInstructions } from './Builder';
import BuilderType from './BuilderType';

export default class BuilderGroup {
    constructor(tolerance: number, maxExtent: Extent, resolution: number, pixelRatio: number, declutter: boolean);
    addDeclutter(group: boolean): DeclutterGroups;
    finish(): { [key: string]: { [key in BuilderType]: SerializableInstructions } };
    getBuilder(zIndex: number | undefined, builderType: BuilderType): VectorContext;
}


text:
import Localization from './localization';

namespace Copy {
    type LocalizedCopyStore = { [language: string]: Localization.LocalizedCopy };
    // Languages for which messages are defined under this dir are acceptable
    export const acceptableLanguages = Localization.Locales.approved;

    export let defaultLocale = '';

    export function setDefaultLocale(locale: string) {
        if (acceptableLanguages.indexOf(locale) !== -1) {
            defaultLocale = locale;
            console.log(`Set the default locale to ${locale}`);
        }
    }

    export function forLocale(locale: string = defaultLocale): Localization.LocalizedCopy {
        const copy = Localization.Locales.allLocales[locale];
        return copy;
    }
}
export default Copy;


text:
Quick python script to download files from image boards using the [vichan api](https://github.com/vichan-devel/vichan-API/).

Mostly intended to be used on lainchan's pdf threads, but should work other places that implement the api.


text:
using BefunExec.Logic;
using BefunExec.View.OpenGL.OGLMath;
using OpenTK.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace BefunExec.View
{
	public class ZoomController
	{
		private enum ZoomSelectionMode { None, Select, Drag, SetBreakPoint, SetWatchPoint }

		private ZoomSelectionMode selectionMode = ZoomSelectionMode.None;
		private Rect2I selectionStartZoom = null;
		private Vec2I selectionStart = null;
		private Rect2I selection = null;

		private readonly Rect2I fullzoom;
		private readonly Stack<Rect2I> zoom = new Stack<Rect2I>();

		private readonly InteropKeyboard keyboard;
		private readonly BefunProg prog;

		public ZoomController(BefunProg p, InteropKeyboard kb)
		{
			prog = p;
			keyboard = kb;

			zoom.Push(fullzoom = new Rect2I(0, 0, prog.Width, prog.Height));
		}

		public ZoomController(BefunProg p, ZoomController copy)
		{
			prog = p;
			keyboard = copy.keyboard;

			fullzoom = copy.fullzoom;
			zoom = new Stack<Rect2I>(copy.zoom.Reverse());
		}

		public void RenderSelection(double offx, double offy, double w, double h, Rect2I currZoom)
		{
			if (selection != null)
			{
				Rect2D rect = new Rect2D(offx + ((selection.tl.X) - currZoom.bl.X) * w, offy + ((currZoom.Height - 1) - ((selection.tl.Y - 1) - currZoom.bl.Y)) * h, selection.Width * w, selection.Height * h);

				GL.Disable(EnableCap.Texture2D);

				GL.Begin(PrimitiveType.LineLoop);
				GL.Translate(0, 0, -3);
				GL.Color4(Color.Black);
				GL.Vertex3(rect.tl.X, rect.tl.Y, 0);
				GL.Vertex3(rect.bl.X, rect.bl.Y, 0);
				GL.Vertex3(rect.br.X, rect.br.Y, 0);
				GL.Vertex3(rect.tr.X, rect.tr.Y, 0);
				GL.Color3(1.0, 1.0, 1.0);
				GL.Translate(0, 0, 3);
				GL.End();

				GL.Begin(PrimitiveType.Quads);
				GL.Translate(0, 0, -4);
				GL.Color4(0.0, 0.0, 0.0, 0.5);
				GL.Vertex3(rect.tl.X, rect.tl.Y, 0);
				GL.Vertex3(rect.bl.X, rect.bl.Y, 0);
				GL.Vertex3(rect.br.X, rect.br.Y, 0);
				GL.Vertex3(rect.tr.X, rect.tr.Y, 0);
				GL.Color3(1.0, 1.0, 1.0);
				GL.Translate(0, 0, 4);
				GL.End();

				GL.Enable(EnableCap.Texture2D);
			}
		}

		public void DoMouseDown(MouseEventArgs e, int selx, int sely)
		{
			if (RunOptions.FOLLOW_MODE) //NOT POSSIBLE WHILE FOLLOWING
				return;

			if (e.Button == MouseButtons.Middle)
			{
				if (selx >= 0 && sely >= 0 && selx < prog.Width && sely < prog.Height)
				{
					selectionMode = ZoomSelectionMode.SetWatchPoint;

					var prev = prog.WatchedFields.FirstOrDefault(p => p.X == selx && p.Y == sely);

					if (prev == null)
					{
						prog.WatchData[selx, sely] = true;
						prog.WatchedFields.Add(new WatchedField(selx, sely));
					}
					else
					{
						prog.WatchedFields.Remove(prev);

						var next = prev.GetNext();
						if (next == null)
						{
							prog.WatchData[selx, sely] = false;
						}
						else
						{
							prog.WatchedFields.Add(next);
						}
					}

				}
			}
			else if (e.Button == MouseButtons.Left)
			{
				if (keyboard.IsDown(Keys.ShiftKey))
				{
					if (selx != -1 && sely != -1)
					{
						selectionMode = ZoomSelectionMode.Drag;

						selectionStartZoom = new Rect2I(Peek());
						selectionStart = new Vec2I(selx, sely);
					}
					else
					{
						selectionStart = null;
					}
				}
				else
				{
					if (selx != -1 && sely != -1)
					{
						selectionMode = ZoomSelectionMode.Select;

						selectionStart = new Vec2I(selx, sely);

						UpdateSelectionCalculation(selx, sely);
					}
					else
					{
						selectionStart = null;
					}
				}
			}
		}

		public void DoMouseMove(MouseEventArgs e, int selx, int sely)
		{
			if (e.Button != MouseButtons.Left)
				selection = null;

			if (selectionStart != null)
			{
				if (selectionMode == ZoomSelectionMode.Select)
				{
					UpdateSelectionCalculation(selx, sely);
				}
				else if (selectionMode == ZoomSelectionMode.Drag)
				{
					UpdateZoomDragging(selx, sely);

					if (!keyboard.IsDown(Keys.ShiftKey)) selectionMode = ZoomSelectionMode.None;
				}
			}
		}

		public void DoMouseUp(MouseEventArgs e, int selx, int sely)
		{
			if (e.Button != MouseButtons.Left)
				selection = null;

			if (selectionStart != null)
			{
				if (selectionMode == ZoomSelectionMode.Select)
				{
					UpdateSelectionCalculation(selx, sely);

					if (selection == null) return;

					if (selection.Width == 1 && selection.Height == 1)
					{
						if (prog.Breakpoints[selection.bl.X, selection.bl.Y])
						{
							prog.Breakpoints[selection.bl.X, selection.bl.Y] = false;
							prog.Breakpointcount--;
						}
						else
						{
							prog.Breakpoints[selection.bl.X, selection.bl.Y] = true;
							prog.Breakpointcount++;
						}
					}
					else if (Math.Abs(selection.Width) > 0 && Math.Abs(selection.Height) > 0)
					{
						if (selection != zoom.Peek())
							zoom.Push(selection);
					}
				}
				else if (selectionMode == ZoomSelectionMode.Drag)
				{
					UpdateZoomDragging(selx, sely);
				}
			}

			selectionMode = ZoomSelectionMode.None;
			selectionStart = null;
			selection = null;
		}

		public void DoMouseWheel(MouseEventArgs e)
		{
			if (RunOptions.FOLLOW_MODE) //NOT POSSIBLE WHILE FOLLOWING
				return;

			for (int i = 0; i < Math.Abs(e.Delta); i += 120)
			{
				if (e.Delta > 0)
					ZoomIn();
				else if (e.Delta < 0)
					ZoomOut();
			}
		}

		private void ZoomIn()
		{
			if (RunOptions.FOLLOW_MODE) //NOT POSSIBLE WHILE FOLLOWING
				return;

			Rect2I z = new Rect2I(zoom.Peek());

			int dx = z.Width / 10;
			int dy = z.Height / 10;

			if (dx == 0)
				dx = 1;

			if (dy == 0)
				dy = 1;

			if (z.Width > 2 * dx)
			{
				z.TrimHorizontal(dx);
			}
			else
			{
				int trim1 = z.Width / 2;
				int trim2 = (z.Width - trim1) - 1;

				z.TrimEast(trim1);
				z.TrimWest(trim2);
			}

			if (z.Height > 2 * dy)
			{
				z.TrimVertical(dy);
			}
			else
			{
				int trim1 = z.Height / 2;
				int trim2 = (z.Height - trim1) - 1;

				z.TrimNorth(trim1);
				z.TrimSouth(trim2);
			}

			if (zoom.Count > 1)
				zoom.Pop();
			zoom.Push(z);
		}

		private void ZoomOut()
		{
			if (RunOptions.FOLLOW_MODE) //NOT POSSIBLE WHILE FOLLOWING
				return;

			Rect2I z = new Rect2I(zoom.Peek());

			int dx = z.Width / 10;
			int dy = z.Height / 10;

			if (dx == 0)
				dx = 1;

			if (dy == 0)
				dy = 1;

			z.TrimHorizontal(-dx);
			z.TrimVertical(-dy);

			z.ForceInside(new Rect2I(0, 0, prog.Width, prog.Height));

			if (zoom.Count > 1)
				zoom.Pop();
			zoom.Push(z);
		}

		public double GetZoomFactor()
		{
			return Math.Min(prog.Width * 1.0 / zoom.Peek().Width, prog.Height * 1.0 / zoom.Peek().Height);
		}

		private void UpdateSelectionCalculation(int mouseX, int mouseY)
		{
			if (mouseX != -1 && mouseY != -1)
			{
				int l = Math.Min(mouseX, selectionStart.X);
				int r = Math.Max(mouseX, selectionStart.X);
				int b = Math.Min(mouseY, selectionStart.Y);
				int t = Math.Max(mouseY, selectionStart.Y);

				selection = new Rect2I(new Vec2I(l, b), new Vec2I(r + 1, t + 1));
			}
		}

		private void UpdateZoomDragging(int mouseX, int mouseY)
		{
			if (mouseX != -1 && mouseY != -1)
			{
				Rect2I r = new Rect2I(selectionStartZoom);

				r.Move(selectionStart.X - mouseX, selectionStart.Y - mouseY);

				r.ForceTranslateInside(fullzoom);

				Replace(r);

				selectionStartZoom = r;
			}
		}

		public Rect2I Peek()
		{
			return zoom.Peek();
		}

		public Rect2I Pop()
		{
			if (Count() > 1)
				return zoom.Pop();
			else
				return null;
		}

		public void PopInvalid()
		{
			if (zoom.Peek() == null || zoom.Peek().bl.X < 0 || zoom.Peek().bl.Y < 0 || zoom.Peek().tr.X > prog.Width || zoom.Peek().tr.Y > prog.Height)
				zoom.Pop();
		}

		public void PopToBase()
		{
			while (Count() > 1)
				Pop();
		}

		public void Clear()
		{
			zoom.Clear();
		}

		public void Push(Rect2I rect)
		{
			if (rect == null || rect.bl.X < 0 || rect.bl.Y < 0 || rect.tr.X > prog.Width || rect.tr.Y > prog.Height)
				return;

			zoom.Push(rect);
		}

		public int Count()
		{
			return zoom.Count();
		}

		public InteropKeyboard GetKeyboard()
		{
			return keyboard;
		}

		public void Replace(Rect2I zr)
		{
			if (Count() > 1)
				Pop();

			Push(zr);
		}
	}
}


text:
#include "sysdeps.h"
#include <assert.h>
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <memory.h>
#include <stdio.h>
#ifndef HAVE_WINSOCK
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#endif

/**  QUEUE
 **/
#define  SYS_MAX_QUEUE  16

typedef struct {
    int    start;
    int    end;
    void*  pending[ SYS_MAX_QUEUE ];
}
SysQueueRec, *SysQueue;

static void
sys_queue_reset( SysQueue  queue )
{
    queue->start = queue->end = 0;
}

static void
sys_queue_add( SysQueue  queue, void*  item )
{
    assert( queue->end - queue->start < SYS_MAX_QUEUE );
    assert( queue->start == 0 );
    assert( item != NULL );
    queue->pending[ queue->end++ ] = item;
}

#if 0
static void
sys_queue_remove( SysQueue  queue, void*  item )
{
    int  nn, count;
    assert( queue->end > queue->start );
    assert( item != NULL );
    count = queue->end - queue->start;
    for ( nn = queue->start; count > 0; ++nn, --count ) {
        if ( queue->pending[nn] == item ) {
            queue->pending[nn] = queue->pending[nn+count-1];
            queue->end -= 1;
            break;
        }
    }
    assert( 0 && "sys_queue_remove: item not found" );
}
#endif

static void*
sys_queue_get( SysQueue  queue )
{
    if (queue->end > queue->start) {
        return queue->pending[ queue->start++ ];
    }
    return NULL;
}

/** CHANNELS
 **/
typedef struct SysChannelRec_ {
    SysChannel          next;
    int                 fd;
    char                active;
    char                pending;
    char                closed;
    int                 wanted;
    int                 ready;
    SysChannelCallback  callback;
    void*               opaque;
} SysChannelRec;

/*** channel allocation ***/
#define  SYS_EVENT_MAX     3
#define  SYS_MAX_CHANNELS  16

static SysChannelRec  _s_channels0[ SYS_MAX_CHANNELS ];
static SysChannel     _s_free_channels;

static SysChannel
sys_channel_alloc( void )
{
    SysChannel  channel = _s_free_channels;
    assert( channel != NULL && "out of free channels" );
    _s_free_channels  = channel->next;
    channel->next     = NULL;
    channel->active   = 0;
    channel->closed   = 0;
    channel->pending  = 0;
    channel->wanted   = 0;
    return channel;
}

static void
sys_channel_free( SysChannel  channel )
{
    if (channel->fd >= 0) {
#ifdef _WIN32
        shutdown( channel->fd, SD_BOTH );
#else
        shutdown( channel->fd, SHUT_RDWR );
#endif
        close(channel->fd);
        channel->fd = -1;
    }
    channel->wanted   = 0;
    channel->ready    = 0;
    channel->callback = NULL;

    channel->next    = _s_free_channels;
    _s_free_channels = channel;
}

/* list of active channels */
static SysChannel     _s_channels;

/* used by select to wait on channel events */
static fd_set         _s_fdsets[SYS_EVENT_MAX];
static int            _s_maxfd;

static void
sys_channel_deactivate( SysChannel  channel )
{
    assert( channel->active != 0 );
    SysChannel  *pnode = &_s_channels;
    for (;;) {
        SysChannel  node = *pnode;
        assert( node != NULL );
        if (node == channel)
            break;
        pnode = &node->next;
    }
    *pnode          = channel->next;
    channel->next   = NULL;
    channel->active = 0;
}

static void
sys_channel_activate( SysChannel  channel )
{
    assert( channel->active == 0 );
    channel->next = _s_channels;
    _s_channels   = channel;
    channel->active = 1;
    if (channel->fd > _s_maxfd)
        _s_maxfd = channel->fd;
}

/* queue of pending channels */
static SysQueueRec    _s_pending_channels[1];

static void
sys_init_channels( void )
{
    int  nn;

    for (nn = 0; nn < SYS_MAX_CHANNELS-1; nn++)
        _s_channels0[nn].next = &_s_channels0[nn+1];
    _s_free_channels = &_s_channels0[0];

    for (nn = 0; nn < SYS_EVENT_MAX; nn++)
        FD_ZERO( &_s_fdsets[nn] );

    _s_maxfd = -1;

    sys_queue_reset( _s_pending_channels );
}

void
sys_channel_on( SysChannel          channel,
                int                 events,
                SysChannelCallback  callback,
                void*               opaque )
{
    int   adds    = events & ~channel->wanted;
    int   removes = channel->wanted & ~events;

    channel->wanted   = events;
    channel->callback = callback;
    channel->opaque   = opaque;

    /* update global fdsets */
    if (adds) {
        int  ee;
        for (ee = 0; ee < SYS_EVENT_MAX; ee++)
            if (adds & (1 << ee))
                FD_SET( channel->fd, &_s_fdsets[ee] );
    }
    if (removes) {
        int  ee;
        for (ee = 0; ee < SYS_EVENT_MAX; ee++)
            if (removes & (1 << ee))
                FD_CLR( channel->fd, &_s_fdsets[ee] );
    }
    if (events && !channel->active) {
        sys_channel_activate( channel );
    }
    else if (!events && channel->active) {
        sys_channel_deactivate( channel );
    }
}

int
sys_channel_read( SysChannel  channel, void*  buffer, int  size )
{
    char*  buff = buffer;
    int    count = 0;

    assert( !channel->closed );

    while (size > 0) {
        int  len = read(channel->fd, buff, size);
        if (len < 0) {
            if (errno == EINTR)
                continue;
            if (count == 0)
                count = -1;
            break;
        }
        buff  += len;
        size  -= len;
        count += len;
    }
    return count;
}

int
sys_channel_write( SysChannel  channel, const void*  buffer, int  size )
{
    const char*  buff = buffer;
    int          count = 0;

    assert( !channel->closed );

    while (size > 0) {
        int  len = write(channel->fd, buff, size);
        if (len < 0) {
            if (errno == EINTR)
                continue;
            if (count == 0)
                count = -1;
            break;
        }
        buff  += len;
        size  -= len;
        count += len;
    }
    return count;
}

void
sys_channel_close( SysChannel  channel )
{
    if (channel->active) {
        sys_channel_on( channel, 0, NULL, NULL );
    }

    if (channel->pending) {
        /* we can't free the channel right now because it */
        /* is in the pending list, set a flag             */
        channel->closed = 1;
        return;
    }

    if (!channel->closed) {
        channel->closed = 1;
    }

    sys_channel_free( channel );
}

/** time measurement
 **/
SysTime  sys_time_ms( void )
{
    struct timeval  tv;
    gettimeofday( &tv, NULL );
    return (SysTime)(tv.tv_usec / 1000) + (SysTime)tv.tv_sec * 1000;
}

/** timers
 **/
typedef struct SysTimerRec_
{
    SysTimer     next;
    SysTime      when;
    SysCallback  callback;
    void*        opaque;
} SysTimerRec;

#define  SYS_MAX_TIMERS  16

static SysTimerRec   _s_timers0[ SYS_MAX_TIMERS ];
static SysTimer      _s_free_timers;
static SysTimer      _s_timers;

static SysQueueRec   _s_pending_timers[1];

static void
sys_init_timers( void )
{
    int  nn;
    for (nn = 0; nn < SYS_MAX_TIMERS-1; nn++) {
        _s_timers0[nn].next = & _s_timers0[nn+1];
    }
    _s_free_timers = &_s_timers0[0];

    sys_queue_reset( _s_pending_timers );
}

SysTimer   sys_timer_create( void )
{
    SysTimer  timer = _s_free_timers;
    assert( timer != NULL && "too many timers allocated" );
    _s_free_timers = timer->next;
    timer->next    = NULL;
    return timer;
}

void  sys_timer_unset( SysTimer  timer )
{
    if (timer->callback != NULL) {
        SysTimer  *pnode, node;
        pnode = &_s_timers;
        for (;;) {
            node = *pnode;
            if (node == NULL)
                break;
            if (node == timer) {
                *pnode = node->next;
                break;
            }
            pnode = &node->next;
        }
        timer->next     = NULL;
        timer->callback = NULL;
        timer->opaque   = NULL;
    }
}

void  sys_timer_set( SysTimer      timer,
                     SysTime       when,
                     SysCallback   callback,
                     void*         opaque )
{
    if (timer->callback != NULL)
        sys_timer_unset(timer);

    if (callback != NULL) {
        SysTime  now = sys_time_ms();

        if (now >= when) {
            callback( opaque );
        } else {
            SysTimer  *pnode, node;
            pnode = &_s_timers;
            for (;;) {
                node = *pnode;
                if (node == NULL || node->when >= when) {
                    break;
                }
                pnode = &node->next;
            }
            timer->next     = *pnode;
            *pnode          = timer;
            timer->when     = when;
            timer->callback = callback;
            timer->opaque   = opaque;
        }
    }
}

void  sys_timer_destroy( SysTimer  timer )
{
    assert( timer != NULL && "sys_timer_destroy: bad argument" );
    if (timer->callback != NULL)
        sys_timer_unset(timer);

    timer->next    = _s_free_timers;
    _s_free_timers = timer;
}

static void
sys_single_loop( void )
{
    fd_set rfd, wfd, efd;
    struct timeval  timeout_tv, *timeout = NULL;
    int    n;

    memcpy(&rfd, &_s_fdsets[0], sizeof(fd_set));
    memcpy(&wfd, &_s_fdsets[1], sizeof(fd_set));
    memcpy(&efd, &_s_fdsets[2], sizeof(fd_set));

    if ( _s_timers != NULL ) {
        SysTime   now   = sys_time_ms();
        SysTimer  first = _s_timers;

        timeout = &timeout_tv;
        if (first->when <= now) {
            timeout->tv_sec  = 0;
            timeout->tv_usec = 0;
        } else {
            SysTime  diff = first->when - now;
            timeout->tv_sec =   diff / 1000;
            timeout->tv_usec = (diff - timeout->tv_sec*1000) * 1000;
        }
    }

    n = select( _s_maxfd+1, &rfd, &wfd, &efd, timeout);
    if(n < 0) {
        if(errno == EINTR) return;
        perror("select");
        return;
    }

    /* enqueue pending channels */
    {
        int  i;

        sys_queue_reset( _s_pending_channels );
        for(i = 0; (i <= _s_maxfd) && (n > 0); i++)
        {
            int  events = 0;

            if(FD_ISSET(i, &rfd)) events |= SYS_EVENT_READ;
            if(FD_ISSET(i, &wfd)) events |= SYS_EVENT_WRITE;
            if(FD_ISSET(i, &efd)) events |= SYS_EVENT_ERROR;

            if (events) {
                SysChannel  channel;

                n--;
                for (channel = _s_channels; channel; channel = channel->next)
                {
                    if (channel->fd != i)
                        continue;

                    channel->ready   = events;
                    channel->pending = 1;
                    sys_queue_add( _s_pending_channels, channel );
                    break;
                }
            }
        }
    }

    /* enqueue pending timers */
    {
        SysTimer  timer = _s_timers;
        SysTime   now   = sys_time_ms();

        sys_queue_reset( _s_pending_timers );
        while (timer != NULL)
        {
            if (timer->when > now)
                break;

            sys_queue_add( _s_pending_timers, timer );
            _s_timers = timer = timer->next;
        }
    }
}

void  sys_main_init( void )
{
    sys_init_channels();
    sys_init_timers();
}

int   sys_main_loop( void )
{
    for (;;) {
        SysTimer    timer;
        SysChannel  channel;

        /* exit if we have nothing to do */
        if (_s_channels == NULL && _s_timers == NULL)
            break;

        sys_single_loop();

        while ((timer = sys_queue_get( _s_pending_timers )) != NULL) {
            timer->callback( timer->opaque );
        }

        while ((channel = sys_queue_get( _s_pending_channels )) != NULL) {
            int  events;

            channel->pending = 0;
            if (channel->closed) {
                /* the channel was closed by a previous callback */
                sys_channel_close(channel);
            }
            events = channel->ready;
            channel->ready = 0;
            channel->callback( channel->opaque, events );
        }
    }
    return 0;
}

SysChannel
sys_channel_create_tcp_server( int port )
{
    SysChannel          channel;
    int                 on = 1;
    const int           BACKLOG = 4;

    channel = sys_channel_alloc();
    if (-1==(channel->fd=socket(AF_INET, SOCK_STREAM, 0))) {
        perror("socket");
        sys_channel_free( channel );
        return NULL;
    }

    /* Enable address re-use for server mode */
    if ( -1==setsockopt( channel->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) )) {
        perror("setsockopt(SO_REUSEADDR)");
    }

    {
        struct sockaddr_in  servname;
        long                in_addr = INADDR_ANY;

        servname.sin_family = AF_INET;
        servname.sin_port   = htons(port);

        servname.sin_addr.s_addr=in_addr;

        if (-1==bind(channel->fd, (struct sockaddr*)&servname, sizeof(servname))) {
            perror("bind");
            sys_channel_close(channel);
            return NULL;
        }

        /* Listen but don't accept */
        if ( listen(channel->fd, BACKLOG) < 0 ) {
            perror("listen");
            sys_channel_close(channel);
            return NULL;
        }
    }
    return channel;
}

SysChannel
sys_channel_create_tcp_handler( SysChannel  server_channel )
{
    int         on      = 1;
    SysChannel  channel = sys_channel_alloc();

    channel->fd = accept( server_channel->fd, NULL, 0 );
    if (channel->fd < 0) {
        perror( "accept" );
        sys_channel_free( channel );
        return NULL;
    }

    /* set to non-blocking and disable TCP Nagle algorithm */
    fcntl(channel->fd, F_SETFL, O_NONBLOCK);
    setsockopt(channel->fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
    return channel;
}

SysChannel
sys_channel_create_tcp_client( const char*  hostname, int  port )
{
    struct hostent*     hp;
    struct sockaddr_in  addr;
    SysChannel          channel = sys_channel_alloc();
    int                 on = 1;

    hp = gethostbyname(hostname);
    if(hp == 0) {
        fprintf(stderr, "unknown host: %s\n", hostname);
        sys_channel_free(channel);
        return NULL;
    };

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = hp->h_addrtype;
    addr.sin_port   = htons(port);
    memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);

    channel->fd = socket(hp->h_addrtype, SOCK_STREAM, 0);
    if(channel->fd < 0) {
        sys_channel_free(channel);
        return NULL;
    }

    if(connect( channel->fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror( "connect" );
        sys_channel_free(channel);
        return NULL;
    }

    /* set to non-blocking and disable Nagle algorithm */
    fcntl(channel->fd, F_SETFL, O_NONBLOCK);
    setsockopt( channel->fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on) );
    return channel;
}


text:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';

@Component({
  selector: 'cs-overlay-loading',
  templateUrl: 'overlay-loading.component.html',
  styleUrls: ['overlay-loading.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OverlayLoadingComponent {
  @Input()
  public active: boolean;
}


text:
package net.chrigel.clusterbrake.settings.constraint;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import net.chrigel.clusterbrake.TestUtility;
import net.chrigel.clusterbrake.media.FileContainer;
import net.chrigel.clusterbrake.media.VideoPackage;
import org.apache.commons.io.FileUtils;
import static org.hamcrest.CoreMatchers.equalTo;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;

public class FileSizeConstraintTest {

    private FileSizeConstraint subject;

    @Mock
    private VideoPackage video;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @BeforeClass
    public static void classSetup() {
        TestUtility.getTestDir().mkdirs();
    }

    @AfterClass
    public static void tearDown() throws IOException {
        FileUtils.deleteDirectory(TestUtility.getTestDir());
    }

    @Test
    public void testAccept_ShouldReturnTrue_IfFileIsGreaterThanMinSize() throws IOException {
        subject = new FileSizeConstraint(2, 0, FileSizeConstraint.BYTES);
        File testFile = new File("testFile");
        FileContainer container = new FileContainer(TestUtility.getTestDirType(), testFile);
        FileUtils.writeLines(container.getFullPath(), Arrays.asList("line", "line", "line", "line"));
        when(video.getSourceFile()).thenReturn(container);

        assertThat(subject.accept(video), equalTo(true));
    }

    @Test
    public void testAccept_ShouldReturnTrue_IfFileIsSmallerThanMaxSize() throws IOException {
        subject = new FileSizeConstraint(0, 100, FileSizeConstraint.BYTES);
        File testFile = new File("testFile");
        FileContainer container = new FileContainer(TestUtility.getTestDirType(), testFile);
        FileUtils.writeLines(container.getFullPath(), Arrays.asList("line"));
        when(video.getSourceFile()).thenReturn(container);

        assertThat(subject.accept(video), equalTo(true));
    }

    @Test
    public void testAccept_ShouldReturnTrue_IfFileIsBetweenMaxAndMinSize() throws IOException {
        subject = new FileSizeConstraint(2, 100, FileSizeConstraint.BYTES);
        File testFile = new File("testFile");
        FileContainer container = new FileContainer(TestUtility.getTestDirType(), testFile);
        FileUtils.writeLines(container.getFullPath(), Arrays.asList("line"));
        when(video.getSourceFile()).thenReturn(container);

        assertThat(subject.accept(video), equalTo(true));
    }

    @Test
    public void testAccept_ShouldReturnFalse_IfFileIsSmallerThanMinSize() throws IOException {
        subject = new FileSizeConstraint(50, 0, FileSizeConstraint.BYTES);
        File testFile = new File("testFile");
        FileContainer container = new FileContainer(TestUtility.getTestDirType(), testFile);
        FileUtils.writeLines(container.getFullPath(), Arrays.asList("line"));
        when(video.getSourceFile()).thenReturn(container);

        assertThat(subject.accept(video), equalTo(false));
    }

    @Test
    public void testAccept_ShouldReturnFalse_IfFileIsGreaterThanMaxSize() throws IOException {
        subject = new FileSizeConstraint(10, 20, FileSizeConstraint.BYTES);
        File testFile = new File("testFile");
        FileContainer container = new FileContainer(TestUtility.getTestDirType(), testFile);
        FileUtils.writeLines(container.getFullPath(), Arrays.asList("line", "line", "line", "line"));
        when(video.getSourceFile()).thenReturn(container);

        assertThat(subject.accept(video), equalTo(false));
    }

}


text:
from django.dispatch import Signal

friend_request_created = Signal(providing_args=['instance', 'user', 'receiver'])
friendship_created = Signal(providing_args=['friend', 'user'])
social_group_created = Signal(providing_args=['instance', 'user'])
social_group_comment_created = Signal(providing_args=['instance', 'user'])
social_group_shared_link_created = Signal(providing_args=['instance', 'user'])
social_group_photo_created = Signal(providing_args=['instance', 'user'])
social_group_membership_request_created = Signal(providing_args=['instance', 'user', 'group'])
social_group_member_added = Signal(providing_args=['group', 'member', 'user'])
feed_comment_created = Signal(providing_args=['instance', 'user'])
follower_relationship_created = Signal(providing_args=['followed', 'user'])
follower_relationship_destroyed = Signal(providing_args=['followed', 'user'])


text:
package ariba.ui.aribaweb.core;

import java.util.Map;

import ariba.ui.aribaweb.util.AWUtil;
import ariba.util.core.MapUtil;
import ariba.util.core.StringUtil;
import ariba.util.fieldvalue.FieldValue;

public final class AWBindingApi extends AWApiDeclaration
{
    protected static final int Both = 2;
    protected static final int Either = 3;
    private Map _bindings;

    // required bindings
    public static final String Key          = "key";
    public static final String Direction    = "direction";
    public static final String Type         = "type";

    // optional bindings
    public static final String Required     = "required";
    public static final String Alternates   = "alternates";
    public static final String Default      = "default";

    // for debugging
    public String toString ()
    {
        AWBinding binding = getBinding(Type, true);
        String className = binding.stringValue(null);
        binding = getBinding(Direction, true);
        String directionString = (String)binding.value(null);

        binding = getBinding(Default, false);
        String defaultValue = (binding != null) ? binding.stringValue(null) : "";

        return ("key: "+key()+ " type: " + className + " direction: " + directionString +
                " required: " + isRequired() + " alternates: " + alternates() + " default: " + defaultValue);
    }

    public void init (String tagName, Map bindingsHashtable)
    {
        _bindings = MapUtil.cloneMap(bindingsHashtable);
        super.init();
    }

    private AWBinding getBinding (String key, boolean required)
    {
        AWBinding binding = (AWBinding)_bindings.get(key);
        if (required && binding == null) {
            throw new RuntimeException("AWBindingApi missing required binding specification \"" + key + "\"");
        }
        return binding;
    }

    private AWBinding getBinding (String key)
    {
        return getBinding(key, false);
    }

    public String key ()
    {
        AWBinding binding = getBinding(Key, true);
        return binding.stringValue(null);
    }

    public int direction ()
    {
        AWBinding binding = getBinding(Direction, true);
        String directionString = (String)binding.value(null);
        int direction = -1;
        if (directionString.equals("get")) {
            direction = FieldValue.Getter;
        }
        else if (directionString.equals("set")) {
            direction = FieldValue.Setter;
        }
        else if (directionString.equals("both")) {
            direction = AWBindingApi.Both;
        }
        else if (directionString.equals("either")) {
            direction = AWBindingApi.Either;
        }
        else {
            throw new RuntimeException("unrecognized direction: " + directionString);
        }
        return direction;
    }

    // defaults to false;
    public boolean isRequired ()
    {
        AWBinding binding = getBinding(Required);
        return binding == null ? false : binding.booleanValue(null);
    }

    public Object defaultValue ()
    {
        Object defaultValue = null;
        AWBinding binding = getBinding(Default, false);
        if (binding != null) {
            defaultValue = binding.value(null);
        }

        return defaultValue;
    }

    public Class type ()
    {
        Class typeClass = null;
        AWBinding binding = getBinding(Type, true);
        String className = binding.stringValue(null);
        if (className.equals("int")) {
            typeClass = Integer.TYPE;
        }
        else if (className.equals("boolean")) {
            typeClass = Boolean.TYPE;
        }
        else if (className.equals("String")) {
            typeClass = String.class;
        }
        else {
            typeClass = AWConcreteApplication.SharedInstance.resourceManager().classForName(className);
        }
        if (typeClass == null) {
            throw new RuntimeException("AWBindingApi: Unrecognized type specified \"" + className + "\"");
        }
        return typeClass;
    }

    public String alternates ()
    {
        AWBinding binding = getBinding(Alternates);
        return (binding != null) ? binding.stringValue(null) : "";
    }

    public String[] alternatesArray ()
    {
        String[] alternates = null;
        String sAlternates = alternates();
        if (StringUtil.nullOrEmptyOrBlankString(sAlternates)) {
            return alternates;
        }

        alternates = AWUtil.parseComponentsString(sAlternates,",");
        return alternates;
    }

    public String directionString ()
    {
        AWBinding binding = getBinding(Direction, true);
        return (String)binding.value(null);
    }

    public String typeString ()
    {
        AWBinding binding = getBinding(Type, true);
        String className = binding.stringValue(null);
        return className;
    }

    public void validate (AWValidationContext validationContext, AWComponent component)
    {
        // todo: should use DTD / schema to validate BindingApi tags
        // todo: validate class types
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Elvo
{
    public partial class FrmAbout : Form
    {
        /**
          *關於表單 - 2016/02/14 IncrEdibLe (Robby)
          */

        Config.Initial ini = new Config.Initial();
        Config.Text txt = new Config.Text();

        private const int WM_NCHITTEST = 0x84;
        private const int HTCLIENT = 0x1;
        private const int HTCAPTION = 0x2;
        private const int WM_LBUTTONDBLCLK = 0x00A3;

        public FrmAbout()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_LBUTTONDBLCLK)
            {
                return;
            }

            switch (m.Msg)
            {
                case WM_NCHITTEST:
                    base.WndProc(ref m);
                    if ((int)m.Result == HTCLIENT)
                        m.Result = (IntPtr)HTCAPTION;
                    return;
            }
            base.WndProc(ref m);
        }

        private void FrmAbout_Load(object sender, EventArgs e)
        {
            lbAbout.Text = Properties.Resources.Version;
            picAbout.Image = Properties.Resources.about;

            // ToolTip
            ini.SetToolTip(picExit, txt.tip_exit);
        }

        private void picExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        private void picExit_MouseLeave(object sender, EventArgs e)
        {
            picExit.Image = Properties.Resources.control_exit1;
        }

        private void picExit_MouseEnter(object sender, EventArgs e)
        {
            picExit.Image = Properties.Resources.control_exit2;
        }

        private void lnkBlog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(Properties.Resources.Blog); // Pixnet Blog
        }

        private void lnkElsInfo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(Properties.Resources.FaceBook); // Pixnet Blog
        }

        private void lnkGit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(Properties.Resources.GitHub); // Pixnet Blog
        }

        private void lnkDot_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(Properties.Resources.DotBlogs); // Pixnet Blog
        }

    }
}


text:
package salarycalculation.web.resources;

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.codahale.metrics.annotation.Timed;

import salarycalculation.database.repository.EmployeeRepositoryDao;
import salarycalculation.domain.employee.Employee;
import salarycalculation.domain.employee.EmployeeRepository;
import salarycalculation.domain.employee.Employees;
import salarycalculation.web.representation.EmployeeView;

/**
 * 従業員に関するリクエストを受け付けるクラス。
 *
 * @author naotake
 */
@Path("/employee")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public class EmployeeResource {

    private EmployeeRepository repository;

    public EmployeeResource() {
        repository = new EmployeeRepositoryDao();
    }

    @GET
    @Timed
    public EmployeeView get(@NotNull @QueryParam("no") String employeeNo) {
        Employee employee = repository.get(employeeNo);
        return new EmployeeView(employee.getId(), employee.getName());
    }

    @GET
    @Timed
    @Path("/list")
    public List<EmployeeView> list() {
        Employees employees = repository.findAll();
        return employees.getEmployees().stream().map(s -> new EmployeeView(s.getId(), s.getName()))
                        .collect(Collectors.toList());
    }
}


text:
title:	Tensorflow input pipeline example
date: 2017-10-17 19:44:00
categories: [tensorflow,cnn]
tags: [tensorflow,python,cnn]
---
*From [TENSORFLOW INPUT PIPELINE EXAMPLE](http://ischlag.github.io/2016/06/19/tensorflow-input-pipeline-example/)*

A brief example of using tensorflows input pipeline to load your own custom data structures into tensorflows computational graph. This includes the partitioning of the data into a test and train set and batching together a set of images. You can find all the code at the bottom of this page. Note: This will not work for large datasets as ops.convert_to_tensor will create constants of your data in your graph! Have a look at this next post in order to use TensorFlow input pipelines with very large datasets.

#### Context

The official tensorflow documentation on reading in data can be found here but also have a look at the API. With this script you can create a jpg based dataset from the compact mnist dataset format. With this dataset, we are going to build a simple and efficient input pipeline. This example was done using tensorflow 0.8.0.

#### Load Data in Tensorflow

<!-- more -->

Ok, let's take one step back. There are two ways on how you can load your data into your tensorflow graph (excluding a third way of loading the data as a constant). In an earlier post, we have used the feeding method where we provide a feed_dict object with our data and labels at every step. This can be problematic if our dataset is too big to be stored in our working memory and so the authors of tensorflow introduced input pipelines. The next steps are going to describe how that pipeline should look like. Only when we start our queue runners right before our session operations the pipeline will be active and loading data.

The input pipeline deals with reading csv files, decode file formats, restructure the data, shuffle the data, data augmentation or other preprocessing, and load the data in batches using threads. However, we do have to write some code to get this to work.

#### Load the Label Data

Make sure you are using the correct paths to the dataset created by the script file linked above.
```python
dataset_path      = "/path/to/out/dataset/mnist/"
test_labels_file  = "test-labels.csv"
train_labels_file = "train-labels.csv"
The first thing we do is loading the label and image path information from the text files we have generated. The encode_label function assigns an int value to our string text. For this example, we are going to simply convert the string label into an integer since they are all numbers. We are not going to train a model in this example so if you want to train e.g. a neural network you probably want to do some one-hot encoding here. But be aware that the format of our label needs to be congruent with the tensor dtype later on!

def encode_label(label):
  return int(label)

def read_label_file(file):
  f = open(file, "r")
  filepaths = []
  labels = []
  for line in f:
    filepath, label = line.split(",")
    filepaths.append(filepath)
    labels.append(encode_label(label))
  return filepaths, labels

# reading labels and file path
train_filepaths, train_labels = read_label_file(dataset_path + train_labels_file)
test_filepaths, test_labels = read_label_file(dataset_path + test_labels_file)
```
#### Do Some Optional Processing on Our String Lists

Next, we will transform the relative image path into a full image path and for the sake of this example we are also going to concat the given train and test set. We then shuffle the data and create our own train and test set later on. Be aware that you should not do this if you want to compare your trained models with other mnist models. We only do this to show the capabilities of the tensorflow input pipeline!

To make the output of the script clearer we will also shrink the full dataset to only 20 samples (did I tell you yet that this is an example?).
```python
# transform relative path into full path
train_filepaths = [ dataset_path + fp for fp in train_filepaths]
test_filepaths = [ dataset_path + fp for fp in test_filepaths]

# for this example we will create or own test partition
all_filepaths = train_filepaths + test_filepaths
all_labels = train_labels + test_labels

# we limit the number of files to 20 to make the output more clear!
all_filepaths = all_filepaths[:20]
all_labels = all_labels[:20]
```
#### Start Building the Pipeline

Now we will start to define our pipeline. Make sure that the dtype of our tensor is matching the type of data that we have in our lists. For the next part, we will need the following imports.
```python
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
With those we can create our tensorflow objects. If you decide to use the train and test data set of mnist as it is given you would just do the next steps for both sets simultaneously.

# convert string into tensors
all_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)
all_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.int32)
```
#### Lets Partition the Data

This step is optional. Since we have all our 20 samples in one (big) set, we want to perform some partitioning to build a test and train set. Tensorflow comes with the ability to do this on-the-fly with tensors so we don't have to do this beforehand. If the partition function is confusing you can read up the official explanation here. For the running example, we define the test_set_size to be 5 samples.

![local_response_normalization](https://sumihui.github.io/source/images/DynamicPartition.png)

A visualization of the dynamic partition function in tensorflow.
```python
# create a partition vector
partitions = [0] * len(all_filepaths)
partitions[:test_set_size] = [1] * test_set_size
random.shuffle(partitions)

# partition our data into a test and train set according to our partition vector
train_images, test_images = tf.dynamic_partition(all_images, partitions, 2)
train_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)
```
#### Build the Input Queues and Define How to Load Images

The slice_input_producer will slice our tensors into single instances and queue them up using threads. There are further parameters to define the number of threads used and the capacity of the queue (look at the API documentation). We then use the path information to read the file into our pipeline and decode it using the jpg decoder (other decoders can be found in the API documentation).
```python
# create input queues
train_input_queue = tf.train.slice_input_producer(
                                    [train_images, train_labels],
                                    shuffle=False)
test_input_queue = tf.train.slice_input_producer(
                                    [test_images, test_labels],
                                    shuffle=False)

# process path and string tensor into an image and a label
file_content = tf.read_file(train_input_queue[0])
train_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
train_label = train_input_queue[1]

file_content = tf.read_file(test_input_queue[0])
test_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
test_label = test_input_queue[1]
```
#### Group Samples into Batches

If you run train_image in a session you would get a single image i.e. (28, 28, 1) since according to the dimensions of our mnist images. Training a model on single images can be inefficient which is why we would like to queue up images into a batch and perform our operations on a whole batch of images instead of a single one. We have yet to start our runners to load images. So far we have only described how the pipeline would look like and tensorflow doesn't know the shape of our images. To use tf.train_batch we need to define the shape of our image tensors before they can be combined into batches. For this example, we will use a batch size of 5 samples.
```python
# define tensor shape
train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])
test_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])

# collect batches of images before processing
train_image_batch, train_label_batch = tf.train.batch(
                                    [train_image, train_label],
                                    batch_size=BATCH_SIZE
                                    #,num_threads=1
                                    )
test_image_batch, test_label_batch = tf.train.batch(
                                    [test_image, test_label],
                                    batch_size=BATCH_SIZE
                                    #,num_threads=1
                                    )
```
#### Run the Queue Runners and Start a Session

We have finished building our input pipeline. However, if we would now try to access e.g. test_image_batch, we would not get any data as we have not started the threads who will load the queues and push data into our tensorflow objects. After doing that, we will have two loops one going over the training data and one going over the test data. You will probably notice that the loops are bigger than the number of samples in each data set. What is the behaviour you expect?
```python
with tf.Session() as sess:

  # initialize the variables
  sess.run(tf.initialize_all_variables())

  # initialize the queue threads to start to shovel data
  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(coord=coord)

  print "from the train set:"
  for i in range(20):
    print sess.run(train_label_batch)

  print "from the test set:"
  for i in range(10):
    print sess.run(test_label_batch)

  # stop our queue threads and properly close the session
  coord.request_stop()
  coord.join(threads)
  sess.close()
```
As you can see in the following output, tensorflow doesn't care about epochs. We are not shuffling the data (see the parameter of the input slicer) and so our input pipeline will just cycle over the training data as often as it has to. It is your own responsibility to make sure that you correctly count the number of epochs. Play around with the batch size and shuffle and try to predict how this will change the output produced. Can you predict what will happen if you change the batch_size to 4 instead of 5?
```python
(tf-env)worker1:~$ python mnist_feed.py
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
input pipeline ready
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GeForce GTX 960
major: 5 minor: 2 memoryClockRate (GHz) 1.253
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.77GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:755] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960, pci bus id: 0000:01:00.0)
from the train set:
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
[1 7 2 6 9]
[5 4 1 9 2]
[1 3 1 3 6]
from the test set:
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
[0 4 5 3 8]
```
Since we shuffled our partition vector you will obviously get different labels but what is important here is that you understand how the loading mechanism works. Since our batch size is as big as our test set every batch is the same.

#### Complete Code for this example

You need the script here (also linked above) to create the dataset and fix the path variables to the dataset at the beginning. This is the complete script.

```python
# Example on how to use the tensorflow input pipelines. The explanation can be found here ischlag.github.io.
import tensorflow as tf
import random
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes

dataset_path      = "/path/to/your/dataset/mnist/"
test_labels_file  = "test-labels.csv"
train_labels_file = "train-labels.csv"

test_set_size = 5

IMAGE_HEIGHT  = 28
IMAGE_WIDTH   = 28
NUM_CHANNELS  = 3
BATCH_SIZE    = 5

def encode_label(label):
  return int(label)

def read_label_file(file):
  f = open(file, "r")
  filepaths = []
  labels = []
  for line in f:
    filepath, label = line.split(",")
    filepaths.append(filepath)
    labels.append(encode_label(label))
  return filepaths, labels

# reading labels and file path
train_filepaths, train_labels = read_label_file(dataset_path + train_labels_file)
test_filepaths, test_labels = read_label_file(dataset_path + test_labels_file)

# transform relative path into full path
train_filepaths = [ dataset_path + fp for fp in train_filepaths]
test_filepaths = [ dataset_path + fp for fp in test_filepaths]

# for this example we will create or own test partition
all_filepaths = train_filepaths + test_filepaths
all_labels = train_labels + test_labels

all_filepaths = all_filepaths[:20]
all_labels = all_labels[:20]

# convert string into tensors
all_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)
all_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.int32)

# create a partition vector
partitions = [0] * len(all_filepaths)
partitions[:test_set_size] = [1] * test_set_size
random.shuffle(partitions)

# partition our data into a test and train set according to our partition vector
train_images, test_images = tf.dynamic_partition(all_images, partitions, 2)
train_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)

# create input queues
train_input_queue = tf.train.slice_input_producer(
                                    [train_images, train_labels],
                                    shuffle=False)
test_input_queue = tf.train.slice_input_producer(
                                    [test_images, test_labels],
                                    shuffle=False)

# process path and string tensor into an image and a label
file_content = tf.read_file(train_input_queue[0])
train_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
train_label = train_input_queue[1]

file_content = tf.read_file(test_input_queue[0])
test_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
test_label = test_input_queue[1]

# define tensor shape
train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])
test_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])

# collect batches of images before processing
train_image_batch, train_label_batch = tf.train.batch(
                                    [train_image, train_label],
                                    batch_size=BATCH_SIZE
                                    #,num_threads=1
                                    )
test_image_batch, test_label_batch = tf.train.batch(
                                    [test_image, test_label],
                                    batch_size=BATCH_SIZE
                                    #,num_threads=1
                                    )

print "input pipeline ready"

with tf.Session() as sess:

  # initialize the variables
  sess.run(tf.initialize_all_variables())

  # initialize the queue threads to start to shovel data
  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(coord=coord)

  print "from the train set:"
  for i in range(20):
    print sess.run(train_label_batch)

  print "from the test set:"
  for i in range(10):
    print sess.run(test_label_batch)

  # stop our queue threads and properly close the session
  coord.request_stop()
  coord.join(threads)
  sess.close()
  ```


text:
import Button from './button';
import Card from './card';
import CardMenu from './card/menu';
import CardMedia from './card/media';
import CardTitle from './card/title';
import CardActions from './card/actions';
import CardTitleText from './card/title-text';
import CardSubtitleText from './card/subtitle-text';
import CardSupportingText from './card/supporting-text';

export default {
  Button,
  Card,
  CardTitle,
  CardTitleText,
  CardSubtitleText,
  CardSupportingText,
  CardMedia,
  CardActions,
  CardMenu
};


text:
import type {PointerEvent} from 'react-native/Libraries/Types/CoreEventTypes';
import {StyleSheet, View, Text} from 'react-native';
import * as React from 'react';
import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes';

export default function EventfulView(props: {|
  name: string,
  emitByDefault?: boolean,
  onLeave?: boolean,
  onLeaveCapture?: boolean,
  onEnter?: boolean,
  onEnterCapture?: boolean,
  onDown?: boolean,
  onDownCapture?: boolean,
  onUp?: boolean,
  onOver?: boolean,
  onOverCapture?: boolean,
  onOut?: boolean,
  onOutCapture?: boolean,
  onUpCapture?: boolean,
  onMove?: boolean,
  onMoveCapture?: boolean,
  onCancel?: boolean,
  onCancelCapture?: boolean,
  log: string => void,
  ...ViewProps,
|}): React.Node {
  const ref = React.useRef<?React.ElementRef<typeof View>>();
  React.useEffect(() => {
    // $FlowFixMe[prop-missing] Using private property
    setTag(ref.current?._nativeTag);
  }, [ref]);

  const {
    log,
    name,
    children,
    emitByDefault,
    onLeave,
    onLeaveCapture,
    onEnter,
    onEnterCapture,
    onDown,
    onDownCapture,
    onUp,
    onUpCapture,
    onMove,
    onMoveCapture,
    onOut,
    onOutCapture,
    onOver,
    onOverCapture,
    onCancel,
    onCancelCapture,
    ...restProps
  } = props;
  const [tag, setTag] = React.useState('');

  const eventLog =
    (eventName: string, handler: ?(e: PointerEvent) => void) =>
    (event: PointerEvent) => {
      // $FlowFixMe Using private property
      log(`${name} - ${eventName} - target: ${event.target._nativeTag}`);
      handler?.(event);
    };

  const listeners = {
    onPointerUp: onUp ? eventLog('up') : null,
    onPointerUpCapture: onUpCapture ? eventLog('up capture') : null,
    onPointerDown: onDown ? eventLog('down') : null,
    onPointerDownCapture: onDownCapture ? eventLog('down capture') : null,
    onPointerLeave: onLeave ? eventLog('leave') : null,
    onPointerLeaveCapture: onLeaveCapture ? eventLog('leave capture') : null,
    onPointerEnter: onEnter ? eventLog('enter') : null,
    onPointerEnterCapture: onEnterCapture ? eventLog('enter capture') : null,
    onPointerMove: onMove ? eventLog('move') : null,
    onPointerMoveCapture: onMoveCapture ? eventLog('move capture') : null,
    onPointerOut: onOut ? eventLog('out') : null,
    onPointerOutCapture: onOutCapture ? eventLog('out capture') : null,
    onPointerOver: onOver ? eventLog('over') : null,
    onPointerOverCapture: onOverCapture ? eventLog('over capture') : null,
    onPointerCancel: onCancel ? eventLog('cancel') : null,
    onPointerCancelCapture: onCancelCapture ? eventLog('cancel capture') : null,
  };

  const listeningTo = Object.keys(listeners)
    .filter(listenerName => listeners[listenerName] != null)
    .join(', ');

  return (
    <View ref={ref} {...listeners} {...restProps}>
      <View style={styles.row}>
        <Text>
          {props.name}, {tag}, {listeningTo}
        </Text>
      </View>
      {props.children}
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
});


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using renderdocui.Code;

namespace renderdoc
{
    public struct Vec3f
    {
        public Vec3f(float X, float Y, float Z) { x = X; y = Y; z = Z; }
        public Vec3f(Vec3f v) { x = v.x; y = v.y; z = v.z; }
        public Vec3f(FloatVector v) { x = v.x; y = v.y; z = v.z; }

        public float Length()
        {
            return (float)Math.Sqrt(x * x + y * y + z * z);
        }

        public Vec3f Sub(Vec3f o)
        {
            return new Vec3f(x - o.x,
                                y - o.y,
                                z - o.z);
        }

        public void Mul(float f)
        {
            x *= f;
            y *= f;
            z *= f;
        }

        public float x, y, z;
    };

    public struct Vec4f
    {
        public float x, y, z, w;
    };

    [StructLayout(LayoutKind.Sequential)]
    public struct FloatVector
    {
        public FloatVector(float X, float Y, float Z, float W) { x = X; y = Y; z = Z; w = W; }
        public FloatVector(float X, float Y, float Z) { x = X; y = Y; z = Z; w = 1; }
        public FloatVector(Vec3f v) { x = v.x; y = v.y; z = v.z; w = 1; }
        public FloatVector(Vec3f v, float W) { x = v.x; y = v.y; z = v.z; w = W; }

        public float x, y, z, w;
    };

    [StructLayout(LayoutKind.Sequential)]
    public struct DirectoryFile : IComparable<DirectoryFile>
    {
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string filename;
        public DirectoryFileProperty flags;
        public UInt32 lastmod;
        public UInt64 size;

        public override string ToString()
        {
            return String.Format("{0} ({1})", filename, flags);
        }

        public int CompareTo(DirectoryFile o)
        {
            // sort directories first
            bool thisdir = flags.HasFlag(DirectoryFileProperty.Directory);
            bool odir = o.flags.HasFlag(DirectoryFileProperty.Directory);

            if (thisdir && !odir)
                return -1;
            if (!thisdir && odir)
                return 1;

            // can't have duplicates with same filename, so just compare filenames
            return filename.CompareTo(o.filename);
        }
    };

    [StructLayout(LayoutKind.Sequential)]
    public class ResourceFormat
    {
        [DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
        private static extern float Maths_HalfToFloat(UInt16 half);

        public ResourceFormat()
        {
            special = false;
            specialFormat = SpecialFormat.Unknown;

            compType = FormatComponentType.None;
            compCount = 0;
            compByteWidth = 0;
            bgraOrder = false;
            srgbCorrected = false;

            strname = "";
        }

        public ResourceFormat(FormatComponentType type, UInt32 count, UInt32 byteWidth)
        {
            special = false;
            specialFormat = SpecialFormat.Unknown;

            compType = type;
            compCount = count;
            compByteWidth = byteWidth;
            bgraOrder = false;
            srgbCorrected = false;

            strname = "";
        }

        // indicates it's not a type represented with the members below
        // usually this means non-uniform across components or block compressed
        public bool special;
        public SpecialFormat specialFormat;

        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string strname;

        public UInt32 compCount;
        public UInt32 compByteWidth;
        public FormatComponentType compType;

        public bool bgraOrder;
        public bool srgbCorrected;

        public override string ToString()
        {
            return strname;
        }

        public override bool Equals(Object obj)
        {
            return obj is ResourceFormat && this == (ResourceFormat)obj;
        }
        public override int GetHashCode()
        {
            int hash = specialFormat.GetHashCode() * 17;
            hash = hash * 17 + compCount.GetHashCode();
            hash = hash * 17 + compByteWidth.GetHashCode();
            hash = hash * 17 + compType.GetHashCode();
            hash = hash * 17 + bgraOrder.GetHashCode();
            hash = hash * 17 + srgbCorrected.GetHashCode();
            return hash;
        }
        public static bool operator ==(ResourceFormat x, ResourceFormat y)
        {
            if ((object)x == null) return (object)y == null;
            if ((object)y == null) return (object)x == null;

            if (x.special || y.special)
                return x.special == y.special && x.specialFormat == y.specialFormat && x.compType == y.compType;

            return x.compCount == y.compCount &&
                x.compByteWidth == y.compByteWidth &&
                x.compType == y.compType &&
                x.bgraOrder == y.bgraOrder &&
                x.srgbCorrected == y.srgbCorrected;
        }
        public static bool operator !=(ResourceFormat x, ResourceFormat y)
        {
            return !(x == y);
        }

        public float ConvertFromHalf(UInt16 comp)
        {
            return Maths_HalfToFloat(comp);
        }

        public object Interpret(UInt16 comp)
        {
            if (compByteWidth != 2 || compType == FormatComponentType.Float) throw new ArgumentException();

            if (compType == FormatComponentType.SInt)
            {
                return (Int16)comp;
            }
            else if (compType == FormatComponentType.UInt)
            {
                return comp;
            }
            else if (compType == FormatComponentType.SScaled)
            {
                return (float)((Int16)comp);
            }
            else if (compType == FormatComponentType.UScaled)
            {
                return (float)comp;
            }
            else if (compType == FormatComponentType.UNorm)
            {
                return (float)comp / (float)UInt16.MaxValue;
            }
            else if (compType == FormatComponentType.SNorm)
            {
                Int16 cast = (Int16)comp;

                float f = -1.0f;

                if (cast == -32768)
                    f = -1.0f;
                else
                    f = ((float)cast) / 32767.0f;

                return f;
            }

            throw new ArgumentException();
        }

        public object Interpret(byte comp)
        {
            if (compByteWidth != 1 || compType == FormatComponentType.Float) throw new ArgumentException();

            if (compType == FormatComponentType.SInt)
            {
                return (sbyte)comp;
            }
            else if (compType == FormatComponentType.UInt)
            {
                return comp;
            }
            else if (compType == FormatComponentType.SScaled)
            {
                return (float)((sbyte)comp);
            }
            else if (compType == FormatComponentType.UScaled)
            {
                return (float)comp;
            }
            else if (compType == FormatComponentType.UNorm)
            {
                return ((float)comp) / 255.0f;
            }
            else if (compType == FormatComponentType.SNorm)
            {
                sbyte cast = (sbyte)comp;

                float f = -1.0f;

                if (cast == -128)
                    f = -1.0f;
                else
                    f = ((float)cast) / 127.0f;

                return f;
            }

            throw new ArgumentException();
        }
    };

    [StructLayout(LayoutKind.Sequential)]
    public class TextureFilter
    {
        public FilterMode minify;
        public FilterMode magnify;
        public FilterMode mip;
        public FilterFunc func;

        public override string ToString()
        {
            string[] filters = { minify.ToString(), magnify.ToString(), mip.ToString() };
            string[] filterPrefixes = { "Min", "Mag", "Mip" };

            string filter = "", filtPrefix = "", filtVal = "";

            for (int a = 0; a < 3; a++)
            {
                if (a == 0 || filters[a] == filters[a - 1])
                {
                    if (filtPrefix != "")
                        filtPrefix += "/";
                    filtPrefix += filterPrefixes[a];
                }
                else
                {
                    filter += filtPrefix + ": " + filtVal + ", ";

                    filtPrefix = filterPrefixes[a];
                }
                filtVal = filters[a];
            }

            filter += filtPrefix + ": " + filtVal;

            return filter;
        }
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchBuffer
    {
        public ResourceId ID;
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string name;
        public bool customName;
        public BufferCreationFlags creationFlags;
        public UInt64 length;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchTexture
    {
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string name;
        public bool customName;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public ResourceFormat format;
        public UInt32 dimension;
        public ShaderResourceType resType;
        public UInt32 width, height, depth;
        public ResourceId ID;
        public bool cubemap;
        public UInt32 mips;
        public UInt32 arraysize;
        public TextureCreationFlags creationFlags;
        public UInt32 msQual, msSamp;
        public UInt64 byteSize;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameConstantBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] bindslots;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] sizes;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameSamplerBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] bindslots;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameResourceBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] types;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] bindslots;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameUpdateStats
    {
        public UInt32 calls;
        public UInt32 clients;
        public UInt32 servers;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] types;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] sizes;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameDrawStats
    {
        public UInt32 calls;
        public UInt32 instanced;
        public UInt32 indirect;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] counts;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameDispatchStats
    {
        public UInt32 calls;
        public UInt32 indirect;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameIndexBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameVertexBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] bindslots;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameLayoutBindStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameShaderStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        public UInt32 redundants;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameBlendStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        public UInt32 redundants;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameDepthStencilStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        public UInt32 redundants;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameRasterizationStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        public UInt32 redundants;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] viewports;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] rects;
    }

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameOutputStats
    {
        public UInt32 calls;
        public UInt32 sets;
        public UInt32 nulls;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt32[] bindslots;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchFrameStatistics
    {
        public UInt32 recorded;
        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = (int)ShaderStageType.Count)]
        public FetchFrameConstantBindStats[] constants;
        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = (int)ShaderStageType.Count)]
        public FetchFrameSamplerBindStats[] samplers;
        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = (int)ShaderStageType.Count)]
        public FetchFrameResourceBindStats[] resources;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameUpdateStats updates;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameDrawStats draws;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameDispatchStats dispatches;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameIndexBindStats indices;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameVertexBindStats vertices;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameLayoutBindStats layouts;
        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = (int)ShaderStageType.Count)]
        public FetchFrameShaderStats[] shaders;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameBlendStats blends;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameDepthStencilStats depths;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameRasterizationStats rasters;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameOutputStats outputs;
    };

[StructLayout(LayoutKind.Sequential)]
    public class FetchFrameInfo
    {
        public UInt32 frameNumber;
        public UInt64 fileOffset;
        public UInt64 uncompressedFileSize;
        public UInt64 compressedFileSize;
        public UInt64 persistentSize;
        public UInt64 initDataSize;
        public UInt64 captureTime;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public FetchFrameStatistics stats;

        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public DebugMessage[] debugMessages;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchAPIEvent
    {
        public UInt32 eventID;

        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public UInt64[] callstack;

        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string eventDesc;

        public UInt64 fileOffset;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class DebugMessage
    {
        public UInt32 eventID;
        public DebugMessageCategory category;
        public DebugMessageSeverity severity;
        public DebugMessageSource source;
        public UInt32 messageID;
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string description;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class EventUsage
    {
        public UInt32 eventID;
        public ResourceUsage usage;
        public ResourceId view;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class FetchDrawcall
    {
        public UInt32 eventID, drawcallID;

        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string name;

        public DrawcallFlags flags;

        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 4)]
        public float[] markerColour;

        public System.Drawing.Color GetColor()
        {
            float red = markerColour[0];
            float green = markerColour[1];
            float blue = markerColour[2];
            float alpha = markerColour[3];

            return System.Drawing.Color.FromArgb(
                (int)(alpha * 255.0f),
                (int)(red * 255.0f),
                (int)(green * 255.0f),
                (int)(blue * 255.0f)
                );
        }

        public System.Drawing.Color GetTextColor(System.Drawing.Color defaultTextCol)
        {
            float backLum = GetColor().GetLuminance();
            float textLum = defaultTextCol.GetLuminance();

            bool backDark = backLum < 0.2f;
            bool textDark = textLum < 0.2f;

            // if they're contrasting, use the text colour desired
            if (backDark != textDark)
                return defaultTextCol;

            // otherwise pick a contrasting colour
            if (backDark)
                return System.Drawing.Color.White;
            else
                return System.Drawing.Color.Black;
        }

        public UInt32 numIndices;
        public UInt32 numInstances;
        public Int32 baseVertex;
        public UInt32 indexOffset;
        public UInt32 vertexOffset;
        public UInt32 instanceOffset;

        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 3)]
        public UInt32[] dispatchDimension;
        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 3)]
        public UInt32[] dispatchThreadsDimension;

        public UInt32 indexByteWidth;
        public PrimitiveTopology topology;

        public ResourceId copySource;
        public ResourceId copyDestination;

        public Int64 parentDrawcall;
        public Int64 previousDrawcall;
        public Int64 nextDrawcall;

        [CustomMarshalAs(CustomUnmanagedType.Skip)]
        public FetchDrawcall parent;
        [CustomMarshalAs(CustomUnmanagedType.Skip)]
        public FetchDrawcall previous;
        [CustomMarshalAs(CustomUnmanagedType.Skip)]
        public FetchDrawcall next;

        [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 8)]
        public ResourceId[] outputs;
        public ResourceId depthOut;

        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public FetchAPIEvent[] events;
        [CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
        public FetchDrawcall[] children;
    };

    [StructLayout(LayoutKind.Sequential)]
    public struct MeshFormat
    {
        public ResourceId idxbuf;
        public UInt64 idxoffs;
        public UInt32 idxByteWidth;
        public Int32 baseVertex;

        public ResourceId buf;
        public UInt64 offset;
        public UInt32 stride;

        public UInt32 compCount;
        public UInt32 compByteWidth;
        public FormatComponentType compType;
        public bool bgraOrder;
        public SpecialFormat specialFormat;

        public FloatVector meshColour;

        public bool showAlpha;

        public PrimitiveTopology topo;
        public UInt32 numVerts;

        public bool unproject;
        public float nearPlane;
        public float farPlane;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class MeshDisplay
    {
        public MeshDataStage type = MeshDataStage.Unknown;

        public IntPtr cam = IntPtr.Zero;

        public bool ortho = false;
        public float fov = 90.0f;
        public float aspect = 0.0f;

        public bool showPrevInstances = false;
        public bool showAllInstances = false;
        public bool showWholePass = false;
        public UInt32 curInstance = 0;

        public UInt32 highlightVert;
        public MeshFormat position;
        public MeshFormat secondary;

        public FloatVector minBounds = new FloatVector();
        public FloatVector maxBounds = new FloatVector();
        public bool showBBox = false;

        public SolidShadeMode solidShadeMode = SolidShadeMode.None;
        public bool wireframeDraw = true;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class TextureDisplay
    {
        public ResourceId texid = ResourceId.Null;
        public FormatComponentType typeHint = FormatComponentType.None;
        public float rangemin = 0.0f;
        public float rangemax = 1.0f;
        public float scale = 1.0f;
        public bool Red = true, Green = true, Blue = true, Alpha = false;
        public bool FlipY = false;
        public float HDRMul = -1.0f;
        public bool linearDisplayAsGamma = true;
        public ResourceId CustomShader = ResourceId.Null;
        public UInt32 mip = 0;
        public UInt32 sliceFace = 0;
        public UInt32 sampleIdx = 0;
        public bool rawoutput = false;

        public float offx = 0.0f, offy = 0.0f;

        public FloatVector lightBackgroundColour = new FloatVector(0.81f, 0.81f, 0.81f);
        public FloatVector darkBackgroundColour = new FloatVector(0.57f, 0.57f, 0.57f);

        public TextureDisplayOverlay overlay = TextureDisplayOverlay.None;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class TextureSave
    {
        public ResourceId id = ResourceId.Null;

        public FormatComponentType typeHint = FormatComponentType.None;

        public FileType destType = FileType.DDS;

        public Int32 mip = -1;

        [StructLayout(LayoutKind.Sequential)]
        public class ComponentMapping
        {
            public float blackPoint;
            public float whitePoint;
        };

        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public ComponentMapping comp = new ComponentMapping();

        [StructLayout(LayoutKind.Sequential)]
        public class SampleMapping
        {
            public bool mapToArray;

            public UInt32 sampleIndex;
        };
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public SampleMapping sample = new SampleMapping();

        [StructLayout(LayoutKind.Sequential)]
        public class SliceMapping
        {
            public Int32 sliceIndex;

            public bool slicesAsGrid;

            public Int32 sliceGridWidth;

            public bool cubeCruciform;
        };
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public SliceMapping slice = new SliceMapping();

        public int channelExtract = -1;

        public AlphaMapping alpha = AlphaMapping.Discard;
        public FloatVector alphaCol = new FloatVector(0.81f, 0.81f, 0.81f);
        public FloatVector alphaColSecondary = new FloatVector(0.57f, 0.57f, 0.57f);

        public int jpegQuality = 90;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class APIProperties
    {
        public GraphicsAPI pipelineType;
        public GraphicsAPI localRenderer;
        public bool degraded;

        public string ShaderExtension
        {
            get
            {
                return pipelineType.IsD3D() ? ".hlsl" : ".glsl";
            }
        }
    };

    [StructLayout(LayoutKind.Sequential)]
    public class CounterDescription
    {
        public UInt32 counterID;
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string name;
        [CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
        public string description;
        public FormatComponentType resultCompType;
        public UInt32 resultByteWidth;
        public CounterUnits units;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class CounterResult
    {
        public UInt32 eventID;
        public UInt32 counterID;

        [StructLayout(LayoutKind.Sequential)]
        public struct ValueUnion
        {
            public float f;
            public double d;
            public UInt32 u32;
            public UInt64 u64;
        };

        [CustomMarshalAs(CustomUnmanagedType.Union)]
        public ValueUnion value;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class PixelValue
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct ValueUnion
        {
            [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 4, FixedType = CustomFixedType.UInt32)]
            public UInt32[] u;

            [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 4, FixedType = CustomFixedType.Float)]
            public float[] f;

            [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 4, FixedType = CustomFixedType.Int32)]
            public Int32[] i;

            [CustomMarshalAs(CustomUnmanagedType.FixedArray, FixedLength = 4, FixedType = CustomFixedType.UInt16)]
            public UInt16[] u16;
        };

        [CustomMarshalAs(CustomUnmanagedType.Union)]
        public ValueUnion value;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class ModificationValue
    {
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public PixelValue col;
        public float depth;
        public Int32 stencil;
    };

    [StructLayout(LayoutKind.Sequential)]
    public class PixelModification
    {
        public UInt32 eventID;

        public bool uavWrite;
        public bool unboundPS;

        public UInt32 fragIndex;
        public UInt32 primitiveID;

        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public ModificationValue preMod;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public ModificationValue shaderOut;
        [CustomMarshalAs(CustomUnmanagedType.CustomClass)]
        public ModificationValue postMod;

        public bool sampleMasked;
        public bool backfaceCulled;
        public bool depthClipped;
        public bool viewClipped;
        public bool scissorClipped;
        public bool shaderDiscarded;
        public bool depthTestFailed;
        public bool stencilTestFailed;

        public bool EventPassed()
        {
            return !sampleMasked && !backfaceCulled && !depthClipped &&
                !viewClipped && !scissorClipped && !shaderDiscarded &&
                !depthTestFailed && !stencilTestFailed;
        }
    };
}


text:
package org.tourgune.pandora.sdk.utils;

public class Log {

    public static boolean LOG = true;

    public static void i(String tag, String string) {
        if (LOG) android.util.Log.i(tag, string);
    }
    public static void e(String tag, String string) {
        if (LOG) android.util.Log.e(tag, string);
    }
    public static void d(String tag, String string) {
        if (LOG) android.util.Log.d(tag, string);
    }
    public static void v(String tag, String string) {
        if (LOG) android.util.Log.v(tag, string);
    }
    public static void w(String tag, String string) {
        if (LOG) android.util.Log.w(tag, string);
    }
}