text:
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2012 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

//#ifdef REMOVED

#ifndef PX_PHYSICS_COMMON_NX_SERIAL_FRAMEWORK
#define PX_PHYSICS_COMMON_NX_SERIAL_FRAMEWORK

/** \addtogroup common
@{
*/

#include "common/PxPhysXCommon.h"
#include "common/PxTypeInfo.h"
#include "common/PxFields.h"
#include "common/PxFieldDescriptor.h"
#include "foundation/PxFlags.h"

#ifndef PX_DOXYGEN
namespace physx
{
#endif

typedef PxU16 PxType;
class PxSerializable;
class PxOutputStream;
class PxSerialStream;

//! Serialized input data must be aligned to this value
#define PX_SERIAL_FILE_ALIGN	128

//! Objects are written in a fixed order within a serialized file.
struct PxSerialOrder
{
	enum Enum
	{
		eCONVEX			= 20,
		eTRIMESH		= 21,
		eHEIGHTFIELD	= 22,
		eDEFMESH		= 23,
		eCLOTHMESH		= 24,
		eMATERIAL		= 50,
		eSHAPE			= 80,
		eSTATIC			= 81,
		eDYNAMIC		= 82,
		eDEFAULT		= 100,
		eARTICULATION	= 120,
		eJOINT			= 150,
		eCONSTRAINT		= 200,
		eAGGREGATE		= 300,
	};
};

typedef PxU64 PxSerialObjectRef;

struct PxSerialObjectAndRef
{
	PxSerializable*		serializable;
	PxSerialObjectRef	ref;
};

/**
\brief Class used to "resolve pointers" during deserialization.

The ref-resolver remaps pointers to PxSerializable objects within a deserialized memory block.
This class is mainly used by the serialization framework. Users should not have to worry about it.

@see PxSerializable
*/
class PX_PHYSX_COMMON_API PxRefResolver
{
	public:
	virtual					~PxRefResolver()														{}

	/**
	\brief Retrieves new address of deserialized object

	This is called by the serialization framework.

	\param[in]	oldAddress	Old address of serialized object
	\return		New address of serialized object
	*/
	virtual	void*			newAddress(void* oldAddress) const	= 0;

	/**
	\brief Sets new address of deserialized object.

	This is called by the serialization framework.

	\param[in]	oldAddress	Old address of serialized object
	\param[in]	newAddress	New address of serialized object
	*/
	virtual	void			setNewAddress(void* oldAddress, void* newAddress)	= 0;

	/**
	\brief Sets current string table.

	This is called by the serialization framework.

	\param[in]	stringTable	Current string table address
	*/
	virtual	void			setStringTable(const char* stringTable)	= 0;

	/**
	\brief Resolves external reference.

	This is called by the serialization framework.

	\param[in]	name	Name to be resolved
	\return		Resolved name
	*/
	virtual	const char*		resolveName(const char* name)	= 0;
};

/**
\brief Container for user-defined names/references

This is mainly a "link" object accessed by the framework when serializing and
deserializing subsets.

@see PxSerializable
*/
class PX_PHYSX_COMMON_API PxUserReferences
{
	public:
	virtual					~PxUserReferences()														{}

	/** \brief Deprecated alias for getObjectFromRef

	\param[in]	ref	user-defined reference for this object
	\return		Corresponding object, or NULL if not found
	*/
	PX_DEPRECATED PX_INLINE	PxSerializable*	getObjectFromID(PxSerialObjectRef ref) const			{	return getObjectFromRef(ref); }

	/** \brief Deprecated alias for setObjectRef

	\param[in]	object		Serializable object. See #PxSerializable
	\param[in]	ref			user-defined object reference for this object

	@see setObjectRef
	*/

	PX_DEPRECATED PX_INLINE	void setUserData(PxSerializable* object, PxSerialObjectRef ref)			{	setObjectRef(*object, ref);	}

	/**
	\brief Gets PxSerializable object from its object reference

	This is called by the framework during deserialization, when external references are
	passed to the deserialize function.

	\param[in]	ref	user-defined reference for this object
	\return		Corresponding object, or NULL if not found

	@see PxSerializable
	*/

	virtual	PxSerializable*	getObjectFromRef(PxSerialObjectRef ref) const					= 0;

	/**
	\brief Sets the object reference for a PxSerializable

	This is called by the framework during deserialization, when object references are
	retrieved from a deserialized collection.

	This can also be called by users to link a subset to a completely different
	subset than the one it was originally linked to.

	\param[in]	object		Serializable object. See #PxSerializable
	\param[in]	ref			user-defined reference for this object
	\return		true if success

	@see PxSerializable
	*/

	virtual	bool			setObjectRef(PxSerializable& object, PxSerialObjectRef ref)		= 0;

	/**
	\brief test whether an object is referenced by this UserReferences

	Note that in general the mapping from references to objects may be many-to-one.

	\return whether the object is referenced

	@see setObjectRef getNbObjectRefs

	*/

	virtual bool			objectIsReferenced(PxSerializable& object) const = 0;

	/**
	\brief Retrieves the number of object references

	\return the number of references

	@see getObjectRefs
	*/
	virtual PxU32			getNbObjectRefs() const = 0;

	/**
	\brief Retrieve all object reference pairs

	\param[in]	buffer  an pointer to a buffer into which to write the pairs
	\param[in]	bufSize the size of the buffer
	\return	the number of pairs written

	@see setObjectRef getNbObjectRefs
	*/

	virtual PxU32			getObjectRefs(PxSerialObjectAndRef* buffer, PxU32 bufSize) const = 0;

	/**
	\brief Deletes a user references object.

	@see PxPhysics::createUserReferences()
	*/

	virtual void			release() = 0;
};

struct PxSerialFlag
{
	enum Enum
	{
		eOWNS_MEMORY			= (1<<0),
//		eDISABLED				= (1<<1),
		eDISABLE_AUTO_RESOLVE	= (1<<1),
		eDISABLE_FIELDS			= (1<<2),
		eIN_SCENE				= (1<<3),
	};
};

#if defined(PX_WINDOWS)
//! \cond
template class PX_PHYSX_COMMON_API PxFlags<PxSerialFlag::Enum, PxU16>;  // needed for dll export
//! \endcond
#endif

typedef PxFlags<PxSerialFlag::Enum, PxU16> PxSerialFlags;
PX_FLAGS_OPERATORS(PxSerialFlag::Enum, PxU16);

typedef PxSerializable*	(*PxClassCreationCallback)(char*& address, PxRefResolver& v);

/**
\brief Collection class for serialization.

A collection is a container for serializable SDK objects. All serializable SDK objects inherit from PxSerializable.
Serialization and deserialization only work through collections.

A scene is typically serialized using the following steps:

1) create a collection
2) collect objects to serialize
3) serialize collection
4) release collection

For example the code may look like this:

	PxPhysics* physics;	// The physics SDK object
	PxScene* scene;		// The physics scene
	SerialStream s;		// The user-defined stream doing the actual write to disk

	PxCollection* collection = physics->createCollection();	// step 1)
	PxCollectForExportSDK(*physics, *collection);			// step 2)
	PxCollectForExportScene(*scene, *collection);			// step 2)
	collection->serialize(s);								// step 3)
	physics->releaseCollection(collection);					// step 4)

A scene is typically deserialized using the following steps:

1) load a serialized block somewhere in memory
2) create a collection object
3) deserialize objects (populate collection with objects from the memory block)
4) add collected objects to scene
5) release collection

For example the code may look like this:

	PxPhysics* physics;	// The physics SDK object
	PxScene* scene;		// The physics scene
	void* memory128;	// a 128-byte aligned buffer previously loaded from disk by the user	- step 1)

	PxCollection* collection = physics->createCollection();		// step 2)
	collection->deserialize(memory128, NULL, NULL);				// step 3)
	physics->addCollection(*collection, scene);					// step 4)
	collection->release();										// step 5)

@see PxSerializable
*/
class PxCollection
{
	friend class PxSerializable;
	virtual	void						addUnique(PxSerializable&)	= 0;

public:
										PxCollection()	{}
	virtual								~PxCollection()	{}

	/** \brief deprecated alias for setObjectRef

	\param[in]	object		Serializable object. See #PxSerializable
	\param[in]	ref			user-defined object reference for this object

	@see setObjectRef
	*/
	PX_DEPRECATED PX_INLINE	void		setUserData(PxSerializable& object, PxSerialObjectRef ref)	{	setObjectRef(object, ref); }

	/**
	\brief Serializes a collection.

	Writes out collected objects to a binary stream. Objects are output in the order
	defined by PxSerialOrder, according to their type.

	Object references and external references, as defined by the setObjectRef and
	addExternalRef functions, are also serialized.

	\param[in]	stream		User-defined serialization stream.
	\param[in]	exportNames	If true, objects' names are serialized along with the objects. Not serializing names produce smaller files.

	@see PxSerialOrder setUserData addExternalRef
	*/

	virtual	void						serialize(PxOutputStream& stream, bool exportNames=false)	= 0;

	/**
	\brief Deserializes a collection.

	Initializes/creates objects within the given input buffer, which must have
	been deserialized from disk already by the user. The input buffer must be
	128-bytes aligned.

	Deserialized objects are added to the collection.

	Object references for the collection can be retrieved, if necessary.
	External references can be passed, if necesary.

	\param[in]	buffer128			Deserialized input buffer, 128-bytes aligned
	\param[out]	newReferences		map of new object references created by deserialization, or NULL. See #PxUserReferences
	\param[in]	externalReferences	map for resolving the collection's external references, or NULL. See #PxUserReferences
	\return		True if success

	@see PxUserReferences
	*/
	virtual	bool						deserialize(void* buffer128, PxUserReferences* newReferences, const PxUserReferences* externalReferences)	= 0;

	/**
	\brief Sets user-data/name for a PxSerializable

	This is used to assign an object reference to a PxSerializable. The references are serialized with the collection, and can be used
	after deserialization to look up objects by reference.

	\param[in]	object		Serializable object. See #PxSerializable
	\param[in]	ref			user-defined object reference for this object
	\return		true if success

	@see PxSerializable addExternalRef getObjectRef
	*/
	virtual	bool						setObjectRef(PxSerializable& object, PxSerialObjectRef ref) = 0;

