text:
<!DOCTYPE html>
<html class="no-js" lang="en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<head>
    <meta charset="utf-8">

    {{ partial "meta.html" . }}

    <base href="{{ .Site.BaseUrl }}">
    <title> {{ .Title }} </title>
    <link rel="canonical" href="{{ .Permalink }}">
    {{ if .RSSlink }}<link href="{{ .RSSlink }}" rel="alternate" type="application/rss+xml" title="{{ .Title }}" />{{ end }}

    {{ partial "head_includes.html" . }}
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
</head>


text:
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.integration_test_example">

    <!-- ${applicationName} is used by the Flutter tool to select the Application
         class to use. For most apps, this is the default Android application.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         Application and put your custom class here. -->
    <application
        android:name="${applicationName}"
        android:label="integration_test_example"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name="io.flutter.embedding.android.FlutterActivity"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data android:name="flutterEmbedding" android:value="2"/>
    </application>
</manifest>

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 14: 150 (1916)

#### Original name
Diplodina cylindrospora Bubák

### Remarks
null


text:
using System.Collections.Generic;

namespace Mkko.EventDefinition
{
    /// <summary>
    /// provides functionality to transform a single element in a log file into a log event
    /// </summary>
    public interface IEventParser
    {
        /// <summary>
        /// returns any events defined for a given <c>LogElement</c>
        /// </summary>
        /// <param name="element">a single <c>LogElement</c> of a log file</param>
        /// <param name="events">contains a list of <c>LogEvent</c>s found in the provided <c>LogElement</c></param>
        /// <remarks>is an <c>out</c> parameter</remarks>
        /// <returns><c>true</c> if a provided <c>LogElement</c> matches any event definition or false otherwise</returns>
        bool GetEvent(LogElement element, out List<LogEvent> events);
    }
}


text:
<?php

namespace Phpillip\Console\Model;

use Phpillip\Routing\Route;
use Silex\Application;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * Static site builder
 */
class Builder
{
    /**
     * Application
     *
     * @var Application
     */
    protected $app;

    /**
     * Path to build route to
     *
     * @var string
     */
    protected $destination;

    /**
     * File system
     *
     * @var FileSystem
     */
    protected $files;

    /**
     * Constructor
     *
     * @param Application $app
     * @param string $destination
     */
    public function __construct(Application $app, $destination)
    {
        $this->app         = $app;
        $this->destination = $destination;
        $this->files       = new Filesystem();
    }

    /**
     * Clear destination folder
     */
    public function clear()
    {
        if ($this->files->exists($this->destination)) {
            $this->files->remove($this->destination);
        }

        $this->files->mkdir($this->destination);
    }

    /**
     * Dump the given Route into a file
     *
     * @param Route $route
     * @param string $name
     * @param array $parameters
     */
    public function build(Route $route, $name, array $parameters = [])
    {
        $url      = $this->app['url_generator']->generate($name, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
        $request  = Request::create($url, 'GET', array_merge(['_format' => $route->getFormat()], $parameters));
        $response = $this->app->handle($request);

        $this->write(
            $this->getFilePath($route, $parameters),
            $response->getContent(),
            $request->getFormat($response->headers->get('Content-Type')),
            $route->getFileName()
        );
    }

    /**
     * Write a file
     *
     * @param string $path The directory to put the file in (in the current destination)
     * @param string $content The file content
     * @param string $filename The file name
     * @param string $extension The file extension
     */
    public function write($path, $content, $extension = 'html', $filename = 'index')
    {
        $directory = sprintf('%s/%s', $this->destination, trim($path, '/'));
        $file      = sprintf('%s.%s', $filename, $extension);

        if (!$this->files->exists($directory)) {
            $this->files->mkdir($directory);
        }

        $this->files->dumpFile(sprintf('%s/%s', $directory, $file), $content);
    }

    /**
     * Get destination file path for the given route / parameters
     *
     * @param Route $route
     * @param array $parameters
     *
     * @return string
     */
    protected function getFilePath(Route $route, array $parameters = [])
    {
        $filepath = trim($route->getFilePath(), '/');

        foreach ($route->getDefaults() as $key => $value) {
            if (isset($parameters[$key]) && $parameters[$key] == $value) {
                $filepath = rtrim(preg_replace(sprintf('#{%s}/?#', $key), null, $filepath), '/');
            }
        }

        foreach ($parameters as $key => $value) {
            $filepath = str_replace(sprintf('{%s}', $key), (string) $value, $filepath);
        }

        return $filepath;
    }
}


text:
namespace System.Runtime.Serialization.Formatters.Binary
{

#if CONFIG_SERIALIZATION

using System.IO;
using System.Reflection;
using System.Collections;
using System.Runtime.Serialization;

internal abstract class BinaryValueWriter
{
	// Builtin writers.
	private static BinaryValueWriter booleanWriter = new BooleanWriter();
	private static BinaryValueWriter byteWriter = new ByteWriter();
	private static BinaryValueWriter sbyteWriter = new SByteWriter();
	private static BinaryValueWriter charWriter = new CharWriter();
	private static BinaryValueWriter int16Writer = new Int16Writer();
	private static BinaryValueWriter uint16Writer = new UInt16Writer();
	private static BinaryValueWriter int32Writer = new Int32Writer();
	private static BinaryValueWriter uint32Writer = new UInt32Writer();
	private static BinaryValueWriter int64Writer = new Int64Writer();
	private static BinaryValueWriter uint64Writer = new UInt64Writer();
	private static BinaryValueWriter singleWriter = new SingleWriter();
	private static BinaryValueWriter doubleWriter = new DoubleWriter();
	private static BinaryValueWriter decimalWriter = new DecimalWriter();
	private static BinaryValueWriter dateTimeWriter = new DateTimeWriter();
	private static BinaryValueWriter timeSpanWriter = new TimeSpanWriter();
	private static BinaryValueWriter stringWriter = new StringWriter();
	private static BinaryValueWriter objectWriter = new ObjectWriter();
	private static BinaryValueWriter infoWriter = new SurrogateWriter(null);
	private static BinaryValueWriter serializableWriter = new ISerializableWriter();
	private static BinaryValueWriter arrayWriter = new ArrayWriter();

	// Context information for writing binary values.
	public class BinaryValueContext
	{
		public BinaryFormatter formatter;
		public BinaryWriter writer;
		public ObjectIDGenerator gen;
		public Queue queue;
		public Queue assemblyQueue;

		// Constructor.
		public BinaryValueContext(BinaryFormatter formatter,
								  BinaryWriter writer)
				{
					this.formatter = formatter;
					this.writer = writer;
					this.gen = new ObjectIDGenerator();
					this.queue = new Queue();
					this.assemblyQueue = new Queue();
				}

		// Process queued objects.
		public void ProcessQueue()
				{
					Assembly assembly;
					bool firstTime;
					long objectID;
					for(;;)
					{
						if(assemblyQueue.Count > 0)
						{
							// Output a pending assembly reference.
							assembly = (assemblyQueue.Dequeue() as Assembly);
							objectID = gen.GetId(assembly, out firstTime);
							writer.Write((byte)(BinaryElementType.Assembly));
							writer.Write((int)objectID);
							WriteAssemblyName(this, assembly);
						}
						else if(queue.Count > 0)
						{
							Object obj = queue.Peek();
							if(OutputAssembly(obj))
							{
								formatter.WriteObject(this, queue.Dequeue());
							}
						}
						else
						{
							break;
						}
					}
				}

		public bool OutputAssembly(Object obj)
		{
			bool firstTime;

			Type tp = obj.GetType();
			while(tp.IsArray)
			{
				tp = tp.GetElementType();
			}
			gen.GetId(tp.Assembly, out firstTime);
			if(firstTime)
			{
				assemblyQueue.Enqueue(tp.Assembly);
			}
			return !firstTime;
		}

	}; // class BinaryValueContext

	// Constructor.
	protected BinaryValueWriter() {}

	// Write the type tag for a type.
	public abstract void WriteTypeTag(BinaryValueContext context, Type type);

	// Write the type specification for a type.
	public abstract void WriteTypeSpec(BinaryValueContext context, Type type);

	// Write the inline form of values for a type.
	public abstract void WriteInline(BinaryValueContext context,
									 Object value, Type type,
									 Type fieldType);

	// Write the object header information for a type.
	public abstract void WriteObjectHeader(BinaryValueContext context,
										   Object value, Type type,
										   long objectID, long prevObject);

	// Write the object form of values for a type.
	public abstract void WriteObject(BinaryValueContext context,
									 Object value, Type type);

	// Get the primitive type code for a type.
	internal static BinaryPrimitiveTypeCode GetPrimitiveTypeCode(Type type)
			{
				if(type == typeof(bool))
				{
					return BinaryPrimitiveTypeCode.Boolean;
				}
				else if(type == typeof(byte))
				{
					return BinaryPrimitiveTypeCode.Byte;
				}
				else if(type == typeof(sbyte))
				{
					return BinaryPrimitiveTypeCode.SByte;
				}
				else if(type == typeof(char))
				{
					return BinaryPrimitiveTypeCode.Char;
				}
				else if(type == typeof(short))
				{
					return BinaryPrimitiveTypeCode.Int16;
				}
				else if(type == typeof(ushort))
				{
					return BinaryPrimitiveTypeCode.UInt16;
				}
				else if(type == typeof(int))
				{
					return BinaryPrimitiveTypeCode.Int32;
				}
				else if(type == typeof(uint))
				{
					return BinaryPrimitiveTypeCode.UInt32;
				}
				else if(type == typeof(long))
				{
					return BinaryPrimitiveTypeCode.Int64;
				}
				else if(type == typeof(ulong))
				{
					return BinaryPrimitiveTypeCode.UInt64;
				}
				else if(type == typeof(float))
				{
					return BinaryPrimitiveTypeCode.Single;
				}
				else if(type == typeof(double))
				{
					return BinaryPrimitiveTypeCode.Double;
				}
				else if(type == typeof(Decimal))
				{
					return BinaryPrimitiveTypeCode.Decimal;
				}
				else if(type == typeof(DateTime))
				{
					return BinaryPrimitiveTypeCode.DateTime;
				}
				else if(type == typeof(TimeSpan))
				{
					return BinaryPrimitiveTypeCode.TimeSpan;
				}
				else if(type == typeof(String))
				{
					return BinaryPrimitiveTypeCode.String;
				}
				else
				{
					return (BinaryPrimitiveTypeCode)0;
				}
			}

