text:
/* 题号:1
 * 要求:根据 20.6.2 节中的内容为 Document 编写一个查找
 * 并替换操作。(我们不要求替换或者被替换的字符串中包含换行符。如果你希望包含
 * 换行符,你需要更加仔细地控制迭代器)
 */
#include "../../std_lib_facilities.h"
namespace Ex1 {
typedef vector<char> Line;		// a line is a vector of characters

class Text_iterator				// keep track of line and character position within a line
{
	list<Line>::iterator ln;
	Line::iterator pos;
public:
	typedef forward_iterator_tag iterator_category;
    typedef char value_type;
    typedef size_t difference_type;
    typedef char* pointer;
    typedef char& reference;

	// start the iterator at line ll's characters position pp:
	Text_iterator(list<Line>::iterator ll, Line::iterator pp)
		:ln(ll), pos(pp) { }

	// getter functions
	list<Line>::iterator line() { return ln; }
	Line::iterator position() { return pos; }

	// operator overloading functions
	char& operator*() { return *pos; }
	Text_iterator& operator++();

	bool operator==(const Text_iterator& other) const
		{ return ln == other.ln && pos == other.pos; }
	bool operator!=(const Text_iterator& other) const
		{ return !(*this == other); }
};

Text_iterator& Text_iterator::operator++()
{
	if (*pos == '\0')			// if *pos equals EOF char
	{
		++pos;
		return *this;
	}

	++pos;					// proceed to next character
	while (pos == (*ln).end())		// loop until the line has characters
									// we do this to skip empty lines
	{
		++ln;				// proceed to next line
		pos = (*ln).begin();
	}
	return *this;
}

template<class Iter>
Iter advance(Iter p, int n)
{
	while (n > 0) { ++p; --n; }	// go forward
	return p;
}

struct Document
{
	list<Line> line;	// a document is a list of lines
						// line[i] is the ith line
	Document() { line.push_back(Line(1, '\0')); }

	Text_iterator begin()		// first character of first line
		{
			list<Line>::iterator first = line.begin();
			while (first != line.end() && first->size() == 0)		// loop until the line has characters
																	// we do this to skip empty lines
				++first;
			return Text_iterator(first, (*first).begin());
		}
	Text_iterator end()			// one beyond the last line
		{
			list<Line>::iterator last = line.end();
			--last;				// we know that the document is not empty
			return Text_iterator(last, (*last).end());
		}

	void update();		// update the line list according to \n characters
};

// rearrange lines to formatted lines (that means the lines are only split by \n)
void Document::update()
{
	for (list<Line>::iterator itr = line.begin(); itr != line.end();)
	{
		Line::iterator char_itr;
		for (char_itr = itr->begin(); char_itr != itr->end(); ++char_itr)
		{
			if (*char_itr == '\n' || *char_itr == '\0')
				break;
		}

		// if not reaching the end
		if (char_itr != itr->end())
		{
			if (*char_itr == '\0')
				break;

			// if not reaching the last char of a line, split it into two lines
			// for example: aaa\nbbb -> Line(aaa\n), Line(bbb)
			if (*char_itr == '\n' && (++char_itr) != itr->end())
			{
				Line new_ln(char_itr, itr->end());	// create new line
				itr->erase(char_itr, itr->end());	// delete old line
				itr = line.insert(++itr, new_ln);	// insert new line and set iterator to new line
				continue;
			}
		}
		else
		{
			// if reaching the last char but it's not \n, merge it with the next line
			if (*itr == line.back())				// fix data error if there is no \0 at the end of document
				line.push_back(Line());

			list<Line>::iterator old_itr = itr++;
			itr->insert(itr->begin(), old_itr->begin(), old_itr->end());	// merge old line to new line
			itr = line.erase(old_itr);				// delete old line and set iterator to new line
			continue;
		}

		// only when the line doesn't need formatting will the iterator be plus one
		++itr;
	}
}

istream& operator>>(istream& is, Document& d)
{
	d.line.back().pop_back();				// del EOF char

	char ch;
	while (is.get(ch))
	{
		d.line.back().push_back(ch);		// add the character
		if (ch == '\n')
			d.line.push_back(Line());		// add another line
	}

	d.line.back().push_back('\0');			// insert EOF char
	return is;
}

ostream& operator<<(ostream& os, Document& d)
{
	for (Text_iterator p = d.begin(); p != d.end(); ++p)
		if (*p != '\0')
			os << *p;

	return os;
}

int linear_position(Document& d, Text_iterator& p)
{
	int pos = 0;
	for (Text_iterator itr = d.begin();
		itr != p && itr != d.end();
		++itr, ++pos)
	{}
	return pos;
}

void erase_line(Document& d, int n)
{
	list<Line>::size_type sn(n);		// convert to size_type type
	if (sn < 0 || d.line.size() <= sn)	// ignore out-of-range lines
		return;
	d.line.back().pop_back();					// del EOF char
	d.line.erase(advance(d.line.begin(), sn));
	d.line.back().push_back('\0');				// insert EOF char
}

bool match(Text_iterator first, Text_iterator last, const string& s)
{
	string::const_iterator p;

	for (p = s.begin();
		p != s.end() && first != last && *p == *first;
		++p, ++first)
	{}

	return p == s.end();
}

Text_iterator find_txt(Text_iterator first, Text_iterator last, const string& s)
{
	if (s.size() == 0) return last;	// can't find an empty string
	char first_char = s[0];
	while (true)
	{
		Text_iterator p = find(first, last, first_char);
		if (p == last || match(p, last, s)) return p;
		first = ++p;				// reset the first iterator
	}
}

// replace fs to rs
void replace(Document&d, const string& fs, const string& rs)
{
	Text_iterator first = d.begin();
	while (true)
	{
		Text_iterator p = find_txt(first, d.end(), fs);
		if (p == d.end())		// no match
			return;

		if (rs.size() <= fs.size())
		{
			for (string::size_type i = 0; i < fs.size(); ++i)
			{
				if (i < rs.size())
				{
					*p = rs[i];
					++p;
					continue;
				}

				// del the rested characters
				if (*p != '\n')
					p = Text_iterator(p.line(),
							p.line()->erase(p.position()));
				else
				{
					p.line()->erase(p.position());

					// move the iterator to a new line
					list<Line>::iterator line = ++p.line();
					p = Text_iterator(line, line->begin());
				}
			}
		}
		else
		{
			for (string::size_type i = 0; i < rs.size(); ++i)
			{
				if (i < fs.size())
					*p = rs[i];
				else
					// insert the rest characters
					p = Text_iterator(p.line(),
							p.line()->insert(p.position(), rs[i]));

				if (i + 1 != rs.size())
					++p;
			}
		}

		if (d.line.back().back() != '\0')	// insert EOF char
			d.line.back().push_back('\0');

		int pos = linear_position(d, p) + 1;	// remember the position of the iterator
		d.update();								// format the document

		first = advance(d.begin(), pos);	// recover the iterator from pos
	}
}

void print(Document& d)
{
	cout << d;
}
}