	/**
	\brief Retrieves the object references specified by the user for this collection.

	note that user references created by deserialization are not returned by this function.

	*/
	virtual PxUserReferences* 			getObjectRefs() const = 0;

	/**
	\brief Declares an reference to an object outside the collection

	Some objects in the collection might have pointers/references to objects that are not within
	the collection. Such objects will not be serialized when the collection is serialized, and the
	references will be marked for resolution when the collection is deserialized.

	\param[in]	object		Serializable object. See #PxSerializable
	\param[in]	ref			user-defined name for this object
	\return		true if success

	@see PxSerializable setObjectRef
	*/
	virtual	bool					addExternalRef(PxSerializable& object, PxSerialObjectRef ref)	= 0;

	/**
	\brief Retrieve all external reference pairs

	\note the pairs retrieved are those set by the application with addExternalRef. No external references are created in the
	collection during deserialization.

	\return	the external references

	@see addExternalRef getNbExternalRefs
	*/

	virtual PxUserReferences*			getExternalRefs() const = 0;

	/**
	\brief Gets number of objects in the collection
	\return	Number of objects in the collection
	*/
	virtual	PxU32						getNbObjects() const = 0;

	/**
	\brief Gets object from the collection

	\param[in]	index	Object index, between 0 (incl) and getNbObjects() (excl).
	\return		Desired object from the collection

	@see PxSerializable
	*/
	virtual	PxSerializable*				getObject(PxU32 index) const = 0;

	/**
	\brief Deletes a collection object.

	This function only deletes the collection object, i.e. the container class. It doesn't delete objects
	that are part of the collection.

	@see PxPhysics::createCollection()
	*/

	virtual void						release() = 0;
};

class PxNameManager
{
	public:
	virtual ~PxNameManager() {}
	virtual	void						registerName(const char**)	= 0;
};

class PxPtrManager
{
	public:
	virtual ~PxPtrManager() {}
	virtual	void						registerPtr(void*)	= 0;
};

/**
\brief Base class for serializable objects

@see PxRefResolver PxCollection
*/
class PxSerializable
{
public:

	/**
	\brief returns string name of dynamic type.
	\return	class name of most derived type of this object.
	*/

	virtual		const char*					getConcreteTypeName()		const	{ return NULL;											}

	/* brief dynamic casts a pointer to a pointer to the given type
	\return a pointer to the given type, or NULL
	*/

	template<class T> T*					is()						{ return typeMatch<T>() ? static_cast<T*>(this) : NULL;			}

	/* brief dynamic casts a pointer-to-const to a pointer to the given type
	\return a pointer to the given type, or NULL
	*/

	template<class T> const T*				is() const					{ return typeMatch<T>() ? static_cast<const T*>(this) : NULL;		}

	/**
	\brief	Returns concrete type of object.
	\return	PxConcreteType::Enum of serialized object

	@see PxConcreteType
	*/
	PX_INLINE	PxType						getConcreteType()	const	{ return mConcreteType;	}

	virtual		PxU32						getOrder()											const	{ return PxSerialOrder::eDEFAULT;						}

	/**
	\brief Adds an object to the collection.

	\param[in]	c				collection to add the object to

	@see PxCollection
	*/
	virtual		void						collectForExport(PxCollection& c)							{ c.addUnique(*this);									}

	virtual		bool						getFields(PxSerialStream&, PxU32)					const	{ return true;											}
	virtual		bool						getFields(PxSerialStream&, PxField::Enum)			const	{ return true;											}
	virtual		bool						getFields(PxSerialStream&)							const	{ return true;											}
	virtual		const PxFieldDescriptor*	getFieldDescriptor(const char*)						const	{ return NULL;											}

	virtual		PxU32						getObjectSize()										const	= 0;

	virtual		void						exportExtraData(PxSerialStream&)							{														}
	virtual		char*						importExtraData(char* address, PxU32&)						{ return address;										}
	virtual		bool						resolvePointers(PxRefResolver&, void*)						{ return true;											}

	virtual		void						registerNameForExport(PxNameManager&)						{														}
	virtual		void						registerPtrsForExport(PxPtrManager& manager)				{ manager.registerPtr(this);							}

	virtual		void						disableInternalCaching(bool)								{}

	PX_INLINE	void						setSerialFlag(PxSerialFlag::Enum flag, bool value)			{ mSerialFlags = value ? mSerialFlags|flag : mSerialFlags&~flag; }
	PX_INLINE	void						setSerialFlags(PxSerialFlags inFlags )						{ mSerialFlags = inFlags;								}
	PX_INLINE	PxSerialFlags				getSerialFlags()									const	{ return mSerialFlags;									}

	static		void						getMetaData(PxSerialStream& stream);
	virtual									~PxSerializable()											{}

protected:
											PxSerializable(PxRefResolver& v)
											{
												mSerialFlags &= ~PxSerialFlag::eOWNS_MEMORY;
											    PX_UNUSED(v);
											}
											PxSerializable() : mConcreteType(PxConcreteType::eUNDEFINED), mSerialFlags(PxSerialFlag::eOWNS_MEMORY)
											{
											}

	PX_INLINE	void						setSerialType(PxType t)											{ mConcreteType = t;														}

	template<class T> bool					typeMatch() const
	{
		return PxU32(PxTypeInfo<T>::eFastTypeId)!=PxU32(PxConcreteType::eUNDEFINED) ? PxU32(getConcreteType()) == PxU32(PxTypeInfo<T>::eFastTypeId)
																					: isKindOf(PxTypeInfo<T>::name());
	}

	virtual		bool						isKindOf(const char* superClass)					const	{ return !strcmp(superClass, "PxSerializable");			}

private:
				PxType						mConcreteType;			// Some kind of class identifier. Could use a string = class name
				PxSerialFlags				mSerialFlags;	// Serialization flags
};

#ifndef PX_DOXYGEN
} // namespace physx
#endif

/** @} */
#endif


text:
//// [recursiveExportAssignmentAndFindAliasedType5_moduleC.ts]
import self = require("recursiveExportAssignmentAndFindAliasedType5_moduleD");
export = self;

//// [recursiveExportAssignmentAndFindAliasedType5_moduleD.ts]
import self = require("recursiveExportAssignmentAndFindAliasedType5_moduleC");
export = self;

//// [recursiveExportAssignmentAndFindAliasedType5_moduleB.ts]
class ClassB { }
export = ClassB;

//// [recursiveExportAssignmentAndFindAliasedType5_moduleA.ts]
import moduleC = require("recursiveExportAssignmentAndFindAliasedType5_moduleC");
import ClassB = require("recursiveExportAssignmentAndFindAliasedType5_moduleB");
export var b: ClassB; // This should result in type ClassB

