text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Numbers</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. The Variadic Macro Data Library 1.9">
<link rel="up" href="../vmd_specific.html" title="Specific macros for working with data types">
<link rel="prev" href="vmd_identifier.html" title="Identifiers">
<link rel="next" href="vmd_type.html" title="Types">

Home
Libraries
People
FAQ
More

Numbers

        A number in VMD is a preprocessing 'pp-number', limited to a Boost PP number.
        This is an integral literal between 0 and 256. The form of the number does
        not contain leading zeros. Acceptable as numbers are:

0
127
33
254
18

        but not:

033
06
009
00

        Problem
        testing any number

        As can be seen from the explanation of an identifier, a number is merely
        a small subset of all possible identifiers, for which VMD internally provides
        registration macros for its use and pre-detection macros for its use. Therefore
        the particular constraint on the input to test is exactly the same as for
        identifiers.

        The constraint is that the beginning input character, ignoring any whitespace,
        passed as the input to test must be either:

            an identifier character, ie. an alphanumeric or an underscore

            the left parenthesis of a tuple

        and if the first character is not the left parenthesis of a tuple the remaining
        characters must be alphanumeric or an underscore until a space character
        or end of input occurs.

        If this is not the case the behavior is undefined, and most likely a preprocessing
        error will occur.

        Testing
        for a number macro

        The macro used to test for any number in VMD is called BOOST_VMD_IS_NUMBER.
        The macro takes a single parameter, the input to test against.

        The macro returns 1 if the parameter is a Boost PP number, otherwise the
        macro returns 0.

        The Boost PP library has a great amount of functionality for working with
        numbers, so once you use VMD to parse/test for a number you can use Boost
        PP to work with that number in various ways. The VMD makes no attempt to
        duplicate the functionality of numbers that in the Boost PP library.

        Any number is also an identifier, which has been registered and pre-detected,
        so you can also use the VMD functionality which works with identifiers to
        work with a number as an identifier if you like.

        Example

        Let us look at an example of how to use BOOST_VMD_IS_NUMBER.

#include <boost/vmd/is_number.hpp>

BOOST_VMD_IS_NUMBER(input)

returns:

if input = 0, 1
if input = 44, 1
if input = SQUARE, 0
if input = 44 DATA, 0 since there are tokens after the number
if input = 044, 0 since no leading zeros are allowed for our Boost PP numbers
if input = 256, 1
if input = 257, 0 since it falls outside the Boost PP number range of 0-256
if input = %44, does not meet the constraint therefore undefined behavior
if input = 44.0, does not meet the constraint therefore undefined behavior
if input = ( 44 ), 0 since the macro begins with a tuple and this can be tested for

        Usage

        To use the BOOST_VMD_IS_NUMBER macro either include the general header:

#include <boost/vmd/vmd.hpp>

        or include the specific header:

#include <boost/vmd/is_number.hpp>

Copyright © 2010-2015 Tropic Software East Inc