using namespace Ex1;

int main()
{
	// if you want to read from a file, use the code commented
	/*
	ifstream is("in.txt");
	if (!is)
	{
		cerr << "Open file error! The file requested is in.txt." << endl;
		return -1;
	}
	Document my_doc;
	is >> my_doc;
	*/
	//string test = "This is the secret\nahomestead as it is. No secret\nas you,\nas well as me,\nhas fallen in love.";
	string test = "11111111";
	istringstream iss(test);
	Document my_doc;
	iss >> my_doc;

	cout << my_doc << endl;

	Text_iterator p =
		find_txt(my_doc.begin(), my_doc.end(), "secret\nahomestead");
	if (p == my_doc.end())
		cout << "not found\n";
	else
		cout << "secret found\n";

	//replace(my_doc, "secret\na", "beauti\nful wom\nan\n");
	//replace(my_doc, "n\nhomestead", "seek");
	//replace(my_doc, "This is the beauti\nful wom\naseek as it is. No beauti\nful wom\nan\ns you,\nas well as me,\nhas fallen in love.", "Now the text is deleted.");
	//replace(my_doc, "wom\nan\ns you,\na", "a");
	replace(my_doc, "1", "11");

	cout << my_doc << endl;

	return 0;
}


text:
class Solution {
	public:
		TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
			if (root == nullptr || root == p || root == q) {
				return root;
			}
			auto left = lowestCommonAncestor(root -> left, p, q);
			auto right = lowestCommonAncestor(root -> right, p, q);
			if (left && right) {
				return root;
			}
			return left? left : right;
		}
};

redpajama_set_name: RedPajamaGithub


text:
\documentclass[11pt]{meetingmins}
\usepackage[utf8]{inputenc}

\setcommittee{BugBusters}

\setmembers{

  D.~Polonio,
  D.~Rigoni,
  M.~Di Pirro,
  G.~Mazzocchin,
  L.~Bianco,
  A.~Mantovani,
  E.~Carraro
}

\setdate{April 22, 2016}

\setpresent{

  D.~Polonio,
  L.~Bianco,
  M.~Di Pirro,
  E.~Carraro,
  D.~Rigoni
}

\absent{

  G.~Mazzocchin,
  A.~Mantovani
}

\alsopresent{None}

\begin{document}

\maketitle

\section{Ordine del giorno}

\begin{enumerate}

\item Discussione su come pianificare l'organizzazione del gruppo

\item Discussione su nuova ridenominazione dei verbali

\item Discussione su l'ordine di codifica di MaaS

\end{enumerate}

\section{Orari}

\begin{itemize}
\item[Inizio]: ore 17:30
\item[Fine]: ore 18:30
\item[Tempo]: Previsto di 60 min, effettivo di 60 min

\end{itemize}

\section{Verbale}