//// [recursiveExportAssignmentAndFindAliasedType5_moduleD.js]
define(["require", "exports"], function (require, exports) {
});
//// [recursiveExportAssignmentAndFindAliasedType5_moduleC.js]
define(["require", "exports"], function (require, exports) {
});
//// [recursiveExportAssignmentAndFindAliasedType5_moduleB.js]
define(["require", "exports"], function (require, exports) {
    var ClassB = (function () {
        function ClassB() {
        }
        return ClassB;
    })();
    return ClassB;
});
//// [recursiveExportAssignmentAndFindAliasedType5_moduleA.js]
define(["require", "exports"], function (require, exports) {
     // This should result in type ClassB
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SwAlgolia\Services\ProductProcessor;

use Shopware\Bundle\StoreFrontBundle\Struct\Product;
use SwAlgolia\Structs\Article;

/**
 * Interface ProcessorInterface.
 */
interface ProcessorInterface
{
    /**
     * @param Product $product    Shopware Product
     * @param Article $article    Algolia Product
     * @param array   $shopConfig Shop Configuration
     */
    public function process(Product $product, Article $article, array $shopConfig);
}


text:
- Support Windows installs
- Bump phantomjs version to 2.1.1

## v1.0.0

- Fork of Seth Vargo's phantomjs with resource added and support for package installs removed


text:
"""
RAM Weigher.  Weigh hosts by their RAM usage.

The default is to spread instances across all hosts evenly.  If you prefer
stacking, you can set the 'ram_weight_multiplier' option to a negative
number and the weighing has the opposite effect of the default.
"""

import nova.conf
from nova.scheduler import weights

CONF = nova.conf.CONF

class RAMWeigher(weights.BaseHostWeigher):
    minval = 0

    def weight_multiplier(self):
        """Override the weight multiplier."""
        return CONF.ram_weight_multiplier

    def _weigh_object(self, host_state, weight_properties):
        """Higher weights win.  We want spreading to be the default."""
        return host_state.free_ram_mb


text:
<?php

namespace TijsVerkoyen\UitDatabank\Entities\Event;

use TijsVerkoyen\UitDatabank\Entities\Event\Location\Label;
use TijsVerkoyen\UitDatabank\Exception;
use TijsVerkoyen\UitDatabank\UitDatabank;

class Location
{
    /**
     * @var Address
     */
    protected $address;

    /**
     * @var Label
     */
    protected $label;

    /**
     * @param \TijsVerkoyen\UitDatabank\Entities\Event\Address $address
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }

    /**
     * @return \TijsVerkoyen\UitDatabank\Entities\Event\Address
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * @param \TijsVerkoyen\UitDatabank\Entities\Event\Label $label
     */
    public function setLabel($label)
    {
        $this->label = $label;
    }

    /**
     * @return \TijsVerkoyen\UitDatabank\Entities\Event\Label
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Convert the raw XML into an object
     *
     * @param \SimpleXMLElement $xml
     * @return Location
     */
    public static function createFromXML(\SimpleXMLElement $xml)
    {
        $location = new Location();

        // loop attributes
        foreach ($xml->attributes() as $attributeName => $value) {
            $method = 'set' . ucfirst($attributeName);

            switch ($attributeName) {
                default:
                    $value = (string) $value;
            }

            if (!method_exists($location, $method)) {
                if (UitDatabank::DEBUG) {
                    throw new Exception('Unknown attribute: ' . $attributeName);
                }
            } else {
                call_user_func(array($location, $method), $value);
            }
        }

        // loop elements
        foreach ($xml as $element) {
            $elementName = $element->getName();
            $method = 'set' . ucfirst($element->getName());

            switch ($elementName) {
                case 'address':
                    $value = Address::createFromXML($element);
                    break;
                case 'label':
                    $value = Label::createFromXML($element);
                    break;
                default:
                    $value = (string) $element;
                    break;
            }

            if (!method_exists($location, $method)) {
                if (UitDatabank::DEBUG) {
                    throw new Exception('Unknown element: ' . $elementName);
                }
            } else {
                call_user_func(array($location, $method), $value);
            }
        }

        return $location;
    }
}


text:
package at.ac.tuwien.service.impl.lucene.analyzers.filters;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.de.GermanLightStemmer;

public class GermanMultiWordStemFilterTest extends MultiWordStemFilterTest {
    private String firstStemmed;
    private String secondStemmed;

    public GermanMultiWordStemFilterTest() {
        // Same stemmer as used in the filter
        GermanLightStemmer germanLightStemmer = new GermanLightStemmer();

        char[] notStemmed = FIRST_NOT_STEMMED_WORD.toCharArray();
        germanLightStemmer.stem(notStemmed, notStemmed.length);
        firstStemmed = new String(notStemmed);

        notStemmed = SECOND_NOT_STEMMED_WORD.toCharArray();
        germanLightStemmer.stem(notStemmed, notStemmed.length);
        secondStemmed = new String(notStemmed);
    }

    @Override
    MultiWordStemFilter getFilter(TokenStream tokenStream) {
        return new GermanMultiWordStemFilter(tokenStream);
    }

    @Override
    String getFirstStemmedWord() {
        return firstStemmed;
    }

    @Override
    String getSecondStemmedWord() {
        return secondStemmed;
    }
}


text:
@interface IKCreateContactViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textFieldName;
@property (weak, nonatomic) IBOutlet UITextField *textFieldEmail;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPhone;

@end

@implementation IKCreateContactViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Creating contact...";
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                target:self
                                                                                action:@selector(createContact:)];
    [[self navigationItem] setRightBarButtonItem:doneButton];
	// Do any additional setup after loading the view.
}
- (IBAction)createContact:(id)sender
{
    if (!self.textFieldName.text || [self.textFieldName.text isEqualToString:@""])
        return;
    NSDictionary * contactDictionary = @{@"name" : self.textFieldName.text
                                         ,@"email" : self.textFieldEmail.text
                                         ,@"phone" : self.textFieldPhone.text};
    IKContact * contact = [[IKContact alloc] initWithDictionary:contactDictionary];
//    [self.contactsRepository createContact:contact success:^(IKContact *contact) {
//        [self.navigationController popViewControllerAnimated:YES];
//    } failure:^(NSString *errorMessage) {
//                [[[UIAlertView alloc]initWithTitle:@"ERROR" message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]show];
//    } ];

	[self.contactsRepository createDocument:contact success:^(id<IJDocumentProtocol>document) {
		[self.navigationController popViewControllerAnimated:YES];
	} failure:^(IJError *error) {
		[[[UIAlertView alloc]initWithTitle:@"ERROR"
								   message:error.localizedDescription
								  delegate:nil
						 cancelButtonTitle:@"OK"
						 otherButtonTitles: nil] show];
	}];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
Email Us

We welcome all feedback and comments you may have about the Research site.

Email Us


text:
module Killbill #:nodoc:
  module Orbital #:nodoc:
    class PaymentPlugin < ::Killbill::Plugin::ActiveMerchant::PaymentPlugin
      FIVE_MINUTES_AGO = (5 * 60)
      ONE_HOUR_AGO = (1 * 3600)

      def initialize
        gateway_builder = Proc.new do |config|
          ::ActiveMerchant::Billing::OrbitalGateway.new :login => config[:login],
                                                        :password => config[:password],
                                                        # ActiveMerchant expects it to be a String
                                                        :merchant_id => config[:merchant_id].to_s
        end

        super(gateway_builder,
              :orbital,
              ::Killbill::Orbital::OrbitalPaymentMethod,
              ::Killbill::Orbital::OrbitalTransaction,
              ::Killbill::Orbital::OrbitalResponse)
      end

      def on_event(event)
        # Require to deal with per tenant configuration invalidation
        super(event)
        #
        # Custom event logic could be added below...
        #
      end

      def authorize_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, with_trace_num_and_order_id(properties))
      end

      def capture_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
        # Pass extra parameters for the gateway here
        options = properties_to_hash properties
        if options[:force_capture]
          last_auth_response = @response_model.send('auth_responses_from_kb_payment_id', kb_payment_id, context.tenant_id).last
          raise "Unable to retrieve last authorization for operation=capture, kb_payment_id=#{kb_payment_id}, kb_payment_transaction_id=#{kb_payment_transaction_id}, kb_payment_method_id=#{kb_payment_method_id}" if last_auth_response.nil?
          options[:payment_processor_account_id] = last_auth_response.payment_processor_account_id
          options[:prior_auth_id] = last_auth_response.params_auth_code
          options[:order_id] = last_auth_response.second_reference_id if options[:order_id].nil?
          purchase_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, hash_to_properties(options), context)
        else
          super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, with_trace_num_and_order_id(properties))
        end
      end

      def purchase_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, with_trace_num_and_order_id(properties))
      end

      def void_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, properties, context, with_trace_num_and_order_id(properties))
      end

      def credit_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, with_trace_num_and_order_id(properties))
      end

      def refund_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, with_trace_num_and_order_id(properties))
      end

      def get_payment_info(kb_account_id, kb_payment_id, properties, context)
        options = properties_to_hash(properties)

        plugin_trxs_info = super(kb_account_id, kb_payment_id, properties, context)
        return super(kb_account_id, kb_payment_id, properties, context) if try_fix_undefined_trxs(plugin_trxs_info, options, context)
        plugin_trxs_info
      end

      def search_payments(search_key, offset, limit, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(search_key, offset, limit, properties, context)
      end

      def add_payment_method(kb_account_id, kb_payment_method_id, payment_method_props, set_default, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_method_id, payment_method_props, set_default, properties, context)
      end

      def delete_payment_method(kb_account_id, kb_payment_method_id, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_method_id, properties, context)
      end

      def get_payment_method_detail(kb_account_id, kb_payment_method_id, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, kb_payment_method_id, properties, context)
      end

      def set_default_payment_method(kb_account_id, kb_payment_method_id, properties, context)
        # TODO
      end

      def get_payment_methods(kb_account_id, refresh_from_gateway, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(kb_account_id, refresh_from_gateway, properties, context)
      end

      def search_payment_methods(search_key, offset, limit, properties, context)
        # Pass extra parameters for the gateway here
        options = {}

        properties = merge_properties(properties, options)
        super(search_key, offset, limit, properties, context)
      end

      def reset_payment_methods(kb_account_id, payment_methods, properties, context)
        super
      end

      private

      def try_fix_undefined_trxs(plugin_trxs_info, options, context)
        stale = false
        plugin_trxs_info.each do |plugin_trx_info|
          next unless should_try_to_fix_trx plugin_trx_info, options
          stale = true if fix_undefined_trx plugin_trx_info, context, options
        end
        stale
      end

      def should_try_to_fix_trx(plugin_trx_info, options)
        plugin_trx_info.status == :UNDEFINED && pass_delay_time(plugin_trx_info, options)
      end

      def fix_undefined_trx(plugin_trx_info, context, options)
        inquiry_response = inquiry(plugin_trx_info, context)
        update_response_if_needed plugin_trx_info, inquiry_response, options
      end

      def update_response_if_needed(plugin_trx_info, inquiry_response, options)
        response_id = find_value_from_properties(plugin_trx_info.properties, 'orbital_response_id')
        response = OrbitalResponse.find_by(:id => response_id)
        updated = false
        if should_update_response inquiry_response, plugin_trx_info
          logger.info("Fixing UNDEFINED kb_transaction_id='#{plugin_trx_info.kb_transaction_payment_id}', success='#{inquiry_response.success?}'")
          response.update_and_create_transaction(inquiry_response)
          updated = true
        elsif should_cancel_payment plugin_trx_info, options
          @logger.info("Canceling UNDEFINED kb_transaction_id='#{plugin_trx_info.kb_transaction_payment_id}'")
          response.cancel
          updated = true
        end
        updated
      end

      def should_update_response(inquiry_response, plugin_trx_info)
        !inquiry_response.nil? && !inquiry_response.params.nil? && inquiry_response.params['order_id'] == plugin_trx_info.second_payment_reference_id
      end

      def should_cancel_payment(plugin_trx_info, options)
        threshold = (Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :cancel_threshold) || ONE_HOUR_AGO).to_i
        delay_since_trx(plugin_trx_info) >= threshold
      end

      def pass_delay_time(plugin_trx_info, options)
        janitor_delay_threshold = (Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :janitor_delay_threshold) || FIVE_MINUTES_AGO).to_i
        delay_since_trx(plugin_trx_info) >= janitor_delay_threshold
      end

      def delay_since_trx(plugin_trx_info)
        delay_since_transaction = now - plugin_trx_info.created_date
        delay_since_transaction < 0 ? 0 : delay_since_transaction
      end

      def now
        Time.parse(@clock.get_clock.get_utc_now.to_s)
      end

      def inquiry(plugin_trx_info, context)
        payment_processor_account_id = find_value_from_properties(plugin_trx_info.properties, 'payment_processor_account_id')
        trace_number = find_value_from_properties(plugin_trx_info.properties, 'trace_number')
        orbital_order_id = plugin_trx_info.second_payment_reference_id

        return nil if trace_number.nil? || orbital_order_id.nil? || payment_processor_account_id.nil?

        gateway = lookup_gateway(payment_processor_account_id, context.tenant_id)
        gateway.inquiry(orbital_order_id, trace_number)
      end

      def with_trace_num_and_order_id(properties)
        {:params_trace_number => find_value_from_properties(properties, :trace_number),
         :params_order_id => find_value_from_properties(properties, :order_id)}.delete_if{|_, value| value.blank?}
      end

    end
  end