	// Get the value writer for a particular type.
	public static BinaryValueWriter GetWriter
				(BinaryValueContext context, Type type)
			{
				BinaryPrimitiveTypeCode code;

				// Handle the primitive types first.
				code = GetPrimitiveTypeCode(type);

				switch(code)
				{
					case BinaryPrimitiveTypeCode.Boolean:
						return booleanWriter;
					case BinaryPrimitiveTypeCode.Byte:
						return byteWriter;
					case BinaryPrimitiveTypeCode.Char:
						return charWriter;
					case BinaryPrimitiveTypeCode.Decimal:
						return decimalWriter;
					case BinaryPrimitiveTypeCode.Double:
						return doubleWriter;
					case BinaryPrimitiveTypeCode.Int16:
						return int16Writer;
					case BinaryPrimitiveTypeCode.Int32:
						return int32Writer;
					case BinaryPrimitiveTypeCode.Int64:
						return int64Writer;
					case BinaryPrimitiveTypeCode.SByte:
						return sbyteWriter;
					case BinaryPrimitiveTypeCode.Single:
						return singleWriter;
					case BinaryPrimitiveTypeCode.TimeSpan:
						return timeSpanWriter;
					case BinaryPrimitiveTypeCode.DateTime:
						return dateTimeWriter;
					case BinaryPrimitiveTypeCode.UInt16:
						return uint16Writer;
					case BinaryPrimitiveTypeCode.UInt32:
						return uint32Writer;
					case BinaryPrimitiveTypeCode.UInt64:
						return uint64Writer;
					case BinaryPrimitiveTypeCode.String:
						return stringWriter;
				}

				// Check for types that implement ISerializable.
				if(typeof(ISerializable).IsAssignableFrom(type))
				{
					return serializableWriter;
				}

				// Handle special types that we recognize.
				if(type == typeof(Object))
				{
					return objectWriter;
				}
				else if(type.IsArray)
				{
					return arrayWriter;
				}

				// Check for surrogates.
				ISurrogateSelector selector;
				ISerializationSurrogate surrogate;
				selector = context.formatter.SurrogateSelector;
				if(selector != null)
				{
					surrogate = selector.GetSurrogate
						(type, context.formatter.Context, out selector);
					if(surrogate != null)
					{
						return new SurrogateWriter(surrogate);
					}
				}

				// Bail out if the type is not marked with the
				// "serializable" flag.
				if(!type.IsSerializable && !type.IsInterface)
				{
					throw new SerializationException
						(String.Format
							(_("Serialize_CannotSerialize"), type));
				}

				// Everything else is handled as an object.
				return objectWriter;
			}

	// Write an assembly name to an output stream.
	private static void WriteAssemblyName(BinaryValueContext context,
										  Assembly assembly)
			{
				String name = assembly.FullName;

				if(context.formatter.AssemblyFormat ==
						FormatterAssemblyStyle.Full)
				{
					context.writer.Write(name);
				}
				else
				{
					int index = name.IndexOf(',');
					if(index != -1)
					{
						context.writer.Write(name.Substring(0, index));
					}
					else
					{
						context.writer.Write(name);
					}
				}
			}

	// if a member-name is used in the current class and in a base class, then the name has to be prefixed by <class>+
	private static String GetMemberName(MemberInfo[] allMembers, MemberInfo member)
	{
		bool prefix = false;
		foreach(MemberInfo mi in allMembers)
		{
			if(mi.Name == member.Name && mi.DeclaringType != member.DeclaringType)
			{
				prefix = true;
				break;
			}
		}

		if(prefix)
		{
			return member.DeclaringType.FullName+"+"+member.Name;
		}
		else
		{
			return member.Name;
		}
	}

	// Write object values.
	private class ObjectWriter : BinaryValueWriter
	{
		// Constructor.
		public ObjectWriter() : base() {}

		// Write the type tag for a type.
		public override void WriteTypeTag
					(BinaryValueContext context, Type type)
				{
					if(type == typeof(Object))
					{
						context.writer.Write((byte)(BinaryTypeTag.ObjectType));
					}
					else if(type.Assembly == Assembly.GetExecutingAssembly())
					{
						context.writer.Write((byte)(BinaryTypeTag.RuntimeType));
					}
					else
					{
						context.writer.Write((byte)(BinaryTypeTag.GenericType));
					}
				}

		// Write the type specification for a type.
		public override void WriteTypeSpec
					(BinaryValueContext context, Type type)
				{
					if(type == typeof(Object))
					{
						// Nothing to do here.
					}
					else if(type.Assembly == Assembly.GetExecutingAssembly())
					{
						context.writer.Write(type.FullName);
					}
					else
					{
						bool firstTime;
						long assemblyId;
						assemblyId = context.gen.GetId
							(type.Assembly, out firstTime);
						context.writer.Write(type.FullName);
						context.writer.Write((int)assemblyId);
						if(firstTime)
						{
							// We need to output the assembly later.
							context.assemblyQueue.Enqueue(type.Assembly);
						}
					}
				}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					BinaryPrimitiveTypeCode code;
					BinaryValueWriter vw;
					bool firstTime;
					long objectID;
					long typeID;

					if(value == null)
					{
						// Write a null value.
						context.writer.Write
							((byte)(BinaryElementType.NullValue));
						return;
					}
					else if(type == typeof(String)) {
						stringWriter.WriteInline(context, value, type, fieldType);
						return;
					}
					else if(type.IsValueType)
					{
						if(fieldType.IsValueType)
						{
							// Expand the value instance inline.
							vw = GetWriter(context, type);
							typeID = context.gen.GetIDForType(type);
							objectID = context.gen.GetId(value, out firstTime);
							if(typeID == -1)
							{
								context.gen.RegisterType(type, objectID);
							}
							vw.WriteObjectHeader(context, value, type,
												 objectID, typeID);
							vw.WriteObject(context, value, type);
							return;
						}
						else if((code = GetPrimitiveTypeCode(type)) != 0)
						{
							// This is a boxed primitive value.
							context.writer.Write
								((byte)(BinaryElementType.
											BoxedPrimitiveTypeValue));
							vw = GetWriter(context, type);
							vw.WriteTypeSpec(context, type);
							vw.WriteInline(context, value, type, type);
							return;
						}
					}