\subsection{Discussione su come pianificare l'organizzazione del gruppo}

Si discute su come iniziare a scrivere MaaS, elencando tutti i vantaggi e gli svantaggi di diverse strategie di implementazioni. Inoltre, sono state definite le attività da svolgere e sono stati identificati i principali task.

\subsection{Discussione su nuova ridenominazione dei verbali}

Viene approvato da tutti di rinominare i verbali secondo l'identificativo suggerito in fase di correzione della Revisione di Progettazione. La rinominazione viene stabilito avere effetto retroattivo, per poter uniformare l'archivio di tutti i verbali fin'ora scritti.

\subsection{Discussione su l'ordine di codifica di MaaS}

Si discute su una possibile strategia per la codifica di MaaS, valutando attentamente svantaggi e vantaggi di eventuali scelte strategiche. Alla fine, viene deciso per sviluppare MaaS nel seguente ordine:
\begin{enumerate}

\item Backend
\item Frontend
\item Interprete
\item Editor grafico
\end{enumerate}

Con questo ordine di sviluppo sar\`a possibile ridurre al minimo il numero di \textit{stub} e \textit{driver} necessari e consentir\`a al gruppo una maggiore velocit\`a nello sviluppo. L'editor grafico viene tenuto alla fine in quanto essendo facoltativo verr\`a codificato negli ultimi tempi.

\nextmeeting{02/05/2016}

\end{document}


text:
<?php

class SpescenaTable extends Doctrine_Table
{
}


text:
(function(angular) {
    'use strict';

    angular
        .module('ui.form')
        .directive('uiFieldImagePreview', uiFieldImagePreview);

    function uiFieldImagePreview(mOxie) {

        // Return the directive configuration.
        return {
            link: link,
            restrict: 'E',
            scope: {
                image: '&'
            }
        };

        // I take the given File object (as presented by
        // Plupoload), and show the client-side-only preview of
        // the selected image object.
        function link($scope, element, attributes) {
            var image = $(new Image()).appendTo(element);

            // Create an instance of the mOxie Image object. This
            // utility object provides several means of reading in
            // and loading image data from various sources.
            // --
            // Wiki: https://github.com/moxiecode/moxie/wiki/Image
            var preloader = new mOxie.Image();

            // Define the onload BEFORE you execute the load()
            // command as load() does not execute async.
            preloader.onload = function() {

                // This will scale the image (in memory) before it
                // tries to render it. This just reduces the amount
                // of Base64 data that needs to be rendered.
                preloader.downsize(300, 300);

                // Now that the image is preloaded, grab the Base64
                // encoded data URL. This will show the image
                // without making an Network request using the
                // client-side file binary.
                image.prop('src', preloader.getAsDataURL());
            };

            // Calling the .getSource() on the file will return an
            // instance of mOxie.File, which is a unified file
            // wrapper that can be used across the various runtimes.
            // --
            // Wiki: https://github.com/moxiecode/plupload/wiki/File
            preloader.load($scope.image().getSource());
        }
    }

})(angular);


text:
using System.Collections.Generic;
using System.Linq;
using XenAdmin.Core;
using XenAdmin.Wizards.GenericPages;
using XenAPI;

namespace XenAdmin.Wizards.CrossPoolMigrateWizard.Filters
{
    internal class WlbEnabledFilter : ReasoningFilter
    {
        private readonly List<VM> preSelectedVMs;

        public WlbEnabledFilter(List<VM> preSelectedVMs) : this(null,preSelectedVMs)
        {
        }

        public WlbEnabledFilter(IXenObject item, List<VM> preSelectedVMs)
            : base(item)
        {
            this.preSelectedVMs = preSelectedVMs;
        }

        public override bool FailureFound
        {
            get
            {
                bool targetWlb = false;

                if(ItemToFilterOn != null)
                    targetWlb = Helpers.WlbEnabledAndConfigured(ItemToFilterOn.Connection);

                bool sourceWlb = preSelectedVMs.Any(vm => Helpers.WlbEnabledAndConfigured(vm.Connection));

                reason = targetWlb ? Messages.CPM_WLB_ENABLED_ON_HOST_FAILURE_REASON : Messages.CPM_WLB_ENABLED_ON_VM_FAILURE_REASON;

                return targetWlb || sourceWlb;
            }
        }

        private string reason = Messages.UNKNOWN;

        public override string Reason { get { return reason; } }
    }
}


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

package org.chromium.net.test.dummy;

/**
 * Does nothing.
 * TODO(newt): Delete after the switch to GN. This is only used in GYP.
 */
class Dummy {}


text:
package config

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func Test_GOWSConfigModel_WorkspaceForProjectLocation(t *testing.T) {

	gowsConfig := GOWSConfigModel{
		Workspaces: map[string]WorkspaceConfigModel{
			"/proj/path/1": WorkspaceConfigModel{
				WorkspaceRootPath: "/p1/ws/root",
			},
		},
	}

	t.Log("Found")
	{
		wsConfig, isFound := gowsConfig.WorkspaceForProjectLocation("/proj/path/1")
		require.Equal(t, true, isFound)
		require.Equal(t, "/p1/ws/root", wsConfig.WorkspaceRootPath)
	}

	t.Log("Not Found")
	{
		wsConfig, isFound := gowsConfig.WorkspaceForProjectLocation("/proj/path/noproj")
		require.Equal(t, false, isFound)
		require.Equal(t, "", wsConfig.WorkspaceRootPath)
	}
}


text:
/**
 * Use to indicate the type for the [ServiceMessage].
 */
export declare enum MessageType {
    /**
     * Use to indicate the message type is informational.
     */
    Information = 1,
    /**
     * Use to indicate the message type is warning.
     */
    Warning = 2,
    /**
     * Use to indicate the message type is error.
     */
    Error = 3,
}


text:
//
//  PNJSONSerialization.m
//  pubnub
//
//  This class encapsulate logic with JSON
//  serialization fallback (pre-iOS 5) and
//  handles JSONP by returning prefix falue.
//
//
//  Created by Sergey Mamontov on 12/5/12.
//
//

#import "PNJSONSerialization.h"
#import "PNLogger+Protected.h"
#import "PNLoggerSymbols.h"

// ARC check
#if !__has_feature(objc_arc)
#error PubNub JSON serializer must be built with ARC.
// You can turn on ARC for only PubNub files by adding '-fobjc-arc' to the build phase for each of its files.
#endif

#pragma mark Private interface methods

@interface PNJSONSerialization ()

#pragma mark - Class methods

/**
 * Try to retrieve callback method name from provided
 * JSON string. If method will be fetched, than this is
 * JSONP string.
 */
+ (void)getCallbackMethodName:(NSString **)callbackMethodName fromJSONString:(NSString *)jsonString;
+ (NSString *)JSONStringFromJSONPString:(NSString *)jsonpString callbackMethodName:(NSString *)callbackMethodName;

#pragma mark - Misc methods

/**
 Perform quck check on whether provided object is JSON encoded string (begins and ends with ").

 @param object
 Any object against which check should be performed

 @return \c YES if specified \a 'object' is JSON encoded string and \c NO in another case.
 */
+ (BOOL)isJSONStringObject:(id)object;
+ (BOOL)isNSJSONAvailable;
+ (BOOL)isJSONKitAvailable;

#pragma mark -

@end

#pragma mark - Public interface methods

@implementation PNJSONSerialization

#pragma mark - Class methods

+ (void)JSONObjectWithData:(NSData *)jsonData
           completionBlock:(void(^)(id result, BOOL isJSONPStyle, NSString *callbackMethodName))completionBlock
                errorBlock:(void(^)(NSError *error))errorBlock {

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    [self JSONObjectWithString:jsonString completionBlock:completionBlock errorBlock:errorBlock];
}

+ (void)JSONObjectWithString:(NSString *)jsonString
             completionBlock:(void(^)(id result, BOOL isJSONPStyle, NSString *callbackMethodName))completionBlock
                  errorBlock:(void(^)(NSError *error))errorBlock {

    id result = nil;
    __autoreleasing NSError *parsingError = nil;
    NSString *jsonCallbackMethodName = nil;
    [self getCallbackMethodName:&jsonCallbackMethodName fromJSONString:jsonString];

    // Check whether callback name was found in JSON string or not
    if(jsonCallbackMethodName != nil) {

        jsonString = [self JSONStringFromJSONPString:jsonString callbackMethodName:jsonCallbackMethodName];
    }

    // Check whether passed string is non-object
    if ([self isJSONStringObject:jsonString]) {

        result = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
    }
    else {

        // Checking whether native JSONSerializer is available or not
        if ([self isNSJSONAvailable]) {

            result = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
                                                     options:NSJSONReadingAllowFragments
                                                       error:&parsingError];
        }
        // Fallback to JSONKit usage
        else if ([self isJSONKitAvailable]) {

            NSData *dataForDeserialization = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
            SEL jsonKitSelector = NSSelectorFromString(@"objectFromJSONDataWithParseOptions:error:");
            NSMethodSignature *jsonKitMethod = [NSData instanceMethodSignatureForSelector:jsonKitSelector];
            NSInvocation *deserializationInvocation = [NSInvocation invocationWithMethodSignature:jsonKitMethod];
            [deserializationInvocation setSelector:jsonKitSelector];
            [deserializationInvocation setTarget:dataForDeserialization];

            NSUInteger parseOption = 0;
            __autoreleasing NSError **parsingErrorForInvocation = &parsingError;
            __unsafe_unretained id invocationResult;
            [deserializationInvocation setArgument:&parseOption atIndex:2];
            [deserializationInvocation setArgument:&parsingErrorForInvocation atIndex:3];
            [deserializationInvocation invoke];
            [deserializationInvocation getReturnValue:&invocationResult];

            result = invocationResult;
        }
        else {

            [NSException raise:@"JSON serialization library"
                        format:@"There is no JSON serialization library available. If you are targeting 4.3+ versions, "
             "please make sure to read 'How-to' on JSONKit addition"];
        }
    }

    // Checking whether parsing was successful or not
    if (result && parsingError == nil) {

        if(completionBlock) {

            completionBlock(result, jsonCallbackMethodName!=nil, jsonCallbackMethodName);
        }
    }
    else if(parsingError != nil){

        if (errorBlock) {

            errorBlock(parsingError);
        }
    }
}

+ (NSString *)stringFromJSONObject:(id)object {

    NSString *JSONString = nil;
    if (![self isJSONString:object]) {

        if ([self isNSJSONAvailable]) {

            if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {

                NSError *serializationError = nil;
                NSData *JSONSerializedObject = [NSJSONSerialization dataWithJSONObject:object
                                                                               options:(NSJSONWritingOptions)0
                                                                                error:&serializationError];
                JSONString = [[NSString alloc] initWithData:JSONSerializedObject encoding:NSUTF8StringEncoding];
            }
            else if ([object isKindOfClass:[NSNumber class]]) {

                JSONString = [(NSNumber *)object stringValue];
            }
            else {

                JSONString = [NSString stringWithFormat:@"\"%@\"", object];
            }
        }
        else if ([self isJSONKitAvailable]) {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            JSONString = [object performSelector:NSSelectorFromString(@"JSONString")];
#pragma clang diagnostic pop
        }
        else {

            [NSException raise:@"JSON serialization library"
                        format:@"There is no JSON serialization library available. If you are targeting 4.3+ versions, "
                                "please make sure to read 'How-to' on JSONKit addition"];
        }
    }
    else {

        JSONString = object;
    }

    // Replace null value has been passed or not (serialized [NSNull null] value)
	if ([JSONString respondsToSelector:@selector(stringByReplacingOccurrencesOfString:withString:)]) {

		JSONString = [JSONString stringByReplacingOccurrencesOfString:@":null" withString:@":\"null\""];
	}

    return JSONString;
}

+ (void)getCallbackMethodName:(NSString **)callbackMethodName fromJSONString:(NSString *)jsonString {

    if (jsonString) {

        // Checking whether there are parenthesis in JSON
        NSRange parenthesisRange = [jsonString rangeOfString:@"("];
        if (parenthesisRange.location != NSNotFound &&
                ([jsonString characterAtIndex:(parenthesisRange.location+parenthesisRange.length)] == '[' ||
                        [jsonString characterAtIndex:(parenthesisRange.location+parenthesisRange.length)] == '{')) {

            NSScanner *scanner = [NSScanner scannerWithString:jsonString];
            [scanner scanUpToString:@"(" intoString:callbackMethodName];
        }
    }
    else {

        [PNLogger logGeneralMessageFrom:self withParametersFromBlock:^NSArray *{

            return @[PNLoggerSymbols.JSONserializer.emptyJSONString];
        }];
    }
}

+ (NSString *)JSONStringFromJSONPString:(NSString *)jsonpString callbackMethodName:(NSString *)callbackMethodName {

    NSScanner *scanner = [NSScanner scannerWithString:jsonpString];
    [scanner scanUpToString:@"(" intoString:NULL];

    NSString *JSONWrappedInParens = [[scanner string] substringFromIndex:[scanner scanLocation]];
    NSCharacterSet *parens = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"%@();",
                                                                                callbackMethodName?callbackMethodName:@""]];

    return [JSONWrappedInParens stringByTrimmingCharactersInSet:parens];
}

#pragma mark - Misc methods

+ (BOOL)isJSONString:(id)object {

    BOOL isJSONString = [object isKindOfClass:[NSNumber class]];
    if ([object isKindOfClass:[NSString class]] && [(NSString *)object length] > 0) {

        unichar expectedCloseingChar;
        unichar nodeStartChar = [(NSString *)object characterAtIndex:0];
        unichar nodeClosingChar = [(NSString *)object characterAtIndex:([(NSString *)object length] - 1)];
        isJSONString = (nodeStartChar == '"' || nodeStartChar == '[' || nodeStartChar == '{');
        if (isJSONString) {

            expectedCloseingChar = (nodeStartChar == '"' ? '"' : (nodeStartChar == '[' ? ']' : '}'));
            isJSONString = (nodeClosingChar == expectedCloseingChar);
        }
    }

    return isJSONString;
}

+ (BOOL)isJSONStringObject:(id)object {

    BOOL isJSONStringObject = [object isKindOfClass:[NSString class]];
    if (isJSONStringObject && [(NSString *)object length] > 0) {

        unichar nodeStartChar = [(NSString *)object characterAtIndex:0];
        unichar nodeClosingChar = [(NSString *)object characterAtIndex:([(NSString *)object length] - 1)];

        isJSONStringObject = nodeStartChar == '"' && nodeClosingChar == '"';
    }

    return isJSONStringObject;
}

+ (BOOL)isNSJSONAvailable {

    static BOOL isNSJSONAvailable;
    static dispatch_once_t isNSJSONAvailableToken;
    dispatch_once(&isNSJSONAvailableToken, ^{

        isNSJSONAvailable = NSClassFromString(@"NSJSONSerialization") != nil;
    });

    return isNSJSONAvailable;
}

+ (BOOL)isJSONKitAvailable {

    static BOOL isJSONKitAvailable;
    static dispatch_once_t isJSONKitAvailableToken;
    dispatch_once(&isJSONKitAvailableToken, ^{

        isJSONKitAvailable = [@"" respondsToSelector:NSSelectorFromString(@"JSONString")];
    });

    return isJSONKitAvailable;
}

#pragma mark -

@end


text:
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, /*hashHistory,*/ browserHistory, IndexRoute} from 'react-router'
import App from './components/App';
import Welcome from './components/Welcome';
import Home from './components/Home';
import Party from './components/Party'
import OL from './components/OL'
import Vacation from './components/Vacation';
import Designer from './components/Designer';
import About from './components/About';
import Detail from './components/Detail'

import 'imports?jQuery=jquery!bootstrap/dist/js/bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import './assets/styles/index.css';

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Welcome}/>
      <Route path="/home" component={Home}/>
      <Route path="/party" component={Party}/>
      <Route path="/ol" component={OL}/>
      <Route path="/vacation" component={Vacation}/>
      <Route path="/designer" component={Designer}/>
      <Route path="/about" component={About}/>
      <Route path="/detail" component={Detail}/>
    </Route>
  </Router>
), document.getElementById('root'));


text:
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using FarseerPhysics.Factories;
using FarseerPhysics.DebugViews;
using AutonomousCar.PathFinding;
using AutonomousCar.Entities;
using AutonomousCar.Helpers;
using AutonomousCar.PathFinding.ReedsShepp;
using AutonomousCar.PathFinding.Algorithms;
using AutonomousCar.PathFollowing;
using C5;
using XNAGameConsole;

namespace AutonomousCar.Simulation
{
    public class AutonomousCarSimulation : Game
    {
        private const string missionFile = @"c:\mtsuparking.json";
        private const string expFile = @"c:\parkingexp.txt";

        private const float CAMERA_FOV = 90.0f;
        private const float CAMERA_ZNEAR = 0.01f;
        private const float CAMERA_ZFAR = 1000.0f;
        private const float CAMERA_OFFSET = 0.0f;

        private const int WINDOWED_WIDTH = 1024;
        private const int WINDOWED_HEIGHT = 768;

        private static Color LIGHT = Color.White;
        private static Color DARK = new Color(0x22, 0x22, 0x22);

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont font;
        DebugViewXNA debug;
        BasicEffect basicEffect;
        World world;
        Car car;
        Camera2 camera;
        Dashboard dashboard;
        Random r;
        KeyboardState currKeyboard, prevKeyboard;
        GameConsole console;
        Thread bg;
        bool gridDone,
            pathDone,
            pathSmoothDone,
            pathSearching,
            pathSearchingDone,
            run,
            isCollided;

        float gas = 0, steer = 0, brake = 0;

        float scale = 4.8f,
            xOffset = 75f,
            yOffset = 75f;

        bool rotateCar = false,
            autoDrive = true,
            watchSearch = false,
            drawGrid = false,
            drawVoro = false,
            drawSearch = false,
            drawPath = false,
            drawFrontPath = false,
            drawSmoothedPath = false,
            drawController = true,
            drawStart = false,
            drawGoal = true,
            drawCurrent = true,
            drawCar = false,
            smoothing = true,
            backgroundLight = false,
            showDebugInfo = true,
            showDashboard = true;

        int cameraView = 1;

        ObstacleGrid grid;
        Pose startPose, goalPose;
        ArrayList<Pose> poses, smoothedPath;
        HybridAStarResults astar;
        StanleyFSMController controller;
        CarControls currentControls;

        public delegate void CarCollisionEvent(object sender, EventArgs e);
        public delegate void MissionCompleteEvent(object sender, ControllerInfo e);
        public event CarCollisionEvent Collided;
        public event MissionCompleteEvent MissionCompleted;

        public AutonomousCarSimulation()
        {
            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";
            r = new Random();

            Components.Add(new FrameRateCounter(this));
        }

        protected override void Initialize()
        {
            graphics.PreferMultiSampling = true;
            graphics.PreferredBackBufferWidth = WINDOWED_WIDTH;
            graphics.PreferredBackBufferHeight = WINDOWED_HEIGHT;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();

            spriteBatch = new SpriteBatch(GraphicsDevice);
            console = new GameConsole(this, spriteBatch, new GameConsoleOptions()
            {
                OpenOnWrite = false,
                Prompt = ">",
                Height = 500,
                ToggleKey = Keys.Escape
            });

            console.AddCommand("antialias",
                args =>
                {
                    graphics.PreferMultiSampling = !graphics.PreferMultiSampling;
                    graphics.ApplyChanges();
                    return "Antialias " + (graphics.PreferMultiSampling ? "on" : "off");
                }, "Toggles antialias");

            console.AddCommand("debug",
                 args =>
                 {
                     showDebugInfo = !showDebugInfo;
                     return "Debug " + (showDebugInfo ? "on" : "off");
                 }, "Toggles the debug info");

            console.AddCommand("dashboard",
                 args =>
                 {
                     showDashboard = !showDashboard;
                     return "Dashboard " + (showDashboard ? "on" : "off");
                 }, "Toggles the dashboard");

            console.AddCommand("param",
                args =>
                {
                    if (args.Length < 1) return "";

                    switch (args[0].ToLower())
                    {
                        case "smoother":
                            return Smoother.HandleParamCommand(args);
                        default:
                            return "";
                    }
                }, "Prints or updates parameters");

            console.AddCommand("smooth",
                args =>
                {
                    if (pathSmoothDone)
                    {
                        bg = new Thread(() =>
                            {
                                DateTime now = DateTime.Now;
                                smoothedPath = Smoother.Smooth(astar.Path, grid);
                                int numUnsafe = Smoother.UnsafeIndices != null ? Smoother.UnsafeIndices.Count : 0;
                                console.WriteLine("Smoothing Time: " + Math.Round((DateTime.Now - now).TotalMilliseconds) + " ms (" + Smoother.NumIterations + " iterations, " + Smoother.Change + "m, " + numUnsafe + " unsafe points)");
                                controller = new StanleyFSMController(smoothedPath, goalPose);
                            });
                        bg.IsBackground = true;
                        bg.Priority = ThreadPriority.Lowest;
                        bg.Start();
                    }

                    return "";
                }, "Smooths the path using the current parameters");

            console.AddCommand("smoothing",
                args =>
                {
                    smoothing = !smoothing;
                    return "Smoothing " + (smoothing ? "on" : "off");
                }, "Toggles smoothing"
            );

            dashboard = new Dashboard(this);
            world = new World(Vector2.Zero);

            //new SmootherExperiment(this, expFile, 100);
            new ParkingExperiment(this, world, expFile);
            //InitSim(false);

            base.Initialize();
        }

        public void InitSim(bool autoStart)
        {
            InitSim(autoStart, smoothing, MissionLoader.LoadFromJson(missionFile, world));
        }

        public void InitSim(bool autoStart, bool smoothingOn)
        {
            InitSim(autoStart, smoothingOn, MissionLoader.LoadFromJson(missionFile, world));
        }

        public void InitSim(bool autoStart, bool smoothingOn, Mission mission)
        {
            gridDone = false;
            pathDone = false;
            pathSmoothDone = false;
            pathSearching = false;
            pathSearchingDone = false;
            autoDrive = true;
            run = false;
            isCollided = false;
            currentControls = new CarControls(0f, 0f, 0f);

            if (camera == null)
            {
                camera = new Camera2(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000f);
                camera.Position = new Vector3(75f, 75f, 180f);
            }

            startPose = mission.Start;
            goalPose = mission.Goal;
            HybridAStar.Epsilon = mission.AStarEpsilon;
            HybridAStar.GridResolution = mission.AStarGridResolution;
            HybridAStar.SafetyFactor = 1.5f;
            HybridAStar.Reset();

            car = new Car(world, startPose);
            grid = new ObstacleGrid(world, mission.Environment);

            car.Body.OnCollision += new OnCollisionEventHandler(OnCollision);

            gridDone = false;
            pathDone = false;
            pathSearchingDone = false;
            bg = new Thread(() =>
            {
                DateTime now = DateTime.Now;
                grid.BuildGVD();
                console.WriteLine("GVD Generation Time: " + Math.Round((DateTime.Now - now).TotalMilliseconds) + " ms");
                gridDone = true;

                now = DateTime.Now;
                pathSearching = true;
                astar = HybridAStar.FindPath(grid, startPose, goalPose);
                TimeSpan astarTime = DateTime.Now - now;
                poses = astar.Path;

                pathSearching = false;
                pathSearchingDone = true;

                if (astar.Path.Count > 0)
                    pathDone = true;

                now = DateTime.Now;
                if (smoothingOn)
                    smoothedPath = Smoother.Smooth(astar.Path, grid);
                else
                    smoothedPath = astar.Path;
                TimeSpan smoothingTime = DateTime.Now - now;

                int numUnsafe = Smoother.UnsafeIndices != null ? Smoother.UnsafeIndices.Count : 0;

                console.WriteLine("A*: Total Planning Time: " + Math.Round((astarTime + smoothingTime).TotalMilliseconds) + " ms");
                console.WriteLine("         Heuristic Time: " + Math.Round(astar.HeuristicInitTime.TotalMilliseconds) + " ms");
                console.WriteLine("         Searching Time: " + Math.Round((astarTime - astar.HeuristicInitTime).TotalMilliseconds) + " ms");
                console.WriteLine("         Smoothing Time: " + Math.Round(smoothingTime.TotalMilliseconds) + " ms (" + Smoother.NumIterations + " iterations, " + Smoother.Change + "m, " + numUnsafe + " unsafe points)");
                console.WriteLine("    " + astar.Discovered.Count + " nodes discovered");
                console.WriteLine("    " + astar.Expanded.Count + " nodes expanded");

                controller = new StanleyFSMController(smoothedPath, goalPose);

                pathSmoothDone = true;
                if (autoStart)
                    run = true;
            });
            bg.IsBackground = true;
            bg.Priority = ThreadPriority.Lowest;
            bg.Start();
        }

        public void ClearWorld()
        {
            if (world != null)
                world.Clear();
        }

        public bool OnCollision(Fixture fixtureA, Fixture fixtureB, Contact contact)
        {
            isCollided = true;
            return true;
        }

        protected override void LoadContent()
        {
            RasterizerState rs = new RasterizerState();
            rs.CullMode = CullMode.None;
            GraphicsDevice.RasterizerState = rs;
            font = Content.Load<SpriteFont>("font");

            car.LoadContent(Content);
            basicEffect = new BasicEffect(GraphicsDevice)
            {
                TextureEnabled = true,
                VertexColorEnabled = true,
            };

            debug = new DebugViewXNA(world);
            debug.LoadContent(GraphicsDevice, Content);

            dashboard.LoadContent(Content);
        }

        private void toggleFullscreen()
        {
            if (graphics.IsFullScreen)
            {
                graphics.PreferredBackBufferWidth = WINDOWED_WIDTH;
                graphics.PreferredBackBufferHeight = WINDOWED_HEIGHT;
                graphics.IsFullScreen = false;
            }
            else
            {
                graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width;
                graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height;
                graphics.IsFullScreen = true;
            }

            graphics.ApplyChanges();
            camera.AspectRatio = (float)graphics.PreferredBackBufferWidth / graphics.PreferredBackBufferHeight;
        }

        protected override void Update(GameTime gameTime)
        {
            currKeyboard = Keyboard.GetState();

            if (currKeyboard.IsKeyDown(Keys.Escape) && currKeyboard.IsKeyDown(Keys.LeftShift))
                this.Exit();

            if (!console.Opened)
            {
                camera.HandleInput();

                // View options
                if (keyPressed(Keys.F11))
                    toggleFullscreen();
                if (keyPressed(Keys.F12))
                    backgroundLight = !backgroundLight;
                if (keyPressed(Keys.C))
                    drawCar = !drawCar;
                if (keyPressed(Keys.R))
                    rotateCar = !rotateCar;
                if (keyPressed(Keys.G))
                    drawGrid = !drawGrid;
                if (keyPressed(Keys.V))
                    drawVoro = !drawVoro;
                if (keyPressed(Keys.B))
                    if (currKeyboard.IsKeyDown(Keys.LeftShift) || currKeyboard.IsKeyDown(Keys.RightShift))
                        watchSearch = !watchSearch;
                    else
                        drawSearch = !drawSearch;
                if (keyPressed(Keys.P))
                    drawPath = !drawPath;
                if (keyPressed(Keys.L))
                {
                    drawSmoothedPath = !drawSmoothedPath;
                    drawController = false;
                }
                if (keyPressed(Keys.O))
                {
                    drawController = !drawController;
                    drawSmoothedPath = false;
                }
                if (keyPressed(Keys.F))
                    drawFrontPath = !drawFrontPath;
                if (keyPressed(Keys.Home))
                    drawStart = !drawStart;
                if (keyPressed(Keys.End))
                    drawGoal = !drawGoal;
                if (keyPressed(Keys.Scroll))
                    drawCurrent = !drawCurrent;

                // Zoom
                if (currKeyboard.IsKeyDown(Keys.OemPlus))
                    scale *= 1.02f;
                if (currKeyboard.IsKeyDown(Keys.OemMinus))
                    scale *= 0.98f;

                // Translate
                if (currKeyboard.IsKeyDown(Keys.Up))
                    yOffset += 5f / scale;
                if (currKeyboard.IsKeyDown(Keys.Down))
                    yOffset -= 5f / scale;
                if (currKeyboard.IsKeyDown(Keys.Right))
                    xOffset += 5f / scale;
                if (currKeyboard.IsKeyDown(Keys.Left))
                    xOffset -= 5f / scale;

                if (currKeyboard.IsKeyDown(Keys.W))
                    gas = 1;
                else if (currKeyboard.IsKeyDown(Keys.S))
                    gas = -1;
                else
                    gas = 0;

                if (currKeyboard.IsKeyDown(Keys.D))
                    steer = -1;
                else if (currKeyboard.IsKeyDown(Keys.A))
                    steer = 1;
                else
                    steer = 0;

                if (currKeyboard.IsKeyDown(Keys.Space))
                    brake = 1;
                else
                    brake = 0;

                if (gas != 0 || brake != 0 || steer != 0)
                    autoDrive = false;

                if (currKeyboard.IsKeyDown(Keys.Enter) && pathSmoothDone)
                    run = true;

                // Camera views
                if (keyPressed(Keys.D1))
                    cameraView = 1;
                if (keyPressed(Keys.D2))
                    cameraView = 2;
                if (keyPressed(Keys.D3))
                    cameraView = 3;
                if (keyPressed(Keys.D4))
                    cameraView = 4;
                if (keyPressed(Keys.D5))
                    cameraView = 5;

                if (keyPressed(Keys.D0))
                {
                    ClearWorld();
                    InitSim(false);
                }
            }

            prevKeyboard = currKeyboard;

            if (autoDrive)
            {
                if (run)
                {
                    currentControls = controller.Update(car.Pose, car.WheelAngle, car.SpeedMetersPerSecond, gameTime);
                    car.Update(currentControls);
                }
            }
            else
            {
                currentControls = new CarControls(gas, brake, steer);
                car.Update(new CarControls(gas, brake, steer));
            }

            if (run && controller.State == StanleyFSMController.ControllerState.MissionComplete && MissionCompleted != null)
                MissionCompleted(this, controller.Info);

            world.Step((float)gameTime.ElapsedGameTime.TotalSeconds);
            dashboard.Update(car.WheelAngle, currentControls.Gas, currentControls.Brake, car.SpeedMPH);

            if (isCollided && Collided != null)
                Collided(this, null);

            base.Update(gameTime);
        }

        private bool keyPressed(Keys key)
        {
            return currKeyboard.IsKeyDown(key) && prevKeyboard.IsKeyUp(key);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(backgroundLight ? LIGHT : DARK);

            Matrix p = camera.Projection;
            Matrix v = camera.View;

            if (cameraView == 2)
            {
                Vector2 headingVector = new Vector2((float)Math.Cos(car.Pose.Orientation), (float)Math.Sin(car.Pose.Orientation));
                v = Matrix.CreateLookAt(new Vector3(car.Pose.Position + -10f * headingVector, 8f), new Vector3(car.Pose.Position + 10f * headingVector, 0f), Vector3.UnitZ);
            }
            else if (cameraView == 3)
            {
                float or = car.Pose.Orientation + MathHelper.ToRadians(120f);
                Vector2 headingVector = new Vector2((float)Math.Cos(or), (float)Math.Sin(or));
                v = Matrix.CreateLookAt(new Vector3(car.Pose.Position + -10f * headingVector, 5f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitZ);
            }
            else if (cameraView == 4)
            {
                float or = goalPose.Orientation;
                Vector2 headingVector = new Vector2((float)Math.Cos(or), (float)Math.Sin(or));
                v = Matrix.CreateLookAt(new Vector3(goalPose.Position + 10f * headingVector, 20f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitZ);
            }
            else if (cameraView == 5)
            {
                v = Matrix.CreateLookAt(new Vector3(Car.GetCenterPosition(car.Pose), 20f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitY);
                if (rotateCar)
                    v *= Matrix.CreateRotationZ(-car.Body.Rotation + MathHelper.PiOver2);
            }

            if (gridDone && drawGrid)
            {
                basicEffect.World = Matrix.Identity;
                basicEffect.View = v;
                basicEffect.Projection = p;
                spriteBatch.Begin(0, null, SamplerState.PointClamp, DepthStencilState.DepthRead, RasterizerState.CullNone, basicEffect);
                grid.Draw(spriteBatch, drawVoro);
                HybridAStar.Draw(spriteBatch);
                spriteBatch.End();
            }

            debug.BeginCustomDraw(ref p, ref v);

            debug.DrawSolidCircle(Car.GetFrontAxlePosition(car.Pose), 0.2f, Color.Green);

            if ((pathSearching && watchSearch || pathSearchingDone && drawSearch) && HybridAStar.Expanded != null && HybridAStar.Expanded.Count > 0)
            {
                LinkedList<HybridAStar.Node> expanded = new LinkedList<HybridAStar.Node>();
                lock (HybridAStar.Expanded)
                {
                    expanded.AddAll(HybridAStar.Expanded);
                    Thread.Sleep(30);
                }

                float pathLength = expanded.Last.f;
                foreach (HybridAStar.Node n in expanded)
                {
                    if (pathDone && n.rsIndex >= 0)
                    {
                        for (int i = n.rsIndex; i < poses.Count - 1; i++)
                            debug.DrawSegment(poses[i].Position, poses[i + 1].Position, Color.Purple, 0.02f);
                    }
                    else if (n.from != null)
                    {
                        Color color;
                        if (n.cell.rev == 0)
                            color = Color.Lerp(Color.Orange, Color.Green, n.g / pathLength);
                        else
                            color = Color.Lerp(Color.Blue, Color.Cyan, n.g / pathLength);

                        debug.DrawSegment(n.from.pose.Position, n.pose.Position, color, 0.02f);
                    }
                }
            }

            if (pathDone)
            {
                if (drawPath)
                {
                    for (int i = 0; i < poses.Count - 1; i++)
                    {
                        Color c = poses[i].Gear == Gear.Forward ? Color.Blue : Color.Red;
                        debug.DrawSegment(poses[i].Position, poses[i + 1].Position, c, 0.04f);
                        debug.DrawPoint(poses[i].Position, 0.1f, c * 0.5f);
                    }
                }
            }

            if (pathSmoothDone)
            {
                if (drawFrontPath && controller.FrontPath != null)
                {
                    int num = controller.FrontPath.Count;
                    for (int i = 0; i < num - 1; i++)
                    {
                        if (controller.FrontPath[i].Gear == Gear.Forward)
                            debug.DrawSegment(controller.FrontPath[i].Position, controller.FrontPath[i + 1].Position, Color.DarkOrange);
                        else
                            debug.DrawSegment(controller.ReverseFrontPath[i].Position, controller.ReverseFrontPath[i + 1].Position, Color.Cyan);
                    }
                }

                if (drawSmoothedPath)
                {
                    for (int i = 0; i < smoothedPath.Count - 1; i++)
                    {
                        debug.DrawSegment(smoothedPath[i].Position, smoothedPath[i + 1].Position, smoothedPath[i].Gear == Gear.Forward ? Color.DarkGreen : Color.Red, 0.04f);
                        if (Smoother.UnsafeIndices != null && Smoother.UnsafeIndices.Contains(i))
                            debug.DrawCircle(smoothedPath[i].Position, 0.2f, Color.Orange);
                    }
                }

                if (drawController)
                    controller.Draw(debug);
            }

            if (drawStart)
                startPose.DrawPose(debug, new Color(0f, 1f, 0f, 0.9f), 1.1f);
            if (drawGoal)
                goalPose.DrawPose(debug, new Color(1f, 0f, 0f, 0.9f), 1.1f);

            if (drawCurrent)
            {
                if (pathSmoothDone && controller.State != StanleyFSMController.ControllerState.MissionComplete)
                {
                    debug.DrawCircle(controller.ClosestPoint, 0.1f, controller.InReverse ? Color.Aqua : Color.Orange);
                    if (controller.InReverse) debug.DrawCircle(controller.FakeFrontAxle, 0.2f, Color.Aqua);
                }

                car.Pose.DrawPose(debug, 0.2f, Color.Red);
            }

            debug.EndCustomDraw();
            debug.RenderDebugData(ref p, ref v);

            if (drawCar)
                car.Draw(v, p);

            if (showDebugInfo)
            {
                string info = String.Format("Speed: {0:0.0}", Math.Round(car.SpeedMPH, 1));
                if (pathSmoothDone)
                {
                    info += String.Format("\nGas: {0:0.00}", Math.Round(currentControls.Gas * 100f, 2));
                    info += String.Format("\nBrake: {0:0.00}", Math.Round(currentControls.Brake * 100f, 2));
                    info += String.Format("\nCTE: {0:0.0000}", Math.Round(controller.CrossTrackError, 4));
                    info += "\n" + controller.State.ToString();
                    info += "\n" + controller.DebugInfo;
                }
                spriteBatch.Begin();
                spriteBatch.DrawString(font, info, new Vector2(8, 4), !backgroundLight ? LIGHT : DARK);
                spriteBatch.End();
            }

            if (showDashboard)
                dashboard.Draw(gameTime);

            base.Draw(gameTime);
        }
    }
}


text:
<?php

abstract class BaseSearch {

	protected $searchDone = false;

	protected $className = null;

	protected $results = array();

	public function  __construct() {

	}

	protected $currentPage = null;
	protected $numberOnAPage = null;
	protected $resultsTotalPages = null;
	protected $totalResultsWithOutPaging = null;

	/** Paging is turned off unless this is called.
	 * Note not all Search classes can do Paging yet.
	**/
	public function setPaging($currentPage=1, $numberOnAPage=20) {
		if ($this->searchDone) throw new Exception("Search already done!");
		if ($currentPage < 1) $currentPage = 1;
		$this->currentPage = $currentPage;
		$this->numberOnAPage = $numberOnAPage;
		return $this;
	}

	public function nextResult() {
		if (!$this->searchDone) $this->execute();
		$d = array_shift($this->results);
		return $d ? new $this->className($d) : null;
	}

	/** @return Integer the number of results  **/
	public function num() {
		if (!$this->searchDone) $this->execute();
		return count($this->results);
	}

	public function getAllResults() {
		$out = array();
		while($r = $this->nextResult()) $out[] = $r;
		return $out;
	}

	public function getAllResultsIndexed() {
		$out = array();
		while($r = $this->nextResult()) $out[$r->getId()] = $r;
		return $out;
	}

	public function getCurrentPage() {
		return $this->currentPage ? $this->currentPage : 1;
	}
	public function getTotalPages() {
		if (!$this->searchDone) $this->execute();
		return $this->resultsTotalPages ? $this->resultsTotalPages : 1;
	}

	public function numOnAllPages() {
		if (!$this->searchDone) $this->execute();
		return $this->totalResultsWithOutPaging;
	}

}


text:
package org.bitcoins.core.script

import org.bitcoins.core.script.arithmetic.OP_1ADD
import org.bitcoins.core.script.bitwise.OP_EQUAL
import org.bitcoins.core.script.constant._
import org.bitcoins.core.script.control.OP_IF
import org.bitcoins.core.script.crypto.OP_RIPEMD160
import org.bitcoins.core.script.locktime.OP_CHECKLOCKTIMEVERIFY
import org.bitcoins.core.script.splice.OP_SUBSTR
import org.bitcoins.core.script.stack.OP_TOALTSTACK
import org.bitcoins.core.util.{ BitcoinSUtil }
import org.scalatest.{ FlatSpec, MustMatchers }

/**
 * Created by chris on 1/9/16.
 */
class ScriptOperationFactoryTest extends FlatSpec with MustMatchers {

  "ScriptOperationFactory" must "match operations with their byte representation" in {

    ScriptOperation(0x00.toByte) must be(Some(OP_0))
    ScriptOperation(0x51.toByte) must be(Some(OP_1))

    ScriptOperation(0x63.toByte) must be(Some(OP_IF))
    ScriptOperation(0x6b.toByte) must be(Some(OP_TOALTSTACK))

    ScriptOperation(135.toByte) must be(Some(OP_EQUAL))

    ScriptOperation(139.toByte) must be(Some(OP_1ADD))

    ScriptOperation(166.toByte) must be(Some(OP_RIPEMD160))
    ScriptOperation(177.toByte) must be(Some(OP_CHECKLOCKTIMEVERIFY))

  }

  it must "find OP_4 from it's byte representation" in {
    val byteRepresentation = BitcoinSUtil.decodeHex("54").head
    ScriptOperation(byteRepresentation) must be(Some(OP_4))
  }

  it must "find a byte to push onto stack from its byte representation" in {
    val result = ScriptOperation(2.toByte)
    result.isDefined must be(true)
    result.get must be(BytesToPushOntoStack(2))
  }

  it must "find a script number from its hex representation" in {
    val result = ScriptOperation("02")
    result.isDefined must be(true)
    result.get must be(BytesToPushOntoStack(2))
  }

  it must "find undefined op codes" in {
    val result = ScriptOperation("ba")
    result.isDefined must be(true)
  }

  it must "find a splice operation from it's hex representation" in {
    val spliceOperation = ScriptOperation("7F")
    spliceOperation.isDefined must be(true)
    spliceOperation.get must be(OP_SUBSTR)
  }

  it must "find OP_1NEGATE from its hex representation" in {
    val negateOperation = ScriptOperation("4f")
    negateOperation.isDefined must be(true)
    negateOperation.get must be(OP_1NEGATE)
  }

}


text:
package ru.ivi.mapping.value;

public interface TokenizedEnum<E extends Enum<E>> {
	String getToken();

	E getDefault();
}


text:
An anagram is a rearrangement of letters to form a new word.
Given a word and a list of candidates, select the sublist of anagrams of the given word.

Given `"listen"` and a list of candidates like `"enlists" "google"
"inlets" "banana"` the program should return a list containing
`"inlets"`.

Run the tests with:

```bash
bats anagram_test.sh
```

After the first test(s) pass, continue by commenting out or removing the
`[[ $BATS_RUN_SKIPPED == true ]] || skip`
annotations prepending other tests.

To run all tests, including the ones with `skip` annotations, run:

```bash
BATS_RUN_SKIPPED=true bats anagram_test.sh
```

## Source

Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup)

## External utilities
`Bash` is a language to write "scripts" -- programs that can call
external tools, such as
[`sed`](https://www.gnu.org/software/sed/),
[`awk`](https://www.gnu.org/software/gawk/),
[`date`](https://www.gnu.org/software/coreutils/manual/html_node/date-invocation.html)
and even programs written in other programming languages,
like [`Python`](https://www.python.org/).
This track does not restrict the usage of these utilities, and as long
as your solution is portable between systems and does not require
installation of third party applications, feel free to use them to solve
the exercise.

For an extra challenge, if you would like to have a better understanding
of the language, try to re-implement the solution in pure `Bash`,
without using any external tools. Note that there are some types of
problems that bash cannot solve, such as performing floating point
arithmetic and manipulating dates: for those, you must call out to an
external tool.

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others
have completed the exercise.