end


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.emulator')

.constant('mmCoreEmulatorLastReceivedNotificationStore', 'mm_emulator_last_received_notification')

.config(function($mmSitesFactoryProvider, mmCoreEmulatorLastReceivedNotificationStore) {
    var stores = [
        {
            name: mmCoreEmulatorLastReceivedNotificationStore,
            keyPath: 'component' // Only 1 entry per component.
        }
    ];
    $mmSitesFactoryProvider.registerStores(stores);
})

.factory('$mmEmulatorHelper', function($log, $mmSitesManager, $mmApp, $q, $mmLocalNotifications, $mmUtil, mmCoreSecondsDay,
            mmCoreEmulatorLastReceivedNotificationStore) {

    $log = $log.getInstance('$mmEmulatorHelper');

    var self = {};

    /**
     * Check if there are new notifications, triggering a local notification if found.
     * Only for desktop apps since they don't support push notifications.
     *
     * @module mm.core.emulator
     * @ngdoc method
     * @name $mmEmulatorHelper#checkNewNotifications
     * @param {String} [siteId] Site ID to check. If not defined, check all sites.
     * @return {Promise}        Promise resolved when done.
     */
    self.checkNewNotifications = function(component, fetchFn, getDataFn, siteId) {
        if (!$mmApp.isDesktop() || !$mmLocalNotifications.isAvailable()) {
            return $q.when();
        }

        if (!$mmApp.isOnline()) {
            $log.debug('Cannot check push notifications because device is offline.');
            return $q.reject();
        }

        var promise;
        if (!siteId) {
            // No site ID defined, check all sites.
            promise = $mmSitesManager.getSitesIds();
        } else {
            promise = $q.when([siteId]);
        }

        return promise.then(function(siteIds) {
            var sitePromises = [];

            angular.forEach(siteIds, function(siteId) {
                // Check new notifications for each site.
                sitePromises.push(checkNewNotificationsForSite(component, fetchFn, getDataFn, siteId));
            });

            return $q.all(sitePromises);
        });
    };

    /**
     * Check if there are new notifications for a certain site, triggering a local notification if found.
     *
     * @param {String} siteId Site ID to check.
     * @return {Promise}      Promise resolved when done.
     */
    function checkNewNotificationsForSite(component, fetchFn, getDataFn, siteId) {
        // Get the last received notification in the app.
        return self.getLastReceivedNotification(component, siteId).then(function(lastNotification) {
            // Now fetch the latest notifications from the server.
            return fetchFn(siteId).then(function(notifications) {
                if (!lastNotification || !notifications.length) {
                    // No last notification stored (first call) or no new notifications. Stop.
                    return;
                }

                var notification = notifications[0];

                if (notification.id == lastNotification.id || notification.timecreated <= lastNotification.timecreated ||
                        $mmUtil.timestamp() - notification.timecreated > mmCoreSecondsDay) {
                    // There are no new notifications or the newest one happened more than a day ago, stop.
                    return;
                }

                // There is a new notification, show it.
                return $q.when(getDataFn(notification)).then(function(titleAndText) {
                    var localNotif = {
                            id: 1,
                            at: new Date(),
                            title: titleAndText.title,
                            text: titleAndText.text,
                            data: {
                                notif: notification,
                                site: siteId
                            }
                        };

                    $mmLocalNotifications.schedule(localNotif, component, siteId);
                });
            });
        });
    }

    /**
     * Get the last notification received in a certain site for a certain component.
     *
     * @module mm.core.emulator
     * @ngdoc method
     * @name $mmEmulatorHelper#getLastReceivedNotification
     * @param  {String} component Component of the notification to get.
     * @param  {String} siteId    Site ID of the notification.
     * @return {Promise}          Promise resolved with the notification or false if not found.
     */
    self.getLastReceivedNotification = function(component, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.getDb().get(mmCoreEmulatorLastReceivedNotificationStore, component);
        }).catch(function() {
            return false;
        });
    };

    /**
     * Check if the app is running in a Windows environment.
     *
     * @module mm.core.emulator
     * @ngdoc method
     * @name $mmEmulatorHelper#isWindows
     * @return {Boolean} Whether it's running in a Windows environment.
     */
    self.isWindows = function() {
        try {
            var os = require('os');
            return os.platform().indexOf('win') === 0;
        } catch(ex) {
            return false;
        }
    };

    /**
     * Store the last notification received in a certain site.
     *
     * @module mm.core.emulator
     * @ngdoc method
     * @name $mmEmulatorHelper#storeLastReceivedNotification
     * @param  {String} component    Component of the notification to store.
     * @param  {Object} notification Notification to store.
     * @param  {String} siteId       Site ID of the notification.
     * @return {Promise}             Promise resolved when done.
     */
    self.storeLastReceivedNotification = function(component, notification, siteId) {
        if (!notification) {
            // No notification, store a fake one.
            notification = {id: -1, timecreated: 0};
        }
        notification.component = component;

        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.getDb().insert(mmCoreEmulatorLastReceivedNotificationStore, notification);
        });
    };

    return self;
});


text:
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

import { newRecord, Item, Goods }       from '../../type';
import { GoodsService }                 from '../goods.service';

import { Store }                        from '../../beehive/store';
import { StoreService }                 from '../../beehive/store.service';

import { ModalComponent }               from '../../shared/modal/modal.component';
import { ItemsComponent }               from './items.component';

@Component({
  moduleId: module.id,
  templateUrl: './warehousing.component.html',
  styles: [`
    .panel-body {
      padding: 30px;
    }

    .table {
      margin-bottom: 10px;
    }

    tbody td {
      line-height: 34px;
    }

    .btn {
      background-color: #18a689;
      color: #fff;
    }

    .btn:hover {
      background-color: #5fc1ad;
      color: #fff;
    }

    p {
      margin: 10px 0 0;
      padding-top: 10px;
      padding-right: 15%;
      text-align: right;
      font-size: 1.5em;
      color: #18a689;
      border-top: 2px solid #ddd;
    }
  `],
  host: {
    '[class.modal-open]': 'modal.isOpened'
  }
})
export class WarehousingComponent implements OnInit {
  @ViewChild(ModalComponent) modal:ModalComponent;
  stores:Store[];  // 仓库
  form:FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private goodsService: GoodsService,
    private storeService: StoreService) {

    this.form = this.formBuilder.group({
            time: ['', Validators.required],
            store: [0, Validators.required],
            charge: ['', Validators.required],
            code: ['', Validators.required],
            list: this.formBuilder.array([]),
            total: 0,
            remark: ''
        });
    this.cal();
  }

  ngOnInit():void {
    this.storeService.getStores().then(stores => this.stores = stores);
  }

  get list():FormArray {
    return this.form.get('list') as FormArray;
  };

  selected(good:any):void {
    const item = this.formBuilder.group({
      id: good.id,
      code: good.code,
      name: good.name,
      quantity: ['', Validators.required],
      price: ['', Validators.required],
      total: 0
    });
    this.list.push(item);
    const quantity = item.get('quantity'), price = item.get('price'), total = item.get('total');
    quantity.valueChanges.distinctUntilChanged().subscribe(
      (value:string) => {
        total.setValue(+quantity.value * +price.value);
      });
    price.valueChanges.distinctUntilChanged().subscribe(
      (value:string) => { total.setValue(+quantity.value * +price.value); });
  }

  add():void {
    this.modal.open('选择入库商品', ItemsComponent, { close:()=>{this.modal.close();} });
  }

  del(index:number):void {
    this.list.removeAt(index);
  }

  cal():void {
    this.list.valueChanges.distinctUntilChanged().subscribe(
      () => {
        let total = 0;
        this.list.value.forEach((item:any)=>{ total += item.total; })
        this.form.get('total').setValue(total);
      }
    );
  }

  onSubmit():void {
    const record = this.form.value;
    record.list.forEach(
      (item:Item) => {
        let good:Goods;
        this.goodsService.detail(item.id).then(result => {
          good = result;
          good.quantity = Number(good.quantity) + Number(item.quantity);
          this.goodsService.update(good).then(() => { console.log(good.quantity); });
        });
      }
    );
  /*  this.goodsService.createRecord(record)
        .then(() => {
          //this.location.back();
        }); */
  }
}


text:
package org.apache.camel;

import javax.xml.bind.annotation.XmlEnum;

/**
 * Level of granularity for performance statistics enabled
 *
 * @version
 */
@XmlEnum
public enum ManagementStatisticsLevel {

    Extended, Default, RoutesOnly, Off;

    public boolean isDefaultOrExtended() {
        return ordinal() == Default.ordinal() || ordinal() == Extended.ordinal();
    }

    public boolean isExtended() {
        return ordinal() == Extended.ordinal();
    }

}


text:
dir="$(dirname "$0")"

sh $dir/npmInstallGlobal.sh bower pm2


text:
package com.amazonaws.services.cloudformation.model;

import java.io.Serializable;

/**
 *

 * Contains high-level information about the specified stack resource.
 *

 */
public class StackResourceSummary implements Serializable, Cloneable {

    /**
     *

     * The logical name of the resource specified in the template.
     *

     */
    private String logicalResourceId;
    /**
     *

     * The name or unique identifier that corresponds to a physical instance ID
     * of the resource.
     *

     */
    private String physicalResourceId;
    /**
     *

     * Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User Guide.)
     *

     */
    private String resourceType;
    /**
     *

     * Time the status was updated.
     *

     */
    private java.util.Date lastUpdatedTimestamp;
    /**
     *

     * Current status of the resource.
     *

     */
    private String resourceStatus;
    /**
     *

     * Success/failure message associated with the resource.
     *

     */
    private String resourceStatusReason;