					// Queue the object to be expanded later.
					objectID = context.gen.GetId(value, out firstTime);
					context.writer.Write
						((byte)(BinaryElementType.ObjectReference));
					context.writer.Write((int)objectID);
					if(firstTime)
					{
						context.queue.Enqueue(value);
					}
				}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					if(prevObject == -1)
					{
						// Write the full type information.
						long assemblyID;
						if(type.Assembly == Assembly.GetExecutingAssembly())
						{
							context.writer.Write
								((byte)(BinaryElementType.RuntimeObject));
							assemblyID = -1;
						}
						else
						{
							bool firstTime;
							assemblyID = context.gen.GetId
								(type.Assembly, out firstTime);
							if(firstTime)
							{
								context.writer.Write
									((byte)(BinaryElementType.Assembly));
								context.writer.Write((int)assemblyID);
								WriteAssemblyName(context, type.Assembly);
							}
							context.writer.Write
								((byte)(BinaryElementType.ExternalObject));
						}
						context.writer.Write((int)objectID);
						context.writer.Write(type.FullName);
						MemberInfo[] members =
							FormatterServices.GetSerializableMembers
								(type, context.formatter.Context);
						// write out number of members
						context.writer.Write((int)members.Length);

						int index;
						Type fieldType;
						for(index = 0; index < members.Length; ++index)
						{
							context.writer.Write(GetMemberName(members, members[index]));
						}
						for(index = 0; index < members.Length; ++index)
						{
							if(members[index] is FieldInfo)
							{
								fieldType = ((FieldInfo)(members[index]))
												.FieldType;
							}
							else
							{
								fieldType = ((PropertyInfo)(members[index]))
												.PropertyType;
							}
							GetWriter(context, fieldType).WriteTypeTag
								(context, fieldType);
						}
						for(index = 0; index < members.Length; ++index)
						{
							if(members[index] is FieldInfo)
							{
								fieldType = ((FieldInfo)(members[index]))
												.FieldType;
							}
							else
							{
								fieldType = ((PropertyInfo)(members[index]))
												.PropertyType;
							}
							GetWriter(context, fieldType).WriteTypeSpec
								(context, fieldType);
						}
						if(assemblyID != -1)
						{
							context.writer.Write((int)assemblyID);
						}
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write
							((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
				{
					MemberInfo[] members =
						FormatterServices.GetSerializableMembers
							(type, context.formatter.Context);
					Object[] values =
						FormatterServices.GetObjectData(value, members);
					int index;
					Type fieldType;
					Type valueType;
					for(index = 0; index < members.Length; ++index)
					{
						if(members[index] is FieldInfo)
						{
							fieldType = ((FieldInfo)(members[index]))
											.FieldType;
						}
						else
						{
							fieldType = ((PropertyInfo)(members[index]))
											.PropertyType;
						}
						if(values[index] != null)
						{
							valueType = values[index].GetType();
						}
						else
						{
							valueType = fieldType;
						}
						GetWriter(context, fieldType).WriteInline
							(context, values[index], valueType, fieldType);
					}
				}

	}; // class ObjectWriter

	private class ISerializableWriter : ObjectWriter
	{
		// Write the object header information for a type.
		// IS11n objects are written like normal objects, but the
		// members are replaced by the key->value pairs from the
		// SerInfo. There is an exception if the Object is serialized
		// using another type (SetType()), then this type is serialized instead
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					// get members
					StreamingContext streamContext = context.formatter.Context;
					SerializationInfo info = new SerializationInfo(type, context.formatter.converter);
					((ISerializable) value).GetObjectData(info, streamContext);
					Assembly iserAssembly = Assembly.Load(info.AssemblyName);

					if(prevObject == -1)
					{
						// Write the full type information.
						long assemblyID;
						if(iserAssembly == Assembly.GetExecutingAssembly())
						{
							context.writer.Write
								((byte)(BinaryElementType.RuntimeObject));
							assemblyID = -1;
						}
						else
						{
							bool firstTime;
							assemblyID = context.gen.GetId
								(iserAssembly, out firstTime);
							if(firstTime)
							{
								context.writer.Write
									((byte)(BinaryElementType.Assembly));
								context.writer.Write((int)assemblyID);
								WriteAssemblyName(context, iserAssembly);
							}
							context.writer.Write
								((byte)(BinaryElementType.ExternalObject));
						}

						context.writer.Write((int)objectID);
						context.writer.Write(info.FullTypeName);

						// write out number of members
						context.writer.Write((int)info.MemberCount);

						foreach(SerializationEntry entry in info)
						{
							context.writer.Write(entry.Name);
						}

						foreach(SerializationEntry entry in info)
						{
							GetWriter(context, entry.ObjectType).WriteTypeTag
								(context, entry.ObjectType);
						}

						foreach(SerializationEntry entry in info)
						{
							GetWriter(context, entry.ObjectType).WriteTypeSpec
								(context, entry.ObjectType);
						}
						if(assemblyID != -1)
						{
							context.writer.Write((int)assemblyID);
						}
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write
							((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
			Object value, Type type)
		{
			StreamingContext streamContext = context.formatter.Context;
			SerializationInfo info = new SerializationInfo(type, context.formatter.converter);

			((ISerializable) value).GetObjectData(info, streamContext);

			// the entries are written using the type-spec supplied when
			// they were put into the SerInfo, but the writer is determined
			// by the real type!
			foreach(SerializationEntry entry in info)
			{
				Object val = entry.Value;
				if(val != null)
				{
					GetWriter(context, val.GetType()).WriteInline
						(context, val, val.GetType(), entry.ObjectType);
				}
				else
				{
					// NULL is always written as object
					GetWriter(context, typeof(Object)).WriteInline
						(context, val, typeof(Object), entry.ObjectType);
				}
			}
		}
	}

	// Write object values using serialization surrogates.
	private class SurrogateWriter : ObjectWriter
	{
		// Internal state.
		private ISerializationSurrogate surrogate;

		// Constructor.
		public SurrogateWriter(ISerializationSurrogate surrogate)
				{
					this.surrogate = surrogate;
				}

		// Get object data using the prevailing surrogate.
		private SerializationInfo GetObjectData
					(BinaryValueContext context, Object value, Type type)
				{
					SerializationInfo info = new SerializationInfo
						(type, context.formatter.converter);
					if(surrogate == null)
					{
						((ISerializable)value).GetObjectData
							(info, context.formatter.Context);
					}
					else
					{
						surrogate.GetObjectData
							(value, info, context.formatter.Context);
					}
					return info;
				}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					if(prevObject == -1)
					{
						// Write the full type information.
						long assemblyID;
						if(type.Assembly == Assembly.GetExecutingAssembly())
						{
							context.writer.Write
								((byte)(BinaryElementType.RuntimeObject));
							assemblyID = -1;
						}
						else
						{
							bool firstTime;
							assemblyID = context.gen.GetId
								(type.Assembly, out firstTime);
							if(firstTime)
							{
								context.writer.Write
									((byte)(BinaryElementType.Assembly));
								context.writer.Write((int)assemblyID);
								WriteAssemblyName(context, type.Assembly);
							}
							context.writer.Write
								((byte)(BinaryElementType.ExternalObject));
						}
						context.writer.Write((int)objectID);
						context.writer.Write(type.FullName);
						SerializationInfo info = GetObjectData
							(context, value, type);
						SerializationInfoEnumerator e = info.GetEnumerator();
						Type objectType;
						while(e.MoveNext())
						{
							context.writer.Write(e.Name);
						}
						e.Reset();
						while(e.MoveNext())
						{
							objectType = e.ObjectType;
							GetWriter(context, objectType)
								.WriteTypeTag(context, objectType);
						}
						e.Reset();
						while(e.MoveNext())
						{
							objectType = e.ObjectType;
							GetWriter(context, objectType)
								.WriteTypeSpec(context, objectType);
						}
						if(assemblyID != -1)
						{
							context.writer.Write((int)assemblyID);
						}
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write
							((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
				{
					SerializationInfo info = GetObjectData
						(context, value, type);
					SerializationInfoEnumerator e = info.GetEnumerator();
					Type objectType;
					Type valueType;
					Object fieldValue;
					while(e.MoveNext())
					{
						objectType = e.ObjectType;
						fieldValue = e.Value;
						if(value == null)
						{
							valueType = objectType;
						}
						else
						{
							valueType = fieldValue.GetType();
						}
						GetWriter(context, objectType).WriteInline
							(context, fieldValue, valueType, objectType);
					}
				}

	}; // class SurrogateWriter

	// Write primitive values.
	private abstract class PrimitiveWriter : BinaryValueWriter
	{
		// Internal state.
		private BinaryPrimitiveTypeCode code;
		protected String fieldName;

		// Constructor.
		public PrimitiveWriter(BinaryPrimitiveTypeCode code)
				{
					this.code = code;
					this.fieldName = "m_value";
				}
		public PrimitiveWriter(BinaryPrimitiveTypeCode code, String fieldName)
				{
					this.code = code;
					this.fieldName = fieldName;
				}

		// Write the type tag for a type.
		public override void WriteTypeTag
					(BinaryValueContext context, Type type)
				{
					context.writer.Write((byte)(BinaryTypeTag.PrimitiveType));
				}

		// Write the type specification for a type.
		public override void WriteTypeSpec
					(BinaryValueContext context, Type type)
				{
					context.writer.Write((byte)code);
				}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					if(prevObject == -1)
					{
						// Write the full type information.
						context.writer.Write
							((byte)(BinaryElementType.RuntimeObject));
						context.writer.Write((int)objectID);
						context.writer.Write(type.FullName);
						context.writer.Write((int)1);
						context.writer.Write(fieldName);
						WriteTypeTag(context, type);
						WriteTypeSpec(context, type);
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write
							((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
				{
					// The object field is just the primitive value itself.
					WriteInline(context, value, type, type);
				}

	}; // class PrimitiveWriter

	// Write boolean values.
	private class BooleanWriter : PrimitiveWriter
	{
		// Constructor.
		public BooleanWriter() : base(BinaryPrimitiveTypeCode.Boolean) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((bool)value);
				}

	}; // class BooleanWriter

	// Write byte values.
	private class ByteWriter : PrimitiveWriter
	{
		// Constructor.
		public ByteWriter() : base(BinaryPrimitiveTypeCode.Byte) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((byte)value);
				}

	}; // class ByteWriter

	// Write sbyte values.
	private class SByteWriter : PrimitiveWriter
	{
		// Constructor.
		public SByteWriter() : base(BinaryPrimitiveTypeCode.SByte) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((sbyte)value);
				}

	}; // class SByteWriter

	// Write char values.
	private class CharWriter : PrimitiveWriter
	{
		// Constructor.
		public CharWriter() : base(BinaryPrimitiveTypeCode.Char) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((char)value);
				}

	}; // class CharWriter

	// Write short values.
	private class Int16Writer : PrimitiveWriter
	{
		// Constructor.
		public Int16Writer() : base(BinaryPrimitiveTypeCode.Int16) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((short)value);
				}

	}; // class Int16Writer

	// Write ushort values.
	private class UInt16Writer : PrimitiveWriter
	{
		// Constructor.
		public UInt16Writer() : base(BinaryPrimitiveTypeCode.UInt16) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((ushort)value);
				}

	}; // class UInt16Writer

	// Write int values.
	private class Int32Writer : PrimitiveWriter
	{
		// Constructor.
		public Int32Writer() : base(BinaryPrimitiveTypeCode.Int32) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((int)value);
				}

	}; // class Int32Writer

	// Write uint values.
	private class UInt32Writer : PrimitiveWriter
	{
		// Constructor.
		public UInt32Writer() : base(BinaryPrimitiveTypeCode.UInt32) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((uint)value);
				}

	}; // class UInt32Writer

	// Write long values.
	private class Int64Writer : PrimitiveWriter
	{
		// Constructor.
		public Int64Writer() : base(BinaryPrimitiveTypeCode.Int64) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((long)value);
				}

	}; // class Int64Writer

	// Write ulong values.
	private class UInt64Writer : PrimitiveWriter
	{
		// Constructor.
		public UInt64Writer() : base(BinaryPrimitiveTypeCode.UInt64) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((ulong)value);
				}

	}; // class UInt64Writer

	// Write float values.
	private class SingleWriter : PrimitiveWriter
	{
		// Constructor.
		public SingleWriter() : base(BinaryPrimitiveTypeCode.Single) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((float)value);
				}

	}; // class SingleWriter

	// Write double values.
	private class DoubleWriter : PrimitiveWriter
	{
		// Constructor.
		public DoubleWriter() : base(BinaryPrimitiveTypeCode.Double) {}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					context.writer.Write((double)value);
				}

	}; // class DoubleWriter

	// Write Decimal values.
	private class DecimalWriter : PrimitiveWriter
	{
		// Constructor.
		public DecimalWriter() : base(BinaryPrimitiveTypeCode.Decimal) {}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					if(prevObject == -1)
					{
						// Write the full type information.
						context.writer.Write
							((byte)(BinaryElementType.RuntimeObject));
						context.writer.Write((int)objectID);
						context.writer.Write(type.FullName);
						context.writer.Write((int)4);
						context.writer.Write("flags");
						context.writer.Write("hi");
						context.writer.Write("lo");
						context.writer.Write("mid");
						int32Writer.WriteTypeTag(context, null);
						int32Writer.WriteTypeTag(context, null);
						int32Writer.WriteTypeTag(context, null);
						int32Writer.WriteTypeTag(context, null);
						int32Writer.WriteTypeSpec(context, null);
						int32Writer.WriteTypeSpec(context, null);
						int32Writer.WriteTypeSpec(context, null);
						int32Writer.WriteTypeSpec(context, null);
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write
							((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}
				// Write the object form of values for a type.
				public override void WriteObject(BinaryValueContext context,
												 Object value, Type type)
				{
					// NOTE: the stupid swapping of the int's is intentional
					Decimal dec = (Decimal) value;
					int[] bits = Decimal.GetBits(dec);
					context.writer.Write(bits[3]);
					context.writer.Write(bits[2]);
					context.writer.Write(bits[0]);
					context.writer.Write(bits[1]);
				}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					// NOTE: it's stupid ... but Bug for bug compatibility
					// was much simpler to write the bits out and read it back
					context.writer.Write(value.ToString());
				}

	}; // class DecimalWriter

	// Write DateTime values.
	private class DateTimeWriter : PrimitiveWriter
	{
		// Constructor.
		public DateTimeWriter()
			: base(BinaryPrimitiveTypeCode.DateTime, "ticks") {}

				// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
												Object value, Type type,
												long objectID, long prevObject)
				{
					if(prevObject == -1)
					{
						// Write the full type information.
						context.writer.Write((byte)(BinaryElementType.RuntimeObject));
						context.writer.Write((int)objectID);
						context.writer.Write(type.FullName);
						context.writer.Write((int)1);
						context.writer.Write(fieldName);
						int64Writer.WriteTypeTag(context, null);
						int64Writer.WriteTypeSpec(context, null);
					}
					else
					{
						// Write a short header, referring to a previous
						// object's type information.
						context.writer.Write((byte)(BinaryElementType.RefTypeObject));
						context.writer.Write((int)objectID);
						context.writer.Write((int)prevObject);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
		{
			// this has to be saved as long
			context.writer.Write((long) ((DateTime)value).Ticks);
		}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
		{
			context.writer.Write(((DateTime)value).Ticks);
		}

	}; // class DateTimeWriter

	// Write TimeSpan values.
	private class TimeSpanWriter : PrimitiveWriter
	{
		// Constructor.
		public TimeSpanWriter()
			: base(BinaryPrimitiveTypeCode.TimeSpan, "_ticks") {}

				// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
		{
			if(prevObject == -1)
			{
				// Write the full type information.
				context.writer.Write((byte)(BinaryElementType.RuntimeObject));
				context.writer.Write((int)objectID);
				context.writer.Write(type.FullName);
				context.writer.Write((int)1);
				context.writer.Write(fieldName);
				int64Writer.WriteTypeTag(context, null);
				int64Writer.WriteTypeSpec(context, null);
			}
			else
			{
				// Write a short header, referring to a previous
				// object's type information.
				context.writer.Write((byte)(BinaryElementType.RefTypeObject));
				context.writer.Write((int)objectID);
				context.writer.Write((int)prevObject);
			}
		}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
		{
			// this has to be saved as long
			context.writer.Write((long) ((TimeSpan)value).Ticks);
		}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
		{
			context.writer.Write(((TimeSpan)value).Ticks);
		}

	}; // class TimeSpanWriter

	// Write String values.
	private class StringWriter : BinaryValueWriter
	{
		// Constructor.
		public StringWriter() : base() {}

		// Write the type tag for a type.
		public override void WriteTypeTag
					(BinaryValueContext context, Type type)
		{
			context.writer.Write((byte)(BinaryTypeTag.String));
		}

		// Write the type specification for a type.
		public override void WriteTypeSpec
					(BinaryValueContext context, Type type)
		{
			// Nothing to do here.
		}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
		{
			bool firstTime;

			if(value == null)
			{
				// Write a null value.
				context.writer.Write((byte)(BinaryElementType.NullValue));
				return;
			}
			else
			{
				long objectID = context.gen.GetId(value, out firstTime);
				if(firstTime)
				{
					context.writer.Write((byte)(BinaryElementType.String));
					context.writer.Write((int)objectID);
					context.writer.Write((String)value);
				}
				else
				{
					context.writer.Write
							((byte)(BinaryElementType.ObjectReference));
					context.writer.Write((int)objectID);
				}
			}
		}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					context.writer.Write((byte)(BinaryElementType.String));
					context.writer.Write((int) objectID);
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
				{
					if(value == null)
					{
						// Write a null value.
						context.writer.Write
								((byte)(BinaryElementType.NullValue));
					}
					else
					{
						context.writer.Write((String)value);
					}
				}

	}; // class StringWriter

	// Write array values.
	private class ArrayWriter : BinaryValueWriter
	{
		// Constructor.
		public ArrayWriter() : base() {}

		// Get the type of an array.
		private BinaryArrayType GetArrayType(Array value, Type type)
				{
					int rank = type.GetArrayRank();
					bool hasLowerBounds = false;
					int dim;
					for(dim = 0; dim < rank; ++dim)
					{
						if(value.GetLowerBound(dim) != 0)
						{
							hasLowerBounds = true;
							break;
						}
					}
					if(type.GetElementType().IsArray)
					{
						if(rank == 1)
						{
							if(hasLowerBounds)
							{
								return BinaryArrayType.JaggedWithLowerBounds;
							}
							else
							{
								return BinaryArrayType.Jagged;
							}
						}
						else
						{
							if(hasLowerBounds)
							{
								return BinaryArrayType.
									MultidimensionalWithLowerBounds;
							}
							else
							{
								return BinaryArrayType.Multidimensional;
							}
						}
					}
					else if(rank == 1)
					{
						if(hasLowerBounds)
						{
							return BinaryArrayType.SingleWithLowerBounds;
						}
						else
						{
							return BinaryArrayType.Single;
						}
					}
					else
					{
						if(hasLowerBounds)
						{
							return BinaryArrayType.
								MultidimensionalWithLowerBounds;
						}
						else
						{
							return BinaryArrayType.Multidimensional;
						}
					}
				}

		// Write the type tag for a type.
		public override void WriteTypeTag
					(BinaryValueContext context, Type type)
				{
					if(type == typeof(Object[]))
					{
						context.writer.Write
							((byte)(BinaryTypeTag.ArrayOfObject));
					}
					else if(type == typeof(String[]))
					{
						context.writer.Write
							((byte)(BinaryTypeTag.ArrayOfString));
					}
					else
					{
						BinaryPrimitiveTypeCode prim;
						prim = GetPrimitiveTypeCode(type.GetElementType());
						if(prim != (BinaryPrimitiveTypeCode)0 &&
						   type.GetArrayRank() == 1)
						{
							context.writer.Write
								((byte)(BinaryTypeTag.ArrayOfPrimitiveType));
						}
						else
						{
							context.writer.Write
								((byte)(BinaryTypeTag.GenericType));
						}
					}
				}

		// Write the type specification for a type.
		public override void WriteTypeSpec
					(BinaryValueContext context, Type type)
				{
					if(type == typeof(Object[]) || type == typeof(String[]))
					{
						return;
					}
					else
					{
						BinaryPrimitiveTypeCode prim;
						prim = GetPrimitiveTypeCode(type.GetElementType());
						if(prim != (BinaryPrimitiveTypeCode)0 &&
						   type.GetArrayRank() == 1)
						{
							context.writer.Write((byte)prim);
						}
						else
						{
							bool firstTime;
							long assemblyId;
							assemblyId = context.gen.GetId
							(type.GetElementType().Assembly, out firstTime);
							context.writer.Write(type.FullName);
							context.writer.Write((int)assemblyId);
							if(firstTime)
							{
								// We need to output the assembly later.
								context.assemblyQueue.Enqueue(type.GetElementType().Assembly);
							}
						}
					}
				}

		// Write the inline form of values for a type.
		public override void WriteInline(BinaryValueContext context,
										 Object value, Type type,
										 Type fieldType)
				{
					bool firstTime;
					long objectID;
					if(value == null)
					{
						// Write a null value.
						context.writer.Write
							((byte)(BinaryElementType.NullValue));
					}
					else
					{
						// Queue the object to be expanded later.
						objectID = context.gen.GetId(value, out firstTime);
						context.writer.Write
							((byte)(BinaryElementType.ObjectReference));
						context.writer.Write((int)objectID);
						if(firstTime)
						{
							context.queue.Enqueue(value);
						}
					}
				}

		// Write the object header information for a type.
		public override void WriteObjectHeader(BinaryValueContext context,
											   Object value, Type type,
											   long objectID, long prevObject)
				{
					BinaryPrimitiveTypeCode prim;
					BinaryArrayType atype;
					prim = GetPrimitiveTypeCode(type.GetElementType());
					atype = GetArrayType((Array)value, type);
					if(type == typeof(Object[]))
					{
						context.writer.Write
							((byte)(BinaryElementType.ArrayOfObject));
						context.writer.Write((int)objectID);
						context.writer.Write(((Array)value).GetLength(0));
					}
					else if(type == typeof(String[]))
					{
						context.writer.Write
							((byte)(BinaryElementType.ArrayOfString));
						context.writer.Write((int)objectID);
						context.writer.Write(((Array)value).GetLength(0));
					}
					else if(prim != (BinaryPrimitiveTypeCode)0 &&
							atype == BinaryArrayType.Single)
					{
						context.writer.Write
							((byte)(BinaryElementType.ArrayOfPrimitiveType));
						context.writer.Write((int)objectID);
						context.writer.Write(((Array)value).GetLength(0));
						context.writer.Write((byte)prim);
					}
					else
					{
						int rank = type.GetArrayRank();
						int dim;
						context.writer.Write
							((byte)(BinaryElementType.GenericArray));
						context.writer.Write((int)objectID);
						context.writer.Write((byte)atype);
						context.writer.Write(rank);
						for(dim = 0; dim < rank; ++dim)
						{
							context.writer.Write
								(((Array)value).GetLength(dim));
						}
						if(((int)atype) >= 3)
						{
							for(dim = 0; dim < rank; ++dim)
							{
								context.writer.Write
									(((Array)value).GetLowerBound(dim));
							}
						}
						BinaryValueWriter vw;
						type = type.GetElementType();
						vw = GetWriter(context, type);
						vw.WriteTypeTag(context, type);
						vw.WriteTypeSpec(context, type);
					}
				}

		// Write the object form of values for a type.
		public override void WriteObject(BinaryValueContext context,
										 Object value, Type type)
				{
					Type elementType = type.GetElementType();

					if(elementType == typeof(Boolean))
					{
						foreach(bool elem in (bool[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Byte))
					{
						context.writer.Write((byte[]) value);
					}
					else if(elementType == typeof(SByte))
					{
						/* wish we had macros */
						foreach(sbyte elem in (sbyte[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Char))
					{
						foreach(char elem in (char[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Int16))
					{
						foreach(short elem in (short[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(UInt16))
					{
						foreach(ushort elem in (ushort[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Int32))
					{
						foreach(int elem in (int[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(UInt32))
					{
						foreach(uint elem in (uint[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Int64))
					{
						foreach(long elem in (long[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(UInt64))
					{
						foreach(ulong elem in (ulong[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Single))
					{
						foreach(float elem in (float[])value)
						{
							context.writer.Write(elem);
						}
					}
					else if(elementType == typeof(Double))
					{
						foreach(double elem in (double[])value)
						{
							context.writer.Write(elem);
						}
					}
					else
					{
						// other arrays are treated with more respect
						Array ar = (Array) value;
						BinaryValueWriter writer = GetWriter(context, elementType);
						if(writer == null)
						{
							throw new SerializationException
								(String.Format
									(_("Serialize_CannotSerialize"), type));
						}
						for(int i = 0; i < ar.GetLength(0); i++)
						{
							object o = ar.GetValue(i);
							if(o == null)
							{
								// Write a null value.
								context.writer.Write
									((byte)(BinaryElementType.NullValue));
							}
							else
							{
								writer.WriteInline(context, o, o.GetType(), type);
							}
						}
					}
				}
	}; // class ArrayWriter

}; // class BinaryValueWriter

#endif // CONFIG_SERIALIZATION

}; // namespace System.Runtime.Serialization.Formatters.Binary


text:
<?php
class PositionManager
{
	const POS_DISTRIBUTOR=1;
	const POS_COMPANY_GROUP=2;
	const POS_DEALERSHIP=2;
	const POS_COMPANY=3;
	const POS_STORE=4;

	public static function is_logged_in()
	{
		return !self::is_anonymous_user();
	}

	public static function is_anonymous_user()
	{
		return !is_uuid($_SESSION['people']['id']);
	}

	public static function get_role_id()
	{
		if(is_uuid($_SESSION['position']['role_id'])) return $_SESSION['position']['role_id'];
		$s=new CSearcher('roles');
		$s['default']=1;
		$roles=$s->fetchPlainArray(1);
		if(empty($roles)) throw new CACLException(CACLException::INVALID_ROLE_ID);
		$_SESSION['role']=$roles[0];
		$_SESSION['position']['role_id']=$roles[0]['id'];
		return $roles[0]['id'];
	}

	public static function get_default_role()
	{
		$s=new CSearcher('roles');
		$s['default']=1;
		$roles=$s->fetchPlainArray(1);
		return $roles[0];
	}

	public static function update_runtime_position($force_update=false)
	{
		if(!$force_update && is_uuid($_SESSION['position']['id'])) return;
		$_SESSION['position']=array();
		$_SESSION['role']=array();
		if(empty($_SESSION['positions']) || !is_array($_SESSION['positions'])) { //--load default position
			$s=new CSearcher('roles');
			$s['default']=1;
			$roles=$s->fetchPlainArray(1);
			if(empty($roles)) throw new Exception('Cannot find default Anonymous User role record!',0);
			$_SESSION['position']['role_id']=$roles[0]['id'];
			$_SESSION['role']=$roles[0];
			return;
		}
		$positions_num=count($_SESSION['positions']);
		if($positions_num==1) {
			$_SESSION['position']=$_SESSION['positions'][0];
			$s=new CSearcher('roles');
			$s['id']=$_SESSION['position']['role_id'];
			$roles=$s->fetchPlainArray(1);
			$_SESSION['role']=$roles[0];
			return;
		}else if($positions_num>1){
			//if(is_uuid($people['last_select_position_id'])) $_SESSION['position']=self::get_position_by_id($people['last_select_position_id']);
			//else $_SESSION['position']=self::get_default_position();
			$_SESSION['position']=self::get_default_position();
			$s=new CSearcher('roles');
			$s['id']=$_SESSION['position']['role_id'];
			$roles=$s->fetchPlainArray(1);
			$_SESSION['role']=$roles[0];
			return;
		}
	}

	public static function change_runtime_position($position_id)
	{
		if(!is_uuid($position_id)) throw new Exception("Invalid position ID!");
		$s=new CSearcher('positions');
		$s['people_id']=$_SESSION['people']['id'];
		$s['id']=$position_id;
		$positions=$s->fetchPlainArray(1);
		if(empty($positions)) throw new Exception("Cannot find position record!");
		$_SESSION['position']=$positions[0];
		$s=new CSearcher('roles');
		$s['id']=$_SESSION['position']['role_id'];
		$roles=$s->fetchPlainArray(1);
		$_SESSION['role']=$roles[0];
	}

	public static function update_last_select_position_id()
	{
		if(!is_uuid($_SESSION['people']['id']) || !is_uuid($_SESSION['position']['id'])) return;
		$sql="UPDATE `peoples` SET `last_select_position_id`=:last_select_position_id WHERE `id`=:people_id LIMIT 1";
		$params=array(
			':last_select_position_id'=>$_SESSION['position']['id'],
			':people_id'=>$_SESSION['people']['id']
		);
		global $APP_ENV;
		$db=$APP_ENV['db'];
		$db->query($sql,$params);
	}

	public static function load_postions()
	{
		if(!is_uuid($_SESSION['people']['id'])) return;
		$s=new CSearcher('positions');
		$s['people_id']=$_SESSION['people']['id'];
		$s->orderBy=array('role_id ASC');
		$positions=$s->fetchPlainArray();
		if(empty($positions)){ //-- load default postion
			$default_role=self::get_default_role();
			if(!empty($default_role)){
				$positions=array(array(
					'id' => null,
					'role_id' => $default_role['id'],
					'people_id' => $_SESSION['people']['id'],
					'default' =>1
				));
			}
		}
		$_SESSION['positions']=$positions;
	}

	public static function get_position_by_id($position_id)
	{
		if(empty($_SESSION['positions']) || !is_array($_SESSION['positions'])) return null;
		if(!is_uuid($position_id)) return null;
		foreach($_SESSION['positions'] as $position)
			if($position['id']==$position_id) return $position;
		return null;
	}

	public static function get_positions_by_role_id($role_id)
	{
		if(empty($_SESSION['positions']) || !is_array($_SESSION['positions'])) return array();
		if(!is_uuid($role_id)) return array();
		$positions=array();
		foreach($_SESSION['positions'] as $position)
			if($position['role_id']==$role_id) $positions[]=$position;
		return $positions;
	}

	public static function get_default_position()
	{
		if(empty($_SESSION['positions']) || !is_array($_SESSION['positions'])) return null;

		foreach($_SESSION['positions'] as $position)
			if($position['default']==1) return $position;
		return $_SESSION['positions'][0];
	}

	public static function set_default_position($position_id)
	{
		if(!is_uuid($_SESSION['people']['id']) || !is_uuid($position_id)) return;
		global $APP_ENV;
		$db=$APP_ENV['db'];
		$sql="UPDATE `positions` SET `default`='0' WHERE `people_id`=:people_id";
		$params=array(':people_id'=>$_SESSION['people']['id']);
		$db->query($sql,$params);

		$sql="UPDATE `positions` SET `default`='1' WHERE `people_id`=:people_id AND `id`=:id LIMIT 1";
		$params=array(':people_id'=>$_SESSION['people']['id'],':id' => $position_id);
		$db->query($sql,$params);

		self::load_postions();

		if($_SESSION['position']['id']==$position_id) $_SESSION['position']['default']='1';
		else $_SESSION['position']['default']='0';
	}

	private static function get_record_name($id,$table)
	{
		if(empty($id)) return null;
		$s=new CSearcher($table);
		$s['id']=$id;
		$s->setFetchDataSet(array('name'));
		$records=$s->fetchPlainArray(1);
		if(empty($records)) return null;
		return $records[0]['name'];
	}

	public static function get_position_description($position)
	{
		if(empty($position)) return 'N/A';

		$com_names=array();
		if(is_uuid($position['store_id'])) $com_names[]='Store: '.self::get_record_name($position['store_id'],'stores');
		if(is_uuid($position['company_id'])) $com_names[]='Company: '.self::get_record_name($position['company_id'],'companies');
		if(is_uuid($position['company_group_id'])) $com_names[]='Group: '.self::get_record_name($position['company_group_id'],'company_groups');
		$com_names=join(', ',$com_names);
		return $com_names;

		if(is_uuid($position['dealership_id'])) {
			$d_names=array();
			$d_names[]='Dealership: '.self::get_record_name($position['dealership_id'],'dealerships');
			if(is_uuid($position['company_id'])) $d_names[]='Company: '.self::get_record_name($position['company_id'],'companies');
			$d_names=join(', ',$d_names);
			return $d_names;
		}

		if(is_uuid($position['distributor_id'])) {
			$dis_name='Distributor: '.self::get_record_name($position['distributor_id'],'distributors');
			return $dis_name;
		}
		return '';
	}

}
?>


text:
import boto3
from botocore.exceptions import ClientError
import datetime
import pytest

from moto import mock_sagemaker
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID

FAKE_ROLE_ARN = f"arn:aws:iam::{ACCOUNT_ID}:role/FakeRole"
FAKE_PROCESSING_JOB_NAME = "MyProcessingJob"
FAKE_CONTAINER = "382416733822.dkr.ecr.us-east-1.amazonaws.com/linear-learner:1"
TEST_REGION_NAME = "us-east-1"

@pytest.fixture(name="sagemaker_client")
def fixture_sagemaker_client():
    with mock_sagemaker():
        yield boto3.client("sagemaker", region_name=TEST_REGION_NAME)

class MyProcessingJobModel(object):
    def __init__(
        self,
        processing_job_name,
        role_arn,
        container=None,
        bucket=None,
        prefix=None,
        app_specification=None,
        network_config=None,
        processing_inputs=None,
        processing_output_config=None,
        processing_resources=None,
        stopping_condition=None,
    ):
        self.processing_job_name = processing_job_name
        self.role_arn = role_arn
        self.container = (
            container
            or "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.23-1-cpu-py3"
        )
        self.bucket = bucket or "my-bucket"
        self.prefix = prefix or "sagemaker"
        self.app_specification = app_specification or {
            "ImageUri": self.container,
            "ContainerEntrypoint": ["python3"],
        }
        self.network_config = network_config or {
            "EnableInterContainerTrafficEncryption": False,
            "EnableNetworkIsolation": False,
        }
        self.processing_inputs = processing_inputs or [
            {
                "InputName": "input",
                "AppManaged": False,
                "S3Input": {
                    "S3Uri": f"s3://{self.bucket}/{self.prefix}/processing/",
                    "LocalPath": "/opt/ml/processing/input",
                    "S3DataType": "S3Prefix",
                    "S3InputMode": "File",
                    "S3DataDistributionType": "FullyReplicated",
                    "S3CompressionType": "None",
                },
            }
        ]
        self.processing_output_config = processing_output_config or {
            "Outputs": [
                {
                    "OutputName": "output",
                    "S3Output": {
                        "S3Uri": f"s3://{self.bucket}/{self.prefix}/processing/",
                        "LocalPath": "/opt/ml/processing/output",
                        "S3UploadMode": "EndOfJob",
                    },
                    "AppManaged": False,
                }
            ]
        }
        self.processing_resources = processing_resources or {
            "ClusterConfig": {
                "InstanceCount": 1,
                "InstanceType": "ml.m5.large",
                "VolumeSizeInGB": 10,
            },
        }
        self.stopping_condition = stopping_condition or {
            "MaxRuntimeInSeconds": 3600,
        }

    def save(self, sagemaker_client):
        params = {
            "AppSpecification": self.app_specification,
            "NetworkConfig": self.network_config,
            "ProcessingInputs": self.processing_inputs,
            "ProcessingJobName": self.processing_job_name,
            "ProcessingOutputConfig": self.processing_output_config,
            "ProcessingResources": self.processing_resources,
            "RoleArn": self.role_arn,
            "StoppingCondition": self.stopping_condition,
        }

        return sagemaker_client.create_processing_job(**params)

def test_create_processing_job(sagemaker_client):
    bucket = "my-bucket"
    prefix = "my-prefix"
    app_specification = {
        "ImageUri": FAKE_CONTAINER,
        "ContainerEntrypoint": ["python3", "app.py"],
    }
    processing_resources = {
        "ClusterConfig": {
            "InstanceCount": 2,
            "InstanceType": "ml.m5.xlarge",
            "VolumeSizeInGB": 20,
        },
    }
    stopping_condition = {"MaxRuntimeInSeconds": 60 * 60}

    job = MyProcessingJobModel(
        processing_job_name=FAKE_PROCESSING_JOB_NAME,
        role_arn=FAKE_ROLE_ARN,
        container=FAKE_CONTAINER,
        bucket=bucket,
        prefix=prefix,
        app_specification=app_specification,
        processing_resources=processing_resources,
        stopping_condition=stopping_condition,
    )
    resp = job.save(sagemaker_client)
    resp["ProcessingJobArn"].should.match(
        rf"^arn:aws:sagemaker:.*:.*:processing-job/{FAKE_PROCESSING_JOB_NAME}$"
    )

    resp = sagemaker_client.describe_processing_job(
        ProcessingJobName=FAKE_PROCESSING_JOB_NAME
    )
    resp["ProcessingJobName"].should.equal(FAKE_PROCESSING_JOB_NAME)
    resp["ProcessingJobArn"].should.match(
        rf"^arn:aws:sagemaker:.*:.*:processing-job/{FAKE_PROCESSING_JOB_NAME}$"
    )
    assert "python3" in resp["AppSpecification"]["ContainerEntrypoint"]
    assert "app.py" in resp["AppSpecification"]["ContainerEntrypoint"]
    assert resp["RoleArn"] == FAKE_ROLE_ARN
    assert resp["ProcessingJobStatus"] == "Completed"
    assert isinstance(resp["CreationTime"], datetime.datetime)
    assert isinstance(resp["LastModifiedTime"], datetime.datetime)

def test_list_processing_jobs(sagemaker_client):
    test_processing_job = MyProcessingJobModel(
        processing_job_name=FAKE_PROCESSING_JOB_NAME, role_arn=FAKE_ROLE_ARN
    )
    test_processing_job.save(sagemaker_client)
    processing_jobs = sagemaker_client.list_processing_jobs()
    assert len(processing_jobs["ProcessingJobSummaries"]).should.equal(1)
    assert processing_jobs["ProcessingJobSummaries"][0][
        "ProcessingJobName"
    ].should.equal(FAKE_PROCESSING_JOB_NAME)

    assert processing_jobs["ProcessingJobSummaries"][0][
        "ProcessingJobArn"
    ].should.match(
        rf"^arn:aws:sagemaker:.*:.*:processing-job/{FAKE_PROCESSING_JOB_NAME}$"
    )
    assert processing_jobs.get("NextToken") is None

def test_list_processing_jobs_multiple(sagemaker_client):
    name_job_1 = "blah"
    arn_job_1 = "arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar"
    test_processing_job_1 = MyProcessingJobModel(
        processing_job_name=name_job_1, role_arn=arn_job_1
    )
    test_processing_job_1.save(sagemaker_client)

    name_job_2 = "blah2"
    arn_job_2 = "arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar2"
    test_processing_job_2 = MyProcessingJobModel(
        processing_job_name=name_job_2, role_arn=arn_job_2
    )
    test_processing_job_2.save(sagemaker_client)
    processing_jobs_limit = sagemaker_client.list_processing_jobs(MaxResults=1)
    assert len(processing_jobs_limit["ProcessingJobSummaries"]).should.equal(1)

    processing_jobs = sagemaker_client.list_processing_jobs()
    assert len(processing_jobs["ProcessingJobSummaries"]).should.equal(2)
    assert processing_jobs.get("NextToken").should.be.none

def test_list_processing_jobs_none(sagemaker_client):
    processing_jobs = sagemaker_client.list_processing_jobs()
    assert len(processing_jobs["ProcessingJobSummaries"]).should.equal(0)

def test_list_processing_jobs_should_validate_input(sagemaker_client):
    junk_status_equals = "blah"
    with pytest.raises(ClientError) as ex:
        sagemaker_client.list_processing_jobs(StatusEquals=junk_status_equals)
    expected_error = f"1 validation errors detected: Value '{junk_status_equals}' at 'statusEquals' failed to satisfy constraint: Member must satisfy enum value set: ['Completed', 'Stopped', 'InProgress', 'Stopping', 'Failed']"
    assert ex.value.response["Error"]["Code"] == "ValidationException"
    assert ex.value.response["Error"]["Message"] == expected_error

    junk_next_token = "asdf"
    with pytest.raises(ClientError) as ex:
        sagemaker_client.list_processing_jobs(NextToken=junk_next_token)
    assert ex.value.response["Error"]["Code"] == "ValidationException"
    assert (
        ex.value.response["Error"]["Message"]
        == 'Invalid pagination token because "{0}".'
    )

def test_list_processing_jobs_with_name_filters(sagemaker_client):
    for i in range(5):
        name = f"xgboost-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    for i in range(5):
        name = f"vgg-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/barfoo-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    xgboost_processing_jobs = sagemaker_client.list_processing_jobs(
        NameContains="xgboost"
    )
    assert len(xgboost_processing_jobs["ProcessingJobSummaries"]).should.equal(5)

    processing_jobs_with_2 = sagemaker_client.list_processing_jobs(NameContains="2")
    assert len(processing_jobs_with_2["ProcessingJobSummaries"]).should.equal(2)

def test_list_processing_jobs_paginated(sagemaker_client):
    for i in range(5):
        name = f"xgboost-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    xgboost_processing_job_1 = sagemaker_client.list_processing_jobs(
        NameContains="xgboost", MaxResults=1
    )
    assert len(xgboost_processing_job_1["ProcessingJobSummaries"]).should.equal(1)
    assert xgboost_processing_job_1["ProcessingJobSummaries"][0][
        "ProcessingJobName"
    ].should.equal("xgboost-0")
    assert xgboost_processing_job_1.get("NextToken").should_not.be.none

    xgboost_processing_job_next = sagemaker_client.list_processing_jobs(
        NameContains="xgboost",
        MaxResults=1,
        NextToken=xgboost_processing_job_1.get("NextToken"),
    )
    assert len(xgboost_processing_job_next["ProcessingJobSummaries"]).should.equal(1)
    assert xgboost_processing_job_next["ProcessingJobSummaries"][0][
        "ProcessingJobName"
    ].should.equal("xgboost-1")
    assert xgboost_processing_job_next.get("NextToken").should_not.be.none

def test_list_processing_jobs_paginated_with_target_in_middle(sagemaker_client):
    for i in range(5):
        name = f"xgboost-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    for i in range(5):
        name = f"vgg-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/barfoo-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    vgg_processing_job_1 = sagemaker_client.list_processing_jobs(
        NameContains="vgg", MaxResults=1
    )
    assert len(vgg_processing_job_1["ProcessingJobSummaries"]).should.equal(0)
    assert vgg_processing_job_1.get("NextToken").should_not.be.none

    vgg_processing_job_6 = sagemaker_client.list_processing_jobs(
        NameContains="vgg", MaxResults=6
    )

    assert len(vgg_processing_job_6["ProcessingJobSummaries"]).should.equal(1)
    assert vgg_processing_job_6["ProcessingJobSummaries"][0][
        "ProcessingJobName"
    ].should.equal("vgg-0")
    assert vgg_processing_job_6.get("NextToken").should_not.be.none

    vgg_processing_job_10 = sagemaker_client.list_processing_jobs(
        NameContains="vgg", MaxResults=10
    )

    assert len(vgg_processing_job_10["ProcessingJobSummaries"]).should.equal(5)
    assert vgg_processing_job_10["ProcessingJobSummaries"][-1][
        "ProcessingJobName"
    ].should.equal("vgg-4")
    assert vgg_processing_job_10.get("NextToken").should.be.none

def test_list_processing_jobs_paginated_with_fragmented_targets(sagemaker_client):
    for i in range(5):
        name = f"xgboost-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/foobar-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    for i in range(5):
        name = f"vgg-{i}"
        arn = f"arn:aws:sagemaker:us-east-1:000000000000:x-x/barfoo-{i}"
        MyProcessingJobModel(processing_job_name=name, role_arn=arn).save(
            sagemaker_client
        )

    processing_jobs_with_2 = sagemaker_client.list_processing_jobs(
        NameContains="2", MaxResults=8
    )
    assert len(processing_jobs_with_2["ProcessingJobSummaries"]).should.equal(2)
    assert processing_jobs_with_2.get("NextToken").should_not.be.none

    processing_jobs_with_2_next = sagemaker_client.list_processing_jobs(
        NameContains="2",
        MaxResults=1,
        NextToken=processing_jobs_with_2.get("NextToken"),
    )
    assert len(processing_jobs_with_2_next["ProcessingJobSummaries"]).should.equal(0)
    assert processing_jobs_with_2_next.get("NextToken").should_not.be.none

    processing_jobs_with_2_next_next = sagemaker_client.list_processing_jobs(
        NameContains="2",
        MaxResults=1,
        NextToken=processing_jobs_with_2_next.get("NextToken"),
    )
    assert len(processing_jobs_with_2_next_next["ProcessingJobSummaries"]).should.equal(
        0
    )
    assert processing_jobs_with_2_next_next.get("NextToken").should.be.none

def test_add_and_delete_tags_in_training_job(sagemaker_client):
    processing_job_name = "MyProcessingJob"
    role_arn = f"arn:aws:iam::{ACCOUNT_ID}:role/FakeRole"
    container = "382416733822.dkr.ecr.us-east-1.amazonaws.com/linear-learner:1"
    bucket = "my-bucket"
    prefix = "my-prefix"
    app_specification = {
        "ImageUri": container,
        "ContainerEntrypoint": ["python3", "app.py"],
    }
    processing_resources = {
        "ClusterConfig": {
            "InstanceCount": 2,
            "InstanceType": "ml.m5.xlarge",
            "VolumeSizeInGB": 20,
        },
    }
    stopping_condition = {"MaxRuntimeInSeconds": 60 * 60}

    job = MyProcessingJobModel(
        processing_job_name,
        role_arn,
        container=container,
        bucket=bucket,
        prefix=prefix,
        app_specification=app_specification,
        processing_resources=processing_resources,
        stopping_condition=stopping_condition,
    )
    resp = job.save(sagemaker_client)
    resource_arn = resp["ProcessingJobArn"]

    tags = [
        {"Key": "myKey", "Value": "myValue"},
    ]
    response = sagemaker_client.add_tags(ResourceArn=resource_arn, Tags=tags)
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = sagemaker_client.list_tags(ResourceArn=resource_arn)
    assert response["Tags"] == tags

    tag_keys = [tag["Key"] for tag in tags]
    response = sagemaker_client.delete_tags(ResourceArn=resource_arn, TagKeys=tag_keys)
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = sagemaker_client.list_tags(ResourceArn=resource_arn)
    assert response["Tags"] == []


text:
package org.apache.tephra;

/**
 * Thrown when transaction has timed out.
 */
public class TransactionNotInProgressException extends TransactionFailureException {
  public TransactionNotInProgressException(String message) {
    super(message);
  }
}


text:
package org.springframework.boot.context.properties.bind;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Validation;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Answers;
import org.mockito.InOrder;

import org.springframework.boot.context.properties.bind.validation.ValidationBindHandler;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.context.properties.source.MockConfigurationPropertySource;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.test.context.support.TestPropertySourceUtils;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link Binder}.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 */
public class BinderTests {

	private List<ConfigurationPropertySource> sources = new ArrayList<>();

	private Binder binder;

	@Before
	public void setup() {
		this.binder = new Binder(this.sources);
	}

	@Test
	public void createWhenSourcesIsNullShouldThrowException() {
		assertThatIllegalArgumentException()
				.isThrownBy(
						() -> new Binder((Iterable<ConfigurationPropertySource>) null))
				.withMessageContaining("Sources must not be null");
	}

	@Test
	public void bindWhenNameIsNullShouldThrowException() {
		assertThatIllegalArgumentException()
				.isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null,
						Bindable.of(String.class), BindHandler.DEFAULT))
				.withMessageContaining("Name must not be null");
	}

	@Test
	public void bindWhenTargetIsNullShouldThrowException() {
		assertThatIllegalArgumentException()
				.isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"),
						null, BindHandler.DEFAULT))
				.withMessageContaining("Target must not be null");
	}

	@Test
	public void bindToValueWhenPropertyIsMissingShouldReturnUnbound() {
		this.sources.add(new MockConfigurationPropertySource());
		BindResult<String> result = this.binder.bind("foo", Bindable.of(String.class));
		assertThat(result.isBound()).isFalse();
	}

	@Test
	public void bindToValueShouldReturnPropertyValue() {
		this.sources.add(new MockConfigurationPropertySource("foo", 123));
		BindResult<Integer> result = this.binder.bind("foo", Bindable.of(Integer.class));
		assertThat(result.get()).isEqualTo(123);
	}

	@Test
	public void bindToValueShouldReturnPropertyValueFromSecondSource() {
		this.sources.add(new MockConfigurationPropertySource("foo", 123));
		this.sources.add(new MockConfigurationPropertySource("bar", 234));
		BindResult<Integer> result = this.binder.bind("bar", Bindable.of(Integer.class));
		assertThat(result.get()).isEqualTo(234);
	}

	@Test
	public void bindToValueShouldReturnConvertedPropertyValue() {
		this.sources.add(new MockConfigurationPropertySource("foo", "123"));
		BindResult<Integer> result = this.binder.bind("foo", Bindable.of(Integer.class));
		assertThat(result.get()).isEqualTo(123);
	}

	@Test
	public void bindToValueWhenMultipleCandidatesShouldReturnFirst() {
		this.sources.add(new MockConfigurationPropertySource("foo", 123));
		this.sources.add(new MockConfigurationPropertySource("foo", 234));
		BindResult<Integer> result = this.binder.bind("foo", Bindable.of(Integer.class));
		assertThat(result.get()).isEqualTo(123);
	}

	@Test
	public void bindToValueWithPlaceholdersShouldResolve() {
		StandardEnvironment environment = new StandardEnvironment();
		TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "bar=23");
		this.sources.add(new MockConfigurationPropertySource("foo", "1${bar}"));
		this.binder = new Binder(this.sources,
				new PropertySourcesPlaceholdersResolver(environment));
		BindResult<Integer> result = this.binder.bind("foo", Bindable.of(Integer.class));
		assertThat(result.get()).isEqualTo(123);
	}

	@Test
	public void bindToValueWithMissingPlaceholderShouldResolveToValueWithPlaceholder() {
		StandardEnvironment environment = new StandardEnvironment();
		this.sources.add(new MockConfigurationPropertySource("foo", "${bar}"));
		this.binder = new Binder(this.sources,
				new PropertySourcesPlaceholdersResolver(environment));
		BindResult<String> result = this.binder.bind("foo", Bindable.of(String.class));
		assertThat(result.get()).isEqualTo("${bar}");
	}

	@Test
	public void bindToValueWithCustomPropertyEditorShouldReturnConvertedValue() {
		this.binder = new Binder(this.sources, null, null, (registry) -> registry
				.registerCustomEditor(JavaBean.class, new JavaBeanPropertyEditor()));
		this.sources.add(new MockConfigurationPropertySource("foo", "123"));
		BindResult<JavaBean> result = this.binder.bind("foo",
				Bindable.of(JavaBean.class));
		assertThat(result.get().getValue()).isEqualTo("123");
	}

	@Test
	public void bindToValueShouldTriggerOnSuccess() {
		this.sources.add(new MockConfigurationPropertySource("foo", "1", "line1"));
		BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS);
		Bindable<Integer> target = Bindable.of(Integer.class);
		this.binder.bind("foo", target, handler);
		InOrder ordered = inOrder(handler);
		ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")),
				eq(target), any(), eq(1));
	}

	@Test
	public void bindToJavaBeanShouldReturnPopulatedBean() {
		this.sources.add(new MockConfigurationPropertySource("foo.value", "bar"));
		JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get();
		assertThat(result.getValue()).isEqualTo("bar");
	}

	@Test
	public void bindToJavaBeanWhenNonIterableShouldReturnPopulatedBean() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource(
				"foo.value", "bar");
		this.sources.add(source.nonIterable());
		JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get();
		assertThat(result.getValue()).isEqualTo("bar");
	}

	@Test
	public void bindToJavaBeanWhenHasPropertyWithSameNameShouldStillBind() {
		// gh-10945
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo", "boom");
		source.put("foo.value", "bar");
		this.sources.add(source);
		JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get();
		assertThat(result.getValue()).isEqualTo("bar");
	}

	@Test
	public void bindToJavaBeanShouldTriggerOnSuccess() {
		this.sources
				.add(new MockConfigurationPropertySource("foo.value", "bar", "line1"));
		BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS);
		Bindable<JavaBean> target = Bindable.of(JavaBean.class);
		this.binder.bind("foo", target, handler);
		InOrder inOrder = inOrder(handler);
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")),
				eq(Bindable.of(String.class)), any(), eq("bar"));
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")),
				eq(target), any(), isA(JavaBean.class));
	}

	@Test
	public void bindWhenHasMalformedDateShouldThrowException() {
		this.sources.add(new MockConfigurationPropertySource("foo",
				"2014-04-01T01:30:00.000-05:00"));
		assertThatExceptionOfType(BindException.class)
				.isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class)))
				.withCauseInstanceOf(ConversionFailedException.class);
	}

	@Test
	public void bindWhenHasAnnotationsShouldChangeConvertedValue() {
		this.sources.add(new MockConfigurationPropertySource("foo",
				"2014-04-01T01:30:00.000-05:00"));
		DateTimeFormat annotation = AnnotationUtils.synthesizeAnnotation(
				Collections.singletonMap("iso", DateTimeFormat.ISO.DATE_TIME),
				DateTimeFormat.class, null);
		LocalDate result = this.binder
				.bind("foo", Bindable.of(LocalDate.class).withAnnotations(annotation))
				.get();
		assertThat(result.toString()).isEqualTo("2014-04-01");
	}

	@Test
	public void bindExceptionWhenBeanBindingFailsShouldHaveNullConfigurationProperty() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo.value", "hello");
		source.put("foo.items", "bar,baz");
		this.sources.add(source);
		Bindable<JavaBean> target = Bindable.of(JavaBean.class);
		assertThatExceptionOfType(BindException.class)
				.isThrownBy(() -> this.binder.bind("foo", target))
				.satisfies(this::noItemsSetterRequirements);
	}

	private void noItemsSetterRequirements(BindException ex) {
		assertThat(ex.getCause().getMessage())
				.isEqualTo("No setter found for property: items");
		assertThat(ex.getProperty()).isNull();
	}

	@Test
	public void bindToValidatedBeanWithResourceAndNonEnumerablePropertySource() {
		ConfigurationPropertySources.from(new PropertySource<String>("test") {

			@Override
			public Object getProperty(String name) {
				return null;
			}

		}).forEach(this.sources::add);
		Validator validator = new SpringValidatorAdapter(Validation.byDefaultProvider()
				.configure().buildValidatorFactory().getValidator());
		this.binder.bind("foo", Bindable.of(ResourceBean.class),
				new ValidationBindHandler(validator));
	}

	@Test
	public void bindToBeanWithCycle() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		this.sources.add(source.nonIterable());
		Bindable<CycleBean1> target = Bindable.of(CycleBean1.class);
		this.binder.bind("foo", target);
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void bindToBeanWithUnresolvableGenerics() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo.bar", "hello");
		this.sources.add(source);
		Bindable<GenericBean> target = Bindable.of(GenericBean.class);
		this.binder.bind("foo", target);
	}

	@Test
	public void bindWithEmptyPrefixShouldIgnorePropertiesWithEmptyName() {
		Map<String, Object> source = new HashMap<>();
		source.put("value", "hello");
		source.put("", "bar");
		Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources
				.from(new MapPropertySource("test", source));
		propertySources.forEach(this.sources::add);
		Bindable<JavaBean> target = Bindable.of(JavaBean.class);
		JavaBean result = this.binder.bind("", target).get();
		assertThat(result.getValue()).isEqualTo("hello");
	}

	public static class JavaBean {

		private String value;

		private List<String> items = Collections.emptyList();

		public String getValue() {
			return this.value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public List<String> getItems() {
			return this.items;
		}

	}

	public enum ExampleEnum {

		FOO_BAR, BAR_BAZ, BAZ_BOO

	}

	@Validated
	public static class ResourceBean {

		private Resource resource;

		public Resource getResource() {
			return this.resource;
		}

		public void setResource(Resource resource) {
			this.resource = resource;
		}

	}

	public static class CycleBean1 {

		private CycleBean2 two;

		public CycleBean2 getTwo() {
			return this.two;
		}

		public void setTwo(CycleBean2 two) {
			this.two = two;
		}

	}

	public static class CycleBean2 {

		private CycleBean1 one;

		public CycleBean1 getOne() {
			return this.one;
		}

		public void setOne(CycleBean1 one) {
			this.one = one;
		}

	}

	public static class GenericBean<T> {

		private T bar;

		public T getBar() {
			return this.bar;
		}

		public void setBar(T bar) {
			this.bar = bar;
		}

	}

	public static class JavaBeanPropertyEditor extends PropertyEditorSupport {

		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			JavaBean value = new JavaBean();
			value.setValue(text);
			setValue(value);
		}

	}

}


text:
<?php

namespace Zotlabs\Update;

class _1035 {
function run() {
	$r = q("CREATE TABLE if not exists `xconfig` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`xchan` CHAR( 255 ) NOT NULL ,
`cat` CHAR( 255 ) NOT NULL ,
`k` CHAR( 255 ) NOT NULL ,
`v` MEDIUMTEXT NOT NULL,
KEY `xchan` ( `xchan` ),
KEY `cat` ( `cat` ),
KEY `k` ( `k` )
) ENGINE = MYISAM DEFAULT CHARSET = utf8");

	if($r)
		return UPDATE_SUCCESS;
	return UPDATE_FAILED;
}

}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_UMFPACKSUPPORT_H
#define EIGEN_UMFPACKSUPPORT_H

/* TODO extract L, extract U, compute det, etc... */

// generic double/complex<double> wrapper functions:

inline void umfpack_free_numeric(void **Numeric, double)
{ umfpack_di_free_numeric(Numeric); }

inline void umfpack_free_numeric(void **Numeric, std::complex<double>)
{ umfpack_zi_free_numeric(Numeric); }

inline void umfpack_free_symbolic(void **Symbolic, double)
{ umfpack_di_free_symbolic(Symbolic); }

inline void umfpack_free_symbolic(void **Symbolic, std::complex<double>)
{ umfpack_zi_free_symbolic(Symbolic); }

inline int umfpack_symbolic(int n_row,int n_col,
                            const int Ap[], const int Ai[], const double Ax[], void **Symbolic,
                            const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO])
{
  return umfpack_di_symbolic(n_row,n_col,Ap,Ai,Ax,Symbolic,Control,Info);
}

inline int umfpack_symbolic(int n_row,int n_col,
                            const int Ap[], const int Ai[], const std::complex<double> Ax[], void **Symbolic,
                            const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO])
{
  return umfpack_zi_symbolic(n_row,n_col,Ap,Ai,&Ax[0].real(),0,Symbolic,Control,Info);
}