text:
class ScriptParams(object):

	mParams = {}

	def __init__(self, argumentString):
		if len( argumentString )>=2:
			cleanedparams = argumentString.replace('?','')
			if ( argumentString[ len( argumentString ) - 1 ] == '/' ):
				argumentString = argumentString[ 0 : len( argumentString ) - 2 ]
			pairsofparams = cleanedparams.split( '&' )
			for i in range( len( pairsofparams ) ):
				splitparams = {}
				splitparams = pairsofparams[ i ].split( '=' )
				if ( len( splitparams ) ) == 2:
					self.mParams[ splitparams[ 0 ] ] = splitparams[ 1 ]

	def GetParamDefault( self, keyName, defValue ):
		try:
			return self.mParams[ keyName ]
		except:
			return defValue

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.json.bvt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.junit.Assert;
import junit.framework.TestCase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class JSONFromObjectTest extends TestCase {

    public void test_0() throws Exception {
        User user = new User();
        user.setId(3);
        user.setName("周访");

        JSONObject json = (JSONObject) JSON.toJSON(user);

        Assert.assertEquals(new Long(3), json.getLong("id"));
        Assert.assertEquals("周访", json.getString("name"));
    }

    public void test_1() throws Exception {
        JSONObject user = new JSONObject();
        user.put("id", 3);
        user.put("name", "周访");

        JSONObject json = (JSONObject) JSON.toJSON(user);

        Assert.assertEquals(new Long(3), json.getLong("id"));
        Assert.assertEquals("周访", json.getString("name"));
    }

    public void test_2() throws Exception {
        HashMap user = new HashMap();
        user.put("id", 3);
        user.put("name", "周访");

        JSONObject json = (JSONObject) JSON.toJSON(user);

        Assert.assertEquals(new Long(3), json.getLong("id"));
        Assert.assertEquals("周访", json.getString("name"));
    }

    public void test_3() throws Exception {
        List users = new ArrayList();
        HashMap user = new HashMap();
        user.put("id", 3);
        user.put("name", "周访");
        users.add(user);

        JSONArray array = (JSONArray) JSON.toJSON(users);
        JSONObject json = array.getJSONObject(0);

        Assert.assertEquals(new Long(3), json.getLong("id"));
        Assert.assertEquals("周访", json.getString("name"));
    }

    public void test_error() throws Exception {
        C c = new C();

        JSONException error = null;
        try {
            JSON.toJSON(c);
        } catch (JSONException e) {
            error = e;
        }
        Assert.assertNotNull(error);
    }

    public static class User {

        private long   id;
        private String name;

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

    public static class C {

        public int getId() {
            throw new UnsupportedOperationException();
        }

        public void setId(int id) {
            throw new UnsupportedOperationException();
        }
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <stdio_file.h>

/*
 * XXX (C99): An output stream is not currently flushed when input is
 * read from an input stream attached to a terminal. This is because
 * we can't currently know what's a terminal and what isn't.
 */

int
fputc(int c, FILE *stream)
{
    lock_stream(stream);

    if(stream->buffer == NULL) {
        stream->buffer = malloc(stream->buf_size);
	if (stream->buffer == NULL)
	    return EOF;
        stream->buf_pos = 0;
        stream->buf_allocated = 1;
    }

    stream->buffer[stream->buf_pos++] = c;

    if(stream->buffering_mode == _IONBF
       || stream->buf_pos == stream->buf_size
       || (stream->buffering_mode == _IOLBF && (c == '\n' || c == '\r'))) {
        unlock_stream(stream);
        if(fflush(stream) != 0) {
            return EOF;
        }
    } else {
        unlock_stream(stream);
    }

    return c;
}


text:
require_relative "../../cheffish"
require_relative "../../cheffish/chef_actor_base"

class Chef
  class Resource
    class ChefClient < Cheffish::ChefActorBase
      provides :chef_client

      # Client attributes
      property :chef_client_name, Cheffish::NAME_REGEX, name_property: true
      property :admin, [TrueClass, FalseClass]
      property :validator, [TrueClass, FalseClass]

      # Input key
      property :source_key # String or OpenSSL::PKey::*
      property :source_key_path, String
      property :source_key_pass_phrase

      # Output public key (if so desired)
      property :output_key_path, String
      property :output_key_format, Symbol, default: :openssh, equal_to: %i{pem der openssh}

      # Proc that runs just before the resource executes.  Called with (resource)
      def before(&block)
        block ? @before = block : @before
      end

      # Proc that runs after the resource completes.  Called with (resource, json, private_key, public_key)
      def after(&block)
        block ? @after = block : @after
      end

      action :create do
        create_actor
      end

      action :delete do
        delete_actor
      end

      action_class do
        def actor_type
          "client"
        end

        def actor_path
          "clients"
        end

        #
        # Helpers
        #

        def resource_class
          Chef::Resource::ChefClient
        end

        def data_handler
          Chef::ChefFS::DataHandler::ClientDataHandler.new
        end

        def keys
          {
            "name" => :chef_client_name,
            "admin" => :admin,
            "validator" => :validator,
            "public_key" => :source_key,
          }
        end
      end
    end
  end
end


text:
package quasar

// Config for a quasar node.
type Config struct {
	DefaultEventTTL  uint32  // decremented every hop
	FilterFreshness  uint64  // in ms (older filters ignored)
	PropagationDelay uint64  // in ms (when filters sent to peers)
	HistoryLimit     uint32  // nr of event entries probably remembered
	HistoryAccuracy  float64 // false positive chance between 0.0 and 1.0
	FiltersDepth     uint32  // attenuated bloom filter depth
	FiltersM         uint64  // bloom filter m bits (multiple of 64)
	FiltersK         uint64  // bloom filter k hashes
}

// StandardConfig uses well agreed upon values, only deviate for testing.
var StandardConfig = Config{
	DefaultEventTTL:  64,              // ~8 missed wells
	FilterFreshness:  50000,           // 50sec (>2.5 propagations)
	PropagationDelay: 20000,           // 20sec (~0.5M/min const traffic)
	HistoryLimit:     1048576,         // remember last 1G events
	HistoryAccuracy:  1.0 / 1048576.0, // avg 1 false positive per 1G
	FiltersDepth:     8,               // covers many many nodes ...
	FiltersM:         10240,           // keep packet under safe MTU 1400
	FiltersK:         7,               // = (m / n) log(2) with n=1024
}


text:
#include <sys/types.h>
#ifdef __MINGW32__
	#include <windows.h>
#else
	#include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define FLV_UI32(x) (int)(((x[0]) << 24) + ((x[1]) << 16) + ((x[2]) << 8) + (x[3]))
#define FLV_UI24(x) (int)(((x[0]) << 16) + ((x[1]) << 8) + (x[2]))
#define FLV_UI16(x) (int)(((x[0]) << 8) + (x[1]))
#define FLV_UI8(x) (int)((x))

#define FLV_AUDIODATA	8
#define FLV_VIDEODATA	9
#define FLV_SCRIPTDATAOBJECT	18

#define FLV_H263VIDEOPACKET	2
#define FLV_SCREENVIDEOPACKET	3
#define	FLV_VP6VIDEOPACKET	4
#define	FLV_VP6ALPHAVIDEOPACKET	5
#define FLV_SCREENV2VIDEOPACKET	6

#define YAMDI_VERSION	"1.4"

#ifndef MAP_NOCORE
	#define MAP_NOCORE	0
#endif

typedef struct {
	int hasKeyframes;
	int hasVideo;
	int hasAudio;
	int hasMetadata;
	int hasCuePoints;
	int canSeekToEnd;

	double audiocodecid;
	double audiosamplerate;
	double audiodatarate;
	double audiosamplesize;
	double audiodelay;
	int stereo;

	double videocodecid;
	double framerate;
	double videodatarate;
	double height;
	double width;

	double datasize;
	double audiosize;
	double videosize;
	double filesize;

	double lasttimestamp;
	double lastvideoframetimestamp;
	double lastkeyframetimestamp;
	double lastkeyframelocation;

	int keyframes;
	double *filepositions;
	double *times;
	double duration;

	char metadatacreator[256];
	char creator[256];

	int onmetadatalength;
	int metadatasize;
	size_t onlastsecondlength;
	size_t lastsecondsize;
	int hasLastSecond;
	int lastsecondTagCount;
	size_t onlastkeyframelength;
	size_t lastkeyframesize;
	int hasLastKeyframe;
} FLVMetaData_t;

FLVMetaData_t flvmetadata;

typedef struct {
	unsigned char signature[3];
	unsigned char version;
	unsigned char flags;
	unsigned char headersize[4];
} FLVFileHeader_t;

typedef struct {
	unsigned char type;
	unsigned char datasize[3];
	unsigned char timestamp[3];
	unsigned char timestamp_ex;
	unsigned char streamid[3];
} FLVTag_t;

typedef struct {
	unsigned char flags;
} FLVAudioData_t;

typedef struct {
	unsigned char flags;
} FLVVideoData_t;

void initFLVMetaData(const char *creator, int lastsecond, int lastkeyframe);
size_t writeFLVMetaData(FILE *fp);
size_t writeFLVLastSecond(FILE *fp, double timestamp);
size_t writeFLVLastKeyframe(FILE *fp);

void readFLVFirstPass(char *flv, size_t streampos, size_t filesize);
void readFLVSecondPass(char *flv, size_t streampos, size_t filesize);
void readFLVH263VideoPacket(const unsigned char *h263);
void readFLVScreenVideoPacket(const unsigned char *sv);
void readFLVVP62VideoPacket(const unsigned char *vp62);
void readFLVVP62AlphaVideoPacket(const unsigned char *vp62a);

size_t writeFLVScriptDataValueArray(FILE *fp, const char *name, size_t len);
size_t writeFLVScriptDataECMAArray(FILE *fp, const char *name, size_t len);
size_t writeFLVScriptDataVariableArray(FILE *fp, const char *name);
size_t writeFLVScriptDataVariableArrayEnd(FILE *fp);
size_t writeFLVScriptDataValueString(FILE *fp, const char *name, const char *value);
size_t writeFLVScriptDataValueBool(FILE *fp, const char *name, int value);
size_t writeFLVScriptDataValueDouble(FILE *fp, const char *name, double value);
size_t writeFLVScriptDataObject(FILE *fp);

size_t writeFLVPreviousTagSize(FILE *fp, size_t datasize);

size_t writeFLVScriptDataString(FILE *fp, const char *s);
size_t writeFLVScriptDataLongString(FILE *fp, const char *s);
size_t writeFLVBool(FILE *fp, int value);
size_t writeFLVDouble(FILE *fp, double v);

void writeFLV(FILE *fp, char *flv, size_t streampos, size_t filesize);
void writeXMLMetadata(FILE *fp, const char *infile, const char *outfile);
void writeFLVHeader(FILE *fp);

void print_usage(void);

int main(int argc, char *argv[]) {
	FILE *fp_infile = NULL, *fp_outfile = NULL, *fp_xmloutfile = NULL, *devnull;
#ifdef __MINGW32__
	HANDLE fh_infile = NULL;
#endif
	int c, lastsecond = 0, lastkeyframe = 0;
	char *flv, *infile, *outfile, *xmloutfile, *creator;
	unsigned int i;
	size_t filesize = 0, streampos, metadatasize;
	struct stat sb;
	FLVFileHeader_t *flvfileheader;

	opterr = 0;

	infile = NULL;
	outfile = NULL;
	xmloutfile = NULL;
	creator = NULL;

	while((c = getopt(argc, argv, "i:o:x:c:lkh")) != -1) {
		switch(c) {
			case 'i':
				if(infile == NULL) {
					infile = optarg;

					if(outfile != NULL) {
						if(!strcmp(infile, outfile)) {
							fprintf(stderr, "Input file and output file must not be the same.\n");
							exit(1);
						}
					}

					if(stat(infile, &sb) == -1) {
						fprintf(stderr, "Couldn't stat on %s.\n", infile);
						exit(1);
					}

					filesize = sb.st_size;

#ifndef __MINGW32__
					fp_infile = fopen(infile, "rb");
#else
					// Open infile with CreateFile() API
					fh_infile = CreateFile(infile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
					// Meaningless type casting here. It is just used to pass the error checking codes.
					fp_infile = (FILE *)fh_infile;
#endif
					if(fp_infile == NULL) {
						fprintf(stderr, "Couldn't open %s.\n", infile);
						exit(1);
					}
				}

				break;
			case 'o':
				if(outfile == NULL) {
					outfile = optarg;

					if(infile != NULL) {
						if(!strcmp(infile, outfile)) {
							fprintf(stderr, "Input file and output file must not be the same.\n");
							exit(1);
						}
					}

					if(strcmp(outfile, "-")) {
						fp_outfile = fopen(outfile, "wb");
						if(fp_outfile == NULL) {
							fprintf(stderr, "Couldn't open %s.\n", outfile);
							exit(1);
						}
					}
					else
						fp_outfile = stdout;
				}
				break;
			case 'x':
				if(xmloutfile == NULL) {
					xmloutfile = optarg;

					fp_xmloutfile = fopen(xmloutfile, "wb");
					if(fp_xmloutfile == NULL) {
						fprintf(stderr, "Couldn't open %s.\n", outfile);
						exit(1);
					}
				}
				break;
			case 'c':
				creator = optarg;
				break;
			case 'l':
				lastsecond = 1;
				break;
			case 'k':
				lastkeyframe = 1;
				break;
			case 'h':
				print_usage();
				exit(1);
				break;
			case ':':
				fprintf(stderr, "The option -%c expects a parameter. -h for help.\n", optopt);
				exit(1);
				break;
			case '?':
				fprintf(stderr, "Unknown option: -%c. -h for help.\n", optopt);
				exit(1);
				break;
			default:
				print_usage();
				exit(1);
				break;
		}
	}

	if(infile == NULL) {
		fprintf(stderr, "Please provide an input file. -h for help.\n");
		exit(1);
	}

	if(outfile == NULL && xmloutfile == NULL) {
		fprintf(stderr, "Please provide at least one output file. -h for help.\n");
		exit(1);
	}

	// mmap von infile erstellen
#ifndef __MINGW32__
	flv = mmap(NULL, filesize, PROT_READ, MAP_NOCORE | MAP_PRIVATE, fileno(fp_infile), 0);
#else
	HANDLE h = NULL;
	h = CreateFileMapping(fh_infile, NULL, PAGE_READONLY | SEC_COMMIT, 0, filesize,  NULL);
	if(h == NULL) {
		fprintf(stderr, "Couldn't create file mapping object %s. Error code: %d\n", infile, (int)GetLastError());
		exit(1);
	}
	flv = MapViewOfFile(h, FILE_MAP_READ, 0, 0, filesize);
#endif
	if(flv == NULL) {
		fprintf(stderr, "Couldn't load %s.\n", infile);
		exit(1);
	}

	if(strncmp(flv, "FLV", 3)) {
		fprintf(stderr, "The input file is not a FLV.\n");
		exit(1);
	}

	// Metadata initialisieren
	initFLVMetaData(creator, lastsecond, lastkeyframe);

	flvfileheader = (FLVFileHeader_t *)flv;

	// Die Position des 1. Tags im FLV bestimmen (Header + PrevTagSize0)
	streampos = FLV_UI32(flvfileheader->headersize) + 4;

	// Das FLV einlesen und Informationen fuer die Metatags extrahieren
	readFLVFirstPass(flv, streampos, filesize);

#ifndef __MINGW32__
	devnull = fopen("/dev/null", "wb");
#else
	devnull = fopen("nul", "wb");
#endif

	if(devnull == NULL) {
		fprintf(stderr, "Couldn't open NULL device.\n");
		exit(1);
	}

	// Die Groessen berechnen
	metadatasize = writeFLVMetaData(devnull);
	flvmetadata.lastsecondsize = writeFLVLastSecond(devnull, 0.0);
	flvmetadata.lastkeyframesize = writeFLVLastKeyframe(devnull);	// Not fully implemented, i.e. has no effect

	fclose(devnull);

	// Falls es Keyframes hat, muss ein 2. Durchgang fuer den Keyframeindex gemacht werden
	if(flvmetadata.hasKeyframes == 1) {
		readFLVSecondPass(flv, streampos, filesize);

		// Die Filepositions korrigieren
		for(i = 0; i < flvmetadata.keyframes; i++)
			flvmetadata.filepositions[i] += (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize);

		flvmetadata.lastkeyframelocation = flvmetadata.filepositions[flvmetadata.keyframes - 1];
	}

	// filesize = FLVFileHeader + PreviousTagSize0 + MetadataSize + DataSize
	flvmetadata.filesize = (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize + flvmetadata.datasize);
	if(flvmetadata.hasLastSecond == 1)
		flvmetadata.filesize += (double)flvmetadata.lastsecondsize;

	if(outfile != NULL)
		writeFLV(fp_outfile, flv, streampos, filesize);

	if(xmloutfile != NULL)
		writeXMLMetadata(fp_xmloutfile, infile, outfile);

	return 0;
}

void writeFLV(FILE *fp, char *flv, size_t streampos, size_t filesize) {
	int tagcount;
	double currenttimestamp;
	size_t datasize;
	FLVTag_t *flvtag;

	writeFLVHeader(fp);
	writeFLVMetaData(fp);

	tagcount = 0;

	for(;;) {
		if(streampos + sizeof(FLVTag_t) > filesize)
			break;

		flvtag = (FLVTag_t *)&flv[streampos];

		// Die Groesse des Tags (Header + Data) + PreviousTagSize
		datasize = sizeof(FLVTag_t) + FLV_UI24(flvtag->datasize) + 4;

		if(streampos + datasize > filesize)
			break;

		if(flvtag->type == FLV_VIDEODATA || flvtag->type == FLV_AUDIODATA) {
			fwrite(&flv[streampos], datasize, 1, fp);

			if(flvtag->type == FLV_VIDEODATA && flvmetadata.hasLastSecond == 1) {
				tagcount++;

				if(tagcount == flvmetadata.lastsecondTagCount) {
					currenttimestamp = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;
					writeFLVLastSecond(fp, currenttimestamp);
				}
			}
		}

		streampos += datasize;
	}

	return;
}

void writeXMLMetadata(FILE *fp, const char *infile, const char *outfile) {
	int i;
	char *hasit;

	fprintf(fp, "<?xml version='1.0' encoding='UTF-8'?>\n");
	fprintf(fp, "<fileset>\n");

	if(outfile != NULL)
		fprintf(fp, "<flv name=\"%s\">\n", outfile);
	else
		fprintf(fp, "<flv name=\"%s\">\n", infile);

	hasit = (flvmetadata.hasKeyframes > 0) ? "true" : "false";
	fprintf(fp, "<hasKeyframes>%s</hasKeyframes>\n", hasit);

	hasit = (flvmetadata.hasVideo > 0) ? "true" : "false";
	fprintf(fp, "<hasVideo>%s</hasVideo>\n", hasit);

	hasit = (flvmetadata.hasAudio > 0) ? "true" : "false";
	fprintf(fp, "<hasAudio>%s</hasAudio>\n", hasit);

	hasit = (flvmetadata.hasMetadata > 0) ? "true" : "false";
	fprintf(fp, "<hasMetadata>%s</hasMetadata>\n", hasit);

	hasit = (flvmetadata.hasCuePoints > 0) ? "true" : "false";
	fprintf(fp, "<hasCuePoints>%s</hasCuePoints>\n", hasit);

	hasit = (flvmetadata.canSeekToEnd > 0) ? "true" : "false";
	fprintf(fp, "<canSeekToEnd>%s</canSeekToEnd>\n", hasit);

	fprintf(fp, "<audiocodecid>%i</audiocodecid>\n", (int)flvmetadata.audiocodecid);
	fprintf(fp, "<audiosamplerate>%i</audiosamplerate>\n", (int)flvmetadata.audiosamplerate);
	fprintf(fp, "<audiodatarate>%i</audiodatarate>\n", (int)flvmetadata.audiodatarate);
	fprintf(fp, "<audiosamplesize>%i</audiosamplesize>\n", (int)flvmetadata.audiosamplesize);
	fprintf(fp, "<audiodelay>%.2f</audiodelay>\n", flvmetadata.audiodelay);
	hasit = (flvmetadata.stereo > 0) ? "true" : "false";
	fprintf(fp, "<stereo>%s</stereo>\n", hasit);

	fprintf(fp, "<videocodecid>%i</videocodecid>\n", (int)flvmetadata.videocodecid);
	fprintf(fp, "<framerate>%.2f</framerate>\n", flvmetadata.framerate);
	fprintf(fp, "<videodatarate>%i</videodatarate>\n", (int)flvmetadata.videodatarate);
	fprintf(fp, "<height>%i</height>\n", (int)flvmetadata.height);
	fprintf(fp, "<width>%i</width>\n", (int)flvmetadata.width);

	fprintf(fp, "<datasize>%i</datasize>\n", (int)flvmetadata.datasize);
	fprintf(fp, "<audiosize>%i</audiosize>\n", (int)flvmetadata.audiosize);
	fprintf(fp, "<videosize>%i</videosize>\n", (int)flvmetadata.videosize);
	fprintf(fp, "<filesize>%i</filesize>\n", (int)flvmetadata.filesize);

	fprintf(fp, "<lasttimestamp>%.2f</lasttimestamp>\n", flvmetadata.lasttimestamp);
	fprintf(fp, "<lastvideoframetimestamp>%.2f</lastvideoframetimestamp>\n", flvmetadata.lastvideoframetimestamp);
	fprintf(fp, "<lastkeyframetimestamp>%.2f</lastkeyframetimestamp>\n", flvmetadata.lastkeyframetimestamp);
	fprintf(fp, "<lastkeyframelocation>%i</lastkeyframelocation>\n", (int)flvmetadata.lastkeyframelocation);

	fprintf(fp, "<keyframes>\n");
	fprintf(fp, "<times>\n");

	for(i = 0; i < flvmetadata.keyframes; ++i)
		fprintf(fp, "<value id=\"%i\">%.2f</value>\n", i, flvmetadata.times[i]);

	fprintf(fp, "</times>\n");
	fprintf(fp, "<filepositions>\n");

	for(i = 0; i < flvmetadata.keyframes; ++i)
		fprintf(fp, "<value id=\"%i\">%i</value>\n", i, (int)flvmetadata.filepositions[i]);

	fprintf(fp, "</filepositions>\n");
	fprintf(fp, "</keyframes>\n");
	fprintf(fp, "<duration>%.2f</duration>\n", flvmetadata.duration);
	fprintf(fp, "</flv>\n");
	fprintf(fp, "</fileset>\n");

	return;
}

void writeFLVHeader(FILE *fp) {
	char *t;
	size_t size;
	FLVFileHeader_t flvheader;

	t = (char *)&flvheader;
	memset(t, 0, sizeof(FLVFileHeader_t));

	flvheader.signature[0] = 'F';
	flvheader.signature[1] = 'L';
	flvheader.signature[2] = 'V';

	flvheader.version = 1;

	if(flvmetadata.hasAudio == 1)
		flvheader.flags |= 0x4;

	if(flvmetadata.hasVideo == 1)
		flvheader.flags |= 0x1;

	size = sizeof(FLVFileHeader_t);
	flvheader.headersize[0] = ((size >> 24) & 0xff);
	flvheader.headersize[1] = ((size >> 16) & 0xff);
	flvheader.headersize[2] = ((size >> 8) & 0xff);
	flvheader.headersize[3] = (size & 0xff);

	fwrite(t, sizeof(FLVFileHeader_t), 1, fp);

	writeFLVPreviousTagSize(fp, 0);

	return;
}

void readFLVSecondPass(char *flv, size_t streampos, size_t filesize) {
	int i, tagcount, afterlastsecond;
	double lastsecond, currenttimestamp;
	size_t datasize, datapos;
	FLVTag_t *flvtag;
	FLVVideoData_t *flvvideo;

	if(flvmetadata.keyframes == 0)
		return;

	i = 0;
	datapos = 0;

	tagcount = 0;
	afterlastsecond = 0;
	lastsecond = flvmetadata.lastvideoframetimestamp - 1.0;

	for(;;) {
		if(streampos + sizeof(FLVTag_t) > filesize)
			break;

		flvtag = (FLVTag_t *)&flv[streampos];

		// TagHeader + TagData + PreviousTagSize
		datasize = sizeof(FLVTag_t) + FLV_UI24(flvtag->datasize) + 4;

		if(streampos + datasize > filesize)
			break;

		if(flvtag->type == FLV_VIDEODATA) {
			flvvideo = (FLVVideoData_t *)&flv[streampos + sizeof(FLVTag_t)];

			// Keyframes
			if(((flvvideo->flags >> 4) & 1) == 1) {
				flvmetadata.filepositions[i] = (double)datapos;
				flvmetadata.times[i] = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;

				i++;
			}
		}

		streampos += datasize;

		if(flvtag->type == FLV_VIDEODATA || flvtag->type == FLV_AUDIODATA) {
			datapos += datasize;

			if(flvtag->type == FLV_VIDEODATA && flvmetadata.hasLastSecond == 1 && afterlastsecond == 0 && lastsecond > 1.0) {
				tagcount++;
				currenttimestamp = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;

				if(currenttimestamp > lastsecond) {
					datapos += flvmetadata.lastsecondsize;
					flvmetadata.lastsecondTagCount = tagcount;
					afterlastsecond = 1;
				}
			}
		}
	}

	return;
}

void readFLVFirstPass(char *flv, size_t streampos, size_t filesize) {
	size_t datasize, videosize = 0, audiosize = 0;
	size_t videotags = 0, audiotags = 0;
	FLVTag_t *flvtag;
	FLVAudioData_t *flvaudio;
	FLVVideoData_t *flvvideo;

	for(;;) {
		if(streampos + sizeof(FLVTag_t) > filesize)
			break;

		flvtag = (FLVTag_t *)&flv[streampos];

		// TagHeader + TagData + PreviousTagSize
		datasize = sizeof(FLVTag_t) + FLV_UI24(flvtag->datasize) + 4;

		if(streampos + datasize > filesize)
			break;

		if(flvtag->type == FLV_AUDIODATA) {
			flvmetadata.datasize += (double)datasize;
			// datasize - PreviousTagSize
			flvmetadata.audiosize += (double)(datasize - 4);

			audiosize += FLV_UI24(flvtag->datasize);
			audiotags++;

			if(flvmetadata.hasAudio == 0) {
				flvaudio = (FLVAudioData_t *)&flv[streampos + sizeof(FLVTag_t)];

				// Sound Codec
				flvmetadata.audiocodecid = (double)((flvaudio->flags >> 4) & 0xf);

				// Sample Rate
				switch(((flvaudio->flags >> 2) & 0x3)) {
					case 0:
						flvmetadata.audiosamplerate = 5500.0;
						break;
					case 1:
						flvmetadata.audiosamplerate = 11000.0;
						break;
					case 2:
						flvmetadata.audiosamplerate = 22000.0;
						break;
					case 3:
						flvmetadata.audiosamplerate = 44100.0;
						break;
					default:
						break;
				}

				// Sample Size
				switch(((flvaudio->flags >> 1) & 0x1)) {
					case 0:
						flvmetadata.audiosamplesize = 8.0;
						break;
					case 1:
						flvmetadata.audiosamplesize = 16.0;
						break;
					default:
						break;
				}

				// Stereo
				flvmetadata.stereo = (flvaudio->flags & 0x1);

				flvmetadata.hasAudio = 1;
			}
		}
		else if(flvtag->type == FLV_VIDEODATA) {
			flvmetadata.datasize += (double)datasize;
			// datasize - PreviousTagSize
			flvmetadata.videosize += (double)(datasize - 4);

			videosize += FLV_UI24(flvtag->datasize);
			videotags++;

			flvvideo = (FLVVideoData_t *)&flv[streampos + sizeof(FLVTag_t)];

			if(flvmetadata.hasVideo == 0) {
				// Video Codec
				flvmetadata.videocodecid = (double)(flvvideo->flags & 0xf);

				flvmetadata.hasVideo = 1;

				switch(flvvideo->flags & 0xf) {
					case FLV_H263VIDEOPACKET:
						readFLVH263VideoPacket((unsigned char *)&flv[streampos + sizeof(FLVTag_t) + sizeof(FLVVideoData_t)]);
						break;
					case FLV_SCREENVIDEOPACKET:
						readFLVScreenVideoPacket((unsigned char *)&flv[streampos + sizeof(FLVTag_t) + sizeof(FLVVideoData_t)]);
						break;
					case FLV_VP6VIDEOPACKET:
						readFLVVP62VideoPacket((unsigned char *)&flv[streampos + sizeof(FLVTag_t) + sizeof(FLVVideoData_t)]);
						break;
					case FLV_VP6ALPHAVIDEOPACKET:
						readFLVVP62AlphaVideoPacket((unsigned char *)&flv[streampos + sizeof(FLVTag_t) + sizeof(FLVVideoData_t)]);
						break;
					case FLV_SCREENV2VIDEOPACKET:
						readFLVScreenVideoPacket((unsigned char *)&flv[streampos + sizeof(FLVTag_t) + sizeof(FLVVideoData_t)]);
						break;
					default:
						break;
				}
			}

			// keyframes
			if(((flvvideo->flags >> 4) & 1) == 1) {
				flvmetadata.canSeekToEnd = 1;
				flvmetadata.keyframes++;
				flvmetadata.lastkeyframetimestamp = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;
			}
			else
				flvmetadata.canSeekToEnd = 0;

			flvmetadata.lastvideoframetimestamp = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;
		}

		flvmetadata.lasttimestamp = (double)((flvtag->timestamp_ex << 24) + (flvtag->timestamp[0] << 16) + (flvtag->timestamp[1] << 8) + flvtag->timestamp[2]) / 1000.0;

		streampos += datasize;
	}

	flvmetadata.duration = flvmetadata.lasttimestamp;

	if(flvmetadata.keyframes != 0)
		flvmetadata.hasKeyframes = 1;

	if(flvmetadata.hasKeyframes == 1) {
		flvmetadata.filepositions = (double *)calloc(flvmetadata.keyframes, sizeof(double));
		flvmetadata.times = (double *)calloc(flvmetadata.keyframes, sizeof(double));

		if(flvmetadata.filepositions == NULL || flvmetadata.times == NULL) {
			fprintf(stderr, "Not enough memory for the keyframe index.\n");
			exit(1);
		}
	}

	// Framerate
	if(videotags != 0)
		flvmetadata.framerate = (double)videotags / flvmetadata.duration;

	// Videodatarate (kb/s)
	if(videosize != 0)
		flvmetadata.videodatarate = (double)(videosize * 8) / 1024.0 / flvmetadata.duration;

	// Audiodatarate (kb/s)
	if(audiosize != 0)
		flvmetadata.audiodatarate = (double)(audiosize * 8) / 1024.0 / flvmetadata.duration;

	return;
}

void readFLVH263VideoPacket(const unsigned char *h263) {
	int startcode, picturesize;

	// 8bit  |pppppppp|pppppppp|pvvvvvrr|rrrrrrss|swwwwwww|whhhhhhh|h
	// 16bit |pppppppp|pppppppp|pvvvvvrr|rrrrrrss|swwwwwww|wwwwwwww|whhhhhhh|hhhhhhhh|h

	startcode = FLV_UI24(h263) >> 7;
	if(startcode != 1)
		return;

	picturesize = ((h263[3] & 0x3) << 1) + ((h263[4] >> 7) & 0x1);

	switch(picturesize) {
		case 0: // Custom 8bit
			flvmetadata.width = (double)(((h263[4] & 0x7f) << 1) + ((h263[5] >> 7) & 0x1));
			flvmetadata.height = (double)(((h263[5] & 0x7f) << 1) + ((h263[6] >> 7) & 0x1));
			break;
		case 1: // Custom 16bit
			flvmetadata.width = (double)(((h263[4] & 0x7f) << 9) + (h263[5] << 1) + ((h263[6] >> 7) & 0x1));
			flvmetadata.height = (double)(((h263[6] & 0x7f) << 9) + (h263[7] << 1) + ((h263[8] >> 7) & 0x1));
			break;
		case 2: // CIF
			flvmetadata.width = 352.0;
			flvmetadata.height = 288.0;
			break;
		case 3: // QCIF
			flvmetadata.width = 176.0;
			flvmetadata.height = 144.0;
			break;
		case 4: // SQCIF
			flvmetadata.width = 128.0;
			flvmetadata.height = 96.0;
			break;
		case 5:
			flvmetadata.width = 320.0;
			flvmetadata.height = 240.0;
			break;
		case 6:
			flvmetadata.width = 160.0;
			flvmetadata.height = 120.0;
			break;
		default:
			break;
	}

	return;
}

void readFLVScreenVideoPacket(const unsigned char *sv) {
	// |1111wwww|wwwwwwww|2222hhhh|hhhhhhhh|

	flvmetadata.width = (double)(((sv[0] & 0xf) << 8) + sv[1]);
	flvmetadata.height = (double)(((sv[2] & 0xf) << 8) + sv[3]);

	return;
}

void readFLVVP62VideoPacket(const unsigned char *vp62) {
	flvmetadata.width = (double)(vp62[4] * 16 - (vp62[0] >> 4));
	flvmetadata.height = (double)(vp62[3] * 16 - (vp62[0] & 0x0f));

	return;
}

void readFLVVP62AlphaVideoPacket(const unsigned char *vp62a) {
	flvmetadata.width = (double)(vp62a[7] * 16 - (vp62a[0] >> 4));
	flvmetadata.height = (double)(vp62a[6] * 16 - (vp62a[0] & 0x0f));

	return;
}

void initFLVMetaData(const char *creator, int lastsecond, int lastkeyframe) {
	char *t;

	t = (char *)&flvmetadata;
	memset(t, 0, sizeof(FLVMetaData_t));

	flvmetadata.hasMetadata = 1;
	flvmetadata.hasLastSecond = lastsecond;
	flvmetadata.hasLastKeyframe = lastkeyframe;

	if(creator != NULL)
		strncpy(flvmetadata.creator, creator, sizeof(flvmetadata.creator));

	strncpy(flvmetadata.metadatacreator, "Yet Another Metadata Injector for FLV - Version " YAMDI_VERSION "\0", sizeof(flvmetadata.metadatacreator));

	return;
}

size_t writeFLVMetaData(FILE *fp) {
	FLVTag_t flvtag;
	int i;
	size_t length = 0, datasize = 0;
	char *t;

	if(fp == NULL)
		return -1;

	// Zuerst ein ScriptDataObject Tag schreiben

	// Alles auf 0 setzen
	t = (char *)&flvtag;
	memset(t, 0, sizeof(FLVTag_t));

	// Tag Type
	flvtag.type = FLV_SCRIPTDATAOBJECT;

	flvtag.datasize[0] = ((flvmetadata.metadatasize >> 16) & 0xff);
	flvtag.datasize[1] = ((flvmetadata.metadatasize >> 8) & 0xff);
	flvtag.datasize[2] = (flvmetadata.metadatasize & 0xff);

metadatapass:
	datasize = 0;
	datasize += fwrite(t, 1, sizeof(FLVTag_t), fp);

	// ScriptDataObject
	datasize += writeFLVScriptDataObject(fp);

	// onMetaData
	datasize += writeFLVScriptDataECMAArray(fp, "onMetaData", flvmetadata.onmetadatalength);

	// creator
	if(strlen(flvmetadata.creator) != 0) {
		datasize += writeFLVScriptDataValueString(fp, "creator", flvmetadata.creator);
		length++;
	}

	// metadatacreator
	datasize += writeFLVScriptDataValueString(fp, "metadatacreator", flvmetadata.metadatacreator);
	length++;

	// hasKeyframes
	datasize += writeFLVScriptDataValueBool(fp, "hasKeyframes", flvmetadata.hasKeyframes);
	length++;

	// hasVideo
	datasize += writeFLVScriptDataValueBool(fp, "hasVideo", flvmetadata.hasVideo);
	length++;

	// hasAudio
	datasize += writeFLVScriptDataValueBool(fp, "hasAudio", flvmetadata.hasAudio);
	length++;

	// hasMetadata
	datasize += writeFLVScriptDataValueBool(fp, "hasMetadata", flvmetadata.hasMetadata);
	length++;

	// canSeekToEnd
	datasize += writeFLVScriptDataValueBool(fp, "canSeekToEnd", flvmetadata.canSeekToEnd);
	length++;

	// duration
	datasize += writeFLVScriptDataValueDouble(fp, "duration", flvmetadata.duration);
	length++;

	// datasize
	datasize += writeFLVScriptDataValueDouble(fp, "datasize", flvmetadata.datasize);
	length++;

	if(flvmetadata.hasVideo == 1) {
		// videosize
		datasize += writeFLVScriptDataValueDouble(fp, "videosize", flvmetadata.videosize);
		length++;

		// videocodecid
		datasize += writeFLVScriptDataValueDouble(fp, "videocodecid", flvmetadata.videocodecid);
		length++;

		// width
		if(flvmetadata.width != 0.0) {
			datasize += writeFLVScriptDataValueDouble(fp, "width", flvmetadata.width);
			length++;
		}

		// height
		if(flvmetadata.height != 0.0) {
			datasize += writeFLVScriptDataValueDouble(fp, "height", flvmetadata.height);
			length++;
		}

		// framerate
		datasize += writeFLVScriptDataValueDouble(fp, "framerate", flvmetadata.framerate);
		length++;

		// videodatarate
		datasize += writeFLVScriptDataValueDouble(fp, "videodatarate", flvmetadata.videodatarate);
		length++;
	}

	if(flvmetadata.hasAudio == 1) {
		// audiosize
		datasize += writeFLVScriptDataValueDouble(fp, "audiosize", flvmetadata.audiosize);
		length++;

		// audiocodecid
		datasize += writeFLVScriptDataValueDouble(fp, "audiocodecid", flvmetadata.audiocodecid);
		length++;

		// audiosamplerate
		datasize += writeFLVScriptDataValueDouble(fp, "audiosamplerate", flvmetadata.audiosamplerate);
		length++;

		// audiosamplesize
		datasize += writeFLVScriptDataValueDouble(fp, "audiosamplesize", flvmetadata.audiosamplesize);
		length++;

		// stereo
		datasize += writeFLVScriptDataValueBool(fp, "stereo", flvmetadata.stereo);
		length++;

		// audiodatarate
		datasize += writeFLVScriptDataValueDouble(fp, "audiodatarate", flvmetadata.audiodatarate);
		length++;
	}

	// filesize
	datasize += writeFLVScriptDataValueDouble(fp, "filesize", flvmetadata.filesize);
	length++;

	// lasttimestamp
	datasize += writeFLVScriptDataValueDouble(fp, "lasttimestamp", flvmetadata.lasttimestamp);
	length++;

	if(flvmetadata.hasKeyframes == 1) {
		// lastkeyframetimestamp
		datasize += writeFLVScriptDataValueDouble(fp, "lastkeyframetimestamp", flvmetadata.lastkeyframetimestamp);
		length++;

		// lastkeyframelocation
		datasize += writeFLVScriptDataValueDouble(fp, "lastkeyframelocation", flvmetadata.lastkeyframelocation);
		length++;

		// keyframes
		datasize += writeFLVScriptDataVariableArray(fp, "keyframes");
		length++;

		// filepositions
		datasize += writeFLVScriptDataValueArray(fp, "filepositions", flvmetadata.keyframes);

		for(i = 0; i < flvmetadata.keyframes; i++)
			datasize += writeFLVScriptDataValueDouble(fp, NULL, flvmetadata.filepositions[i]);

		// times
		datasize += writeFLVScriptDataValueArray(fp, "times", flvmetadata.keyframes);

		for(i = 0; i < flvmetadata.keyframes; i++)
			datasize += writeFLVScriptDataValueDouble(fp, NULL, flvmetadata.times[i]);

		// Variable Array End Object
		datasize += writeFLVScriptDataVariableArrayEnd(fp);
	}

	if(flvmetadata.onmetadatalength == 0) {
		flvmetadata.onmetadatalength = length;
		goto metadatapass;
	}

	datasize += writeFLVScriptDataVariableArrayEnd(fp);

	flvmetadata.metadatasize = datasize - sizeof(FLVTag_t);

	datasize += writeFLVPreviousTagSize(fp, datasize);

	return datasize;
}

size_t writeFLVLastSecond(FILE *fp, double timestamp) {
	FLVTag_t flvtag;
	int currenttimestamp;
	size_t datasize = 0;
	char *t;

	// Zuerst ein ScriptDataObject Tag schreiben

	// Alles auf 0 setzen
	t = (char *)&flvtag;
	memset(t, 0, sizeof(FLVTag_t));

	// Tag Type
	flvtag.type = FLV_SCRIPTDATAOBJECT;

	// Timestamp
	currenttimestamp = (int)(timestamp * 1000.0);
	flvtag.timestamp_ex = ((currenttimestamp >> 24) & 0xff);
	flvtag.timestamp[0] = ((currenttimestamp >> 16) & 0xff);
	flvtag.timestamp[1] = ((currenttimestamp >> 8) & 0xff);
	flvtag.timestamp[2] = (currenttimestamp & 0xff);

	flvtag.datasize[0] = ((flvmetadata.onlastsecondlength >> 16) & 0xff);
	flvtag.datasize[1] = ((flvmetadata.onlastsecondlength >> 8) & 0xff);
	flvtag.datasize[2] = (flvmetadata.onlastsecondlength & 0xff);

	datasize = 0;
	datasize += fwrite(t, 1, sizeof(FLVTag_t), fp);

	// ScriptDataObject
	datasize += writeFLVScriptDataObject(fp);

	// onLastSecond
	datasize += writeFLVScriptDataECMAArray(fp, "onLastSecond", 0);

	datasize += writeFLVScriptDataVariableArrayEnd(fp);

	flvmetadata.onlastsecondlength = datasize - sizeof(FLVTag_t);

	datasize += writeFLVPreviousTagSize(fp, datasize);

	return datasize;
}

size_t writeFLVLastKeyframe(FILE *fp) {
	FLVTag_t flvtag;
	size_t datasize = 0;
	char *t;

	// Zuerst ein ScriptDataObject Tag schreiben

	// Alles auf 0 setzen
	t = (char *)&flvtag;
	memset(t, 0, sizeof(FLVTag_t));

	// Tag Type
	flvtag.type = FLV_SCRIPTDATAOBJECT;

	flvtag.datasize[0] = ((flvmetadata.onlastkeyframelength >> 16) & 0xff);
	flvtag.datasize[1] = ((flvmetadata.onlastkeyframelength >> 8) & 0xff);
	flvtag.datasize[2] = (flvmetadata.onlastkeyframelength & 0xff);

	datasize = 0;
	datasize += fwrite(t, 1, sizeof(FLVTag_t), fp);

	// ScriptDataObject
	datasize += writeFLVScriptDataObject(fp);

	// onLastKeyframe
	datasize += writeFLVScriptDataECMAArray(fp, "onLastKeyframe", 0);

	datasize += writeFLVScriptDataVariableArrayEnd(fp);

	flvmetadata.onlastkeyframelength = datasize - sizeof(FLVTag_t);

	datasize += writeFLVPreviousTagSize(fp, datasize);

	return datasize;
}

size_t writeFLVPreviousTagSize(FILE *fp, size_t datasize) {
	unsigned char length[4];

	length[0] = ((datasize >> 24) & 0xff);
	length[1] = ((datasize >> 16) & 0xff);
	length[2] = ((datasize >> 8) & 0xff);
	length[3] = (datasize & 0xff);

	fwrite(length, 1, 4, fp);

	return 4;
}

size_t writeFLVScriptDataObject(FILE *fp) {
	size_t datasize = 0;
	char type;

	type = 2;
	datasize += fwrite(&type, 1, 1, fp);

	return datasize;
}

size_t writeFLVScriptDataECMAArray(FILE *fp, const char *name, size_t len) {
	size_t datasize = 0;
	unsigned char length[4];
	char type;

	datasize += writeFLVScriptDataString(fp, name);
	type = 8;	// ECMAArray
	datasize += fwrite(&type, 1, 1, fp);

	length[0] = ((len >> 24) & 0xff);
	length[1] = ((len >> 16) & 0xff);
	length[2] = ((len >> 8) & 0xff);
	length[3] = (len & 0xff);

	datasize += fwrite(length, 1, 4, fp);

	return datasize;
}

size_t writeFLVScriptDataValueArray(FILE *fp, const char *name, size_t len) {
	size_t datasize = 0;
	unsigned char length[4];
	char type;

	datasize += writeFLVScriptDataString(fp, name);
	type = 10;	// Value Array
	datasize += fwrite(&type, 1, 1, fp);

	length[0] = ((len >> 24) & 0xff);
	length[1] = ((len >> 16) & 0xff);
	length[2] = ((len >> 8) & 0xff);
	length[3] = (len & 0xff);

	datasize += fwrite(length, 1, 4, fp);

	return datasize;
}

size_t writeFLVScriptDataVariableArray(FILE *fp, const char *name) {
	size_t datasize = 0;
	char type;

	datasize += writeFLVScriptDataString(fp, name);
	type = 3;	// Variable Array
	datasize += fwrite(&type, 1, 1, fp);

	return datasize;
}

size_t writeFLVScriptDataVariableArrayEnd(FILE *fp) {
	size_t datasize = 0;
	unsigned char length[3];

	length[0] = 0;
	length[1] = 0;
	length[2] = 9;

	datasize += fwrite(length, 1, 3, fp);

	return datasize;
}

size_t writeFLVScriptDataValueString(FILE *fp, const char *name, const char *value) {
	size_t datasize = 0;
	char type;

	if(name != NULL)
		datasize += writeFLVScriptDataString(fp, name);

	type = 2;	// DataString
	datasize += fwrite(&type, 1, 1, fp);
	datasize += writeFLVScriptDataString(fp, value);

	return datasize;
}

size_t writeFLVScriptDataValueBool(FILE *fp, const char *name, int value) {
	size_t datasize = 0;
	char type;

	if(name != NULL)
		datasize += writeFLVScriptDataString(fp, name);

	type = 1;	// Bool
	datasize += fwrite(&type, 1, 1, fp);
	datasize += writeFLVBool(fp, value);

	return datasize;
}

size_t writeFLVScriptDataValueDouble(FILE *fp, const char *name, double value) {
	size_t datasize = 0;
	char type;

	if(name != NULL)
		datasize += writeFLVScriptDataString(fp, name);

	type = 0;	// Double
	datasize += fwrite(&type, 1, 1, fp);
	datasize += writeFLVDouble(fp, value);

	return datasize;
}

size_t writeFLVScriptDataString(FILE *fp, const char *s) {
	size_t datasize = 0, len;
	unsigned char length[2];

	len = strlen(s);

	if(len > 0xffff)
		datasize += writeFLVScriptDataLongString(fp, s);
	else {
		length[0] = ((len >> 8) & 0xff);
		length[1] = (len & 0xff);

		datasize += fwrite(length, 1, 2, fp);
		datasize += fwrite(s, 1, len, fp);
	}

	return datasize;
}

size_t writeFLVScriptDataLongString(FILE *fp, const char *s) {
	size_t datasize = 0, len;
	unsigned char length[4];

	len = strlen(s);

	if(len > 0xffffffff)
		len = 0xffffffff;

	length[0] = ((len >> 24) & 0xff);
	length[1] = ((len >> 16) & 0xff);
	length[2] = ((len >> 8) & 0xff);
	length[3] = (len & 0xff);

	datasize += fwrite(length, 1, 4, fp);
	datasize += fwrite(s, 1, len, fp);

	return datasize;
}

size_t writeFLVBool(FILE *fp, int value) {
	size_t datasize = 0;
	unsigned char b;

	b = (value & 1);

	datasize += fwrite(&b, 1, 1, fp);

	return datasize;
}

size_t writeFLVDouble(FILE *fp, double value) {
	union {
		unsigned char dc[8];
		double dd;
	} d;
	unsigned char b[8];
	size_t datasize = 0;

	d.dd = value;

	b[0] = d.dc[7];
	b[1] = d.dc[6];
	b[2] = d.dc[5];
	b[3] = d.dc[4];
	b[4] = d.dc[3];
	b[5] = d.dc[2];
	b[6] = d.dc[1];
	b[7] = d.dc[0];

	datasize += fwrite(b, 1, 8, fp);

	return datasize;
}

void print_usage(void) {
	fprintf(stderr, "NAME\n");
	fprintf(stderr, "\tyamdi -- Yet Another Metadata Injector for FLV\n");
	fprintf(stderr, "\tVersion: " YAMDI_VERSION "\n");
	fprintf(stderr, "\n");

	fprintf(stderr, "SYNOPSIS\n");
	fprintf(stderr, "\tyamdi -i input file [-x xml file | -o output file [-x xml file]]\n");
	fprintf(stderr, "\t      [-c creator] [-l] [-h]\n");
	fprintf(stderr, "\n");

	fprintf(stderr, "DESCRIPTION\n");
	fprintf(stderr, "\tyamdi is a metadata injector for FLV files.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\tOptions:\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-i\tThe source FLV file.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-o\tThe resulting FLV file with the metatags. If the file\n");
	fprintf(stderr, "\t\tname is '-' the output will be written to stdout.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-x\tAn XML file with the resulting metadata information. If the\n");
	fprintf(stderr, "\t\toutput file is ommited, only metadata will be generated.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-c\tA string that will be written into the creator tag.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-l\tAdd the onLastSecond event.\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t-h\tThis description.\n");
	fprintf(stderr, "\n");

	fprintf(stderr, "COPYRIGHT\n");
	fprintf(stderr, "\t(c) 2008 Ingo Oppermann\n");
	fprintf(stderr, "\n");
	return;
}


text:
require 'set'

module RubyProf
  # Generates a graphviz graph in dot format.
  # To use the dot printer:
  #
  #   result = RubyProf.profile do
  #     [code to profile]
  #   end
  #
  #   printer = RubyProf::DotPrinter.new(result)
  #   printer.print(STDOUT)
  #
  # You can use either dot viewer such as GraphViz, or the dot command line tool
  # to reformat the output into a wide variety of outputs:
  #
  #   dot -Tpng graph.dot > graph.png
  #
  class DotPrinter < RubyProf::AbstractPrinter
    CLASS_COLOR = '"#666666"'
    EDGE_COLOR  = '"#666666"'

    # Creates the DotPrinter using a RubyProf::Result.
    def initialize(result)
      super(result)
      @seen_methods = Set.new
    end

    # Print a graph report to the provided output.
    #
    # output - Any IO object, including STDOUT or a file. The default value is
    # STDOUT.
    #
    # options - Hash of print options.  See #setup_options
    # for more information.
    #
    # When profiling results that cover a large number of method calls it
    # helps to use the :min_percent option, for example:
    #
    #   DotPrinter.new(result).print(STDOUT, :min_percent=>5)
    #
    def print(output = STDOUT, options = {})
      @output = output
      setup_options(options)

      puts 'digraph "Profile" {'
      #puts "label=\"#{mode_name} >=#{min_percent}%\\nTotal: #{total_time}\";"
      puts "labelloc=t;"
      puts "labeljust=l;"
      print_threads
      puts '}'
    end

    private

    # Something of a hack, figure out which constant went with the
    # RubyProf.measure_mode so that we can display it.  Otherwise it's easy to
    # forget what measurement was made.
    def mode_name
      RubyProf.constants.find{|c| RubyProf.const_get(c) == RubyProf.measure_mode}
    end

    def print_threads
      @result.threads.each do |thread|
        puts "subgraph \"Thread #{thread.id}\" {"

        print_thread(thread)
        puts "}"

        print_classes(thread)
      end
    end

    # Determines an ID to use to represent the subject in the Dot file.
    def dot_id(subject)
      subject.object_id
    end

    def print_thread(thread)
      total_time = thread.total_time
      thread.methods.sort_by(&sort_method).reverse_each do |method|
        total_percentage = (method.total_time/total_time) * 100

        next if total_percentage < min_percent
        name = method_name(method).split("#").last
        puts "#{dot_id(method)} [label=\"#{name}\\n(#{total_percentage.round}%)\"];"
        @seen_methods << method
        print_edges(total_time, method)
      end
    end

    def print_classes(thread)
      grouped = {}
      thread.methods.each{|m| grouped[m.klass_name] ||= []; grouped[m.klass_name] << m}
      grouped.each do |cls, methods2|
        # Filter down to just seen methods
        big_methods = methods2.select{|m| @seen_methods.include? m}

        if !big_methods.empty?
          puts "subgraph cluster_#{cls.object_id} {"
          puts "label = \"#{cls}\";"
          puts "fontcolor = #{CLASS_COLOR};"
          puts "fontsize = 16;"
          puts "color = #{CLASS_COLOR};"
          big_methods.each do |m|
            puts "#{m.object_id};"
          end
          puts "}"
        end
      end
    end

    def print_edges(total_time, method)
      method.aggregate_children.sort_by(&:total_time).reverse.each do |child|

        target_percentage = (child.target.total_time / total_time) * 100.0
        next if target_percentage < min_percent

        # Get children method
        puts "#{dot_id(method)} -> #{dot_id(child.target)} [label=\"#{child.called}/#{child.target.called}\" fontsize=10 fontcolor=#{EDGE_COLOR}];"
      end
    end

    # Silly little helper for printing to the @output
    def puts(str)
      @output.puts(str)
    end

  end
end


text:
@interface AddFriendsController : UITableViewController

@end


text:
===============
Writing Plugins
===============

nose2 supports plugins for test collection, selection, observation and
reporting -- among other things. There are two basic rules for plugins:

* Plugin classes must subclass :class:`nose2.events.Plugin`.

* Plugins may implement any of the methods described in the
  :doc:`hook_reference`.

Hello World
===========

Here's a basic plugin. It doesn't do anything besides log a message at
the start of a test run.

.. code-block:: python

    import logging
    import os

    from nose2.events import Plugin

    log = logging.getLogger('nose2.plugins.helloworld')

    class HelloWorld(Plugin):
        configSection = 'helloworld'
        commandLineSwitch = (None, 'hello-world', 'Say hello!')

        def startTestRun(self, event):
            log.info('Hello pluginized world!')

To see this plugin in action, save it into an importable module, then
add that module to the ``plugins`` key in the ``[unittest]`` section
of a config file loaded by nose2, such as ``unittest.cfg``. Then run
nose2::

  nose2 --log-level=INFO --hello-world

And you should see the log message before the first dot appears.

Loading plugins
===============

As mentioned above, for nose2 to find a plugin, it must be in an
importable module, and the module must be listed under the ``plugins``
key in the ``[unittest]`` section of a config file loaded by nose2:

.. code-block:: ini

   [unittest]
   plugins = mypackage.someplugin
             otherpackage.thatplugin
             thirdpackage.plugins.metoo

As you can see, plugin *modules* are listed, one per line. All plugin
classes in those modules will be loaded -- but not necessarily
active. Typically plugins do not activate themselves ("register")
without seeing a command-line flag, or ``always-on = True`` in their
config file section.

Command-line Options
====================

nose2 uses `argparse`_ for command-line argument parsing. Plugins may
enable command-line options that register them as active, or take
arguments or flags controlling their operation.

The most basic thing to do is to set the plugin's
``commandLineSwitch`` attribute, which will automatically add a
command-line flag that registers the plugin.

To add other flags or arguments, you can use the Plugin methods
:meth:`nose2.events.Plugin.addFlag`,
:meth:`nose2.events.Plugin.addArgument` or
:meth:`nose2.events.Plugin.addOption`. If those don't offer enough
flexibility, you can directly manipulate the argument parser by
accessing ``self.session.argparse`` or the plugin option group by
accessing ``self.session.pluginargs``.

Please note though that the *majority* of your plugin's configuration
should be done via config file options, not command line options.

Config File Options
===================

Plugins may specify a config file section that holds their
configuration by setting their ``configSection`` attribute. All
plugins, regardless of whether they specify a config section, have a
``config`` attribute that holds a :class:`nose2.config.Config`
instance. This will be empty of values if the plugin does not specify
a config section or if no loaded config file includes that section.

Plugins should extract the user's configuration selections from their
config attribute in their ``__init__`` methods. Plugins that want to
use nose2's `Sphinx`_ extension to automatically document themselves
**must** do so.

Config file options may be extracted as strings, ints, booleans or
lists.

You should provide reasonable defaults for all config options.

Guidelines
==========

Events
------

nose2's plugin api is based on the api in unittest2's
under-development plugins branch. It differs from nose's plugins api
in one major area: what it passes to hooks. Where nose passes a
variety of arguments, nose2 *always passes an event*. The events are
listed in the :doc:`event_reference`.

Here's the key thing about that: *event attributes are
read-write*. Unless stated otherwise in the documentation for a hook,
you can set a new value for any event attribute, and *this will do
something*. Plugins and nose2 systems will see that new value and
either use it instead of what was originally set in the event
(example: the reporting stream or test executor), or use it to
supplement something they find elsewhere (example: extraTests on a
test loading event).

"Handling" events
~~~~~~~~~~~~~~~~~

Many hooks give plugins a chance to completely handle events,
bypassing other plugins and any core nose2 operations. To do this, a
plugin sets ``event.handled`` to True and, generally, returns an
appropriate value from the hook method. What is an appropriate value
varies by hook, and some hooks *can't* be handled in this way. But
even for hooks where handling the event doesn't stop all processing,
it *will* stop subsequently-loaded plugins from seeing the event.

Logging
-------

nose2 uses the logging classes from the standard library. To enable users
to view debug messages easily, plugins should use ``logging.getLogger()`` to
acquire a logger in the ``nose2.plugins`` namespace.

.. todo ::

   more guidelines

Recipes
=======

* Writing a plugin that monitors or controls test result output

  Implement any of the ``report*`` hook methods, especially if you
  want to output to the console. If outputing to file or other system,
  you might implement :func:`testOutcome` instead.

  Example: :class:`nose2.plugins.result.ResultReporter`

* Writing a plugin that handles exceptions

  If you just want to handle some exceptions as skips or failures
  instead of errors, see :class:`nose2.plugins.outcomes.Outcomes`,
  which offers a simple way to do that. Otherwise, implement
  :func:`setTestOutcome` to change test outcomes.

  Example: :class:`nose2.plugins.outcomes.Outcomes`

* Writing a plugin that adds detail to error reports

  Implement :func:`testOutcome` and put your extra information into
  ``event.metadata``, then implement :func:`outcomeDetail` to extract
  it and add it to the error report.

  Examples: :class:`nose2.plugins.buffer.OutputBufferPlugin`, :class:`nose2.plugins.logcapture.LogCapture`

* Writing a plugin that loads tests from files other than python modules

  Implement :func:`handleFile`.

  Example: :class:`nose2.plugins.doctests.DocTestLoader`

* Writing a plugin that loads tests from python modules

  Implement at least :func:`loadTestsFromModule`.

  .. _loading-from-module:

  .. warning ::

     One thing to beware of here is that if you return tests as
     dynamically-generated test cases, or instances of a testcase
     class that is defined *anywhere* but the module being loaded, you
     *must* use :func:`nose2.util.transplant_class` to make the test
     case class appear to have originated in that module. Otherwise,
     module-level fixtures will not work for that test, and may be
     ignored entirely for the module if there are no test cases that
     are or appear to be defined there.

* Writing a plugin that prints a report

  Implement :func:`beforeErrorList`, :func:`beforeSummaryReport` or
  :func:`afterSummaryReport`

  Example: :class:`nose2.plugins.prof.Profiler`

* Writing a plugin that selects or rejects tests

  Implement :class:`matchPath` or :class:`getTestCaseNames`.

  Example: :class:`nose2.plugins.loader.parameters.Parameters`

.. _argparse : http://pypi.python.org/pypi/argparse/1.2.1
.. _Sphinx : http://sphinx.pocoo.org/


text:
module Spree
  module Preferences
    module StaticallyConfigurable
      extend ActiveSupport::Concern

      class_methods do
        def preference_sources
          Spree::Config.static_model_preferences.for_class(self)
        end

        def available_preference_sources
          preference_sources.keys
        end
      end

      # override assignment to cast empty string to nil
      def preference_source=(val)
        super(val.presence)
      end

      def preferences
        if respond_to?(:preference_source) && preference_source
          self.class.preference_sources[preference_source] || {}
        else
          self[:preferences]
        end
      end

      def preferences=(val)
        if respond_to?(:preference_source) && preference_source
        else
          self[:preferences] = val
        end
      end
    end
  end
end


text:
package org.sleuthkit.autopsy.report;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.TskCoreException;

class ReportExcel implements TableReportModule {

    private static final Logger logger = Logger.getLogger(ReportExcel.class.getName());
    private static ReportExcel instance;

    private Workbook wb;
    private Sheet sheet;
    private CellStyle titleStyle;
    private CellStyle setStyle;
    private CellStyle elementStyle;
    private int rowIndex = 0;
    private int sheetColCount = 0;
    private String reportPath;

    // Get the default instance of this report
    public static synchronized ReportExcel getDefault() {
        if (instance == null) {
            instance = new ReportExcel();
        }
        return instance;
    }

    // Hidden constructor
    private ReportExcel() {
    }

    /**
     * Start the Excel report by creating the Workbook, initializing styles, and
     * writing the summary.
     *
     * @param baseReportDir path to save the report
     */
    @Override
    public void startReport(String baseReportDir) {
        // Set the path and save it for when the report is written to disk.
        this.reportPath = baseReportDir + getRelativeFilePath();

        // Make a workbook.
        wb = new XSSFWorkbook();

        // Create some cell styles.
        // TODO: The commented out cell style settings below do not work as desired when
        // the output file is loaded by MS Excel or OfficeLibre. The font height and weight
        // settings only work as expected when the output file is loaded by OfficeLibre.
        // The alignment and text wrap settings appear to have no effect.
        titleStyle = wb.createCellStyle();
//        titleStyle.setBorderBottom((short) 1);
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short) 12);
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.LEFT);
        titleStyle.setWrapText(true);

        setStyle = wb.createCellStyle();
        Font setFont = wb.createFont();
        setFont.setFontHeightInPoints((short) 14);
        setFont.setBold(true);
        setStyle.setFont(setFont);
        setStyle.setAlignment(HorizontalAlignment.LEFT);
        setStyle.setWrapText(true);

        elementStyle = wb.createCellStyle();
//        elementStyle.setF illBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
        Font elementFont = wb.createFont();
        elementFont.setFontHeightInPoints((short) 14);
        elementStyle.setFont(elementFont);
        elementStyle.setAlignment(HorizontalAlignment.LEFT);
        elementStyle.setWrapText(true);

        writeSummaryWorksheet();
    }

    /**
     * Write the Workbook to a file and end the report.
     */
    @Override
    public void endReport() {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(reportPath);
            wb.write(out);
            Case.getCurrentCase().addReport(reportPath, NbBundle.getMessage(this.getClass(),
                    "ReportExcel.endReport.srcModuleName.text"), "");
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "Failed to write Excel report.", ex); //NON-NLS
        } catch (TskCoreException ex) {
            String errorMessage = String.format("Error adding %s to case as a report", reportPath); //NON-NLS
            logger.log(Level.SEVERE, errorMessage, ex);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                }
            }
        }
    }

    /**
     * Start a new worksheet for the given data type. Note: This method is a
     * temporary workaround to avoid modifying the TableReportModule interface.
     *
     * @param name    Name of the data type
     * @param comment Comment on the data type, may be the empty string
     */
    @Override
    public void startDataType(String name, String description) {
        // Create a worksheet for the data type (assumed to be an artifact type).
        name = escapeForExcel(name);
        sheet = wb.createSheet(name);
        sheet.setAutobreaks(true);
        rowIndex = 0;

        // There will be at least two columns, one each for the artifacts count and its label.
        sheetColCount = 2;
    }

    /**
     * End the current data type and sheet.
     */
    @Override
    public void endDataType() {
        // Now that the sheet is complete, size the columns to the content.
        for (int i = 0; i < sheetColCount; ++i) {
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * Start a new set for the current data type.
     *
     * @param setName name of the set
     */
    @Override
    public void startSet(String setName) {
        setName = escapeForExcel(setName);
        Row row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(setName);
        ++rowIndex;
    }

    /**
     * End the current set.
     */
    @Override
    public void endSet() {
        // Add an empty row as a separator.
        sheet.createRow(rowIndex);
        ++rowIndex;
    }

    @Override
    public void addSetIndex(List<String> sets) {
        // Ignored in Excel Report
    }

    /**
     * Add an element to the set
     *
     * @param elementName element name
     */
    @Override
    public void addSetElement(String elementName) {
        elementName = escapeForExcel(elementName);
        Row row = sheet.createRow(rowIndex);
        row.setRowStyle(elementStyle);
        row.createCell(0).setCellValue(elementName);
        ++rowIndex;
    }

    /**
     * Label the top of this sheet with the table column names.
     *
     * @param titles column names
     */
    @Override
    public void startTable(List<String> titles) {
        int tableColCount = 0;
        Row row = sheet.createRow(rowIndex);
        row.setRowStyle(titleStyle);
        for (int i = 0; i < titles.size(); i++) {
            row.createCell(i).setCellValue(titles.get(i));
            ++tableColCount;
        }
        ++rowIndex;

        // Keep track of the number of columns with data in them for later column auto-sizing.
        if (tableColCount > sheetColCount) {
            sheetColCount = tableColCount;
        }
    }

    @Override
    public void endTable() {
        // Add an empty row as a separator.
        sheet.createRow(rowIndex);
        ++rowIndex;
    }

    /**
     * Add a row of information to the report.
     *
     * @param row cells to add
     */
    @Override
    public void addRow(List<String> rowData) {
        Row row = sheet.createRow(rowIndex);
        for (int i = 0; i < rowData.size(); ++i) {
            row.createCell(i).setCellValue(rowData.get(i));
        }
        ++rowIndex;
    }

    /**
     * Return the given long date as a String.
     *
     * @param date as a long
     *
     * @return String date
     */
    @Override
    public String dateToString(long date) {
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(new java.util.Date(date * 1000));
    }

    @Override
    public String getName() {
        return NbBundle.getMessage(this.getClass(), "ReportExcel.getName.text");
    }

    @Override
    public String getDescription() {
        return NbBundle.getMessage(this.getClass(), "ReportExcel.getDesc.text");
    }

    @Override
    public String getRelativeFilePath() {
        return "Excel.xlsx"; //NON-NLS
    }

    /**
     * Escape special chars for Excel that would cause errors/hangs in
     * generating report The following are not valid for sheet names: ? / \ * :
     *
     * @param text
     *
     * @return
     */
    private static String escapeForExcel(String text) {
        return text.replaceAll("[\\/\\:\\?\\*\\\\]", "_");
    }

    private void writeSummaryWorksheet() {
        sheet = wb.createSheet(NbBundle.getMessage(this.getClass(), "ReportExcel.sheetName.text"));
        rowIndex = 0;

        Row row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(NbBundle.getMessage(this.getClass(), "ReportExcel.cellVal.summary"));
        ++rowIndex;

        sheet.createRow(rowIndex);
        ++rowIndex;

        Case currentCase = Case.getCurrentCase();

        row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(NbBundle.getMessage(this.getClass(), "ReportExcel.cellVal.caseName"));
        row.createCell(1).setCellValue(currentCase.getDisplayName());
        ++rowIndex;

        row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(NbBundle.getMessage(this.getClass(), "ReportExcel.cellVal.caseNum"));
        row.createCell(1).setCellValue(currentCase.getNumber());
        ++rowIndex;

        row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(NbBundle.getMessage(this.getClass(), "ReportExcel.cellVal.examiner"));
        row.createCell(1).setCellValue(currentCase.getExaminer());
        ++rowIndex;

        row = sheet.createRow(rowIndex);
        row.setRowStyle(setStyle);
        row.createCell(0).setCellValue(NbBundle.getMessage(this.getClass(), "ReportExcel.cellVal.numImages"));
        int numImages;
        try {
            numImages = currentCase.getDataSources().size();
        } catch (TskCoreException ex) {
            numImages = 0;
        }
        row.createCell(1).setCellValue(numImages);
        ++rowIndex;

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
    }
}


text:
package org.diirt.datasource.expression;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Implementation class for {@link SourceRateReadWriteExpressionList}.
 *
 * @param <R> type of the read payload
 * @param <W> type of the write payload
 * @author carcassi
 */
public class SourceRateReadWriteExpressionListImpl<R, W> implements SourceRateReadWriteExpressionList<R, W> {

    private List<SourceRateReadWriteExpression<R, W>> sourceRateReadWriteExpressions = new ArrayList<SourceRateReadWriteExpression<R, W>>();

    final void addThis() {
        sourceRateReadWriteExpressions.add((SourceRateReadWriteExpression<R, W>) this);
    }

    @Override
    public final SourceRateReadWriteExpressionList<R, W> and(SourceRateReadWriteExpressionList<? extends R, ? extends W> expressions) {
        @SuppressWarnings("unchecked")
        SourceRateReadWriteExpressionList<R, W> newExpression = (SourceRateReadWriteExpressionList<R, W>) (SourceRateReadWriteExpressionList) expressions;
        sourceRateReadWriteExpressions.addAll(newExpression.getSourceRateReadWriteExpressions());
        return this;
    }

    @Override
    public final List<SourceRateReadWriteExpression<R, W>> getSourceRateReadWriteExpressions() {
        return sourceRateReadWriteExpressions;
    }

    @Override
    public final SourceRateExpressionList<R> and(SourceRateExpressionList<? extends R> expressions) {
        @SuppressWarnings("unchecked")
        SourceRateExpressionList<R> newExpression = (SourceRateExpressionList<R>) (SourceRateExpressionList) expressions;
        return new SourceRateExpressionListImpl<R>(sourceRateReadWriteExpressions).and(newExpression);
    }

    @Override
    public final List<SourceRateExpression<R>> getSourceRateExpressions() {
        return Collections.<SourceRateExpression<R>>unmodifiableList(sourceRateReadWriteExpressions);
    }

    @Override
    public final WriteExpressionList<W> and(WriteExpressionList<? extends W> expressions) {
        @SuppressWarnings("unchecked")
        WriteExpressionList<W> newExpression = (WriteExpressionList<W>) (WriteExpressionList) expressions;
        return new WriteExpressionListImpl<W>(sourceRateReadWriteExpressions).and(newExpression);
    }

    @Override
    public final List<WriteExpression<W>> getWriteExpressions() {
        return Collections.<WriteExpression<W>>unmodifiableList(sourceRateReadWriteExpressions);
    }

}


text:
function submit_symbols {
    param($productgroup, $productver, $buildname, $buildid, $buildnum, $buildtype, $filetype, $sourcedir, $reqdir, $contacts)

    $request = `
    "BuildId=$buildid $filetype
BuildLabPhone=7058786
BuildRemark=$buildname
ContactPeople=$contacts
Directory=$sourcedir
Project=TechnicalComputing
Recursive=yes
StatusMail=$contacts
UserName=$env:username
SubmitToArchive=all
SubmitToInternet=yes
ProductGroup=$productgroup
ProductName=$($productgroup)_$($productver)
Release=$buildnum
Build=$buildnum
BuildType=$buildtype
LocaleCode=en-US"

    Write-Output "*** Symbol Submission Text ***
$request"

    # Dump it to the file as well so that it can be manually submitted for testing.
    $reqfile = "$reqdir\symreq_$filetype.txt"
    $request | Out-File -Encoding ascii -FilePath "$reqfile"
}

function _find_sdk_tool {
    param($tool)

    $_tool_item = ""
    foreach ($ver in ("v8.1A", "v8.0A")) {
        foreach ($kit in ("WinSDK-NetFx40Tools-x64", "WinSDK-NetFx40Tools-x86", "WinSDK-NetFx40Tools")) {
            $_kit_path = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SDKs\Windows\$ver\$kit" -EA 0)
            if (-not $_kit_path) {
                $_kit_path = (Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\$ver\$kit" -EA 0)
            }

            if ($_kit_path -and (Test-Path $_kit_path.InstallationFolder)) {
                $_tool_item = Get-Item "$($_kit_path.InstallationFolder)\$tool.exe" -EA 0
                if (-not (Test-Path alias:\$tool) -and $_tool_item) {
                    Set-Alias -Name $tool -Value $_tool_item.FullName -Scope Global
                }
            }
        }
    }
    foreach ($ver in ("KitsRoot81", "KitsRoot")) {
        $_kit_path = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots" -Name $ver -EA 0).$ver
        if (-not $_kit_path) {
            $_kit_path = (Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows Kits\Installed Roots" -Name $ver -EA 0).$ver
        }

        foreach ($kit in ("x64", "x86")) {
            if ($_kit_path -and (Test-Path "$_kit_path\bin\$kit")) {
                $_tool_item = Get-Item "$_kit_path\bin\$kit\$tool.exe" -EA 0
                if (-not (Test-Path alias:\$tool) -and $_tool_item) {
                    Set-Alias -Name $tool -Value $_tool_item.FullName -Scope Global
                    return
                }
            }
        }
    }
}

function begin_sign_files {
    param($files, $outdir, $approvers, $projectName, $projectUrl, $jobDescription, $jobKeywords, $certificates, [switch] $delaysigned)

    if ($files.Count -eq 0) {
        return
    }

    if ($delaysigned) {
        # Ensure that all files are delay-signed
        # "sn -q -v ..." is true if the assembly has strong name and skip verification
        _find_sdk_tool "sn"
        if (Test-Path alias:\sn) {
            $not_delay_signed = $files | %{ gi $_.path } | ?{ sn -q -v $_ }
            if ($not_delay_signed) {
                Throw "Delay-signed check failed: $($not_delay_signed.Name -join '
')
You may need to skip strong name verification on this machine."
            }
        }
    }

    [Reflection.Assembly]::Load("CODESIGN.Submitter, Version=4.1.0.0, Culture=neutral, PublicKeyToken=3d8252bd1272440d, processorArchitecture=MSIL") | Out-Null
    [Reflection.Assembly]::Load("CODESIGN.PolicyManager, Version=4.1.0.0, Culture=neutral, PublicKeyToken=3d8252bd1272440d, processorArchitecture=MSIL") | Out-Null

    $job = [CODESIGN.Submitter.Job]::Initialize("codesign.gtm.microsoft.com", 9556, $True)
    $msg = "*** Signing Job Details ***
job.Description:  $jobDescription
job.Keywords:     $jobKeywords"
    $job.Description = $jobDescription
    $job.Keywords = $jobKeywords

    if ($certificates -match "authenticode") {
        $msg = "$msg
job.SelectCertificate(401)"
        $job.SelectCertificate("401")    # Authenticode for binaries
    }
    if ($certificates -match "msi") {
        $msg = "$msg
job.SelectCertificate(400)"
        $job.SelectCertificate("400")    # Authenticode for MSI
    }
    if ($certificates -match "strongname") {
        $msg = "$msg
job.SelectCertificate(67)"
        $job.SelectCertificate("67")     # StrongName key
    }
    if ($certificates -match "vsix") {
        $msg = "$msg
job.SelectCertificate(100040160)"
        $job.SelectCertificate("100040160") # Microsoft OPC Publisher (VSIX)
    }

    foreach ($approver in $approvers) {
        $msg = "$msg
job.AddApprover($approver)"
        $job.AddApprover($approver)
    }

    foreach ($file in $files) {
        $msg = "$msg
job.AddFile($($file.path), $($file.name), $projectUrl, None)"
        $job.AddFile($file.path, $file.name, $projectUrl, [CODESIGN.JavaPermissionsTypeEnum]::None)
    }

    $msg = "$msg
Returning @{filecount=$($files.Count); outdir=$outdir}"
    Write-Debug $msg

    $uniqueJobFolderID = ((Get-Date -format "yyyyMMdd-HHmmss").ToString() + "-" + (Get-Date).Millisecond.ToString())

    $folder = ((Get-Item $($files[0].path)).DirectoryName.ToString() + "\MockSigned")

    $mockJob = New-Object PSObject
    $mockJob | Add-Member NoteProperty JobID $uniqueJobFolderID
    $mockJob | Add-Member NoteProperty JobMockFolder $folder
    $mockJob | Add-Member NoteProperty JobCompletionPath $folder\$uniqueJobFolderID

    $mockFolderPath = $mockJob.JobCompletionPath
    mkdir $mockFolderPath -EA 0 | Out-Null

    foreach($file in $files) {
        $destPath = "$($mockFolderPath)\$($fileInfo.Name)"
        copy -path $($file.path) -dest $destPath
        if (-not $?) {
            Write-Output "Failed to copy $($file.path) to $destPath"
        }
    }

    return @{rjob=$job; job=$mockJob; description=$jobDescription; filecount=$($files.Count); outdir=$outdir}
}

function end_sign_files {
    param($jobs)

    if ($jobs.Count -eq 0) {
        return
    }

    foreach ($jobinfo in $jobs) {
        $job = $jobinfo.job
        if($job -eq $null) {
            throw "jobinfo in unexpected format $jobinfo"
        }
        $filecount = $jobinfo.filecount
        $outdir = $jobinfo.outdir
        $activity = "Processing $($jobinfo.description) (Job ID $($job.JobID))"
        $percent = 0
        $jobCompletionPath = $job.JobCompletionPath

        if([string]::IsNullOrWhiteSpace($jobCompletionPath)) {
            throw "job.JobCompletionPath is not valid: $($job.JobCompletionPath)"
        }

        do {
            $files = @()
            Write-Progress -activity $activity -status "Waiting for completion: $jobCompletionPath" -percentcomplete $percent;
            $percent = ($percent + 5) % 100
            if ($percent -eq 90) {
                $files = dir $jobCompletionPath
            }
            sleep -Milliseconds 50
        } while(-not $files -or $files.Count -ne $filecount);

        mkdir $outdir -EA 0 | Out-Null
        Write-Progress -Activity $activity -Completed

        Write-Output "Copying from $jobCompletionPath to $outdir"
        $retries = 9
        $delay = 2
        $copied = $null
        while ($retries) {
            try {
                $copied = (Copy-Item -path $jobCompletionPath\* -dest $outdir -Force -PassThru)
                break
            } catch {
                if ($retries -eq 0) {
                    break
                }
                Write-Warning "Failed to copy - retrying in $delay seconds ($retries tries remaining)"
                Sleep -seconds $delay
                --$retries
                $delay += $delay
            }
        }
        if (-not $copied) {
            Throw "Failed to copy $jobCompletionPath to $outdir"
        } else {
            Write-Output "Copied $($copied.Count) files"
        }

        #Get rid of the MockSigned directory
        Remove-Item -Recurse $jobCompletionPath\*
        Remove-Item -Recurse $jobCompletionPath

        if((Get-Item $($job.JobMockFolder)).GetDirectories().Count -eq 0) {
            Remove-Item -Recurse $($job.JobMockFolder)
        }
    }
}

function start_virus_scan {
    param($description, $contact, $path)

    $xml = New-Object XML
    $xml.LoadXml("<root><description /><contact /><path /><region>AOC</region></root>")
    $xml.root.description = $description
    $xml.root.contact = $contact
    $xml.root.path = $path

    Write-Debug "Posting to http://vcs/process.asp:
$($xml.OuterXml)"
}

function check_signing {
    param($outdir)

    _find_sdk_tool "signtool"

    $unsigned = @()

    $msis = gci $outdir\*.msi
    foreach ($m in $msis) {
        Write-Host "Checking signatures for $m"
        & signtool verify /pa "$m" 2>&1 | Out-Null
        # All files should be unsigned
        if ($?) {
            $unsigned += "$m"
        }

        $dir = mkdir -fo "${env:TEMP}\msi_test"
        & msiexec /q /a "$m" TARGETDIR="$dir" | Out-Null

        foreach ($f in (gci $dir\*.exe, $dir\*.dll -r)) {
            & signtool verify /pa "$f" 2>&1 | Out-Null
            # All files should be unsigned
            if ($?) {
                $unsigned += "$m - $($f.Name)"
            }
        }

        rmdir -r -fo $dir
    }

    Add-Type -assembly "System.IO.Compression.FileSystem"
    $zips = gci $outdir\*.vsix
    foreach ($m in $zips) {
        Write-Host "Checking signatures for $m"
        $dir = mkdir -fo "${env:TEMP}\msi_test"
        [IO.Compression.ZipFile]::ExtractToDirectory($m, $dir)

        # All files should be unsigned
        if ((Test-Path "$dir\package\services\digital-signature\xml-signature")) {
            $unsigned += "$m"
        }

        foreach ($f in (gci $dir\*.exe, $dir\*.dll -r)) {
            & signtool verify /pa "$f" 2>&1 | Out-Null
            # All files should be unsigned
            if ($?) {
                $unsigned += "$m - $($f.Name)"
            }
        }

        rmdir -r -fo $dir
    }

    if ($unsigned) {
        throw "Following files have invalid signatures:
$(($unsigned | select -unique) -join '
')"
    }
}


text:
CREATE TEMPORARY VIEW entities AS
SELECT 'PLAYBOX'  AS id, 'reserved' AS etype                  UNION
SELECT 'CIV'      AS id, 'reserved' AS etype                  UNION
SELECT 'FRC'      AS id, 'reserved' AS etype                  UNION
SELECT 'ORG'      AS id, 'reserved' AS etype                  UNION
SELECT 'ALL'      AS id, 'reserved' AS etype                  UNION
SELECT 'NONE'     AS id, 'reserved' AS etype                  UNION
SELECT 'SELF'     AS id, 'reserved' AS etype                  UNION
SELECT n          AS id, 'nbhood'   AS etype FROM nbhoods     UNION
SELECT agent_id   AS id, 'agent'    AS etype FROM agents      UNION
SELECT g          AS id, 'group'    AS etype FROM groups      UNION
SELECT k          AS id, 'cap'      AS etype FROM caps        UNION
SELECT iom_id     AS id, 'iom'      AS etype FROM ioms        UNION
SELECT c          AS id, 'concern'  AS etype FROM concerns    UNION
SELECT a          AS id, 'activity' AS etype FROM activity    UNION
SELECT u          AS id, 'unit'     AS etype FROM units       UNION
SELECT curse_id   AS id, 'curse'    AS etype FROM curses      UNION
SELECT hook_id    AS id, 'hook'     AS etype FROM hooks;

-----------------------------------------------------------------------
-- End of File
-----------------------------------------------------------------------