    /**
     *

     * The logical name of the resource specified in the template.
     *

     *
     * @param logicalResourceId
     *        The logical name of the resource specified in the template.
     */
    public void setLogicalResourceId(String logicalResourceId) {
        this.logicalResourceId = logicalResourceId;
    }

    /**
     *

     * The logical name of the resource specified in the template.
     *

     *
     * @return The logical name of the resource specified in the template.
     */
    public String getLogicalResourceId() {
        return this.logicalResourceId;
    }

    /**
     *

     * The logical name of the resource specified in the template.
     *

     *
     * @param logicalResourceId
     *        The logical name of the resource specified in the template.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public StackResourceSummary withLogicalResourceId(String logicalResourceId) {
        setLogicalResourceId(logicalResourceId);
        return this;
    }

    /**
     *

     * The name or unique identifier that corresponds to a physical instance ID
     * of the resource.
     *

     *
     * @param physicalResourceId
     *        The name or unique identifier that corresponds to a physical
     *        instance ID of the resource.
     */
    public void setPhysicalResourceId(String physicalResourceId) {
        this.physicalResourceId = physicalResourceId;
    }

    /**
     *

     * The name or unique identifier that corresponds to a physical instance ID
     * of the resource.
     *

     *
     * @return The name or unique identifier that corresponds to a physical
     *         instance ID of the resource.
     */
    public String getPhysicalResourceId() {
        return this.physicalResourceId;
    }

    /**
     *

     * The name or unique identifier that corresponds to a physical instance ID
     * of the resource.
     *

     *
     * @param physicalResourceId
     *        The name or unique identifier that corresponds to a physical
     *        instance ID of the resource.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public StackResourceSummary withPhysicalResourceId(String physicalResourceId) {
        setPhysicalResourceId(physicalResourceId);
        return this;
    }

    /**
     *

     * Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User Guide.)
     *

     *
     * @param resourceType
     *        Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User
     *        Guide.)
     */
    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
    }

    /**
     *

     * Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User Guide.)
     *

     *
     * @return Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User
     *         Guide.)
     */
    public String getResourceType() {
        return this.resourceType;
    }

    /**
     *

     * Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User Guide.)
     *

     *
     * @param resourceType
     *        Type of resource. (For more information, go to  AWS Resource Types Reference in the AWS CloudFormation User
     *        Guide.)
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public StackResourceSummary withResourceType(String resourceType) {
        setResourceType(resourceType);
        return this;
    }

    /**
     *

     * Time the status was updated.
     *

     *
     * @param lastUpdatedTimestamp
     *        Time the status was updated.
     */
    public void setLastUpdatedTimestamp(java.util.Date lastUpdatedTimestamp) {
        this.lastUpdatedTimestamp = lastUpdatedTimestamp;
    }

    /**
     *

     * Time the status was updated.
     *

     *
     * @return Time the status was updated.
     */
    public java.util.Date getLastUpdatedTimestamp() {
        return this.lastUpdatedTimestamp;
    }

    /**
     *

     * Time the status was updated.
     *

     *
     * @param lastUpdatedTimestamp
     *        Time the status was updated.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public StackResourceSummary withLastUpdatedTimestamp(
            java.util.Date lastUpdatedTimestamp) {
        setLastUpdatedTimestamp(lastUpdatedTimestamp);
        return this;
    }

    /**
     *

     * Current status of the resource.
     *

     *
     * @param resourceStatus
     *        Current status of the resource.
     * @see ResourceStatus
     */
    public void setResourceStatus(String resourceStatus) {
        this.resourceStatus = resourceStatus;
    }

    /**
     *

     * Current status of the resource.
     *

     *
     * @return Current status of the resource.
     * @see ResourceStatus
     */
    public String getResourceStatus() {
        return this.resourceStatus;
    }

    /**
     *

     * Current status of the resource.
     *

     *
     * @param resourceStatus
     *        Current status of the resource.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see ResourceStatus
     */
    public StackResourceSummary withResourceStatus(String resourceStatus) {
        setResourceStatus(resourceStatus);
        return this;
    }

    /**
     *

     * Current status of the resource.
     *

     *
     * @param resourceStatus
     *        Current status of the resource.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see ResourceStatus
     */
    public void setResourceStatus(ResourceStatus resourceStatus) {
        this.resourceStatus = resourceStatus.toString();
    }

    /**
     *

     * Current status of the resource.
     *

     *
     * @param resourceStatus
     *        Current status of the resource.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see ResourceStatus
     */
    public StackResourceSummary withResourceStatus(ResourceStatus resourceStatus) {
        setResourceStatus(resourceStatus);
        return this;
    }

    /**
     *

     * Success/failure message associated with the resource.
     *

     *
     * @param resourceStatusReason
     *        Success/failure message associated with the resource.
     */
    public void setResourceStatusReason(String resourceStatusReason) {
        this.resourceStatusReason = resourceStatusReason;
    }

    /**
     *

     * Success/failure message associated with the resource.
     *

     *
     * @return Success/failure message associated with the resource.
     */
    public String getResourceStatusReason() {
        return this.resourceStatusReason;
    }

    /**
     *

     * Success/failure message associated with the resource.
     *

     *
     * @param resourceStatusReason
     *        Success/failure message associated with the resource.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public StackResourceSummary withResourceStatusReason(
            String resourceStatusReason) {
        setResourceStatusReason(resourceStatusReason);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLogicalResourceId() != null)
            sb.append("LogicalResourceId: " + getLogicalResourceId() + ",");
        if (getPhysicalResourceId() != null)
            sb.append("PhysicalResourceId: " + getPhysicalResourceId() + ",");
        if (getResourceType() != null)
            sb.append("ResourceType: " + getResourceType() + ",");
        if (getLastUpdatedTimestamp() != null)
            sb.append("LastUpdatedTimestamp: " + getLastUpdatedTimestamp()
                    + ",");
        if (getResourceStatus() != null)
            sb.append("ResourceStatus: " + getResourceStatus() + ",");
        if (getResourceStatusReason() != null)
            sb.append("ResourceStatusReason: " + getResourceStatusReason());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StackResourceSummary == false)
            return false;
        StackResourceSummary other = (StackResourceSummary) obj;
        if (other.getLogicalResourceId() == null
                ^ this.getLogicalResourceId() == null)
            return false;
        if (other.getLogicalResourceId() != null
                && other.getLogicalResourceId().equals(
                        this.getLogicalResourceId()) == false)
            return false;
        if (other.getPhysicalResourceId() == null
                ^ this.getPhysicalResourceId() == null)
            return false;
        if (other.getPhysicalResourceId() != null
                && other.getPhysicalResourceId().equals(
                        this.getPhysicalResourceId()) == false)
            return false;
        if (other.getResourceType() == null ^ this.getResourceType() == null)
            return false;
        if (other.getResourceType() != null
                && other.getResourceType().equals(this.getResourceType()) == false)
            return false;
        if (other.getLastUpdatedTimestamp() == null
                ^ this.getLastUpdatedTimestamp() == null)
            return false;
        if (other.getLastUpdatedTimestamp() != null
                && other.getLastUpdatedTimestamp().equals(
                        this.getLastUpdatedTimestamp()) == false)
            return false;
        if (other.getResourceStatus() == null
                ^ this.getResourceStatus() == null)
            return false;
        if (other.getResourceStatus() != null
                && other.getResourceStatus().equals(this.getResourceStatus()) == false)
            return false;
        if (other.getResourceStatusReason() == null
                ^ this.getResourceStatusReason() == null)
            return false;
        if (other.getResourceStatusReason() != null
                && other.getResourceStatusReason().equals(
                        this.getResourceStatusReason()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getLogicalResourceId() == null) ? 0
                        : getLogicalResourceId().hashCode());
        hashCode = prime
                * hashCode
                + ((getPhysicalResourceId() == null) ? 0
                        : getPhysicalResourceId().hashCode());
        hashCode = prime
                * hashCode
                + ((getResourceType() == null) ? 0 : getResourceType()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getLastUpdatedTimestamp() == null) ? 0
                        : getLastUpdatedTimestamp().hashCode());
        hashCode = prime
                * hashCode
                + ((getResourceStatus() == null) ? 0 : getResourceStatus()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getResourceStatusReason() == null) ? 0
                        : getResourceStatusReason().hashCode());
        return hashCode;
    }

    @Override
    public StackResourceSummary clone() {
        try {
            return (StackResourceSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
package org.lumongo.client.pool;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.lumongo.util.LumongoThreadFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkPool {

	private ListeningExecutorService pool;
	private final static AtomicInteger threadNumber = new AtomicInteger(1);

	public WorkPool(int threads) {
		this(threads, threads * 10);
	}

	public WorkPool(int threads, int maxQueued) {
		this(threads, maxQueued, "workPool-" + threadNumber.getAndIncrement());
	}

	public WorkPool(int threads, int maxQueued, String poolName) {
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(maxQueued) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean offer(Runnable e) {
				try {
					put(e);
				}
				catch (InterruptedException e1) {
					throw new RuntimeException(e1);
				}
				return true;
			}

		};

		pool = MoreExecutors
						.listeningDecorator(new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, workQueue, new LumongoThreadFactory(poolName)));
	}

	public <T> ListenableFuture<T> executeAsync(Callable<T> task) {
		return pool.submit(task);
	}

	public <T> T execute(Callable<T> task) throws Exception {
		try {
			return executeAsync(task).get();
		}
		catch (InterruptedException e) {
			throw e;
		}
		catch (ExecutionException e) {
			Throwable cause = e.getCause();
			if (cause != null) {
				if (cause instanceof Exception) {
					throw (Exception) cause;
				}
			}
			throw e;
		}
	}

	public void shutdown() throws Exception {
		pool.shutdown();
		boolean terminated = false;
		try {
			while (!terminated) {
				// terminates immediately on completion
				terminated = pool.awaitTermination(1, TimeUnit.HOURS);
			}
		}
		catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
% Project Assignment #3
%===============================================================================
% C.1 : Implementation of the Steger's algorithm
%===============================================================================
close all%, clc

%===============================================================================
% User's image location settings
inputDir1 = 'curve_detection_images';
filename = 'curv_det_01.tif';

imagePath = [inputDir1, filesep, filename];     % Cross-platform format
img = imread(imagePath);

%===============================================================================
% Settings
sigma = ApplyStegersAlgor(img);   % calculate sigma by obtaining line width
width = ceil(3*sigma);   % get the range for convolve

curveDetectImage = img;

%curveDetectImage = b5_directionalanisotropicfilter(curveDetectImage, k, l);
% ordering of imshow() changed to compensate for xstarmatrix() plotting behavior
figure('Name','C.1 : Curve Detection'), imshow(curveDetectImage, [])
curveDetectImage = xstarmatrix_general(curveDetectImage, width, sigma);
disp('Finished')


text:
package org.docksidestage.mysql.dbflute.whitebox.dfprop;

import java.time.LocalDate;
import java.util.List;

import org.dbflute.cbean.ConditionBean;
import org.dbflute.cbean.coption.FromToOption;
import org.dbflute.cbean.coption.LikeSearchOption;
import org.dbflute.exception.ConditionInvokingFailureException;
import org.dbflute.util.DfCollectionUtil;
import org.docksidestage.mysql.dbflute.cbean.MemberCB;
import org.docksidestage.mysql.unit.UnitContainerTestCase;

/**
 * @author jflute
 * @since 0.9.9.0C (2011/08/23 Tuesday)
 */