inline int umfpack_numeric( const int Ap[], const int Ai[], const double Ax[],
                            void *Symbolic, void **Numeric,
                            const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO])
{
  return umfpack_di_numeric(Ap,Ai,Ax,Symbolic,Numeric,Control,Info);
}

inline int umfpack_numeric( const int Ap[], const int Ai[], const std::complex<double> Ax[],
                            void *Symbolic, void **Numeric,
                            const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO])
{
  return umfpack_zi_numeric(Ap,Ai,&Ax[0].real(),0,Symbolic,Numeric,Control,Info);
}

inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const double Ax[],
                          double X[], const double B[], void *Numeric,
                          const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO])
{
  return umfpack_di_solve(sys,Ap,Ai,Ax,X,B,Numeric,Control,Info);
}

inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const std::complex<double> Ax[],
                          std::complex<double> X[], const std::complex<double> B[], void *Numeric,
                          const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO])
{
  return umfpack_zi_solve(sys,Ap,Ai,&Ax[0].real(),0,&X[0].real(),0,&B[0].real(),0,Numeric,Control,Info);
}

inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, double)
{
  return umfpack_di_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric);
}

inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, std::complex<double>)
{
  return umfpack_zi_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric);
}

inline int umfpack_get_numeric(int Lp[], int Lj[], double Lx[], int Up[], int Ui[], double Ux[],
                               int P[], int Q[], double Dx[], int *do_recip, double Rs[], void *Numeric)
{
  return umfpack_di_get_numeric(Lp,Lj,Lx,Up,Ui,Ux,P,Q,Dx,do_recip,Rs,Numeric);
}

