text:
#import <Foundation/Foundation.h>

@class YapDatabaseConnection;

/**
 * Welcome to YapDatabase!
 *
 * The project page has a wealth of documentation if you have any questions.
 * https://github.com/yapstudios/YapDatabase
 *
 * If you're new to the project you may want to visit the wiki.
 * https://github.com/yapstudios/YapDatabase/wiki
 *
 * Transactions represent atomic access to a database.
 * There are two types of transactions:
 * - Read-Only transactions
 * - Read-Write transactions
 *
 * Once a transaction is started, all data access within the transaction from that point forward until completion
 * represents an atomic "snapshot" of the current state of the database. For example, if a read-write operation
 * occurs in parallel with a read-only transaction, the read-only transaction won't see the changes made by
 * the read-write operation. But once the read-write operation completes, all transactions started from that point
 * forward will see the changes.
 *
 * You first create and configure a YapDatabase instance.
 * Then you can spawn one or more connections to the database file.
 * Each connection allows you to execute transactions in a serial fashion.
 * For concurrent access, you can create multiple connections,
 * and execute transactions on each connection simulataneously.
 *
 * Concurrency is straight-forward. Here are the rules:
 *
 * - You can have multiple connections.
 * - Every connection is thread-safe.
 * - You can have multiple read-only transactions simultaneously without blocking.
 *   (Each simultaneous transaction would be going through a separate connection.)
 * - You can have multiple read-only transactions and a single read-write transaction simultaneously without blocking.
 *   (Each simultaneous transaction would be going through a separate connection.)
 * - There can only be a single transaction per connection at a time.
 *   (Transactions go through a per-connection serial queue.)
 * - There can only be a single read-write transaction at a time.
 *   (Read-write transactions go through a per-database serial queue.)
**/

/**
 * A YapDatabaseReadTransaction encompasses a single read-only database transaction.
 * You can execute multiple operations within a single transaction.
 *
 * A transaction allows you to safely access the database as needed in a thread-safe and optimized manner.
**/
@interface YapDatabaseReadTransaction : NSObject

/**
 * Transactions are light-weight objects created by connections.
 *
 * Connections are the parent objects of transactions.
 * Connections own the transaction objects.
 *
 * Transactions store nearly all their state in the parent connection object.
 * This reduces the memory requirements for transactions objects,
 * and reduces the overhead associated in creating them.
**/
@property (nonatomic, unsafe_unretained, readonly) YapDatabaseConnection *connection;

/**
 * The userInfo property allows arbitrary info to be associated with the transaction.
 * This propery is not used by YapDatabaseTransaction in any way.
 *
 * Keep in mind that transactions are short lived objects.
 * Each transaction is a new/different transaction object.
**/
@property (nonatomic, strong, readwrite) id userInfo;

#pragma mark Count

/**
 * Returns the total number of collections.
 * Each collection may have 1 or more key/object pairs.
**/
- (NSUInteger)numberOfCollections;

/**
 * Returns the total number of keys in the given collection.
 * Returns zero if the collection doesn't exist (or all key/object pairs from the collection have been removed).
**/
- (NSUInteger)numberOfKeysInCollection:(NSString *)collection;

/**
 * Returns the total number of key/object pairs in the entire database (including all collections).
**/
- (NSUInteger)numberOfKeysInAllCollections;

#pragma mark List

/**
 * Returns a list of all collection names.
**/
- (NSArray *)allCollections;

/**
 * Returns a list of all keys in the given collection.
**/
- (NSArray *)allKeysInCollection:(NSString *)collection;

#pragma mark Object & Metadata

/**
 * Object access.
 * Objects are automatically deserialized using database's configured deserializer.
**/
- (id)objectForKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Returns whether or not the given key/collection exists in the database.
**/
- (BOOL)hasObjectForKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Provides access to both object and metadata in a single call.
 *
 * @return YES if the key exists in the database. NO otherwise, in which case both object and metadata will be nil.
**/
- (BOOL)getObject:(id *)objectPtr metadata:(id *)metadataPtr forKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Provides access to the metadata.
 * This fetches directly from the metadata dictionary stored in memory, and thus never hits the disk.
**/
- (id)metadataForKey:(NSString *)key inCollection:(NSString *)collection;

#pragma mark Primitive

/**
 * Primitive access.
 * This method is available in-case you have a need to fetch the raw serializedObject from the database.
 *
 * This method is slower than objectForKey:inCollection:, since that method makes use of the objectCache.
 * In contrast, this method always fetches the raw data from disk.
 *
 * @see objectForKey:inCollection:
**/
- (NSData *)serializedObjectForKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Primitive access.
 * This method is available in-case you have a need to fetch the raw serializedMetadata from the database.
 *
 * This method is slower than metadataForKey:inCollection:, since that method makes use of the metadataCache.
 * In contrast, this method always fetches the raw data from disk.
 *
 * @see metadataForKey:inCollection:
**/
- (NSData *)serializedMetadataForKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Primitive access.
 * This method is available in-case you have a need to fetch the raw serialized forms from the database.
 *
 * This method is slower than getObject:metadata:forKey:inCollection:, since that method makes use of the caches.
 * In contrast, this method always fetches the raw data from disk.
 *
 * @see getObject:metadata:forKey:inCollection:
**/
- (BOOL)getSerializedObject:(NSData **)serializedObjectPtr
         serializedMetadata:(NSData **)serializedMetadataPtr
                     forKey:(NSString *)key
               inCollection:(NSString *)collection;

#pragma mark Enumerate

/**
 * Fast enumeration over all the collections in the database.
 *
 * This uses a "SELECT collection FROM database" operation,
 * and then steps over the results invoking the given block handler.
**/
- (void)enumerateCollectionsUsingBlock:(void (^)(NSString *collection, BOOL *stop))block;

/**
 * This method is rarely needed, but may be helpful in certain situations.
 *
 * This method may be used if you have the key, but not the collection for a particular item.
 * Please note that this is not the ideal situation.
 *
 * Since there may be numerous collections for a given key, this method enumerates all possible collections.
**/
- (void)enumerateCollectionsForKey:(NSString *)key usingBlock:(void (^)(NSString *collection, BOOL *stop))block;

/**
 * Fast enumeration over all keys in the given collection.
 *
 * This uses a "SELECT key FROM database WHERE collection = ?" operation,
 * and then steps over the results invoking the given block handler.
**/
- (void)enumerateKeysInCollection:(NSString *)collection
                       usingBlock:(void (^)(NSString *key, BOOL *stop))block;

/**
 * Fast enumeration over all keys in the given collection.
 *
 * This uses a "SELECT collection, key FROM database" operation,
 * and then steps over the results invoking the given block handler.
**/
- (void)enumerateKeysInAllCollectionsUsingBlock:(void (^)(NSString *collection, NSString *key, BOOL *stop))block;

/**
 * Fast enumeration over all keys and associated metadata in the given collection.
 *
 * This uses a "SELECT key, metadata FROM database WHERE collection = ?" operation and steps over the results.
 *
 * If you only need to enumerate over certain items (e.g. keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the deserialization step for those items you're not interested in.
 *
 * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration).
**/
- (void)enumerateKeysAndMetadataInCollection:(NSString *)collection
                                  usingBlock:(void (^)(NSString *key, id metadata, BOOL *stop))block;

/**
 * Fast enumeration over all keys and associated metadata in the given collection.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key.
 * If the filter block returns NO, then the block handler is skipped for the given key,
 * which avoids the cost associated with deserializing the object.
 *
 * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration).
**/
- (void)enumerateKeysAndMetadataInCollection:(NSString *)collection
                                  usingBlock:(void (^)(NSString *key, id metadata, BOOL *stop))block
                                  withFilter:(BOOL (^)(NSString *key))filter;

/**
 * Fast enumeration over all key/metadata pairs in all collections.
 *
 * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation, and steps over the results.
 *
 * If you only need to enumerate over certain objects (e.g. keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the deserialization step for those objects you're not interested in.
 *
 * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration).
**/
- (void)enumerateKeysAndMetadataInAllCollectionsUsingBlock:
                                        (void (^)(NSString *collection, NSString *key, id metadata, BOOL *stop))block;

/**
 * Fast enumeration over all key/metadata pairs in all collections.
 *
 * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation and steps over the results.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key.
 * If the filter block returns NO, then the block handler is skipped for the given key,
 * which avoids the cost associated with deserializing the object.
 *
 * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration).
 **/
- (void)enumerateKeysAndMetadataInAllCollectionsUsingBlock:
                                        (void (^)(NSString *collection, NSString *key, id metadata, BOOL *stop))block
                             withFilter:(BOOL (^)(NSString *collection, NSString *key))filter;

/**
 * Fast enumeration over all objects in the database.
 *
 * This uses a "SELECT key, object from database WHERE collection = ?" operation, and then steps over the results,
 * deserializing each object, and then invoking the given block handler.
 *
 * If you only need to enumerate over certain objects (e.g. keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the serialization step for those objects you're not interested in.
**/
- (void)enumerateKeysAndObjectsInCollection:(NSString *)collection
                                 usingBlock:(void (^)(NSString *key, id object, BOOL *stop))block;

/**
 * Fast enumeration over objects in the database for which you're interested in.
 * The filter block allows you to decide which objects you're interested in.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key.
 * If the filter block returns NO, then the block handler is skipped for the given key,
 * which avoids the cost associated with deserializing the object.
**/
- (void)enumerateKeysAndObjectsInCollection:(NSString *)collection
                                 usingBlock:(void (^)(NSString *key, id object, BOOL *stop))block
                                 withFilter:(BOOL (^)(NSString *key))filter;