public class WxIncludeQueryTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                        NormalColumn
    //                                                                        ============
    public void test_NormalColumn_String_included() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();

        // ## Act & Assert ##
        // [included]
        // expect no exception
        cb.localCQ().invokeQuery("MEMBER_NAME", "Equal", "foo");
        cb.localCQ().invokeQuery("MEMBER_NAME", "NotEqual", "foo");
        cb.localCQ().invokeQuery("MEMBER_NAME", "InScope", DfCollectionUtil.newArrayList("foo"));
        cb.localCQ().invokeQuery("MEMBER_NAME", "NotInScope", DfCollectionUtil.newArrayList("bar"));
        // disappeared since 1.1
        //cb.localCQ().invokeQuery("MEMBER_NAME", "PrefixSearch", "foo");
        cb.localCQ().invokeQuery("MEMBER_NAME", "LikeSearch", "foo", new LikeSearchOption().likeContain());
        cb.localCQ().invokeQuery("MEMBER_NAME", "NotLikeSearch", "foo", new LikeSearchOption().likeContain());

        // [excluded]
        doTest_invokeQuery_excluded(cb, "MEMBER_NAME", "foo", "GreaterThan", "LessThan", "GreaterEqual", "LessEqual");
    }

    public void test_NormalColumn_Date_included() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        // ## Act & Assert ##
        // [included]
        // expect no exception
        cb.localCQ().invokeQuery("BIRTHDATE", "Equal", currentLocalDate());
        cb.localCQ().invokeQuery("BIRTHDATE", "GreaterThan", currentLocalDate());
        cb.localCQ().invokeQuery("BIRTHDATE", "LessThan", currentLocalDate());
        cb.localCQ().invokeQuery("BIRTHDATE", "GreaterEqual", currentLocalDate());
        cb.localCQ().invokeQuery("BIRTHDATE", "LessEqual", currentLocalDate());
        cb.enableOverridingQuery(() -> {
            List<LocalDate> fromToList = newArrayList(currentLocalDate(), currentLocalDate());
            cb.localCQ().invokeQuery("BIRTHDATE", "FromTo", fromToList, new FromToOption().compareAsDate());
            // disappeared since 1.1
            //cb.localCQ().invokeQuery("BIRTHDATE", "DateFromTo", fromToList);
        });
        cb.localCQ().invokeQuery("BIRTHDATE", "IsNull", new Object());
        cb.localCQ().invokeQuery("BIRTHDATE", "IsNotNull", new Object());

        // [excluded]
        doTest_invokeQuery_excluded(cb, "BIRTHDATE", "2011/11/11", "NotEqual", "InScope", "NotInScope");
    }

    // ===================================================================================
    //                                                                        CommonColumn
    //                                                                        ============
    public void test_CommonColumn_String_excluded() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();

        // ## Act & Assert ##
        // [included]
        // expect no exception
        cb.localCQ().invokeQuery("REGISTER_USER", "Equal", "foo");

        // [excluded]
        String name = "REGISTER_USER";
        doTest_invokeQuery_excluded(cb, name, "foo", "NotEqual");
        doTest_invokeQuery_excluded(cb, name, "foo", "GreaterThan", "LessThan", "GreaterEqual", "LessEqual");
        doTest_invokeQuery_excluded(cb, name, "foo", "InScope", "NotInScope");
        doTest_invokeQuery_excluded(cb, name, "foo", "PrefixSearch", "LikeSearch", "NotLikeSearch");
    }

    public void test_CommonColumn_Date_excluded() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();

        // ## Act & Assert ##
        // [included]
        // expect no exception
        cb.localCQ().invokeQuery("REGISTER_DATETIME", "Equal", currentLocalDateTime());

        // [excluded]
        String name = "REGISTER_DATETIME";
        doTest_invokeQuery_excluded(cb, name, "2011/11/23", "NotEqual");
        doTest_invokeQuery_excluded(cb, name, "2011/11/23", "GreaterThan", "LessThan", "GreaterEqual", "LessEqual");
        doTest_invokeQuery_excluded(cb, name, "2011/11/23", "InScope", "NotInScope");
        doTest_invokeQuery_excluded(cb, name, "2011/11/23", "FromTo", "DateFromTo");
    }

    // ===================================================================================
    //                                                                           VersionNo
    //                                                                           =========
    public void test_VersionNo_Number_excluded() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();

        // ## Act & Assert ##
        // [included]
        // expect no exception
        cb.localCQ().invokeQuery("VERSION_NO", "Equal", 1L);

        // [excluded]
        doTest_invokeQuery_excluded(cb, "VERSION_NO", 1, "NotEqual");
        doTest_invokeQuery_excluded(cb, "VERSION_NO", 1, "GreaterThan", "LessThan", "GreaterEqual", "LessEqual");
        doTest_invokeQuery_excluded(cb, "VERSION_NO", 1, "InScope", "NotInScope");
    }

    // ===================================================================================
    //                                                                         Test Helper
    //                                                                         ===========
    protected void doTest_invokeQuery_excluded(ConditionBean cb, String columnName, Object value, String... ckeys) {
        for (String ckey : ckeys) {
            // ## Act ##
            try {
                cb.localCQ().invokeQuery(columnName, ckey, value);

                // ## Assert ##
                fail();
            } catch (ConditionInvokingFailureException e) {
                // OK
                log(e.getMessage());
                assertTrue(e.getMessage().contains("Not found the method"));
            }
        }
    }
}


text:
from django.db.models import Count
from django.views.generic import TemplateView, DetailView

from ..departments.models import Department
from ..professors.models import Professor
from ..comments.models import Comment

from .models import University

class UniversitiesView(TemplateView):
    template_name = 'universities.html'

    def get_context_data(self, **kwargs):
        if 'view' not in kwargs:
            kwargs['view'] = self
        kwargs['universities'] = University.objects.all().annotate(
            Count('professor')).order_by('-professor__count', '-emblem')
        return kwargs

class UniversityView(DetailView):
    model = University
    template_name = 'university.html'

    def get_context_data(self, **kwargs):
        if 'view' not in kwargs:
            kwargs['view'] = self

        professors = Professor.objects.filter(
            university=self.object,
            score__gt=0).select_related('university')
        comments = Comment.objects.filter(
            professor__in=professors).select_related(
                'created_by').exclude(
                    body__exact='').order_by('-created_at', '-id')

        kwargs['specified_university'] = self.object
        kwargs['grade'] = self.object.get_grade()
        kwargs['departments'] = Department.objects.all()
        kwargs['hi_professors'] = professors.order_by('-score')[:5]
        kwargs['low_professors'] = professors.order_by('score')[:5]
        kwargs['recent_comments'] = comments.order_by('-created_at')[:5]
        return kwargs


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>tagyu</groupId>
  <artifactId>tagyu4j</artifactId>
  <packaging>jar</packaging>
  <version>0.6-SNAPSHOT</version>
  <description>Java API for Tagyu Service APIs http://www.tagyu.com/tools/rest.</description>
  <inceptionYear>2005</inceptionYear>
  <name>Tagyu4J</name>
  <url>http://code.google.com/p/tagyu4j/</url>
  <issueManagement>
    <system>Google Code Issue</system>
    <url>http://code.google.com/p/tagyu4j/issues/list</url>
  </issueManagement>
  <ciManagement>
    <system>hudson</system>
    <url>http://tools.cliffano.com/hudson/job/tagyu-tagyu4j/</url>
    <notifiers>
      <notifier>
        <type>mail</type>
        <configuration>
          <address>blah@cliffano.com</address>
        </configuration>
      </notifier>
    </notifiers>
  </ciManagement>
  <distributionManagement>
    <site>
      <id>studio</id>
      <url>scp://teuchi:2218/var/www/cliffano.com/studio/tagyu/tagyu4j</url>
    </site>
  </distributionManagement>
  <scm>
    <connection>
      scm:svn:http://tagyu4j.googlecode.com/svn/trunk/
    </connection>
  </scm>
  <developers>
    <developer>
      <id>cliffano</id>
      <name>Cliffano Subagio</name>
      <email>blah@cliffano.com</email>
      <url>http://blog.cliffano.com</url>
      <roles>
        <role>Developer</role>
      </roles>
      <timezone>+10</timezone>
    </developer>
  </developers>
  <licenses>
    <license>
      <name>BSD License</name>
      <url>LICENSE.txt</url>
    </license>
  </licenses>
  <organization>
    <name>Studio Cliffano</name>
    <url>http://cliffano.com</url>
  </organization>
  <dependencies>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.0.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <version>2.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymockclassextension</artifactId>
      <version>2.2.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.4</source>
          <target>1.4</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <artifactId>maven-changes-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-checkstyle-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <configuration>
          <formats>
            <format>xml</format>
            <format>html</format>
          </formats>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <configuration>
          <xmlOutput>true</xmlOutput>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
          <show>private</show>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>javancss-maven-plugin</artifactId>
        <version>2.0-beta-1</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jdepend-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-jxr-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-pmd-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-report-plugin</artifactId>
      </plugin>
    </plugins>
  </reporting>