inline int umfpack_get_numeric(int Lp[], int Lj[], std::complex<double> Lx[], int Up[], int Ui[], std::complex<double> Ux[],
                               int P[], int Q[], std::complex<double> Dx[], int *do_recip, double Rs[], void *Numeric)
{
  return umfpack_zi_get_numeric(Lp,Lj,Lx?&Lx[0].real():0,0,Up,Ui,Ux?&Ux[0].real():0,0,P,Q,
                               Dx?&Dx[0].real():0,0,do_recip,Rs,Numeric);
}

inline int umfpack_get_determinant(double *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO])
{
  return umfpack_di_get_determinant(Mx,Ex,NumericHandle,User_Info);
}

inline int umfpack_get_determinant(std::complex<double> *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO])
{
  return umfpack_zi_get_determinant(&Mx->real(),0,Ex,NumericHandle,User_Info);
}

template<typename MatrixType>
class SparseLU<MatrixType,UmfPack> : public SparseLU<MatrixType>
{
  protected:
    typedef SparseLU<MatrixType> Base;
    typedef typename Base::Scalar Scalar;
    typedef typename Base::RealScalar RealScalar;
    typedef Matrix<Scalar,Dynamic,1> Vector;
    typedef Matrix<int, 1, MatrixType::ColsAtCompileTime> IntRowVectorType;
    typedef Matrix<int, MatrixType::RowsAtCompileTime, 1> IntColVectorType;
    typedef SparseMatrix<Scalar,LowerTriangular|UnitDiagBit> LMatrixType;
    typedef SparseMatrix<Scalar,UpperTriangular> UMatrixType;
    using Base::m_flags;
    using Base::m_status;