/**
 * Enumerates all key/object pairs in all collections.
 *
 * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection
 * before moving onto another collection.
 *
 * If you only need to enumerate over certain objects (e.g. subset of collections, or keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the serialization step for those objects you're not interested in.
**/
- (void)enumerateKeysAndObjectsInAllCollectionsUsingBlock:
                                            (void (^)(NSString *collection, NSString *key, id object, BOOL *stop))block;

/**
 * Enumerates all key/object pairs in all collections.
 * The filter block allows you to decide which objects you're interested in.
 *
 * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection
 * before moving onto another collection.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given
 * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair,
 * which avoids the cost associated with deserializing the object.
**/
- (void)enumerateKeysAndObjectsInAllCollectionsUsingBlock:
                                            (void (^)(NSString *collection, NSString *key, id object, BOOL *stop))block
                                 withFilter:(BOOL (^)(NSString *collection, NSString *key))filter;

/**
 * Fast enumeration over all rows in the database.
 *
 * This uses a "SELECT key, data, metadata from database WHERE collection = ?" operation,
 * and then steps over the results, deserializing each object & metadata, and then invoking the given block handler.
 *
 * If you only need to enumerate over certain rows (e.g. keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the serialization step for those rows you're not interested in.
**/
- (void)enumerateRowsInCollection:(NSString *)collection
                       usingBlock:(void (^)(NSString *key, id object, id metadata, BOOL *stop))block;

/**
 * Fast enumeration over rows in the database for which you're interested in.
 * The filter block allows you to decide which rows you're interested in.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key.
 * If the filter block returns NO, then the block handler is skipped for the given key,
 * which avoids the cost associated with deserializing the object & metadata.
**/
- (void)enumerateRowsInCollection:(NSString *)collection
                       usingBlock:(void (^)(NSString *key, id object, id metadata, BOOL *stop))block
                       withFilter:(BOOL (^)(NSString *key))filter;

/**
 * Enumerates all rows in all collections.
 *
 * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection
 * before moving onto another collection.
 *
 * If you only need to enumerate over certain rows (e.g. subset of collections, or keys with a particular prefix),
 * consider using the alternative version below which provides a filter,
 * allowing you to skip the serialization step for those objects you're not interested in.
**/
- (void)enumerateRowsInAllCollectionsUsingBlock:
                            (void (^)(NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block;

/**
 * Enumerates all rows in all collections.
 * The filter block allows you to decide which objects you're interested in.
 *
 * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection
 * before moving onto another collection.
 *
 * From the filter block, simply return YES if you'd like the block handler to be invoked for the given
 * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair,
 * which avoids the cost associated with deserializing the object.
**/
- (void)enumerateRowsInAllCollectionsUsingBlock:
                            (void (^)(NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block
                 withFilter:(BOOL (^)(NSString *collection, NSString *key))filter;

/**
 * Enumerates over the given list of keys (unordered).
 *
 * This method is faster than fetching individual items as it optimizes cache access.
 * That is, it will first enumerate over items in the cache and then fetch items from the database,
 * thus optimizing the cache and reducing query size.
 *
 * If any keys are missing from the database, the 'metadata' parameter will be nil.
 *
 * IMPORTANT:
 * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter.
**/
- (void)enumerateMetadataForKeys:(NSArray *)keys
                    inCollection:(NSString *)collection
             unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id metadata, BOOL *stop))block;

/**
 * Enumerates over the given list of keys (unordered).
 *
 * This method is faster than fetching individual items as it optimizes cache access.
 * That is, it will first enumerate over items in the cache and then fetch items from the database,
 * thus optimizing the cache and reducing query size.
 *
 * If any keys are missing from the database, the 'object' parameter will be nil.
 *
 * IMPORTANT:
 * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter.
**/
- (void)enumerateObjectsForKeys:(NSArray *)keys
                   inCollection:(NSString *)collection
            unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id object, BOOL *stop))block;

/**
 * Enumerates over the given list of keys (unordered).
 *
 * This method is faster than fetching individual items as it optimizes cache access.
 * That is, it will first enumerate over items in the cache and then fetch items from the database,
 * thus optimizing the cache and reducing query size.
 *
 * If any keys are missing from the database, the 'object' and 'metadata' parameter will be nil.
 *
 * IMPORTANT:
 * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter.
**/
- (void)enumerateRowsForKeys:(NSArray *)keys
                inCollection:(NSString *)collection
         unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id object, id metadata, BOOL *stop))block;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Extensions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Returns an extension transaction corresponding to the extension type registered under the given name.
 * If the extension has not yet been opened, it is done so automatically.
 *
 * @return
 *     A subclass of YapDatabaseExtensionTransaction,
 *     according to the type of extension registered under the given name.
 *
 * One must register an extension with the database before it can be accessed from within connections or transactions.
 * After registration everything works automatically using just the registered extension name.
 *
 * @see [YapDatabase registerExtension:withName:]
**/
- (id)extension:(NSString *)extensionName;
- (id)ext:(NSString *)extensionName; // <-- Shorthand (same as extension: method)

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@interface YapDatabaseReadWriteTransaction : YapDatabaseReadTransaction

/**
 * Under normal circumstances, when a read-write transaction block completes,
 * the changes are automatically committed. If, however, something goes wrong and
 * you'd like to abort and discard all changes made within the transaction,
 * then invoke this method.
 *
 * You should generally return (exit the transaction block) after invoking this method.
 * Any changes made within the the transaction before and after invoking this method will be discarded.
**/
- (void)rollback;

/**
 * The YapDatabaseModifiedNotification is posted following a readwrite transaction which made changes.
 *
 * These notifications are used in a variety of ways:
 * - They may be used as a general notification mechanism to detect changes to the database.
 * - They may be used by extensions to post change information.
 *   For example, YapDatabaseView will post the index changes, which can easily be used to animate a tableView.
 * - They are integrated into the architecture of long-lived transactions in order to maintain a steady state.
 *
 * Thus it is recommended you integrate your own notification information into this existing notification,
 * as opposed to broadcasting your own separate notification.
 *
 * For more information, and code samples, please see the wiki article:
 * https://github.com/yapstudios/YapDatabase/wiki/YapDatabaseModifiedNotification
**/
@property (nonatomic, strong, readwrite) id yapDatabaseModifiedNotificationCustomObject;

#pragma mark Object & Metadata