</project>


text:
GUITouchEventReturn GUI_HandleTouch(u16 x, u16 y, GUITouchEventType type);

#endif


text:
'use strict';

angular.module('phi.system')
	.controller('HeaderCtrl', [
		'$scope',
		'$rootScope',
		'$location',
		'$http',
		'security',
		'i18nNotifications',
		'phi.locale',
		'localizedMessages',
	  function ($scope, $rootScope, $location, $http, security, i18nNotifications, locale, localizedMessages) {

	  	$scope.user = security.getCurrentUser;
	  	$scope.isAuthenticated = security.isAuthenticated;

	    $scope.menus = [
				{
					title: localizedMessages.get('menu.title.projects.create'),
					link: '/projects/new',
					show: security.isAuthenticated
				}, {
					title: localizedMessages.get('menu.title.projects.list'),
					link: '/projects',
					show: security.isAuthenticated
				}
			];

			$scope.locales = [
				{key: 'en-gb', label: 'English'},
				{key: 'fr-fr', label: 'Français'}
			];
			$scope.form = {locale: locale};
			$scope.$watch('form.locale', function(newValue, oldValue) {
				if (newValue === oldValue) {
					return;
				}
				$http.get('/locale/' + newValue)
					.then(function(/*data*/) {
						window.location.reload();
					}, function(data) {
						i18nNotifications.pushForCurrentRoute(data.data.message, 'warning');
					});
			});

		  $scope.isActive = function (linkPath) {
		  	var path = $location.path().replace('/', '\/'), re = new RegExp('^' + path);
		    return re.test(linkPath);
		  };

		  $scope.logout = function() {
		  	security.logout('/');
		  };

		  $scope.login = function() {
		  	security.showLogin();
		  };

		  $scope.register = function() {
		  	security.showSignup();
		  };

		  $scope.refreshProjects = function() {
		  	$rootScope.$broadcast('refreshProjects');
		  };
	  }
	]);


text:
README
######

This is a ESRI shapefile viewer written in C++ with the framework Qt.

This code is released under the MIT license.

Building
========

Requirement
-----------

Shapes requires following libraries.

 * glew, http://glew.sourceforge.net/
 * shapelib, http://shapelib.maptools.org/
 * Qt, http://qt-project.org/

Shapes has been developed in Qt Creator, also found at http://qt-project.org/.

Shapes has been tested on Qt 4.8.1, glew 1.?, shapelib 1.2.


text:
#include "tensorflow_serving/batching/streaming_batch_scheduler.h"

#include <vector>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow_serving/test_util/fake_clock_env.h"

using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;

namespace tensorflow {
namespace serving {
namespace {

class FakeTask : public BatchTask {
 public:
  explicit FakeTask(size_t size) : size_(size) {}

  ~FakeTask() override = default;

  size_t size() const override { return size_; }

 private:
  const size_t size_;

  TF_DISALLOW_COPY_AND_ASSIGN(FakeTask);
};

// Creates a FakeTask of size 'task_size', and calls 'scheduler->Schedule()' on
// that task. Returns the resulting status.
Status ScheduleTask(size_t task_size, BatchScheduler<FakeTask>* scheduler) {
  std::unique_ptr<FakeTask> task(new FakeTask(task_size));
  Status status = scheduler->Schedule(&task);
  // Schedule() should have consumed 'task' iff it returned Status::OK.
  CHECK_EQ(status.ok(), task == nullptr);
  return status;
}

TEST(StreamingBatchSchedulerTest, Basic) {
  bool callback_called = false;
  auto callback = [&callback_called](std::unique_ptr<Batch<FakeTask>> batch) {
    callback_called = true;
    batch->WaitUntilClosed();
    ASSERT_EQ(2, batch->num_tasks());
    EXPECT_EQ(3, batch->task(0).size());
    EXPECT_EQ(5, batch->task(1).size());
  };
  {
    StreamingBatchScheduler<FakeTask>::Options options;
    options.max_batch_size = 10;
    options.batch_timeout_micros = 100 * 1000;  // 100 milliseconds
    options.num_batch_threads = 1;
    std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
    TF_ASSERT_OK(StreamingBatchScheduler<FakeTask>::Create(options, callback,
                                                           &scheduler));
    TF_ASSERT_OK(ScheduleTask(3, scheduler.get()));
    TF_ASSERT_OK(ScheduleTask(5, scheduler.get()));
  }
  EXPECT_TRUE(callback_called);
}

TEST(StreamingBatchSchedulerTest, ObeyBatchSizeConstraint) {
  // Set up a callback that captures the batches' task sizes.
  mutex mu;
  std::vector<std::vector<size_t>> callback_data;
  auto callback = [&mu,
                   &callback_data](std::unique_ptr<Batch<FakeTask>> batch) {
    batch->WaitUntilClosed();
    std::vector<size_t> batch_data;
    for (int i = 0; i < batch->num_tasks(); ++i) {
      batch_data.push_back(batch->mutable_task(i)->size());
    }
    {
      mutex_lock l(mu);
      callback_data.push_back(batch_data);
    }
  };

  // Run a batch scheduler and inject some tasks.
  {
    StreamingBatchScheduler<FakeTask>::Options options;
    options.max_batch_size = 10;
    options.batch_timeout_micros = 100 * 1000;  // 100 milliseconds
    options.num_batch_threads = 2;
    std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
    TF_ASSERT_OK(StreamingBatchScheduler<FakeTask>::Create(options, callback,
                                                           &scheduler));

    // First batch.
    TF_ASSERT_OK(ScheduleTask(3, scheduler.get()));
    TF_ASSERT_OK(ScheduleTask(5, scheduler.get()));

    // Second batch (due to size overage).
    TF_ASSERT_OK(ScheduleTask(3 /* (3+5) + 3 > 10 */, scheduler.get()));
    TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));
    TF_ASSERT_OK(ScheduleTask(6, scheduler.get()));

    // (Empty third batch, since the second batch exactly hit the size limit.)
  }

  // Expect a certain grouping of the tasks into batches.
  EXPECT_THAT(
      callback_data,
      UnorderedElementsAre(ElementsAre(3, 5), ElementsAre(3, 1, 6), IsEmpty()));
}

TEST(StreamingBatchSchedulerTest, Timeout) {
  // Set up a fake clock, which only advances when we explicitly tell it to.
  test_util::FakeClockEnv env(Env::Default());

  Notification first_batch_processed, second_batch_processed,
      third_batch_processed;
  auto callback = [&first_batch_processed, &second_batch_processed,
                   &third_batch_processed](
      std::unique_ptr<Batch<FakeTask>> batch) {
    batch->WaitUntilClosed();
    if (batch->size() == 1) {
      first_batch_processed.Notify();
    } else if (batch->size() == 2) {
      second_batch_processed.Notify();
    } else if (batch->size() == 3) {
      third_batch_processed.Notify();
    }
  };

  StreamingBatchScheduler<FakeTask>::Options options;
  options.max_batch_size = 4;
  options.batch_timeout_micros = 10;
  options.num_batch_threads = 10;  // Plenty of threads to avoid "fullness".
  options.env = &env;
  // Set non-timeout-related sleep times to 0 for this test.
  options.no_tasks_wait_time_micros = 0;
  std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
  TF_ASSERT_OK(
      StreamingBatchScheduler<FakeTask>::Create(options, callback, &scheduler));

  // Create an underfull batch, and ensure that it gets processed when the clock
  // hits the timeout.
  TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));
  env.BlockUntilSleepingThread(10);
  env.AdvanceByMicroseconds(9);
  Env::Default()->SleepForMicroseconds(10 * 1000 /* 10 milliseconds */);
  EXPECT_FALSE(first_batch_processed.HasBeenNotified());
  env.AdvanceByMicroseconds(1);
  first_batch_processed.WaitForNotification();

  // Start creating a batch, then advance the clock until just before the
  // timeout. Then submit a new task that overflows into the next batch, causing
  // the original batch to close.
  TF_ASSERT_OK(ScheduleTask(2, scheduler.get()));
  env.BlockUntilSleepingThread(20);
  env.AdvanceByMicroseconds(9);
  Env::Default()->SleepForMicroseconds(10 * 1000 /* 10 milliseconds */);
  EXPECT_FALSE(second_batch_processed.HasBeenNotified());
  TF_ASSERT_OK(ScheduleTask(3, scheduler.get()));
  second_batch_processed.WaitForNotification();

  // Allow the third batch to hit its timeout, and ensure it gets closed at the
  // right time.
  env.AdvanceByMicroseconds(9);
  Env::Default()->SleepForMicroseconds(10 * 1000 /* 10 milliseconds */);
  EXPECT_FALSE(third_batch_processed.HasBeenNotified());
  env.BlockUntilSleepingThread(29);
  env.AdvanceByMicroseconds(1);
  third_batch_processed.WaitForNotification();
}

TEST(StreamingBatchSchedulerTest, RealClockTimeout) {
  Notification first_batch_processed, second_batch_processed;
  auto callback = [&first_batch_processed, &second_batch_processed](
      std::unique_ptr<Batch<FakeTask>> batch) {
    batch->WaitUntilClosed();
    if (batch->size() == 1) {
      first_batch_processed.Notify();
    } else if (batch->size() == 2) {
      second_batch_processed.Notify();
    }
  };

  StreamingBatchScheduler<FakeTask>::Options options;
  options.max_batch_size = 10;
  options.batch_timeout_micros = 10 * 1000;  // 10 milliseconds
  options.num_batch_threads = 10;  // Plenty of threads to avoid "fullness".
  std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
  TF_ASSERT_OK(
      StreamingBatchScheduler<FakeTask>::Create(options, callback, &scheduler));

  // Submit a single task that doesn't fill up the batch.
  // Ensure that it gets processed due to the timeout.
  TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));
  first_batch_processed.WaitForNotification();

  // Do it again.
  TF_ASSERT_OK(ScheduleTask(2, scheduler.get()));
  second_batch_processed.WaitForNotification();
}