  public:

    SparseLU(int flags = NaturalOrdering)
      : Base(flags), m_numeric(0)
    {
    }

    SparseLU(const MatrixType& matrix, int flags = NaturalOrdering)
      : Base(flags), m_numeric(0)
    {
      compute(matrix);
    }

    ~SparseLU()
    {
      if (m_numeric)
        umfpack_free_numeric(&m_numeric,Scalar());
    }

    inline const LMatrixType& matrixL() const
    {
      if (m_extractedDataAreDirty) extractData();
      return m_l;
    }

    inline const UMatrixType& matrixU() const
    {
      if (m_extractedDataAreDirty) extractData();
      return m_u;
    }

    inline const IntColVectorType& permutationP() const
    {
      if (m_extractedDataAreDirty) extractData();
      return m_p;
    }

    inline const IntRowVectorType& permutationQ() const
    {
      if (m_extractedDataAreDirty) extractData();
      return m_q;
    }

    Scalar determinant() const;

    template<typename BDerived, typename XDerived>
    bool solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x) const;

    void compute(const MatrixType& matrix);

  protected:

    void extractData() const;

  protected:
    // cached data:
    void* m_numeric;
    const MatrixType* m_matrixRef;
    mutable LMatrixType m_l;
    mutable UMatrixType m_u;
    mutable IntColVectorType m_p;
    mutable IntRowVectorType m_q;
    mutable bool m_extractedDataAreDirty;
};