/**
 * Sets the object for the given key/collection.
 * The object is automatically serialized using the database's configured objectSerializer.
 *
 * If you pass nil for the object, then this method will remove the row from the database (if it exists).
 * This method implicitly sets the associated metadata to nil.
 *
 * @param object
 *   The object to store in the database.
 *   This object is automatically serialized using the database's configured objectSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
**/
- (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Sets the object & metadata for the given key/collection.
 *
 * If you pass nil for the object, then this method will remove the row from the database (if it exists).
 *
 * @param object
 *   The object to store in the database.
 *   This object is automatically serialized using the database's configured objectSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
 *
 * @param metadata
 *   The metadata to store in the database.
 *   This metadata is automatically serialized using the database's configured metadataSerializer.
 *   The metadata is optional. You can pass nil for the metadata is unneeded.
 *   If non-nil then the metadata is also written to the database (metadata is also persistent).
**/
- (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection withMetadata:(id)metadata;

/**
 * Sets the object & metadata for the given key/collection.
 *
 * If you pass nil for the object, then this method will remove the row from the database (if it exists).
 *
 * This method allows for a bit of optimization if you happen to already have a serialized version of
 * the object and/or metadata. For example, if you downloaded an object in serialized form,
 * and you still have the raw serialized NSData, then you can use this method to skip the serialization step
 * when storing the object to the database.
 *
 * @param object
 *   The object to store in the database.
 *   This object is automatically serialized using the database's configured objectSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
 *
 * @param metadata
 *   The metadata to store in the database.
 *   This metadata is automatically serialized using the database's configured metadataSerializer.
 *   The metadata is optional. You can pass nil for the metadata is unneeded.
 *   If non-nil then the metadata is also written to the database (metadata is also persistent).
 *
 * @param preSerializedObject
 *   This value is optional.
 *   If non-nil then the object serialization step is skipped, and this value is used instead.
 *   It is assumed that preSerializedObject is equal to what we would get if we ran the object through
 *   the database's configured objectSerializer.
 *
 * @param preSerializedMetadata
 *   This value is optional.
 *   If non-nil then the metadata serialization step is skipped, and this value is used instead.
 *   It is assumed that preSerializedMetadata is equal to what we would get if we ran the metadata through
 *   the database's configured metadataSerializer.
 *
 * The preSerializedObject is only used if object is non-nil.
 * The preSerializedMetadata is only used if metadata is non-nil.
**/
- (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection
                                                    withMetadata:(id)metadata
                                                serializedObject:(NSData *)preSerializedObject
                                              serializedMetadata:(NSData *)preSerializedMetadata;

/**
 * If a row with the given key/collection exists, then replaces the object for that row with the new value.
 *
 * It only replaces the object. The metadata for the row doesn't change.
 * If there is no row in the database for the given key/collection then this method does nothing.
 *
 * If you pass nil for the object, then this method will remove the row from the database (if it exists).
 *
 * @param object
 *   The object to store in the database.
 *   This object is automatically serialized using the database's configured objectSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
**/
- (void)replaceObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * If a row with the given key/collection exists, then replaces the object for that row with the new value.
 *
 * It only replaces the object. The metadata for the row doesn't change.
 * If there is no row in the database for the given key/collection then this method does nothing.
 *
 * If you pass nil for the object, then this method will remove the row from the database (if it exists).
 *
 * This method allows for a bit of optimization if you happen to already have a serialized version of
 * the object and/or metadata. For example, if you downloaded an object in serialized form,
 * and you still have the raw serialized NSData, then you can use this method to skip the serialization step
 * when storing the object to the database.
 *
 * @param object
 *   The object to store in the database.
 *   This object is automatically serialized using the database's configured objectSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
 *
 * @param preSerializedObject
 *   This value is optional.
 *   If non-nil then the object serialization step is skipped, and this value is used instead.
 *   It is assumed that preSerializedObject is equal to what we would get if we ran the object through
 *   the database's configured objectSerializer.
**/
- (void)replaceObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection
                                                withSerializedObject:(NSData *)preSerializedObject;

/**
 * If a row with the given key/collection exists, then replaces the metadata for that row with the new value.
 *
 * It only replaces the metadata. The object for the row doesn't change.
 * If there is no row in the database for the given key/collection then this method does nothing.
 *
 * If you pass nil for the metadata, any metadata previously associated with the key/collection is removed.
 *
 * @param metadata
 *   The metadata to store in the database.
 *   This metadata is automatically serialized using the database's configured metadataSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
**/
- (void)replaceMetadata:(id)metadata forKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * If a row with the given key/collection exists, then replaces the metadata for that row with the new value.
 *
 * It only replaces the metadata. The object for the row doesn't change.
 * If there is no row in the database for the given key/collection then this method does nothing.
 *
 * If you pass nil for the metadata, any metadata previously associated with the key/collection is removed.
 *
 * This method allows for a bit of optimization if you happen to already have a serialized version of
 * the object and/or metadata. For example, if you downloaded an object in serialized form,
 * and you still have the raw serialized NSData, then you can use this method to skip the serialization step
 * when storing the object to the database.
 *
 * @param metadata
 *   The metadata to store in the database.
 *   This metadata is automatically serialized using the database's configured metadataSerializer.
 *
 * @param key
 *   The lookup key.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   This value should not be nil. If a nil key is passed, then this method does nothing.
 *
 * @param collection
 *   The lookup collection.
 *   The <collection, key> tuple is used to uniquely identify the row in the database.
 *   If a nil collection is passed, then the collection is implicitly the empty string (@"").
 *
 * @param preSerializedMetadata
 *   This value is optional.
 *   If non-nil then the metadata serialization step is skipped, and this value is used instead.
 *   It is assumed that preSerializedMetadata is equal to what we would get if we ran the metadata through
 *   the database's configured metadataSerializer.
**/
- (void)replaceMetadata:(id)metadata forKey:(NSString *)key inCollection:(NSString *)collection
                                                  withSerializedMetadata:(NSData *)preSerializedMetadata;

#pragma mark Touch

/**
 * You can touch an object if you want to mark it as updated without actually writing any changes to disk.
 *
 * For example:
 *
 *   You have a BNBook object in your database.
 *   One of the properties of the book object is a URL pointing to an image for the front cover of the book.
 *   This image gets changed on the server. Thus the UI representation of the book needs to be updated
 *   to reflect the updated image on the server. You realize that all your views are already listening for
 *   YapDatabaseModified notifications, so if you update the object in the database then all your views are
 *   already wired to update the UI appropriately. However, the actual object itself didn't change. So while
 *   there technically isn't any reason to update the object on disk, doing so would be the easiest way to
 *   keep the UI up-to-date. So what you really want is a way to "mark" the object as updated, without actually
 *   incurring the overhead of rewriting it to disk.
 *
 * And this is exactly what the touch methods were designed for.
 * It won't actually cause the object to get rewritten to disk.
 * However, it will mark the object as "updated" within the YapDatabaseModified notification,
 * so any UI components listening for changes will see this object as updated, and can update as appropriate.
 *
 * The touchObjectForKey:inCollection: method is similar to calling setObject:forKey:inCollection:withMetadata:,
 * and passing the object & metadata that already exists for the key. But without the overhead of fetching the items,
 * or re-writing the items to disk.
 *
 * The touchMetadataForKey: method is similar to calling replaceMetadata:forKey:,
 * and passing the metadata that already exists for the key. But without the overhead of fetching the metadata,
 * or re-writing the metadata to disk.
 *
 * Note: It is safe to touch objects during enumeration.
 * Normally, altering the database while enumerating it will result in an exception (just like altering an array
 * while enumerating it). However, it's safe to touch objects during enumeration.
**/
- (void)touchObjectForKey:(NSString *)key inCollection:(NSString *)collection;
- (void)touchMetadataForKey:(NSString *)key inCollection:(NSString *)collection;

#pragma mark Remove

/**
 * Deletes the database row with the given key/collection.
 *
 * This method is automatically called if you invoke
 * setObject:forKey:collection: and pass a nil object.
**/
- (void)removeObjectForKey:(NSString *)key inCollection:(NSString *)collection;

/**
 * Deletes the database rows with the given keys in the given collection.
**/
- (void)removeObjectsForKeys:(NSArray *)keys inCollection:(NSString *)collection;

/**
 * Deletes every key/object pair from the given collection.
 * No trace of the collection will remain afterwards.
**/
- (void)removeAllObjectsInCollection:(NSString *)collection;

/**
 * Removes every key/object pair in the entire database (from all collections).
**/
- (void)removeAllObjectsInAllCollections;

@end


text:
package com.intellij.xdebugger.impl.breakpoints;

import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.xdebugger.XDebuggerBundle;
import com.intellij.xdebugger.XDebuggerUtil;

import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;

class RemoveBreakpointGutterIconAction extends DumbAwareAction {
  private final XBreakpointBase<?,?,?> myBreakpoint;

  RemoveBreakpointGutterIconAction(XBreakpointBase<?, ?, ?> breakpoint) {
    super(XDebuggerBundle.message("xdebugger.remove.line.breakpoint.action.text"));
    myBreakpoint = breakpoint;
    AnAction action = ActionManager.getInstance().getAction("ToggleLineBreakpoint");
    copyShortcutFrom(action);
  }

  @Override
  public void actionPerformed(final AnActionEvent e) {
    InputEvent event = e.getInputEvent();
    // for mouse events check that no modifiers applied
    if (!(event instanceof MouseEvent) || event.getModifiersEx() == 0) {
      XDebuggerUtil.getInstance().removeBreakpoint(myBreakpoint.getProject(), myBreakpoint);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

</animation-list>


text:
/*	$OpenBSD: sha2.h,v 1.5 2014/11/16 17:39:09 tedu Exp $	*/

/*
 * FILE:	sha2.h
 * AUTHOR:	Aaron D. Gifford <me@aarongifford.com>
 *
 * Copyright (c) 2000-2001, Aaron D. Gifford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $From: sha2.h,v 1.1 2001/11/08 00:02:01 adg Exp adg $
 */

#ifndef _SHA2_H
#define _SHA2_H

/*** SHA-256/384/512 Various Length Definitions ***********************/
#define SHA256_BLOCK_LENGTH		64
#define SHA256_DIGEST_LENGTH		32
#define SHA256_DIGEST_STRING_LENGTH	(SHA256_DIGEST_LENGTH * 2 + 1)
#define SHA384_BLOCK_LENGTH		128
#define SHA384_DIGEST_LENGTH		48
#define SHA384_DIGEST_STRING_LENGTH	(SHA384_DIGEST_LENGTH * 2 + 1)
#define SHA512_BLOCK_LENGTH		128
#define SHA512_DIGEST_LENGTH		64
#define SHA512_DIGEST_STRING_LENGTH	(SHA512_DIGEST_LENGTH * 2 + 1)

/*** SHA-256/384/512 Context Structure *******************************/
typedef struct _SHA2_CTX {
	union {
		u_int32_t	st32[8];
		u_int64_t	st64[8];
	} state;
	u_int64_t	bitcount[2];
	u_int8_t	buffer[SHA512_BLOCK_LENGTH];
} SHA2_CTX;

#ifdef __cplusplus
extern "C" {
#endif
void SHA256Init(SHA2_CTX *);
void SHA256Update(SHA2_CTX *, const void *, size_t)
	__attribute__((__bounded__(__string__,2,3)));
void SHA256Final(u_int8_t[SHA256_DIGEST_LENGTH], SHA2_CTX *)
	__attribute__((__bounded__(__minbytes__,1,SHA256_DIGEST_LENGTH)));

void SHA384Init(SHA2_CTX *);
void SHA384Update(SHA2_CTX *, const void *, size_t)
	__attribute__((__bounded__(__string__,2,3)));
void SHA384Final(u_int8_t[SHA384_DIGEST_LENGTH], SHA2_CTX *)
	__attribute__((__bounded__(__minbytes__,1,SHA384_DIGEST_LENGTH)));

void SHA512Init(SHA2_CTX *);
void SHA512Update(SHA2_CTX *, const void *, size_t)
	__attribute__((__bounded__(__string__,2,3)));
void SHA512Final(u_int8_t[SHA512_DIGEST_LENGTH], SHA2_CTX *)
	__attribute__((__bounded__(__minbytes__,1,SHA512_DIGEST_LENGTH)));
#ifdef __cplusplus
}
#endif

#endif /* _SHA2_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>java-modules-context-boot-build</artifactId>
		<groupId>io.github.tomdw.java.modules.spring</groupId>
		<version>0.0.7-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>integration-tests-spring-boot</artifactId>

	<dependencies>
		<dependency>
			<groupId>io.github.tomdw.java.modules.spring</groupId>
			<artifactId>java-modules-context-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.github.tomdw.java.modules.spring.samples.basicapplication</groupId>
			<artifactId>application</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>3.1.0</version>
				<executions>
					<execution>
						<id>add-test-source</id>
						<phase>generate-test-sources</phase>
						<goals>
							<goal>add-test-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests</source>
							</sources>
						</configuration>
					</execution>
					<execution>
						<id>add-test-resource</id>
						<phase>generate-test-resources</phase>
						<goals>
							<goal>add-test-resource</goal>
						</goals>
						<configuration>
							<resources>
								<resource>
									<directory>src/main/resources</directory>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>


text:
namespace boost
{
  namespace function_types
  {
    template<typename T> struct function_arity
      : mpl::if_
        < function_types::is_callable_builtin<T>
        , typename components<T>::function_arity, boost::blank
        >::type
    {
      BOOST_MPL_AUX_LAMBDA_SUPPORT(1,function_arity,(T))
    };
  }
}

#endif


text:
package android.graphics;

import android.content.res.AssetManager;
import android.util.Log;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * A family of typefaces with different styles.
 *
 * @hide
 */
public class FontFamily {

    private static String TAG = "FontFamily";

    /**
     * @hide
     */
    public long mNativePtr;

    public FontFamily() {
        mNativePtr = nCreateFamily(null, 0);
        if (mNativePtr == 0) {
            throw new IllegalStateException("error creating native FontFamily");
        }
    }

    public FontFamily(String lang, String variant) {
        int varEnum = 0;
        if ("compact".equals(variant)) {
            varEnum = 1;
        } else if ("elegant".equals(variant)) {
            varEnum = 2;
        }
        mNativePtr = nCreateFamily(lang, varEnum);
        if (mNativePtr == 0) {
            throw new IllegalStateException("error creating native FontFamily");
        }
    }

    @Override
    protected void finalize() throws Throwable {
        try {
            nUnrefFamily(mNativePtr);
        } finally {
            super.finalize();
        }
    }

    public boolean addFont(String path, int ttcIndex) {
        try (FileInputStream file = new FileInputStream(path)) {
            FileChannel fileChannel = file.getChannel();
            long fontSize = fileChannel.size();
            ByteBuffer fontBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fontSize);
            return nAddFont(mNativePtr, fontBuffer, ttcIndex);
        } catch (IOException e) {
            Log.e(TAG, "Error mapping font file " + path);
            return false;
        }
    }

    public boolean addFontWeightStyle(ByteBuffer font, int ttcIndex, List<FontListParser.Axis> axes,
            int weight, boolean style) {
        return nAddFontWeightStyle(mNativePtr, font, ttcIndex, axes, weight, style);
    }

    public boolean addFontFromAsset(AssetManager mgr, String path) {
        return nAddFontFromAsset(mNativePtr, mgr, path);
    }

    private static native long nCreateFamily(String lang, int variant);
    private static native void nUnrefFamily(long nativePtr);
    private static native boolean nAddFont(long nativeFamily, ByteBuffer font, int ttcIndex);
    private static native boolean nAddFontWeightStyle(long nativeFamily, ByteBuffer font,
            int ttcIndex, List<FontListParser.Axis> listOfAxis,
            int weight, boolean isItalic);
    private static native boolean nAddFontFromAsset(long nativeFamily, AssetManager mgr,
            String path);
}


text:
package org.apache.qpid.jms.provider.amqp;

import org.apache.qpid.jms.JmsTemporaryDestination;
import org.apache.qpid.proton.engine.Sender;

/**
 * Manages a Temporary Destination linked to a given Connection.
 *
 * In order to create a temporary destination and keep it active for the life of the connection
 * we must create a sender with a dynamic target value.  Once the sender is open we can read
 * the actual name assigned by the broker from the target and that is the real temporary
 * destination that we will return.
 *
 * The open of the Sender instance will also allow us to catch any security errors from
 * the broker in the case where the user does not have authorization to access temporary
 * destinations.
 */
public class AmqpTemporaryDestination extends AmqpAbstractResource<JmsTemporaryDestination, Sender> {

    private final AmqpConnection connection;
    private final AmqpSession session;

    public AmqpTemporaryDestination(AmqpSession session, JmsTemporaryDestination destination, Sender endpoint) {
        super(destination, endpoint, session);

        this.session = session;
        this.connection = session.getConnection();
    }

    public AmqpConnection getConnection() {
        return connection;
    }

    public AmqpSession getSession() {
        return session;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + " { " + getResourceInfo() + "}";
    }
}


text:
@implementation DCRevealTransitionView

- (void)animateWithDuration:(CFTimeInterval)duration
{
	CGPoint endPoint;
	CGSize viewSize = [self frame].size;

	switch ([self direction]) {
		case DCTransitionDirectionLeft:
			endPoint = CGPointMake(-viewSize.width, 0);
			break;
		case DCTransitionDirectionRight:
			endPoint = CGPointMake(viewSize.width, 0);
			break;

		case DCTransitionDirectionUp:
			endPoint = CGPointMake(0, -viewSize.height);
			break;

		case DCTransitionDirectionDown:
			endPoint = CGPointMake(0, viewSize.height);
	}

	[self bringSubviewToFront:[self fromView]];
	[[self toView] setHidden:NO];

	CABasicAnimation *reveal = [CABasicAnimation animationWithKeyPath:@"transform.translation"];
	[reveal setDelegate:[self delegate]];
	[reveal setValue:@([self mode]) forKey:@"mode"];
	[reveal setFromValue:[NSValue valueWithCGPoint:CGPointZero]];
	[reveal setToValue:[NSValue valueWithCGPoint:endPoint]];
	[reveal setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
	[reveal setDuration:duration];
	[reveal setFillMode:kCAFillModeForwards];
	[reveal setRemovedOnCompletion:NO];

	[[[self fromView] layer] addAnimation:reveal forKey:nil];
}

@end


text:
const Promise = require('bluebird');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const config = {
    slashToken: process.env.SLASH_TOKEN,
};

var redis = require('redis');
Promise.promisifyAll(redis.RedisClient.prototype);
const client = redis.createClient(process.env.REDIS_URL);

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
};

app.use(allowCrossDomain);
app.use(bodyParser.urlencoded({extended: false}));

require('./controllers/slash.js')(app, config, client);
var server = http.createServer(app);
server.listen(process.env.PORT || 8080);


text:
Master Encore Task

        <form class="form-horizontal form-label-left" method="post" action="<?php echo base_url().'ctr_encoretask/Update_encoretask' ?>">

            ID

              <input id="id_encore_task" name="id_encore_task" type="text" class="form-control" value="<?php echo $encoretask->id_encore_task; ?>" readonly="readonly">

            Nama

              <input id="nama" name="nama" class="form-control col-md-7 col-xs-12" data-validate-length-range="5" type="text" value="<?php echo $encoretask->nama_encore_task; ?>" >

              <a class="btn btn-primary" href="<?php echo base_url(); ?>index.php/ctr_encoretask" >Back
              <button type="submit" class="btn btn-success">Submit</button>

        </form>


text:
<!DOCTYPE HTML>
<meta charset=utf-8>
<title>Element Timing: observe generated CSS text</title>


text:
using System;
using System.Linq.Expressions;
using TITcs.SharePoint.Query.SharedSource.Utilities;

namespace TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions
{
  /// <summary>
  /// Represents an expression tree node that points to a query source represented by a <see cref="FromClauseBase"/>. These expressions should always
  /// point back, to a clause defined prior to the clause holding a <see cref="QuerySourceReferenceExpression"/>. Otherwise, exceptions might be
  /// thrown at runtime.
  /// </summary>
  /// <remarks>
  /// This particular expression overrides <see cref="Equals"/>, i.e. it can be compared to another <see cref="QuerySourceReferenceExpression"/> based
  /// on the <see cref="ReferencedQuerySource"/>.
  /// </remarks>
  public class QuerySourceReferenceExpression : Expression
  {
    private readonly Type _type;
    public const ExpressionType ExpressionType = (ExpressionType) 100001;

    public QuerySourceReferenceExpression (IQuerySource querySource)
    {
      ArgumentUtility.CheckNotNull ("querySource", querySource);

      _type = querySource.ItemType;
      ReferencedQuerySource = querySource;
    }

    public override ExpressionType NodeType
    {
      get { return ExpressionType; }
    }

    public override Type Type
    {
      get { return _type; }
    }

    /// <summary>
    /// Gets the query source referenced by this expression.
    /// </summary>
    /// <value>The referenced query source.</value>
    public IQuerySource ReferencedQuerySource { get; private set; }

    /// <summary>
    /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="QuerySourceReferenceExpression"/> by
    /// comparing the <see cref="ReferencedQuerySource"/> properties for reference equality.
    /// </summary>
    /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="QuerySourceReferenceExpression"/>.</param>
    /// <returns>
    /// <see langword="true" /> if the specified <see cref="T:System.Object"/> is a <see cref="QuerySourceReferenceExpression"/> that points to the
    /// same <see cref="ReferencedQuerySource"/>; otherwise, false.
    /// </returns>
    public override bool Equals (object obj)
    {
      var other = obj as QuerySourceReferenceExpression;
      return other != null && ReferencedQuerySource == other.ReferencedQuerySource;
    }

    public override int GetHashCode ()
    {
      return ReferencedQuerySource.GetHashCode ();
    }
  }
}


text:
package com.vmware.o11n.plugin.cache.finder;

import com.hazelcast.core.Member;
import com.vmware.o11n.plugin.cache.hazelcast.HazelcastInstanceWrapper;
import com.vmware.o11n.sdk.modeldriven.FoundObject;
import com.vmware.o11n.sdk.modeldriven.ObjectFinder;
import com.vmware.o11n.sdk.modeldriven.PluginContext;
import com.vmware.o11n.sdk.modeldriven.Sid;
import org.springframework.beans.factory.annotation.Autowired;

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

public class MemberFinder implements ObjectFinder<Member> {

    @Autowired
    private HazelcastInstanceWrapper instanceWrapper;

    @Override
    public Member find(PluginContext pluginContext, String s, Sid sid) {
        List<Member> members = instanceWrapper.getMembers();
        for (Member m : members) {
            if (m.getUuid().equals(sid.getString("uuid"))) {
                return m;
            }
        }
        return null;
    }

    @Override
    public List<FoundObject<Member>> query(PluginContext pluginContext, String s, String s1) {
        return Collections.emptyList();
    }

    @Override
    public Sid assignId(Member member, Sid sid) {
        return Sid.empty().with("uuid", member.getUuid());
    }
}


text:
package org.psjava.ds;

import java.util.HashSet;
import java.util.Set;

public class SetFromIterableV2 {
    public static <T> Set<T> create(Iterable<T> iterable) {
        HashSet<T> r = new HashSet<T>();
        AddAllToSet.insertAll(r, iterable);
        return r;
    }
}


text:
package org.apache.cassandra.dht;

import static org.junit.Assert.assertEquals;

import org.apache.cassandra.db.DecoratedKey;
import org.junit.Test;

public class RandomPartitionerTest extends PartitionerTestCase<BigIntegerToken>
{
    public void initPartitioner()
    {
        partitioner = new RandomPartitioner();
    }
}


text:
package com.buy.tsg.service;

import javax.jws.WebParam;
import javax.jws.WebService;
@WebService(targetNamespace ="/service.jws/")
public interface SendService {

	public boolean sendOA(@WebParam(name="param") String param);

}


text:
import sys
import tweepy

CONSUMER_KEY = 'xxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxx'
ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxxxxxxxxxx'

if (len(sys.argv) > 1):
    tweetFile = sys.argv[1]
else:
    tweetFile = "/tmp/tweets.txt"

f = open(tweetFile, "r")
tweetList = f.readlines()
f.close()
try:
    firstTweet = tweetList.pop(0)
except Exception as e:
    sys.exit(0)

# If we made it this far, the tweet file must have tweets.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
try:
    api.update_status(firstTweet)
    print "Tweet sent: " + firstTweet
except Exception as e:
    print "Error sending tweet [" + str(len(firstTweet)) + " length]: " + firstTweet

f = open(tweetFile, "w")
for i in tweetList:
    f.write(i)
f.close()


text:
/**
 * @class Function
 *
 * @brief A polymorphic function wrapper that is not copyable and does not
 *    require the wrapped function to be copy constructible.
 *
 * `folly::Function` is a polymorphic function wrapper, similar to
 * `std::function`. The template parameters of the `folly::Function` define
 * the parameter signature of the wrapped callable, but not the specific
 * type of the embedded callable. E.g. a `folly::Function<int(int)>`
 * can wrap callables that return an `int` when passed an `int`. This can be a
 * function pointer or any class object implementing one or both of
 *
 *     int operator(int);
 *     int operator(int) const;
 *
 * If both are defined, the non-const one takes precedence.
 *
 * Unlike `std::function`, a `folly::Function` can wrap objects that are not
 * copy constructible. As a consequence of this, `folly::Function` itself
 * is not copyable, either.
 *
 * Another difference is that, unlike `std::function`, `folly::Function` treats
 * const-ness of methods correctly. While a `std::function` allows to wrap
 * an object that only implements a non-const `operator()` and invoke
 * a const-reference of the `std::function`, `folly::Function` requires you to
 * declare a function type as const in order to be able to execute it on a
 * const-reference.
 *
 * For example:
 *
 *     class Foo {
 *      public:
 *       void operator()() {
 *         // mutates the Foo object
 *       }
 *     };
 *
 *     class Bar {
 *       std::function<void(void)> foo_; // wraps a Foo object
 *      public:
 *       void mutateFoo() const
 *       {
 *         foo_();
 *       }
 *     };
 *
 * Even though `mutateFoo` is a const-method, so it can only reference `foo_`
 * as const, it is able to call the non-const `operator()` of the Foo
 * object that is embedded in the foo_ function.
 *
 * `folly::Function` will not allow you to do that. You will have to decide
 * whether you need to invoke your wrapped callable from a const reference
 * (like in the example above), in which case it will only wrap a
 * `operator() const`. If your functor does not implement that,
 * compilation will fail. If you do not require to be able to invoke the
 * wrapped function in a const context, you can wrap any functor that
 * implements either or both of const and non-const `operator()`.
 *
 * The template parameter of `folly::Function`, the `FunctionType`, can be
 * const-qualified. Be aware that the const is part of the function signature.
 * It does not mean that the function type is a const type.
 *
 *   using FunctionType = R(Args...);
 *   using ConstFunctionType = R(Args...) const;
 *
 * In this example, `FunctionType` and `ConstFunctionType` are different
 * types. `ConstFunctionType` is not the same as `const FunctionType`.
 * As a matter of fact, trying to use the latter should emit a compiler
 * warning or error, because it has no defined meaning.
 *
 *     // This will not compile:
 *     folly::Function<void(void) const> func = Foo();
 *     // because Foo does not have a member function of the form:
 *     //   void operator()() const;
 *
 *     // This will compile just fine:
 *     folly::Function<void(void)> func = Foo();
 *     // and it will wrap the existing member function:
 *     //   void operator()();
 *
 * When should a const function type be used? As a matter of fact, you will
 * probably not need to use const function types very often. See the following
 * example:
 *
 *     class Bar {
 *       folly::Function<void()> func_;
 *       folly::Function<void() const> constFunc_;
 *
 *       void someMethod() {
 *         // Can call func_.
 *         func_();
 *         // Can call constFunc_.
 *         constFunc_();
 *       }
 *
 *       void someConstMethod() const {
 *         // Can call constFunc_.
 *         constFunc_();
 *         // However, cannot call func_ because a non-const method cannot
 *         // be called from a const one.
 *       }
 *     };
 *
 * As you can see, whether the `folly::Function`'s function type should
 * be declared const or not is identical to whether a corresponding method
 * would be declared const or not.
 *
 * You only require a `folly::Function` to hold a const function type, if you
 * intend to invoke it from within a const context. This is to ensure that
 * you cannot mutate its inner state when calling in a const context.
 *
 * This is how the const/non-const choice relates to lambda functions:
 *
 *     // Non-mutable lambdas: can be stored in a non-const...
 *     folly::Function<void(int)> print_number =
 *       [] (int number) { std::cout << number << std::endl; };
 *
 *     // ...as well as in a const folly::Function
 *     folly::Function<void(int) const> print_number_const =
 *       [] (int number) { std::cout << number << std::endl; };
 *
 *     // Mutable lambda: can only be stored in a non-const folly::Function:
 *     int number = 0;
 *     folly::Function<void()> print_number =
 *       [number] () mutable { std::cout << ++number << std::endl; };
 *     // Trying to store the above mutable lambda in a
 *     // `folly::Function<void() const>` would lead to a compiler error:
 *     // error: no viable conversion from '(lambda at ...)' to
 *     // 'folly::Function<void () const>'
 *
 * Casting between const and non-const `folly::Function`s:
 * conversion from const to non-const signatures happens implicitly. Any
 * function that takes a `folly::Function<R(Args...)>` can be passed
 * a `folly::Function<R(Args...) const>` without explicit conversion.
 * This is safe, because casting from const to non-const only entails giving
 * up the ability to invoke the function from a const context.
 * Casting from a non-const to a const signature is potentially dangerous,
 * as it means that a function that may change its inner state when invoked
 * is made possible to call from a const context. Therefore this cast does
 * not happen implicitly. The function `folly::constCastFunction` can
 * be used to perform the cast.
 *
 *     // Mutable lambda: can only be stored in a non-const folly::Function:
 *     int number = 0;
 *     folly::Function<void()> print_number =
 *       [number] () mutable { std::cout << ++number << std::endl; };
 *
 *     // const-cast to a const folly::Function:
 *     folly::Function<void() const> print_number_const =
 *       constCastFunction(std::move(print_number));
 *
 * When to use const function types?
 * Generally, only when you need them. When you use a `folly::Function` as a
 * member of a struct or class, only use a const function signature when you
 * need to invoke the function from const context.
 * When passing a `folly::Function` to a function, the function should accept
 * a non-const `folly::Function` whenever possible, i.e. when it does not
 * need to pass on or store a const `folly::Function`. This is the least
 * possible constraint: you can always pass a const `folly::Function` when
 * the function accepts a non-const one.
 *
 * How does the const behaviour compare to `std::function`?
 * `std::function` can wrap object with non-const invokation behaviour but
 * exposes them as const. The equivalent behaviour can be achieved with
 * `folly::Function` like so:
 *
 *     std::function<void(void)> stdfunc = someCallable;
 *
 *     folly::Function<void(void) const> uniqfunc = constCastFunction(
 *       folly::Function<void(void)>(someCallable)
 *     );
 *
 * You need to wrap the callable first in a non-const `folly::Function` to
 * select a non-const invoke operator (or the const one if no non-const one is
 * present), and then move it into a const `folly::Function` using
 * `constCastFunction`.
 * The name of `constCastFunction` should warn you that something
 * potentially dangerous is happening. As a matter of fact, using
 * `std::function` always involves this potentially dangerous aspect, which
 * is why it is not considered fully const-safe or even const-correct.
 * However, in most of the cases you will not need the dangerous aspect at all.
 * Either you do not require invokation of the function from a const context,
 * in which case you do not need to use `constCastFunction` and just
 * use the inner `folly::Function` in the example above, i.e. just use a
 * non-const `folly::Function`. Or, you may need invokation from const, but
 * the callable you are wrapping does not mutate its state (e.g. it is a class
 * object and implements `operator() const`, or it is a normal,
 * non-mutable lambda), in which case you can wrap the callable in a const
 * `folly::Function` directly, without using `constCastFunction`.
 * Only if you require invokation from a const context of a callable that
 * may mutate itself when invoked you have to go through the above procedure.
 * However, in that case what you do is potentially dangerous and requires
 * the equivalent of a `const_cast`, hence you need to call
 * `constCastFunction`.
 */

#pragma once

#include <functional>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>

#include <folly/CppAttributes.h>
#include <folly/Portability.h>

namespace folly {

template <typename FunctionType>
class Function;

template <typename ReturnType, typename... Args>
Function<ReturnType(Args...) const> constCastFunction(
    Function<ReturnType(Args...)>&&) noexcept;

namespace detail {
namespace function {

enum class Op { MOVE, NUKE, FULL, HEAP };

union Data {
  void* big;
  std::aligned_storage<6 * sizeof(void*)>::type tiny;
};

template <typename Fun, typename FunT = typename std::decay<Fun>::type>
using IsSmall = std::integral_constant<
    bool,
    (sizeof(FunT) <= sizeof(Data::tiny) &&
     // Same as is_nothrow_move_constructible, but w/ no template instantiation.
     noexcept(FunT(std::declval<FunT&&>()))
     )>;
using SmallTag = std::true_type;
using HeapTag = std::false_type;

struct CoerceTag {};

template <typename T>
bool isNullPtrFn(T* p) {
  return p == nullptr;
}
template <typename T>
std::false_type isNullPtrFn(T&&) {
  return {};
}

inline bool uninitNoop(Op, Data*, Data*) {
  return false;
}

template <typename FunctionType>
struct FunctionTraits;

template <typename ReturnType, typename... Args>
struct FunctionTraits<ReturnType(Args...)> {
  using Call = ReturnType (*)(Data&, Args&&...);
  using IsConst = std::false_type;
  using ConstSignature = ReturnType(Args...) const;
  using NonConstSignature = ReturnType(Args...);
  using OtherSignature = ConstSignature;

  template <typename F, typename G = typename std::decay<F>::type>
  using ResultOf = decltype(
      static_cast<ReturnType>(std::declval<G&>()(std::declval<Args>()...)));

  template <typename Fun>
  static ReturnType callSmall(Data& p, Args&&... args) {
    return static_cast<ReturnType>((*static_cast<Fun*>(
        static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
  }

  template <typename Fun>
  static ReturnType callBig(Data& p, Args&&... args) {
    return static_cast<ReturnType>(
        (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
  }

  static ReturnType uninitCall(Data&, Args&&...) {
    throw std::bad_function_call();
  }

  ReturnType operator()(Args... args) {
    auto& fn = *static_cast<Function<ReturnType(Args...)>*>(this);
    return fn.call_(fn.data_, static_cast<Args&&>(args)...);
  }

  struct SharedFunctionImpl {
    std::shared_ptr<Function<ReturnType(Args...)>> sp_;
    ReturnType operator()(Args&&... args) const {
      return (*sp_)(static_cast<Args&&>(args)...);
    }
  };
};

template <typename ReturnType, typename... Args>
struct FunctionTraits<ReturnType(Args...) const> {
  using Call = ReturnType (*)(Data&, Args&&...);
  using IsConst = std::true_type;
  using ConstSignature = ReturnType(Args...) const;
  using NonConstSignature = ReturnType(Args...);
  using OtherSignature = NonConstSignature;

  template <typename F, typename G = typename std::decay<F>::type>
  using ResultOf = decltype(static_cast<ReturnType>(
      std::declval<const G&>()(std::declval<Args>()...)));

  template <typename Fun>
  static ReturnType callSmall(Data& p, Args&&... args) {
    return static_cast<ReturnType>((*static_cast<const Fun*>(
        static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
  }

  template <typename Fun>
  static ReturnType callBig(Data& p, Args&&... args) {
    return static_cast<ReturnType>(
        (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
  }

  static ReturnType uninitCall(Data&, Args&&...) {
    throw std::bad_function_call();
  }

  ReturnType operator()(Args... args) const {
    auto& fn = *static_cast<const Function<ReturnType(Args...) const>*>(this);
    return fn.call_(fn.data_, static_cast<Args&&>(args)...);
  }

  struct SharedFunctionImpl {
    std::shared_ptr<Function<ReturnType(Args...) const>> sp_;
    ReturnType operator()(Args&&... args) const {
      return (*sp_)(static_cast<Args&&>(args)...);
    }
  };
};

template <typename Fun>
bool execSmall(Op o, Data* src, Data* dst) {
  switch (o) {
    case Op::MOVE:
      ::new (static_cast<void*>(&dst->tiny))
          Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
      FOLLY_FALLTHROUGH;
    case Op::NUKE:
      static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
      break;
    case Op::FULL:
      return true;
    case Op::HEAP:
      break;
  }
  return false;
}

template <typename Fun>
bool execBig(Op o, Data* src, Data* dst) {
  switch (o) {
    case Op::MOVE:
      dst->big = src->big;
      src->big = nullptr;
      break;
    case Op::NUKE:
      delete static_cast<Fun*>(src->big);
      break;
    case Op::FULL:
    case Op::HEAP:
      break;
  }
  return true;
}

} // namespace function
} // namespace detail

FOLLY_PUSH_WARNING
FOLLY_MSVC_DISABLE_WARNING(4521) // Multiple copy constructors
FOLLY_MSVC_DISABLE_WARNING(4522) // Multiple assignment operators
template <typename FunctionType>
class Function final : private detail::function::FunctionTraits<FunctionType> {
  // These utility types are defined outside of the template to reduce
  // the number of instantiations, and then imported in the class
  // namespace for convenience.
  using Data = detail::function::Data;
  using Op = detail::function::Op;
  using SmallTag = detail::function::SmallTag;
  using HeapTag = detail::function::HeapTag;
  using CoerceTag = detail::function::CoerceTag;

  using Traits = detail::function::FunctionTraits<FunctionType>;
  using Call = typename Traits::Call;
  using Exec = bool (*)(Op, Data*, Data*);

  template <typename Fun>
  using IsSmall = detail::function::IsSmall<Fun>;

  using OtherSignature = typename Traits::OtherSignature;

  // The `data_` member is mutable to allow `constCastFunction` to work without
  // invoking undefined behavior. Const-correctness is only violated when
  // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
  // is the result of calling `constCastFunction`.
  mutable Data data_;
  Call call_{&Traits::uninitCall};
  Exec exec_{&detail::function::uninitNoop};

  friend Traits;
  friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
      Function<typename Traits::NonConstSignature>&&) noexcept;
  friend class Function<OtherSignature>;

  template <typename Fun>
  Function(Fun&& fun, SmallTag) noexcept {
    using FunT = typename std::decay<Fun>::type;
    if (!detail::function::isNullPtrFn(fun)) {
      ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
      call_ = &Traits::template callSmall<FunT>;
      exec_ = &detail::function::execSmall<FunT>;
    }
  }

  template <typename Fun>
  Function(Fun&& fun, HeapTag) {
    using FunT = typename std::decay<Fun>::type;
    data_.big = new FunT(static_cast<Fun&&>(fun));
    call_ = &Traits::template callBig<FunT>;
    exec_ = &detail::function::execBig<FunT>;
  }

  Function(Function<OtherSignature>&& that, CoerceTag) noexcept {
    that.exec_(Op::MOVE, &that.data_, &data_);
    std::swap(call_, that.call_);
    std::swap(exec_, that.exec_);
  }

 public:
  /**
   * Default constructor. Constructs an empty Function.
   */
  Function() = default;

  // not copyable
  // NOTE: Deleting the non-const copy constructor is unusual but necessary to
  // prevent copies from non-const `Function` object from selecting the
  // perfect forwarding implicit converting constructor below
  // (i.e., `template <typename Fun> Function(Fun&&)`).
  Function(Function&) = delete;
  Function(const Function&) = delete;
  Function(const Function&&) = delete;

  /**
   * Move constructor
   */
  Function(Function&& that) noexcept {
    that.exec_(Op::MOVE, &that.data_, &data_);
    std::swap(call_, that.call_);
    std::swap(exec_, that.exec_);
  }

  /**
   * Constructs an empty `Function`.
   */
  /* implicit */ Function(std::nullptr_t) noexcept {}

  /**
   * Constructs a new `Function` from any callable object. This
   * handles function pointers, pointers to static member functions,
   * `std::reference_wrapper` objects, `std::function` objects, and arbitrary
   * objects that implement `operator()` if the parameter signature
   * matches (i.e. it returns R when called with Args...).
   * For a `Function` with a const function type, the object must be
   * callable from a const-reference, i.e. implement `operator() const`.
   * For a `Function` with a non-const function type, the object will
   * be called from a non-const reference, which means that it will execute
   * a non-const `operator()` if it is defined, and falls back to
   * `operator() const` otherwise.
   *
   * \note `typename = ResultOf<Fun>` prevents this overload from being
   * selected by overload resolution when `fun` is not a compatible function.
   */
  template <class Fun, typename = typename Traits::template ResultOf<Fun>>
  /* implicit */ Function(Fun&& fun) noexcept(IsSmall<Fun>::value)
      : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}

  /**
   * For moving a `Function<X(Ys..) const>` into a `Function<X(Ys...)>`.
   */
  template <
      bool Const = Traits::IsConst::value,
      typename std::enable_if<!Const, int>::type = 0>
  Function(Function<OtherSignature>&& that) noexcept
      : Function(std::move(that), CoerceTag{}) {}

  /**
   * If `ptr` is null, constructs an empty `Function`. Otherwise,
   * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
   */
  template <
      typename Member,
      typename Class,
      // Prevent this overload from being selected when `ptr` is not a
      // compatible member function pointer.
      typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
  /* implicit */ Function(Member Class::*ptr) noexcept {
    if (ptr) {
      *this = std::mem_fn(ptr);
    }
  }

  ~Function() {
    exec_(Op::NUKE, &data_, nullptr);
  }

  Function& operator=(Function&) = delete;
  Function& operator=(const Function&) = delete;

  /**
   * Move assignment operator
   */
  Function& operator=(Function&& that) noexcept {
    if (&that != this) {
      // Q: Why is is safe to destroy and reconstruct this object in place?
      // A: Two reasons: First, `Function` is a final class, so in doing this
      //    we aren't slicing off any derived parts. And second, the move
      //    operation is guaranteed not to throw so we always leave the object
      //    in a valid state.
      this->~Function();
      ::new (this) Function(std::move(that));
    }
    return *this;
  }

  /**
   * Assigns a callable object to this `Function`. If the operation fails,
   * `*this` is left unmodified.
   *
   * \note `typename = ResultOf<Fun>` prevents this overload from being
   * selected by overload resolution when `fun` is not a compatible function.
   */
  template <class Fun, typename = typename Traits::template ResultOf<Fun>>
  Function& operator=(Fun&& fun) noexcept(
      noexcept(/* implicit */ Function(std::declval<Fun>()))) {
    // Doing this in place is more efficient when we can do so safely.
    if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
      // Q: Why is is safe to destroy and reconstruct this object in place?
      // A: See the explanation in the move assignment operator.
      this->~Function();
      ::new (this) Function(static_cast<Fun&&>(fun));
    } else {
      // Construct a temporary and (nothrow) swap.
      Function(static_cast<Fun&&>(fun)).swap(*this);
    }
    return *this;
  }

  /**
   * Clears this `Function`.
   */
  Function& operator=(std::nullptr_t) noexcept {
    return (*this = Function());
  }

  /**
   * If `ptr` is null, clears this `Function`. Otherwise, this assignment
   * operator is equivalent to `*this = std::mem_fn(ptr)`.
   */
  template <typename Member, typename Class>
  auto operator=(Member Class::*ptr) noexcept
      // Prevent this overload from being selected when `ptr` is not a
      // compatible member function pointer.
      -> decltype(operator=(std::mem_fn(ptr))) {
    return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
  }

  /**
   * Call the wrapped callable object with the specified arguments.
   */
  using Traits::operator();

  /**
   * Exchanges the callable objects of `*this` and `that`.
   */
  void swap(Function& that) noexcept {
    std::swap(*this, that);
  }

  /**
   * Returns `true` if this `Function` contains a callable, i.e. is
   * non-empty.
   */
  explicit operator bool() const noexcept {
    return exec_(Op::FULL, nullptr, nullptr);
  }

  /**
   * Returns `true` if this `Function` stores the callable on the
   * heap. If `false` is returned, there has been no additional memory
   * allocation and the callable is stored inside the `Function`
   * object itself.
   */
  bool hasAllocatedMemory() const noexcept {
    return exec_(Op::HEAP, nullptr, nullptr);
  }

  /**
   * Construct a `std::function` by moving in the contents of this `Function`.
   * Note that the returned `std::function` will share its state (i.e. captured
   * data) across all copies you make of it, so be very careful when copying.
   */
  std::function<typename Traits::NonConstSignature> asStdFunction() && {
    using Impl = typename Traits::SharedFunctionImpl;
    return Impl{std::make_shared<Function>(std::move(*this))};
  }
};
FOLLY_POP_WARNING

template <typename FunctionType>
void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
  lhs.swap(rhs);
}

template <typename FunctionType>
bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
  return !fn;
}

template <typename FunctionType>
bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
  return !fn;
}

template <typename FunctionType>
bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
  return !(fn == nullptr);
}

template <typename FunctionType>
bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
  return !(nullptr == fn);
}

/**
 * NOTE: See detailed note about `constCastFunction` at the top of the file.
 * This is potentially dangerous and requires the equivalent of a `const_cast`.
 */
template <typename ReturnType, typename... Args>
Function<ReturnType(Args...) const> constCastFunction(
    Function<ReturnType(Args...)>&& that) noexcept {
  return Function<ReturnType(Args...) const>{std::move(that),
                                             detail::function::CoerceTag{}};
}

template <typename ReturnType, typename... Args>
Function<ReturnType(Args...) const> constCastFunction(
    Function<ReturnType(Args...) const>&& that) noexcept {
  return std::move(that);
}
} // namespace folly


text:
package sshdemo.web;

public class PageInfo {

    private int page;
    private int pageSize;
    private int startIndex;
    private int count;
    private int pageCount;
    private String jsonData;

    public PageInfo() {}

    public PageInfo(final int page, final int pageSize, final int startIndex, final int count, final int pageCount) {
        super();
        this.page = page;
        this.pageSize = pageSize;
        this.startIndex = startIndex;
        this.count = count;
        this.pageCount = pageCount;
    }

    public PageInfo(final int page, final int pageSize, final int startIndex, final int count, final int pageCount, final String jsonData) {
        super();
        this.page = page;
        this.pageSize = pageSize;
        this.startIndex = startIndex;
        this.count = count;
        this.pageCount = pageCount;
        this.jsonData = jsonData;
    }

    public int getPage() {
        return page;
    }

    public void setPage(final int page) {
        this.page = page;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(final int pageSize) {
        this.pageSize = pageSize;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(final int startIndex) {
        this.startIndex = startIndex;
    }

    public int getCount() {
        return count;
    }

    public void setCount(final int count) {
        this.count = count;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(final int pageCount) {
        this.pageCount = pageCount;
    }

    public String getJsonData() {
        return jsonData;
    }

    public void setJsonData(final String jsonData) {
        this.jsonData = jsonData;
    }

}


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Describes the settings for the subdomain.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SubDomainSetting implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The prefix setting for the subdomain.
     *

     */
    private String prefix;
    /**
     *

     * The branch name setting for the subdomain.
     *

     */
    private String branchName;

    /**
     *

     * The prefix setting for the subdomain.
     *

     *
     * @param prefix
     *        The prefix setting for the subdomain.
     */

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    /**
     *

     * The prefix setting for the subdomain.
     *

     *
     * @return The prefix setting for the subdomain.
     */

    public String getPrefix() {
        return this.prefix;
    }

    /**
     *

     * The prefix setting for the subdomain.
     *

     *
     * @param prefix
     *        The prefix setting for the subdomain.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SubDomainSetting withPrefix(String prefix) {
        setPrefix(prefix);
        return this;
    }

    /**
     *

     * The branch name setting for the subdomain.
     *

     *
     * @param branchName
     *        The branch name setting for the subdomain.
     */

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    /**
     *

     * The branch name setting for the subdomain.
     *

     *
     * @return The branch name setting for the subdomain.
     */

    public String getBranchName() {
        return this.branchName;
    }

    /**
     *

     * The branch name setting for the subdomain.
     *

     *
     * @param branchName
     *        The branch name setting for the subdomain.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SubDomainSetting withBranchName(String branchName) {
        setBranchName(branchName);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPrefix() != null)
            sb.append("Prefix: ").append(getPrefix()).append(",");
        if (getBranchName() != null)
            sb.append("BranchName: ").append(getBranchName());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof SubDomainSetting == false)
            return false;
        SubDomainSetting other = (SubDomainSetting) obj;
        if (other.getPrefix() == null ^ this.getPrefix() == null)
            return false;
        if (other.getPrefix() != null && other.getPrefix().equals(this.getPrefix()) == false)
            return false;
        if (other.getBranchName() == null ^ this.getBranchName() == null)
            return false;
        if (other.getBranchName() != null && other.getBranchName().equals(this.getBranchName()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getPrefix() == null) ? 0 : getPrefix().hashCode());
        hashCode = prime * hashCode + ((getBranchName() == null) ? 0 : getBranchName().hashCode());
        return hashCode;
    }

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

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.amplify.model.transform.SubDomainSettingMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
ContextMenuContentTypeFactory::ContextMenuContentTypeFactory() {
}

ContextMenuContentTypeFactory::~ContextMenuContentTypeFactory() {
}

// static.
ContextMenuContentType* ContextMenuContentTypeFactory::Create(
    content::WebContents* web_contents,
    const content::ContextMenuParams& params) {
  if (WebViewGuest::FromWebContents(web_contents))
    return new ContextMenuContentTypeWebView(web_contents, params);

  if (chrome::IsRunningInForcedAppMode())
    return new ContextMenuContentTypeAppMode(web_contents, params);

  const extensions::ViewType view_type = extensions::GetViewType(web_contents);

  if (view_type == extensions::VIEW_TYPE_APP_WINDOW)
    return new ContextMenuContentTypePlatformApp(web_contents, params);

  if (view_type == extensions::VIEW_TYPE_EXTENSION_POPUP)
    return new ContextMenuContentTypeExtensionPopup(web_contents, params);

  if (view_type == extensions::VIEW_TYPE_PANEL)
    return new ContextMenuContentTypePanel(web_contents, params);

  return new ContextMenuContentType(web_contents, params, true);
}


text:
{% extends "admin_utils/base.html" %}

{% block title %}{{ block.super }}{% endblock %}

{% block head %}
{{ block.super }}
{% endblock %}

{% block crumbs %}
{{ block.super }}

Käyttäjät

{% endblock %}

{% block jquery %}
{{ block.super }}
{% endblock %}

{% block content %}
{{ block.super }}

Käyttäjät

Käyttäjät

    Käyttäjälistaus kaikista rekisteröityneistä käyttäjistä. Kannattaa huomata, että "openiduser[n]"-tunnukset ovat vanhentuneita tunnuksia
    vanhasta kirjautumisjärjestelmästä. "staff"-ryhmän jäseniä voi muokata vain pääkäyttäjä-tason oikeuksilla.

    Siirry selaamaan käyttäjiä »

Loki

    Lokisivulla voi seurata käyttäjien toimia. Lokiin tallentuu myös muita tapahtumia järjestelmän toiminnasta.

    Siirry selaamaan lokia »

{% endblock %}


text: Sample APK for classLoader


text:
<?php

namespace app\models;

use Yii;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/**
 * This is the model class for table "tbl_pengurusan_jkk_jkp_program".
 *
 * @property integer $pengurusan_jkk_jkp_program_id
 * @property integer $pengurusan_jkk_jkp_id
 * @property string $tarikh_mula_program
 * @property string $lokasi_program
 * @property string $nama_program
 * @property string $nama_pesserta
 */
class PengurusanJkkJkpProgram extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_pengurusan_jkk_jkp_program';
    }

    public function behaviors()
    {
        return [
            'bedezign\yii2\audit\AuditTrailBehavior',
            [
                'class' => \yii\behaviors\BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'created',
                'updatedAtAttribute' => 'updated',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pengurusan_jkk_jkp_id', 'tarikh_mula_program', 'tarikh_tamat_program', 'lokasi_program', 'nama_program', 'nama_pesserta'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['pengurusan_jkk_jkp_id'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['tarikh_mula_program', 'tarikh_tamat_program'], 'safe'],
            [['lokasi_program'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['nama_program', 'nama_pesserta'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['lokasi_program','nama_program', 'nama_pesserta'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'pengurusan_jkk_jkp_program_id' => GeneralLabel::pengurusan_jkk_jkp_program_id,
            'pengurusan_jkk_jkp_id' => GeneralLabel::pengurusan_jkk_jkp_id,
            'tarikh_mula_program' => GeneralLabel::tarikh_mula_program,
            'tarikh_tamat_program' => GeneralLabel::tarikh_tamat_program,
            'lokasi_program' => GeneralLabel::lokasi_program,
            'nama_program' => GeneralLabel::nama_program,
            'nama_pesserta' => GeneralLabel::nama_pesserta,

        ];
    }
}


text:
using namespace foundation;
using namespace renderer;
using namespace std;

namespace appleseed {
namespace studio {

//
// SettingsWindow class implementation.
//

SettingsWindow::SettingsWindow(ParamArray& settings, QWidget* parent)
  : WindowBase(parent, "settings_window")
  , m_ui(new Ui::SettingsWindow())
  , m_settings(settings)
{
    m_ui->setupUi(this);

    setWindowFlags(Qt::Window);

    build_connections();

    WindowBase::load_settings();

    load_settings();
}

SettingsWindow::~SettingsWindow()
{
    delete m_ui;
}

void SettingsWindow::build_connections()
{
    connect(m_ui->buttonbox, SIGNAL(accepted()), SLOT(slot_save_configuration_and_close()));
    connect(m_ui->buttonbox, SIGNAL(rejected()), SLOT(slot_restore_configuration_and_close()));

    connect(
        create_window_local_shortcut(this, Qt::Key_Return), SIGNAL(activated()),
        SLOT(slot_save_configuration_and_close()));

    connect(
        create_window_local_shortcut(this, Qt::Key_Enter), SIGNAL(activated()),
        SLOT(slot_save_configuration_and_close()));

    connect(
        create_window_local_shortcut(this, Qt::Key_Escape), SIGNAL(activated()),
        SLOT(slot_restore_configuration_and_close()));
}

void SettingsWindow::load_settings()
{
    // Exploit the fact that category values match combobox item indices exactly.
    const string message_verbosity =
        m_settings.get_path_optional<string>(SETTINGS_MESSAGE_VERBOSITY, "info");
    m_ui->combobox_message_verbosity->setCurrentIndex(
        message_verbosity == "debug"   ? 0 :
        message_verbosity == "info"    ? 1 :
        message_verbosity == "warning" ? 2 :
        message_verbosity == "error"   ? 3 :
        message_verbosity == "fatal"   ? 4 :
        1);     // info if an unknown value was found

    // Sampling mode.
    const string sampling_mode =
        m_settings.get_path_optional<string>(SETTINGS_SAMPLING_MODE, "qmc");
    m_ui->combobox_sampling_mode->setCurrentIndex(
        sampling_mode == "rng" ? 0 :
        sampling_mode == "qmc" ? 1 :
        1);     // qmc if an unknown value was found

    // Autosave.
    m_ui->checkbox_autosave->setChecked(
        m_settings.get_path_optional<bool>(SETTINGS_AUTOSAVE, false));

    // Render region triggers rendering.
    m_ui->checkbox_render_region_triggers_rendering->setChecked(
        m_settings.get_path_optional<bool>(SETTINGS_RENDER_REGION_TRIGGERS_RENDERING, true));

    // Print final average luminance.
    m_ui->checkbox_print_final_average_luminance->setChecked(
        m_settings.get_path_optional<bool>(SETTINGS_PRINT_FINAL_AVERAGE_LUMINANCE, false));
}

void SettingsWindow::save_settings()
{
    // Exploit the fact that category values match combobox item indices exactly.
    const auto sampling_mode_index = m_ui->combobox_message_verbosity->currentIndex();
    m_settings.insert_path(SETTINGS_MESSAGE_VERBOSITY,
        sampling_mode_index == 0 ? "debug" :
        sampling_mode_index == 1 ? "info" :
        sampling_mode_index == 2 ? "warning" :
        sampling_mode_index == 3 ? "error" :
                                   "fatal");

    // Sampling mode.
    m_settings.insert_path(SETTINGS_SAMPLING_MODE,
        m_ui->combobox_sampling_mode->currentIndex() == 0 ? "rng" : "qmc");

    // Autosave.
    m_settings.insert_path(SETTINGS_AUTOSAVE, m_ui->checkbox_autosave->isChecked());

    // Render region triggers rendering.
    m_settings.insert_path(SETTINGS_RENDER_REGION_TRIGGERS_RENDERING,
        m_ui->checkbox_render_region_triggers_rendering->isChecked());

    // Print final average luminance.
    m_settings.insert_path(SETTINGS_PRINT_FINAL_AVERAGE_LUMINANCE,
        m_ui->checkbox_print_final_average_luminance->isChecked());

    emit signal_settings_modified();
}

void SettingsWindow::slot_save_configuration_and_close()
{
    save_settings();
    close();
}

void SettingsWindow::slot_restore_configuration_and_close()
{
    load_settings();
    close();
}

}   // namespace studio
}   // namespace appleseed

#include "mainwindow/moc_cpp_settingswindow.cxx"


text:
package com.fedorvlasov.lazylist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import de.mangelow.debdroid.R;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.TextView;

public class ImageLoader {

	MemoryCache memoryCache=new MemoryCache();
	FileCache fileCache;
	private Map<TextView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<TextView, String>());
	ExecutorService executorService;
	Handler handler=new Handler();//handler to display images in UI thread

	private Context context;

	public ImageLoader(Context context){

		this.context = context;

		fileCache=new FileCache(context);
		executorService=Executors.newFixedThreadPool(5);
	}

	final int stub_id=R.drawable.stub;
	public void DisplayImage(String url, TextView textView)
	{
		imageViews.put(textView, url);
		Bitmap bitmap=memoryCache.get(url);
		if(bitmap!=null) {

			@SuppressWarnings("deprecation")
			Drawable drawable = new BitmapDrawable(getResizedBitmap(bitmap, 50, 50));
			textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
		}
		else
		{
			queuePhoto(url, textView);
			textView.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(stub_id), null, null, null);
		}
	}

	private void queuePhoto(String url, TextView textView)
	{
		PhotoToLoad p=new PhotoToLoad(url, textView);
		executorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmap(String url)
	{
		File f=fileCache.getFile(url);

		//from SD cache
		Bitmap b = decodeFile(f);
		if(b!=null)
			return b;

		//from web
		try {
			Bitmap bitmap=null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is=conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			Utils.CopyStream(is, os);
			os.close();
			conn.disconnect();
			bitmap = decodeFile(f);
			return bitmap;
		} catch (Throwable ex){
			ex.printStackTrace();
			if(ex instanceof OutOfMemoryError)
				memoryCache.clear();
			return null;
		}
	}

	//decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f){
		try {
			//decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			FileInputStream stream1=new FileInputStream(f);
			BitmapFactory.decodeStream(stream1,null,o);
			stream1.close();

			//Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE=70;
			int width_tmp=o.outWidth, height_tmp=o.outHeight;
			int scale=1;
			while(true){
				if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
					break;
				width_tmp/=2;
				height_tmp/=2;
				scale*=2;
			}

			//decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize=scale;
			FileInputStream stream2=new FileInputStream(f);
			Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
			stream2.close();
			return bitmap;
		} catch (FileNotFoundException e) {
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	//Task for the queue
	private class PhotoToLoad
	{
		public String url;
		public TextView textView;
		public PhotoToLoad(String u, TextView i){
			url=u;
			textView=i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;
		PhotosLoader(PhotoToLoad photoToLoad){
			this.photoToLoad=photoToLoad;
		}

		@Override
		public void run() {
			try{
				if(imageViewReused(photoToLoad))
					return;
				Bitmap bmp=getBitmap(photoToLoad.url);
				memoryCache.put(photoToLoad.url, bmp);
				if(imageViewReused(photoToLoad))
					return;
				BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
				handler.post(bd);
			}catch(Throwable th){
				th.printStackTrace();
			}
		}
	}

	boolean imageViewReused(PhotoToLoad photoToLoad){
		String tag=imageViews.get(photoToLoad.textView);
		if(tag==null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	//Used to display bitmap in the UI thread
	class BitmapDisplayer implements Runnable
	{
		Bitmap bitmap;
		PhotoToLoad photoToLoad;
		public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
		public void run()
		{
			if(imageViewReused(photoToLoad))
				return;

			if(bitmap!=null) {

				Drawable drawable = new BitmapDrawable(getResizedBitmap(bitmap, 50, 50));

				photoToLoad.textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
			}
			else
				photoToLoad.textView.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(stub_id), null, null, null);

		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation

		Matrix matrix = new Matrix();

		// resize the bit map

		matrix.postScale(scaleWidth, scaleHeight);

		// recreate the new Bitmap

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

		return resizedBitmap;

	}

}