TEST(StreamingBatchSchedulerTest, FinalUnderfullBatchProcessedUponDeletion) {
  bool callback_called = false;
  auto callback = [&callback_called](std::unique_ptr<Batch<FakeTask>> batch) {
    batch->WaitUntilClosed();
    callback_called = true;
  };

  {
    StreamingBatchScheduler<FakeTask>::Options options;
    options.max_batch_size = 10;
    options.batch_timeout_micros = 100 * 1000;  // 100 milliseconds
    options.num_batch_threads = 1;
    std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
    TF_ASSERT_OK(StreamingBatchScheduler<FakeTask>::Create(options, callback,
                                                           &scheduler));

    // Submit a single task that doesn't fill up the batch.
    // Ensure that it gets processed when the destructor is called.
    TF_ASSERT_OK(ScheduleTask(3, scheduler.get()));
  }
  EXPECT_TRUE(callback_called);
}

TEST(StreamingBatchSchedulerTest, BatchHandedToCallbackWhenFirstCreated) {
  Notification stop_scheduler;
  auto callback = [&stop_scheduler](std::unique_ptr<Batch<FakeTask>> batch) {
    EXPECT_LE(batch->num_tasks(), 1);
    EXPECT_FALSE(batch->IsClosed());
    stop_scheduler.Notify();
    batch->WaitUntilClosed();
  };

  StreamingBatchScheduler<FakeTask>::Options options;
  options.max_batch_size = 100;
  options.batch_timeout_micros = 100 * 1000;  // 100 milliseconds
  options.num_batch_threads = 1;
  std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
  TF_ASSERT_OK(
      StreamingBatchScheduler<FakeTask>::Create(options, callback, &scheduler));

  // Submit a single task of size 1, into a batch with much larger capacity.
  TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));

  stop_scheduler.WaitForNotification();
}

TEST(StreamingBatchSchedulerTest, ConstMethods) {
  for (const int num_threads : {1, 2, 3}) {
    Notification proceed;
    auto callback = [&proceed](std::unique_ptr<Batch<FakeTask>> batch) {
      batch->WaitUntilClosed();
      proceed.WaitForNotification();
    };

    StreamingBatchScheduler<FakeTask>::Options options;
    options.max_batch_size = 2;
    options.batch_timeout_micros = 1 * 1000 * 1000;  // Don't trigger.
    options.num_batch_threads = num_threads;
    std::unique_ptr<StreamingBatchScheduler<FakeTask>> scheduler;
    TF_ASSERT_OK(StreamingBatchScheduler<FakeTask>::Create(options, callback,
                                                           &scheduler));

    // Submit 'num_threads' full batches, to make the scheduling threads "full".
    // (At all times, the queue length should show as 0, since
    // StreamingBatchScheduler never enqueues tasks.)
    for (int i = 0; i < num_threads; ++i) {
      EXPECT_EQ(0, scheduler->NumEnqueuedTasks());
      EXPECT_EQ((num_threads - i) * 2, scheduler->SchedulingCapacity());
      TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));
      EXPECT_EQ(0, scheduler->NumEnqueuedTasks());
      EXPECT_EQ((num_threads - i) * 2 - 1, scheduler->SchedulingCapacity());
      TF_ASSERT_OK(ScheduleTask(1, scheduler.get()));
    }
    EXPECT_EQ(0, scheduler->NumEnqueuedTasks());
    EXPECT_EQ(0, scheduler->SchedulingCapacity());

    // Make another Schedule() call while the threads are full, which should
    // yield an UNAVAILABLE error.
    Status status = ScheduleTask(1, scheduler.get());
    EXPECT_FALSE(status.ok());
    EXPECT_EQ(error::UNAVAILABLE, status.code());
    EXPECT_EQ(0, scheduler->NumEnqueuedTasks());
    EXPECT_EQ(0, scheduler->SchedulingCapacity());

    // Allow the processing to proceed, and wait plenty of time for it to finish
    // and the scheduler to get back to full capacity.
    proceed.Notify();
    Env::Default()->SleepForMicroseconds(100 * 1000 /* 100 milliseconds */);

    // Now, SchedulingCapacity() should show as full and Schedule() should
    // succeed.
    EXPECT_EQ(num_threads * 2, scheduler->SchedulingCapacity());
    TF_EXPECT_OK(ScheduleTask(1, scheduler.get()));
  }
}

}  // namespace
}  // namespace serving
}  // namespace tensorflow


text:
package cli_test

import (
	"fmt"
	"github.com/qadium/plumber/cli"
	"io/ioutil"
	"os"
	"reflect"
	"testing"
)

// bundle with everything filled out
const goodBundle = `
language: python
name: foobar
inputs:
  - name: a
    description: none
    type: int
outputs:
  - name: b
    description: none
    type: int
env:
  - SECRET=1234
install:
  - make -j4
  - make install`

// bundle with all optional stuff left out
// includes an extra field which should just be ignored
const optBundle = `
language: python
name: foobar
inputs:
  - name: a
    type: string
outputs:
  - name: b
    type: string
extra: field`

// bundle with missing fields
const missingFields = `
language: go
name: foobar`

// bundle with missing name on inputs
const missingInputName = `
language: go
name: foobar
inputs:
  - type: foo
outputs:
  - foobar: a`

const missingOutputName = `
language: go
name: foobar
outputs:
  - hello: 1
inputs:
  - name: a`

func writeBundle(t *testing.T, bundle string) string {
	configFile, err := ioutil.TempFile("", "plumberTest")
	if err != nil {
		t.Errorf("Had an issue creating the temp file to test, '%v'", err)
	}

	if _, err := configFile.WriteString(bundle); err != nil {
		t.Errorf("Had an error writing the bundle file to test, '%v'", err)
	}

	return configFile.Name()
}

// if the expectedBundle is nil, then we'll check if an error is thrown
func parseBundle(t *testing.T, expectedBundle *cli.Bundle, bundle string) {
	configFile := writeBundle(t, bundle)
	defer func() {
		if err := os.RemoveAll(configFile); err != nil {
			t.Errorf("Had an issue removing the temp file, '%v'", err)
		}
	}()

	ctx, err := cli.ParseBundle(configFile)

	if expectedBundle == nil {
		if err == nil {
			t.Errorf("Expected an error, but got '%v'", ctx)
		}
	} else {
		if err != nil {
			t.Errorf("Had an issue parsing the bundle file, '%v'", err)
		}

		if !reflect.DeepEqual(ctx, expectedBundle) {
			t.Errorf("Got '%v', expected '%v'", ctx, expectedBundle)
		}
	}
}

func TestParseBundle(t *testing.T) {
	ctx := &cli.Bundle{
		Language: "python",
		Name:     "foobar",
		Inputs: []cli.Field{
			cli.Field{
				Name:        "a",
				Description: "none",
				Type:        "int",
			},
		},
		Outputs: []cli.Field{
			cli.Field{
				Name:        "b",
				Description: "none",
				Type:        "int",
			},
		},
		Env:     []string{"SECRET=1234"},
		Install: []string{"make -j4", "make install"},
	}
	parseBundle(t, ctx, goodBundle)
}

func TestParseOptBundle(t *testing.T) {
	ctx := &cli.Bundle{
		Language: "python",
		Name:     "foobar",
		Inputs: []cli.Field{
			cli.Field{
				Name:        "a",
				Description: "",
				Type:        "string",
			},
		},
		Outputs: []cli.Field{
			cli.Field{
				Name:        "b",
				Description: "",
				Type:        "string",
			},
		},
		Env:     nil,
		Install: nil,
	}
	parseBundle(t, ctx, optBundle)
}

func TestParseMissingFields(t *testing.T) {
	parseBundle(t, nil, missingFields)
}

func TestParseMissingInputName(t *testing.T) {
	parseBundle(t, nil, missingInputName)
}

func TestParseMissingOutputName(t *testing.T) {
	parseBundle(t, nil, missingOutputName)
}

func TestParseMissingLanguage(t *testing.T) {
	parseBundle(t, nil, `name: hello`)
}

func TestParseMissingOutputs(t *testing.T) {
	parseBundle(t, nil, `language: python
name: hello
inputs:
  - name: a`)
}
func TestParseMissingName(t *testing.T) {
	parseBundle(t, nil, `language: python`)
}

func TestParseBundleFromDir(t *testing.T) {
	tempDir, err := ioutil.TempDir("", "plumberTest")
	if err != nil {
		t.Errorf("Could not make temp dir; got error '%v'", err)
	}
	defer func() {
		if err := os.RemoveAll(tempDir); err != nil {
			t.Errorf("Had an issue removing the temp directory, '%v'", err)
		}
	}()

	filename := fmt.Sprintf("%s/.plumb.yml", tempDir)

	if err := ioutil.WriteFile(filename, []byte(goodBundle), 0644); err != nil {
		t.Errorf("Could not write .plumb.yml; got error '%v'", err)
	}

	expected := &cli.Bundle{
		Language: "python",
		Name:     "foobar",
		Inputs: []cli.Field{
			cli.Field{
				Name:        "a",
				Description: "none",
				Type:        "int",
			},
		},
		Outputs: []cli.Field{
			cli.Field{
				Name:        "b",
				Description: "none",
				Type:        "int",
			},
		},
		Env:     []string{"SECRET=1234"},
		Install: []string{"make -j4", "make install"},
	}

	ctx, err := cli.ParseBundleFromDir(tempDir)
	if err != nil {
		t.Errorf("Should have parsed properly, got error '%v'", err)
	}

	if !reflect.DeepEqual(ctx, expected) {
		t.Errorf("Got '%v', expected '%v'", ctx, expected)
	}
}