template<typename MatrixType>
void SparseLU<MatrixType,UmfPack>::compute(const MatrixType& a)
{
  const int rows = a.rows();
  const int cols = a.cols();
  ei_assert((MatrixType::Flags&RowMajorBit)==0 && "Row major matrices are not supported yet");

  m_matrixRef = &a;

  if (m_numeric)
    umfpack_free_numeric(&m_numeric,Scalar());

  void* symbolic;
  int errorCode = 0;
  errorCode = umfpack_symbolic(rows, cols, a._outerIndexPtr(), a._innerIndexPtr(), a._valuePtr(),
                                  &symbolic, 0, 0);
  if (errorCode==0)
    errorCode = umfpack_numeric(a._outerIndexPtr(), a._innerIndexPtr(), a._valuePtr(),
                                   symbolic, &m_numeric, 0, 0);

  umfpack_free_symbolic(&symbolic,Scalar());

  m_extractedDataAreDirty = true;

  Base::m_succeeded = (errorCode==0);
}

template<typename MatrixType>
void SparseLU<MatrixType,UmfPack>::extractData() const
{
  if (m_extractedDataAreDirty)
  {
    // get size of the data
    int lnz, unz, rows, cols, nz_udiag;
    umfpack_get_lunz(&lnz, &unz, &rows, &cols, &nz_udiag, m_numeric, Scalar());

    // allocate data
    m_l.resize(rows,std::min(rows,cols));
    m_l.resizeNonZeros(lnz);

    m_u.resize(std::min(rows,cols),cols);
    m_u.resizeNonZeros(unz);

    m_p.resize(rows);
    m_q.resize(cols);

    // extract
    umfpack_get_numeric(m_l._outerIndexPtr(), m_l._innerIndexPtr(), m_l._valuePtr(),
                        m_u._outerIndexPtr(), m_u._innerIndexPtr(), m_u._valuePtr(),
                        m_p.data(), m_q.data(), 0, 0, 0, m_numeric);

    m_extractedDataAreDirty = false;
  }
}

template<typename MatrixType>
typename SparseLU<MatrixType,UmfPack>::Scalar SparseLU<MatrixType,UmfPack>::determinant() const
{
  Scalar det;
  umfpack_get_determinant(&det, 0, m_numeric, 0);
  return det;
}

template<typename MatrixType>
template<typename BDerived,typename XDerived>
bool SparseLU<MatrixType,UmfPack>::solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived> *x) const
{
  //const int size = m_matrix.rows();
  const int rhsCols = b.cols();
//   ei_assert(size==b.rows());
  ei_assert((BDerived::Flags&RowMajorBit)==0 && "UmfPack backend does not support non col-major rhs yet");
  ei_assert((XDerived::Flags&RowMajorBit)==0 && "UmfPack backend does not support non col-major result yet");

  int errorCode;
  for (int j=0; j<rhsCols; ++j)
  {
    errorCode = umfpack_solve(UMFPACK_A,
        m_matrixRef->_outerIndexPtr(), m_matrixRef->_innerIndexPtr(), m_matrixRef->_valuePtr(),
        &x->col(j).coeffRef(0), &b.const_cast_derived().col(j).coeffRef(0), m_numeric, 0, 0);
    if (errorCode!=0)
      return false;
  }
//   errorCode = umfpack_di_solve(UMFPACK_A,
//       m_matrixRef._outerIndexPtr(), m_matrixRef._innerIndexPtr(), m_matrixRef._valuePtr(),
//       x->derived().data(), b.derived().data(), m_numeric, 0, 0);

  return true;
}

#endif // EIGEN_UMFPACKSUPPORT_H


text:
/**
 * Created by Shawn Liu on 2015/5/21.
 */

var expect = require('chai').expect;
var RetailerObject = require("../../../../components/crawler/retailers");

describe("Test components/crawler/retailers/index.js", function () {

    it("#format() format result with oos selector error", function (done) {
        var result = {
            status: false,
            productURL: 'http://www.tesco.com/groceries/Product/Details/?id=273797773',
            price_now: '£1.37',
            name: 'Carex Handgel Original 50Ml',
            updateDate: new Date(),
            "errors": [
                {
                    "message": "no such element",
                    "code": 7,
                    "selector": {
                        selectorType: 'css',
                        content: 'div.noStock p.un',
                        field: 'oos',
                        scrapeType: 'text'
                    }
                }
            ]
        };
        //var retailerScript = new RetailerObject(result.productURL, "en_gb");
        RetailerObject.format(result)
            .then(function (t) {
                console.log(t);
            })
            .catch(function (err) {
                console.error(err);
            })
            .finally(function () {
                done();
            })
    });
    it.only("Get retailer config", function (done) {
        var url = "http://www.tesco.com/groceries/Product/Details/?id=273797773";
        //var retailerScript = new RetailerObject(url, "en_gb");
        RetailerObject.getSelector(url, "en_gb")
            .then(function (config) {
                expect(config.id).equal("groceries.tesco.com")
            })
            .catch(function (err) {
                console.error(err);
            })
            .finally(function () {
                done();
            })

    })
})


text:
'use strict';

function crossfilter_identity(d) {
  return d;
}

module.exports = crossfilter_identity;