text:
@implementation NanoStoreBagTests

- (void)setUp
{
    [super setUp];

    _defaultTestInfo = [NSFNanoStore _defaultTestData];

    NSFSetIsDebugOn (NO);
}

- (void)tearDown
{

    NSFSetIsDebugOn (NO);

    [super tearDown];
}

#pragma mark -

- (void)testBagClassMethod
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;
    NSString *key = bag.key;
    NSArray *returnedKeys = [bag dictionaryRepresentation][NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && (nil != key) && ([key length] > 0) && (nil != returnedKeys) && ([returnedKeys count] == 0), @"Expected the bag to be properly initialized.");
}

- (void)testBagDescription
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSString *description = [bag description];
    XCTAssertTrue ((description.length > 0), @"Expected to obtain the bag description.");
}

- (void)testBagEqualToSelf
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    XCTAssertTrue (([bag isEqualToNanoBag:bag] == YES), @"Expected to test to be true.");
}

- (void)testBagForUUID
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSString *objectKey = [bag nanoObjectKey];
    XCTAssertTrue ((nil != objectKey) && ([objectKey length] > 0), @"Expected the bag to return a valid UUID.");

    bag = [[NSFNanoBag alloc]init];
    objectKey = [bag nanoObjectKey];
    XCTAssertTrue ((nil != objectKey) && ([objectKey length] > 0), @"Expected the bag to return a valid UUID.");
}

- (void)testBagInitNilObjects
{
    NSFNanoBag *bag = nil;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"

    @try {
        bag = [NSFNanoBag bagWithObjects:nil];
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }

#pragma clang diagnostic pop
}

- (void)testBagSettingNameManually
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    XCTAssertTrue (nil == [bag name], @"Expected the name of the bag to be nil.");
    bag.name = @"FooBar";
    XCTAssertTrue ([bag hasUnsavedChanges], @"Expected the bag to have unsaved changes.");
    XCTAssertTrue (nil != [bag name], @"Expected the name of the bag to be hold a value.");
    bag.name = nil;
    XCTAssertTrue (nil == [bag name], @"Expected the name of the bag to be nil.");
}

- (void)testBagWithNameEmptyBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bagWithName:@"FooBar"];
    XCTAssertTrue (nil != [bag name], @"Expected the name of the bag to not be nil.");

    NSError *error = nil;
    [nanoStore addObjectsFromArray:@[bag] error:&error];
    XCTAssertTrue (nil == error, @"Saving bag A should have succeded.");

    NSFNanoBag *retrievedBag = [nanoStore bagWithName:bag.name];
    XCTAssertTrue ([[retrievedBag name]isEqualToString:bag.name] == YES, @"We should have found the bag by name.");

    [nanoStore closeWithError:nil];
}

- (void)testBagWithNameBagNotEmpty
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];
    NSFNanoBag *bag = [NSFNanoBag bagWithName:@"FooBar" andObjects:objects];
    XCTAssertTrue (nil != [bag name], @"Expected the name of the bag to be nil.");

    NSError *error = nil;
    [nanoStore addObjectsFromArray:@[bag] error:&error];
    XCTAssertTrue (nil == error, @"Saving bag A should have succeded.");

    NSFNanoBag *retrievedBag = [nanoStore bagWithName:bag.name];
    XCTAssertTrue ([[retrievedBag name]isEqualToString:bag.name] == YES, @"We should have found the bag by name.");

    [nanoStore closeWithError:nil];
}

- (void)testBagSearchByName
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    bag.name = @"FooBar";
    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSFNanoBag *retrievedBag = [nanoStore bagWithName:bag.name];
    XCTAssertTrue ([[retrievedBag name]isEqualToString:bag.name] == YES, @"We should have found the bag by name.");

    [nanoStore closeWithError:nil];
}

- (void)testBagInitEmptyListOfObjects
{
    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:[NSArray array]];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;
    NSString *key = bag.key;
    NSArray *returnedKeys = [bag dictionaryRepresentation][NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && (nil != key) && ([key length] > 0) && (nil != returnedKeys) && ([returnedKeys count] == 0), @"Expected the bag to be properly initialized.");
}

- (void)testBagInitTwoConformingObjects
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:objects];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;
    NSString *key = bag.key;
    NSArray *returnedKeys = [bag dictionaryRepresentation][NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && (nil != key) && ([key length] > 0) && (nil != returnedKeys) && ([returnedKeys count] == 2), @"Expected the bag to contain two returnedKeys.");
}

- (void)testBagInitPartiallyConformingObjects
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        @"foo"];

    @try {
        [NSFNanoBag bagWithObjects:objects];
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

- (void)testBagEmptyDictionaryRepresentation
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSDictionary *info = [bag dictionaryRepresentation];
    NSString *key = info[NSF_Private_NSFNanoBag_NSFKey];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue ((nil != key) && ([key length] > 0) && (nil != returnedKeys) && ([returnedKeys count] == 0) && (nil != info) && ([info count] == 2), @"Expected the bag to provide a properly formatted dictionary.");
}

- (void)testBagWithTwoConformingObjectsDictionaryRepresentation
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:objects];
    NSDictionary *info = [bag dictionaryRepresentation];
    NSString *key = info[NSF_Private_NSFNanoBag_NSFKey];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue ((nil != key) && ([key length] > 0) && (nil != returnedKeys) && ([returnedKeys count] == 2) && (nil != info) && ([info count] == 2), @"Expected the bag to provide a properly formatted dictionary.");
}

- (void)testBagEmptyCount
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    XCTAssertTrue (0 == bag.count, @"Expected the bag to have zero elements.");
}

- (void)testBagCountTwo
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:objects];
    XCTAssertTrue (2 == bag.count, @"Expected the bag to have two elements.");
}

- (void)testTwoBagsWithSameName
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag1 = [NSFNanoBag bagWithName:@"foo" andObjects:@[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]]];
    NSFNanoBag *bag2 = [NSFNanoBag bagWithName:@"foo" andObjects:@[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]]];
    [nanoStore addObjectsFromArray:@[bag1, bag2] error:nil];
    NSArray *bags = [nanoStore bagsWithName:@"foo"];
    XCTAssertTrue (2 == bags.count, @"Expected to find two bags.");

    [nanoStore closeWithError:nil];
}

- (void)testBagCountTwoDeleteOne
{
    NSFNanoObject *objectOne = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSArray *objects = @[objectOne,
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:objects];
    XCTAssertTrue (2 == bag.count, @"Expected the bag to have two elements.");
    [bag removeObject:objectOne];
    XCTAssertTrue (1 == bag.count, @"Expected the bag to have one element.");
}

- (void)testBagCountAfterSaveEmpty
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bagWithName:@"CountTest"];
    [nanoStore addObjectsFromArray:@[bag] error:nil];
    NSFNanoBag *receivedBag = [nanoStore bagWithName:@"CountTest"];
    XCTAssertTrue (0 == receivedBag.count, @"Expected the bag to have zero elements.");

    [nanoStore closeWithError:nil];
}

- (void)testBagCountAfterSaveTwoObjectsDeleteOne
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoObject *objectOne = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSArray *objects = @[objectOne,
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithName:@"CountTest" andObjects:objects];
    [nanoStore addObjectsFromArray:@[bag] error:nil];
    NSFNanoBag *receivedBag = [nanoStore bagWithName:@"CountTest"];
    XCTAssertTrue (2 == receivedBag.count, @"Expected the bag to have two elements.");
    [receivedBag removeObject:objectOne];
    XCTAssertTrue (1 == receivedBag.count, @"Expected the bag to have one element.");

    [nanoStore closeWithError:nil];
}

- (void)testBagCountRemoveAll
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bagWithObjects:objects];
    XCTAssertTrue (2 == bag.count, @"Expected the bag to have two elements.");
    [bag removeAllObjects];
    XCTAssertTrue (0 == bag.count, @"Expected the bag to have zero elements.");
}

#pragma mark -

- (void)testBagAddNilObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    @try {
        NSError *outError = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
        [bag addObject:nil error:&outError];
#pragma clang diagnostic pop
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

- (void)testBagAddNonConformingObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    @try {
        [bag addObject:(id)@"foo" error:nil];
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

- (void)testBagAddConformingObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSError *outError = nil;
    BOOL success = [bag addObject:[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo] error:&outError];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && success && (nil == outError) && (nil != returnedKeys) && ([returnedKeys count] == 1), @"Adding a conforming object to a bag should have succeeded.");
}

- (void)testBagAddNilObjectList
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSError *outError = nil;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
    BOOL success = [bag addObjectsFromArray:nil error:&outError];
#pragma clang diagnostic pop

    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && (NO == success) && (nil != outError) && (nil != returnedKeys) && ([returnedKeys count] == 0), @"Adding a nil object list to a bag should have failed.");
}

- (void)testBagAddWithEmptyObjectList
{
    NSFNanoBag *bag = [NSFNanoBag bag];
    NSError *outError = nil;
    BOOL success = [bag addObjectsFromArray:[NSArray array] error:&outError];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && success && (nil == outError) && (nil != returnedKeys) && ([returnedKeys count] == 0), @"Adding an empty object list to a bag should have failed.");
}

- (void)testBagAddTwoConformingObjects
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSError *outError = nil;
    BOOL success = [bag addObjectsFromArray:objects error:&outError];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && success && (nil == outError) && (nil != returnedKeys) && ([returnedKeys count] == 2), @"Adding a conforming object list to a bag should have succeded.");
}

- (void) testBagAddTwoNSObjectsConformingToProtocol
{
    id car1 = [[NanoCarTestClass alloc] initNanoObjectFromDictionaryRepresentation:@{@"kName" : @"XJ-7"} forKey:[NSFNanoEngine stringWithUUID] store:nil];
    id car2 = [[NanoCarTestClass alloc] initNanoObjectFromDictionaryRepresentation:@{@"kName" : @"Jupiter 8"} forKey:[NSFNanoEngine stringWithUUID] store:nil];

    NSArray *objects = @[car1, car2];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSError *outError = nil;
    BOOL success = [bag addObjectsFromArray:objects error:&outError];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag nanoObjectDictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (success, @"expected bag to have saved");
    XCTAssertTrue (hasUnsavedChanges, @"expected bag to have no unsaved changes");
    XCTAssertNil (outError, @"expect bag to return no error on save");
    XCTAssertTrue ([returnedKeys count]== [objects count], @"expected saved bag to return %lu object keys", [objects count]);
}

- (void)testBagAddPartiallyConformingObjects
{
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo],
                        @"foo"];

    NSFNanoBag *bag = [NSFNanoBag bag];

    @try {
        [bag addObjectsFromArray:objects error:nil];
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

#pragma mark -

- (void)testBagRemoveNilObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    [bag addObject:[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo] error:nil];

    @try {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
        [bag removeObject:nil];
#pragma clang diagnostic pop
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

- (void)testBagRemoveNonConformingObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObject:obj1 error:nil];

    @try {
        [bag removeObject:(id)@"foo"];
    } @catch (NSException *e) {
        XCTAssertTrue (e != nil, @"We should have caught the exception.");
    }
}

- (void)testBagRemoveOneConformingObject
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2] error:nil];
    [bag removeObject:obj1];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];
    NSString *returnedKey = returnedKeys.lastObject;

    XCTAssertTrue (hasUnsavedChanges && (nil != returnedKeys) && ([returnedKeys count] == 1) && ([returnedKey isEqualToString:obj2.key]), @"Removing a conforming object from a bag should have succeded.");
}

- (void)restBagRemoveWithEmptyListOfObjects
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2] error:nil];
    [bag removeObject:obj1];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];
    NSString *returnedKey = returnedKeys.lastObject;

    XCTAssertTrue (hasUnsavedChanges && (nil != returnedKeys) && ([returnedKeys count] == 1) && ([returnedKey isEqualToString:obj2.key]), @"Removing a conforming object from a bag should have succeded.");
}

- (void)testBagRemoveTwoConformingObjects
{
    NSFNanoBag *bag = [NSFNanoBag bag];

    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSArray *objects = @[obj1, obj2];
    [bag addObjectsFromArray:objects error:nil];
    [bag removeObjectsInArray:objects];
    BOOL hasUnsavedChanges = bag.hasUnsavedChanges;

    NSDictionary *info = [bag dictionaryRepresentation];
    NSArray *returnedKeys = info[NSF_Private_NSFNanoBag_NSFObjectKeys];

    XCTAssertTrue (hasUnsavedChanges && (nil != returnedKeys) && ([returnedKeys count] == 0), @"Removing conforming objects from a bag should have succeded.");
}

#pragma mark -

- (void)testBagSaveEmptyBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    [nanoStore addObjectsFromArray:@[bag] error:nil];
    NSArray *bags = [nanoStore bags];

    [nanoStore closeWithError:nil];

    XCTAssertTrue ([bags count] == 1, @"Saving an empty bag should have succeded.");
}

- (void)testBagSaveBagWithThreeObjectsAssociatedToStore
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bags];

    [nanoStore closeWithError:nil];

    XCTAssertTrue ([[[bags lastObject]savedObjects]count] == 3, @"Saving a bag should have succeded.");
}

- (void)testBagSaveBagWithThreeObjectsNotAssociatedToStore
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bags];

    [nanoStore closeWithError:nil];

    XCTAssertTrue ([[[bags lastObject]savedObjects]count] == 3, @"Saving a bag should have succeded.");
}

- (void)testBagSaveBagRemovingObjects
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bags];
    NSFNanoBag *savedBag = bags.lastObject;
    [savedBag removeObjectsWithKeysInArray:@[obj1.key, obj2.key]];

    XCTAssertTrue (([bags count] == 1) && ([[savedBag savedObjects]count] == 1) && ([[savedBag unsavedObjects]count] == 0) && ([[savedBag removedObjects]count] == 2), @"Removing objects from a bag should have succeded.");

    NSError *outError = nil;
    [savedBag saveAndReturnError:&outError];
    XCTAssertTrue (nil == outError, @"Saving the bag failed. Reason: %@.", [outError localizedDescription]);

    savedBag = [nanoStore bags].lastObject;

    [nanoStore closeWithError:nil];

    XCTAssertTrue (([[savedBag savedObjects]count] == 1) && ([[savedBag unsavedObjects]count] == 0) && ([[savedBag removedObjects]count] == 0), @"Removing objects from a bag should have succeded.");
}

- (void)testBagSaveBagEditingObjects
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObject:bag error:nil];

    NSArray *bags = [nanoStore bags];
    NSFNanoBag *savedBag = bags.lastObject;

    NSError *outError = nil;
    NSFNanoObject *editedObject = savedBag.savedObjects.allValues.lastObject;
    NSString *editedKey = editedObject.key;
    NSUInteger originalCount = editedObject.info.count;
    editedObject[@"fooKey"] = @"fooValue";
    [savedBag addObject:editedObject error:&outError];
    XCTAssertTrue (([[savedBag savedObjects]count] == 2) && ([[savedBag unsavedObjects]count] == 1) && ([[savedBag removedObjects]count] == 0), @"Editing objects from a bag should have succeded.");

    [savedBag saveAndReturnError:&outError];
    XCTAssertTrue (nil == outError, @"Saving the bag failed. Reason: %@.", [outError localizedDescription]);

    savedBag = [nanoStore bags].lastObject;
    [nanoStore closeWithError:nil];

    XCTAssertTrue (([[savedBag savedObjects]count] == 3), @"Expected savedObjects to have 3 elements.");
    XCTAssertTrue (([[savedBag unsavedObjects]count] == 0), @"Expected unsavedObjects to have 0 elements.");
    XCTAssertTrue (([[savedBag removedObjects]count] == 0), @"Expected removedObjects to have 0 elements.");
    XCTAssertTrue (([[[savedBag savedObjects][editedKey]info]count] == originalCount + 1), @"Editing objects from a bag should have succeded.");
}

- (void)testBagDeleteBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    NSError *outError = nil;
    [nanoStore addObjectsFromArray:@[bag] error:&outError];
    XCTAssertTrue (nil == outError, @"Could not save the bag. Reason: %@", [outError localizedDescription]);

    NSArray *savedBags = [nanoStore bags];
    NSString *keyToBeRemoved = [[savedBags lastObject]key];
    XCTAssertTrue (nil != keyToBeRemoved, @"The key of the bag to be removed cannot be nil.");

    [nanoStore removeObjectsWithKeysInArray:@[keyToBeRemoved] error:nil];

    NSArray *removedBags = [nanoStore bags];

    [nanoStore closeWithError:nil];

    XCTAssertTrue (([savedBags count] == 1) && [removedBags count] == 0, @"Removing a bag should have succeded.");
}

- (void)testBagReloadBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bags];
    NSFNanoBag *savedBagA = bags.lastObject;

    // Edit an object, replace it in savedBagA
    NSError *outError = nil;
    NSFNanoObject *editedObject = savedBagA.savedObjects.allValues.lastObject;
    editedObject[@"fooKey"] = @"fooValue";
    [savedBagA addObject:editedObject error:&outError];
    XCTAssertTrue (([[savedBagA savedObjects]count] == 2) && ([[savedBagA unsavedObjects]count] == 1) && ([[savedBagA removedObjects]count] == 0), @"Editing objects from a bag should have succeded.");

    // Remove an object from savedBagA and save it
    [savedBagA removeObjectWithKey:obj1.key];
    BOOL success = [savedBagA saveAndReturnError:&outError];
    XCTAssertTrue (success && (nil == outError), @"Saving the bag should have succeded.");
    XCTAssertTrue (([[savedBagA savedObjects]count] == 2) && ([[savedBagA unsavedObjects]count] == 0) && ([[savedBagA removedObjects]count] == 0), @"Removing an object from a bag should have succeded.");

    bags = [nanoStore bags];
    NSFNanoBag *savedBagB = bags.lastObject;

    editedObject = savedBagB.savedObjects.allValues.lastObject;
    editedObject[@"fooKey"] = @"fooValue";
    [savedBagB addObject:editedObject error:&outError];
    success = [savedBagB reloadBagWithError:&outError];
    XCTAssertTrue (success, @"The bad reload should have succeeded.");

    success = YES;
    NSArray *sortedArrayA = [[savedBagA.savedObjects allKeys]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSArray *sortedArrayB = [[savedBagB.savedObjects allKeys]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    if (NO == [sortedArrayA isEqualToArray:sortedArrayB]) {
        success = NO;
    }

    XCTAssertTrue ((NO == success), @"The bag comparison should have failed.");
    XCTAssertTrue (([[savedBagB savedObjects]count] == 1) && ([[savedBagB unsavedObjects]count] == 1) && ([[savedBagB removedObjects]count] == 0), @"Reloading the bag should have preserved the change.");

    [nanoStore closeWithError:nil];
}

- (void)testBagUndoUnsavedBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    NSError *outError = nil;
    [bag undoChangesWithError:&outError];

    [nanoStore closeWithError:nil];

    XCTAssertTrue (([[bag savedObjects]count] == 0) && ([[bag unsavedObjects]count] == 0) && ([[bag removedObjects]count] == 0), @"Undoing the changes of an unsaved bag should have succeded.");
}

- (void)testBagUndoSavedBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bags];
    NSFNanoBag *savedBag = bags.lastObject;

    NSError *outError = nil;
    NSFNanoObject *editedObject = savedBag.savedObjects.allValues.lastObject;
    editedObject[@"fooKey"] = @"fooValue";
    [savedBag addObject:editedObject error:&outError];
    XCTAssertTrue (([[savedBag savedObjects]count] == 2) && ([[savedBag unsavedObjects]count] == 1) && ([[savedBag removedObjects]count] == 0), @"Editing objects from a bag should have succeded.");

    [savedBag undoChangesWithError:&outError];

    [nanoStore closeWithError:nil];

    XCTAssertTrue (([[savedBag savedObjects]count] == 3) && ([[savedBag unsavedObjects]count] == 0) && ([[savedBag removedObjects]count] == 0), @"Undoing the changes of a saved bag should have succeded.");
}

- (void)testBagSearchBagsWithKeys
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

    NSError *outError = nil;
    [nanoStore removeAllObjectsFromStoreAndReturnError:&outError];

    NSFNanoBag *bag1 = [NSFNanoBag bag];
    NSArray *objects = @[[NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo]];
    [bag1 addObjectsFromArray:objects error:nil];

    NSFNanoBag *bag2 = [NSFNanoBag bag];
    [bag2 addObjectsFromArray:objects error:nil];

    [nanoStore addObjectsFromArray:@[bag1, bag2] error:nil];

    NSArray *savedBags = [nanoStore bags];
    XCTAssertTrue ([savedBags count] == 2, @"Expected to find two bags.");

    savedBags = [nanoStore bagsWithKeysInArray:@[bag1.key, bag2.key]];

    [nanoStore closeWithError:nil];

    XCTAssertTrue ([savedBags count] == 2, @"Expected to find bags by their key.");
}

- (void)testBagSearchBagsContainingObjectsWithKey
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

    NSError *outError = nil;
    [nanoStore removeAllObjectsFromStoreAndReturnError:&outError];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSArray *bags = [nanoStore bagsContainingObjectWithKey:obj3.key];

    [nanoStore closeWithError:nil];

    XCTAssertTrue (([bags count] == 1) && ([[[bags lastObject]key]isEqualToString:[bag key]]), @"Searching a bag containing a specific key should have succeded.");
}

- (void)testBagCopyBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];
    [nanoStore addObject:bag error:nil];

    NSFNanoBag *copiedBag = [bag copy];

    XCTAssertTrue (([bag isEqualToNanoBag:copiedBag]), @"Equality test should have succeeded.");
}

- (void)testBagIsEqualToNanoBag
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObject:bag error:nil];

    NSArray *bags = [nanoStore bags];
    NSFNanoBag *savedBagA = bags.lastObject;
    bags = [nanoStore bags];
    NSFNanoBag *savedBagB = bags.lastObject;

    XCTAssertTrue (([savedBagA isEqualToNanoBag:savedBagB]), @"Equality test should have succeeded.");

    NSError *outError = nil;
    NSFNanoObject *editedObject = [NSFNanoObject nanoObjectWithDictionary:@{@"fooKey": @"fooObject"}];
    [savedBagB addObject:editedObject error:&outError];

    XCTAssertTrue ((NO == [savedBagA isEqualToNanoBag:savedBagB]), @"Equality test should have failed.");

    [nanoStore closeWithError:nil];
}

#pragma mark -

- (void)testBagDeflate
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSFNanoBag *resultBag = [nanoStore bags].lastObject;

    [resultBag deflateBag];

    NSDictionary *savedObjects = resultBag.savedObjects;
    BOOL deflated = YES;
    for (NSString *objectKey in savedObjects) {
        if ([NSNull null] != savedObjects[objectKey]) {
            deflated = NO;
            break;
        }
    }

    [nanoStore closeWithError:nil];

    XCTAssertTrue (deflated, @"Expected the bag to be deflated.");
}

- (void)testBagInflate
{
    NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
    [nanoStore removeAllObjectsFromStoreAndReturnError:nil];

    NSFNanoBag *bag = [NSFNanoBag bag];
    NSFNanoObject *obj1 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj2 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    NSFNanoObject *obj3 = [NSFNanoObject nanoObjectWithDictionary:_defaultTestInfo];
    [bag addObjectsFromArray:@[obj1, obj2, obj3] error:nil];

    [nanoStore addObjectsFromArray:@[bag] error:nil];

    NSFNanoBag *resultBag = [nanoStore bags].lastObject;

    [resultBag deflateBag];
    [resultBag inflateBag];

    NSDictionary *savedObjects = resultBag.savedObjects;
    BOOL inflated = YES;
    for (NSString *objectKey in savedObjects) {
        if ([NSNull null] == savedObjects[objectKey]) {
            inflated = NO;
            break;
        }
    }

    [nanoStore closeWithError:nil];

    XCTAssertTrue (inflated, @"Expected the bag to be inflated.");
}

@end


text:
package pft.addressbook.appmanager;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.io.File;

/**
 * Created by kshyniakov on 28.11.2016.
 */
public class BaseHelper {
    protected WebDriver wd;

    public BaseHelper(WebDriver wd) {
        this.wd = wd;
    }

    protected void click(By locator) {
        wd.findElement(locator).click();
    }

    protected void fillUpField(By locator, String text) {
        WebElement e = wd.findElement(locator);
        if (text!=null) {
            String existingText = e.getAttribute("value");
            if (!text.equals(existingText)) {
                e.clear();
                e.sendKeys(text);
            }
        }
    }

    protected void attach(By locator, File file) {
        if (file!=null) {
            wd.findElement(locator).sendKeys(file.getAbsolutePath());
        }
    }

    public boolean isAlertPresent() {
        try {
            wd.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    protected boolean isElementPresent(By locator) {
        try {
            wd.findElement(locator);
            return true;
        } catch (NoSuchElementException e){
            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('view:edit-student', 'Unit | View | edit student');

// Replace this with your real tests.
test('it exists', function(assert) {
  var view = this.subject();
  assert.ok(view);
});


text:
import raw from './raw'
import parsers from './parsers'

export default function (options = {}) {
  const rawParser = raw(options)
  return function (context) {
    return new Promise((resolve, reject) => {
      rawParser(context)
        .then(content => {
          const contentType = context.headers['content-type']
          context.body = contentType ? parsers.parseFromContentType(contentType, content.rawBody, options) : parsers.parse(content.rawBody, options)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

// check Content-Type header and check if there is converter available (raw?)
// content-type -> json -> x-www-form-urlencoded -> form-data -> binary


text:
<meta>
    <info name="Race" description="arc_'s MTA Race implementation" author="arc_" type="gamemode" version="0.8.3" build="r926 MrGreen version" edf:definition="edf/race.edf" />
    <download_priority_group>-10</download_priority_group> <!-- should be low so that the player joins race after everything is downloaded -->

    <include resource="scoreboard" />
    <include resource="votemanager" />
    <include resource="customblips" />
	<include resource="custom_coronas" />

    <script src="_common.lua" type="server" />
    <script src="_joiner.lua" type="server" />
    <script src="util_server.lua" type="server" />
    <script src="racemap.lua" type="server" />
    <script src="countdown.lua" type="server" />
    <script src="rankingboard.lua" type="server" />
    <script src="customcountdown/customcountdown_s.lua" type="server" />

	<file src="audio/mission_accomplished.mp3"/>
	<file src="audio/123.mp3"/>
	<file src="audio/go.mp3"/>

    <script src="modes/base.lua" type="server" />
    <script src="modes/destructionderby.lua" type="server" />
    <script src="modes/freeroam.lua" type="server" />
    <script src="modes/sprint.lua" type="server" />
    <script src="modes/nts.lua" type="server" />
    <script src="modes/ctf.lua" 	type="server" />
    <script src="modes/ctf_c.lua" 	type="client" />
    <script src="modes/rtf.lua" type="server" />
    <script src="modes/manhunt.lua" type="server" />
    <script src="modes/shooter.lua" type="server" />
    <script src="modes/shooter_c.lua" type="client" />
    <file src="modes/cargamefiles/cargame.html" />

    <script src="fixedvehiclecolors.lua" type="server" />
    <script src="race_server.lua" type="server" />
    <script src="racevoting_server.lua" type="server" />
    <script src="racestates_server.lua" type="server" />
    <script src="config_server.lua" type="server" />
    <script src="override_server.lua" type="server" />
    <script src="editor_support_server.lua" type="server" />

    <script src="_common.lua" type="client" />
    <script src="_joiner_client.lua" type="client" />
    <script src="util_client.lua" type="client" />
    <script src="fancyprogress.lua" type="client" />
    <script src="nametags.lua" type="client" />
    <script src="client_anim.lua" type="client" />
    <script src="countdown_client.lua" type="client" />
    <script src="customcountdown/customcountdown_c.lua" type="client" />
    <script src="rankingboard_client.lua" type="client" />
    <script src="race_client.lua" type="client" />
    <script src="textlib.lua" type="client" />
    <script src="textlib_anim.lua" type="client" />
    <script src="config_client.lua" type="client" />
    <script src="override_client.lua" type="client" />
    <script src="editor_support_client.lua" type="client" />

    <file src="img/progress_health_bg.png" />
    <file src="img/progress_health.png" />
    <file src="img/progress_speed_bg.png" />
    <file src="img/progress_speed.png" />
    <file src="img/countdown_3.png" />
    <file src="img/countdown_2.png" />
    <file src="img/countdown_1.png" />
    <file src="img/countdown_0.png" />
    <file src="img/timeleft.png" />
    <file src="img/hurry.png" />
    <file src="img/specprev.png" />
    <file src="img/specprev_hi.png" />
    <file src="img/specnext.png" />
    <file src="img/specnext_hi.png" />
    <file src="img/blank.png" />
    <file src="img/title.png" />
    <file src="img/travelling.png" />
    <file src="img/travelling_anniversary.png" />
    <file src="img/killmessage.png" />
    <file src="img/circle.png" />
    <file src="img/pj_red.png" />
    <file src="img/pj_blue.png" />
    <file src="img/arrow-up.png" />
    <file src="img/rocket66.png" />

    <file src="modes/cargamefiles/Roboto-Black.ttf" />
    <!-- SHADERS -->
    <file src="shaders/paintjob.fx"/>

    <file src="model/nitro.dff" />
    <file src="model/nitro.txd" />
    <file src="model/repair.dff" />
    <file src="model/repair.txd" />
    <file src="model/vehiclechange.dff" />
    <file src="model/vehiclechange.txd" />
    <file src="model/classic_nitro.dff" />
    <file src="model/classic_nitro.txd" />
    <file src="model/classic_repair.dff" />
    <file src="model/classic_repair.txd" />
    <file src="model/classic_vehiclechange.dff" />
    <file src="model/classic_vehiclechange.txd" />
    <file src="model/kmb_rcflag.dff" />
    <file src="model/rcflagxblue.txd" />
    <file src="model/rcflagxred.txd" />
    <file src="model/Blipid19.png" />
    <file src="model/Blipid53.png" />

    <file src="edf/checkpoint.png" />
    <file src="edf/pickup.png" />
    <file src="edf/spawnpoint.png" />

    <export function="getTimePassed" type="server" />
    <export function="getPlayerRank" type="server" />
    <export function="isPlayerFinished" type="server" />
    <export function="getPlayerVehicle" type="server" />
    <export function="getRaceMode" type="shared" />
    <export function="getCheckPoints" type="shared" />
    <export function="getStartTick" type="client" />
    <export function="getWhichDataSourceToUse" type="client" />
    <export function="getWatchedPlayer" type="client" />
    <export function="e_getPickups" type="client" />
    <export function="getShooterMode" type="server" />
	<export function="export_setPlayerVehicle" type="server" />

    <settings>
        <!-- *****************************************************
			 All these settings are adjustable in the Admin Panel:
				1. start admin
				2. press 'p'
				3. select Resources tab
				4. double click on 'race'
			 ***************************************************** -->

        <setting name="*color" value="#D27350" friendlyname="Message color" group="Display" accept="*" examples="#FF0000,#776655" desc="Color of the Race chat box messages." />

        <setting name="*hurrytime" value="15" friendlyname="Hurry time" accept="0-120" group="Gameplay" desc="Display HURRY! message this many seconds before the time runs out." />

        <setting name="*timeafterfirstfinish" value="30" friendlyname="Finish race time" accept="0-120" group="Gameplay" desc="The number of seconds the race continues for after someone wins." />

        <setting name="*respawnmode" value="none" friendlyname="Respawn mode" accept="timelimit,none" group="Gameplay" desc="Default respawn mode, if one is not set in the map." />

        <setting name="*respawntime" value="10" friendlyname="Respawn time" accept="0-60" group="Gameplay" desc="Default respawn time in seconds, if one is not set in the map." />

        <setting name="*duration" value="600" friendlyname="Map duration" accept="1-3600" group="Gameplay" desc="Default duration in seconds, if one is not set in the map." />

        <setting name="*ghostmode" value="false" friendlyname="Ghost mode" accept="false,true" group="Gameplay" desc="Set to true to disable collisions." />

        <setting name="*ghostalpha" value="false" friendlyname="Ghost alpha" accept="false,true" group="Graphics" desc="Set to true to make vehicle semi-transparent when collisions are disabled." />

        <setting name="*randommaps" value="false" friendlyname="Random maps" accept="false,true" group="Gameplay" desc="Set to true to make the next map selection automatic." />

        <setting name="#statskey" value="name" accept="name,serial" group="none" desc="To identify players for stats." />

        <setting name="*vehiclecolors" value="random" friendlyname="Vehicle colors" accept="file,random" group="Graphics" desc="Set to file to use the server file: mods\deathmatch\vehiclecolors.conf" />

        <setting name="*skins" value="cj" friendlyname="Driver skin" group="Graphics" accept="*" examples="cj,random,7 10 16-20 15" desc="Choose a driver skin. Acceptable values can be 'cj' or 'random' or a range list like this:'7 10 16-20 15'" />

        <setting name="*vehicleweapons" value="true" friendlyname="Vehicle weapons" group="Gameplay" accept="false,true" desc="Set to true to allow vehicle weapons." />

        <setting name="*autopimp" value="true" friendlyname="Auto pimp" group="Graphics" accept="false,true" desc="Set to true to apply a selection of visual upgrades to vehicles." />

        <setting name="*firewater" value="false" friendlyname="Fire water" group="Graphics" accept="false,true" desc="Set to true to explode the player when entering the water." />

        <setting name="*admingroup" value="Admin,SuperModerator" friendlyname="Admin group list" group="_Advanced" accept="*" examples="Admin,Moderator,SuperModerator" desc="To issue certain commands, the player must belong to one of the groups listed." />

        <setting name="#addons" value="race_toptimes,race_traffic_sensor" accept="*" desc="List of race addon resources to load automatically" />

        <setting name="*blur" value="36" friendlyname="Blur level" group="Display" accept="0-36" desc="Set to 0 to turn off blur." />

        <setting name="*clouds" value="true" friendlyname="Clouds enable" group="Display" accept="false,true" desc="Set to false to turn off clouds." />

        <setting name="*joinspectating" value="true" friendlyname="Join spectating" group="Spectating" accept="false,true" desc="Set to true to make joining players spectate the race in progress." />

        <setting name="*stealthspectate" value="true" friendlyname="Admin stealth spectate" group="Spectating" accept="false,true" desc="Set to true to hide the state of spectating admins." />

        <setting name="*classicchangez" value="true" friendlyname="Classic change Z" group="_Advanced" accept="false,true" desc="Set to true to move the player up when changing vehicles." />

        <setting name="*countdowneffect" value="true" friendlyname="Countdown effect" group="Display" accept="false,true" desc="Set to true for a fancy effect on the last countdown image." />

        <setting name="*showmapname" value="true" friendlyname="Show map name" group="Display" accept="false,true" desc="Set to true to show the current map name in the bottom left." />

        <setting name="*hunterminigun" value="true" friendlyname="Hunter minigun enable" group="Gameplay" accept="false,true" desc="Set to true to allow the Hunter minigun." />

        <setting name="*securitylevel" value="2" friendlyname="Security level" group="_Advanced" accept="0-2" desc="Detect fake packets. 0-No checks  1-Some checks  2-All checks." />

        <setting name="*anyonecanspec" value="true" friendlyname="Anyone can spectate" group="Spectating" accept="false,true" desc="Allow any player to start spectating with the 'B' key. (Does not work in no repawn maps)" />

        <setting name="*norsadminspectate" value="false" friendlyname="Admin no respawn spectate" group="Spectating" accept="false,true" desc="Allow admins to spectate while alive in no respawn maps." />

        <setting name="*racerespawn" value="true" friendlyname="Race respawn after spectate" group="Spectating" accept="false,true" desc="Force players to spawn like after death." />

        <setting name="*joinrandomvote" value="true" friendlyname="Random vote on join" group="Gameplay" accept="false,true" desc="If someone joins a lone player, start a vote to change to a random map." />

        <setting name="*asyncloading" value="true" friendlyname="Asynchronous Loading" group="_Advanced" accept="false,true" desc="Enabling this can reduce model loading lag for certain maps. It is only applied for clients who have chosen the 'Auto' option for asynchronous loading in their main settings menu." />

        <setting name="*showauthorname" value="true" friendlyname="Show author name" group="Display" accept="false,true" desc="Set to true to show the map author name on the travelling screen." />

        <setting name="*ghostmode_map_can_override" friendlyname="Ghost mode map override" group="Gameplay" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*skins_map_can_override" friendlyname="Driver skin map override" group="Graphics" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*vehicleweapons_map_can_override" friendlyname="Vehicle weapons map override" group="Gameplay" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*autopimp_map_can_override" friendlyname="Auto pimp map override" group="Graphics" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*firewater_map_can_override" friendlyname="Firewater map override" group="Graphics" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*classicchangez_map_can_override" friendlyname="Classic change Z map override" group="_Advanced" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />
        <setting name="*hunterminigun_map_can_override" friendlyname="Hunter minigun map override" group="Gameplay" value="true" accept="false,true" desc="Set to true to allow the map to override this setting" />

        <setting name="*ghostmode_warning_if_map_override" friendlyname="Ghost mode override warning" group="Gameplay" value="true" accept="false,true" desc="Set to true to issue a warning to players in the chatbox, if the map overrides this setting" />
        <setting name="*vehicleweapons_warning_if_map_override" friendlyname="Vehicle weapons override warning" group="Gameplay" value="true" accept="false,true" desc="Set to true to issue a warning to players in the chatbox, if the map overrides this setting" />
    </settings>

    <!--
        Settings in the map files
        +++++++++++++++++++++++++
        To add the 'ghostmode','skins','vehicleweapons','autopimp','firewater','classicchangez' or 'hunterminigun'
        setting to a map, insert (or update) a <settings...> section into the maps meta.xml file.
        For example:

        <settings>
            <setting name="*vehicleweapons" value="false"/>
            <setting name="*autopimp" value="false"/>
        </settings>
    -->

    <min_mta_version client="1.3.0-9.04491"></min_mta_version>
</meta>


text:
using System;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.VersionUtils;
using NUnit.Framework;

namespace JetBrains.ReSharper.Plugins.Tests.Unity.UnityEditorIntegration.VersionUtils
{
    [TestFixture]
    public class VersionExTests
    {
        [Test]
        public void CompareToLenient_MatchingMajorMinorComponents()
        {
            var version = new Version(2020, 2);

            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 3)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 1)));
        }

        [Test]
        public void CompareToLenient_MatchingMajorMinorBuildComponents()
        {
            var version = new Version(2020, 2, 100);

            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2, 100)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 2, 101)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 2, 99)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 3, 100)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 1, 100)));
        }

        [Test]
        public void CompareToLenient_MatchingMajorMinorBuildRevisionComponents()
        {
            var version = new Version(2020, 2, 100, 42);

            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2, 100, 42)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 2, 100, 43)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 2, 100, 41)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 3, 100, 42)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 1, 100, 42)));
        }

        [Test]
        public void CompareToLenient_OtherHasMoreComponents()
        {
            var version = new Version(2020, 2);

            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2, 100)));
            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2, 0)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 3, 100)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 1, 100)));
        }

        [Test]
        public void CompareToLenient_OtherHasLessComponents()
        {
            var version = new Version(2020, 2, 1);

            Assert.AreEqual(0, version.CompareToLenient(new Version(2020, 2)));
            Assert.AreEqual(-1, version.CompareToLenient(new Version(2020, 3)));
            Assert.AreEqual(1, version.CompareToLenient(new Version(2020, 1)));
        }
    }
}


text:
using System.Drawing;
using System.Text;
using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.HighlightingStrategy;

namespace WorldBankBBS.ICSharpCode.TextEditor.Src.Document
{
	public enum BracketMatchingStyle {
		Before,
		After
	}

	public class DefaultTextEditorProperties : ITextEditorProperties
	{
		int                   tabIndent             = 4;
		int                   indentationSize       = 4;
		IndentStyle           indentStyle           = IndentStyle.Smart;
		DocumentSelectionMode documentSelectionMode = DocumentSelectionMode.Normal;
		Encoding              encoding              = System.Text.Encoding.UTF8;
		BracketMatchingStyle  bracketMatchingStyle  = BracketMatchingStyle.After;
		FontContainer fontContainer;
		static Font DefaultFont;

		public DefaultTextEditorProperties()
		{
			if (DefaultFont == null) {
				DefaultFont = new Font("Courier New", 10);
			}
			this.fontContainer = new FontContainer(DefaultFont);
		}

		bool        allowCaretBeyondEOL = false;

		bool        showMatchingBracket = true;
		bool        showLineNumbers     = true;

		bool        showSpaces          = false;
		bool        showTabs            = false;
		bool        showEOLMarker       = false;

		bool        showInvalidLines    = false;

		bool        isIconBarVisible    = false;
		bool        enableFolding       = true;
		bool        showHorizontalRuler = false;
		bool        showVerticalRuler   = true;
		bool        convertTabsToSpaces = false;
		System.Drawing.Text.TextRenderingHint textRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
		bool        mouseWheelScrollDown = true;
		bool        mouseWheelTextZoom   = true;

		bool        hideMouseCursor      = false;
		bool        cutCopyWholeLine     = true;

		int         verticalRulerRow    = 80;
		LineViewerStyle  lineViewerStyle = LineViewerStyle.None;
		string      lineTerminator = "\r\n";
		bool        autoInsertCurlyBracket = true;
		bool        supportReadOnlySegments = false;

		public int TabIndent {
			get {
				return tabIndent;
			}
			set {
				tabIndent = value;
			}
		}

		public int IndentationSize {
			get { return indentationSize; }
			set { indentationSize = value; }
		}

		public IndentStyle IndentStyle {
			get {
				return indentStyle;
			}
			set {
				indentStyle = value;
			}
		}
		public DocumentSelectionMode DocumentSelectionMode {
			get {
				return documentSelectionMode;
			}
			set {
				documentSelectionMode = value;
			}
		}
		public bool AllowCaretBeyondEOL {
			get {
				return allowCaretBeyondEOL;
			}
			set {
				allowCaretBeyondEOL = value;
			}
		}
		public bool ShowMatchingBracket {
			get {
				return showMatchingBracket;
			}
			set {
				showMatchingBracket = value;
			}
		}
		public bool ShowLineNumbers {
			get {
				return showLineNumbers;
			}
			set {
				showLineNumbers = value;
			}
		}
		public bool ShowSpaces {
			get {
				return showSpaces;
			}
			set {
				showSpaces = value;
			}
		}
		public bool ShowTabs {
			get {
				return showTabs;
			}
			set {
				showTabs = value;
			}
		}
		public bool ShowEOLMarker {
			get {
				return showEOLMarker;
			}
			set {
				showEOLMarker = value;
			}
		}
		public bool ShowInvalidLines {
			get {
				return showInvalidLines;
			}
			set {
				showInvalidLines = value;
			}
		}
		public bool IsIconBarVisible {
			get {
				return isIconBarVisible;
			}
			set {
				isIconBarVisible = value;
			}
		}
		public bool EnableFolding {
			get {
				return enableFolding;
			}
			set {
				enableFolding = value;
			}
		}
		public bool ShowHorizontalRuler {
			get {
				return showHorizontalRuler;
			}
			set {
				showHorizontalRuler = value;
			}
		}
		public bool ShowVerticalRuler {
			get {
				return showVerticalRuler;
			}
			set {
				showVerticalRuler = value;
			}
		}
		public bool ConvertTabsToSpaces {
			get {
				return convertTabsToSpaces;
			}
			set {
				convertTabsToSpaces = value;
			}
		}
		public System.Drawing.Text.TextRenderingHint TextRenderingHint {
			get { return textRenderingHint; }
			set { textRenderingHint = value; }
		}

		public bool MouseWheelScrollDown {
			get {
				return mouseWheelScrollDown;
			}
			set {
				mouseWheelScrollDown = value;
			}
		}
		public bool MouseWheelTextZoom {
			get {
				return mouseWheelTextZoom;
			}
			set {
				mouseWheelTextZoom = value;
			}
		}

		public bool HideMouseCursor {
			get {
				return hideMouseCursor;
			}
			set {
				hideMouseCursor = value;
			}
		}

		public bool CutCopyWholeLine {
			get {
				return cutCopyWholeLine;
			}
			set {
				cutCopyWholeLine = value;
			}
		}

		public Encoding Encoding {
			get {
				return encoding;
			}
			set {
				encoding = value;
			}
		}
		public int VerticalRulerRow {
			get {
				return verticalRulerRow;
			}
			set {
				verticalRulerRow = value;
			}
		}
		public LineViewerStyle LineViewerStyle {
			get {
				return lineViewerStyle;
			}
			set {
				lineViewerStyle = value;
			}
		}
		public string LineTerminator {
			get {
				return lineTerminator;
			}
			set {
				lineTerminator = value;
			}
		}
		public bool AutoInsertCurlyBracket {
			get {
				return autoInsertCurlyBracket;
			}
			set {
				autoInsertCurlyBracket = value;
			}
		}

		public Font Font {
			get {
				return fontContainer.DefaultFont;
			}
			set {
				fontContainer.DefaultFont = value;
			}
		}

		public FontContainer FontContainer {
			get {
				return fontContainer;
			}
		}

		public BracketMatchingStyle  BracketMatchingStyle {
			get {
				return bracketMatchingStyle;
			}
			set {
				bracketMatchingStyle = value;
			}
		}

		public bool SupportReadOnlySegments {
			get {
				return supportReadOnlySegments;
			}
			set {
				supportReadOnlySegments = value;
			}
		}
	}
}


text:
Yii2 Framework - Yee CMS - Menu Module
=====

Module for managing menus
------------

This module is part of Yee CMS. This module allows you to create and manage menus on Yee Control Panel.
Also, this module includes a widget to render menus on frontend.

Installation
------------

- Either run

```
composer require --prefer-dist yeesoft/yii2-yee-menu "~0.1.0"
```

or add

```
"yeesoft/yii2-yee-menu": "~0.1.0"
```

to the require section of your `composer.json` file.

- Run migrations:

```php
yii migrate --migrationPath=@vendor/yeesoft/yii2-yee-menu/migrations/
```

Configuration
------

- In your backend config file

```php
'modules'=>[
    'menu' => [
        'class' => 'yeesoft\menu\MenuModule',
    ],
],
```

Usage on frontend
---

- Widget namespace:
```php
use yeesoft\menu\widgets\Menu;
```

- Render menu by ID:

```php
echo Menu::widget(['id' => 'main-menu']);
```

Menu Widget Options
-------

Use this options to configurate menu widget:

- `id` - Menu model id to render navigation.

- `wrapper` - Menu wrapper - two dimensional array. First element will be placed before menu, second element will be placed after menu

- `options` - Menu and submenus options.

  If `options` is one dimensional array then this options will be applied to all sub-menus. Example:
    ```php
    'options' => ['class' => 'nav nav-menu']
    ```

  If `options` is two dimensional array then this options will be applied according to nested submenu level. If there is no options for current level, default settings will be applied. Example:
    ```php
    'options' => [
      [ 'class' => 'nav nav-first-level'],
      [ 'class' => 'nav nav-second-level']
    ]
    ```

- `encodeLabels` - Whether the nav items labels should be HTML-encoded.

- `dropDownCaret` - This property allows you to customize the HTML which is used to generate the drop down caret symbol, which is displayed next to the button text to indicate the drop down functionality.

  Example of widget settings:
  ```php
  echo Menu::widget([
    'id' => 'main-menu',
    'dropDownCaret' => '<span class="arrow"></span>',
    'wrapper' => [
      '<div class="navbar-default sidebar" role="navigation">',
      '</div>'
    ],
    'options' => [
      [ 'class' => 'nav nav-first-level'],
      [ 'class' => 'nav nav-second-level'],
      [ 'class' => 'nav nav-third-level']
    ],
  ])
  ```

Screenshots
-------

[Flickr - Yee CMS Menus Module](https://www.flickr.com/photos/134050409@N07/sets/72157655803713779)


text:
package io.vertx.mqtt.message;

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

public final class SubAck extends MqttIdBasedMessage<SubAck> {
    private List<Qos> qoses = Collections.emptyList();

    public SubAck setQoses(List<Qos> qoses) {
        this.qoses = Collections.unmodifiableList(qoses);
        return this;
    }

    public List<Qos> getQoses() {
        return qoses;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

        <title>Generics and Subtyping (The Java™ Tutorials >
            Bonus > Generics)
</title>

     <meta name="description" content="This Java tutorial describes generics, full screen mode API, and Java certification related resources" />
     <meta name="keywords" content="java programming, learn java, java sample code, java generics, full screen mode API, certification" />

A browser with JavaScript enabled is required for this page to operate properly.

                            Download
                                the JDK

                            Search the
                                Tutorials

                            Hide the TOC

        Trail: Bonus

Lesson: Generics

Generics

Introduction

Defining Simple Generics

Generics and Subtyping

Wildcards

Generic Methods

Interoperating with Legacy Code

The Fine Print

Class Literals as Runtime-Type Tokens

More Fun with Wildcards

Converting Legacy Code to Use Generics

Acknowledgements

                Home Page
                >
                Bonus
                >
                Generics

                « Previous • Trail • Next »

Generics and Subtyping

Let's test your understanding of generics.
Is the following code snippet legal?

List<String> ls = new ArrayList<String>(); // 1
List<Object> lo = ls; // 2

Line 1 is certainly legal. The trickier part of the question is line 2.
This boils down to the question: is a List of
String a List of
Object. Most people instinctively answer, "Sure!"

Well, take a look at the next few lines:

lo.add(new Object()); // 3
String s = ls.get(0); // 4: Attempts to assign an Object to a String!

Here we've aliased ls and lo.
Accessing ls, a list of String,
through the alias lo, we can insert arbitrary objects into it. As
a result ls does not hold just Strings anymore,
and when we try and
get something out of it, we get a rude surprise.

The Java compiler will prevent this from happening of course. Line 2
will cause a compile time error.

In general, if Foo is a subtype (subclass or subinterface) of
Bar,
and G is some generic type declaration, it is not the case
that G<Foo> is a subtype of G<Bar>.
This is probably the hardest thing
you need to learn about generics, because it goes against our deeply
held intuitions.

We should not assume that collections don't change. Our instinct
may lead us to think of these things as immutable.

For example, if the department of motor vehicles supplies a list
of drivers to the census bureau, this seems reasonable. We think
that a List<Driver> is a List<Person>, assuming that
Driver is a subtype of
Person.
In fact, what is being passed is a copy of the registry
of drivers. Otherwise, the census bureau could add new people who
are not drivers into the list, corrupting the DMV's records.

To cope with this sort of situation, it's useful to consider
more flexible generic types. The rules we've seen so far are quite restrictive.

            « Previous
            •
            Trail
            •
            Next »

Problems with the examples? Try Compiling and Running
        the Examples: FAQs.

    Complaints? Compliments? Suggestions? Give
    us your feedback.

Your use of this page and all the material on pages under "The Java Tutorials" banner,
and all the material on pages under "The Java Tutorials" banner is subject to the Java SE Tutorial Copyright
and License.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
Code
Sample License.

About Oracle | Oracle Technology Network | Terms of Service

Copyright © 1995, 2011 Oracle and/or its affiliates. All rights reserved.

        Previous page: Defining Simple Generics

Next page: Wildcards

A browser with JavaScript enabled is required for this page to operate properly.


text:
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

/**
 * @requires packet/secret_key
 * @requires enums
 * @module packet/secret_subkey
 */

module.exports = SecretSubkey;

var secretKey = require('./secret_key.js'),
  enums = require('../enums.js');

/**
 * @constructor
 * @extends module:packet/secret_key
 */
function SecretSubkey() {
  secretKey.call(this);
  this.tag = enums.packet.secretSubkey;
}

SecretSubkey.prototype = new secretKey();
SecretSubkey.prototype.constructor = SecretSubkey;


text:
%Returns the gradient of the sigmoid function
%evaluated at z

function g = sigmoidGradient(z)
    g = zeros(size(z));
    g = sigmoid(z).*(1-sigmoid(z));
end


text:
CMasternodeConfig masternodeConfig;

CMasternodeConfig::CMasternodeEntry* CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex)
{
    CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
    entries.push_back(cme);
    return &(entries[entries.size()-1]);
}

void CMasternodeConfig::remove(std::string alias) {
    LOCK(cs_entries);
    int pos = -1;
    for (int i = 0; i < ((int) entries.size()); ++i) {
        CMasternodeEntry e = entries[i];
        if (e.getAlias() == alias) {
            pos = i;
            break;
        }
    }
    entries.erase(entries.begin() + pos);
}

bool CMasternodeConfig::read(std::string& strErr)
{
    LOCK(cs_entries);
    int linenumber = 1;
    fs::path pathMasternodeConfigFile = GetMasternodeConfigFile();
    fsbridge::ifstream streamConfig(pathMasternodeConfigFile);

    if (!streamConfig.good()) {
        FILE* configFile = fsbridge::fopen(pathMasternodeConfigFile, "a");
        if (configFile != NULL) {
            std::string strHeader = "# Masternode config file\n"
                                    "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
                                    "# Example: mn1 127.0.0.2:51472 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0"
                                    "#\n";
            fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
            fclose(configFile);
        }
        return true; // Nothing to read, so just return
    }

    for (std::string line; std::getline(streamConfig, line); linenumber++) {
        if (line.empty()) continue;

        std::istringstream iss(line);
        std::string comment, alias, ip, privKey, txHash, outputIndex;

        if (iss >> comment) {
            if (comment.at(0) == '#') continue;
            iss.str(line);
            iss.clear();
        }

        if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
            iss.str(line);
            iss.clear();
            if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
                strErr = _("Could not parse masternode.conf") + "\n" +
                         strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
                streamConfig.close();
                return false;
            }
        }

        int port = 0;
        int nDefaultPort = Params().GetDefaultPort();
        std::string hostname = "";
        SplitHostPort(ip, port, hostname);
        if(port == 0 || hostname == "") {
            strErr = _("Failed to parse host:port string") + "\n"+
                     strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
            streamConfig.close();
            return false;
        }

        if (port != nDefaultPort && !Params().IsRegTestNet()) {
            strErr = strprintf(_("Invalid port %d detected in masternode.conf"), port) + "\n" +
                     strprintf(_("Line: %d"), linenumber) + "\n\"" + ip + "\"" + "\n" +
                     strprintf(_("(must be %d for %s-net)"), nDefaultPort, Params().NetworkIDString());
            streamConfig.close();
            return false;
        }

        add(alias, ip, privKey, txHash, outputIndex);
    }

    streamConfig.close();
    return true;
}

bool CMasternodeConfig::CMasternodeEntry::castOutputIndex(int &n) const
{
    try {
        n = std::stoi(outputIndex);
    } catch (const std::exception& e) {
        LogPrintf("%s: %s on getOutputIndex\n", __func__, e.what());
        return false;
    }

    return true;
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSyntheticBrowserBridge = function (browser) {
};
//# sourceMappingURL=index.js.map


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_loop_61b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-61b.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using new[] and set data pointer to a small buffer
 * GoodSource: Allocate using new[] and set data pointer to a large buffer
 * Sinks: loop
 *    BadSink : Copy TwoIntsClass array to data using a loop
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_loop_61
{

#ifndef OMITBAD

TwoIntsClass * badSource(TwoIntsClass * data)
{
    /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
    data = new TwoIntsClass[50];
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
TwoIntsClass * goodG2BSource(TwoIntsClass * data)
{
    /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
    data = new TwoIntsClass[100];
    return data;
}

#endif /* OMITGOOD */

} /* close namespace */


text:
package ru.job4j.profession;

/**
 * Created by Comp on 11.06.2017.
 */
public class Wine {
    public String name;

    public Wine(String name, int id) {
        this.name = name;
    }
}


text:
`
<!DOCTYPE html>

  <title>Vator - voice of the entrepreneur</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="shortcut icon" href="img/home/favicon.ico">

  <link rel='stylesheet' type='text/css' href='//fonts.googleapis.com/css?family=Open+Sans:400,300,600&subset=cyrillic,latin'>

  <link rel="stylesheet" href="plugins/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/home/one.style.css">

  <link rel="stylesheet" href="css/home/footers/footer-v7.css">

  <link rel="stylesheet" href="plugins/animate.css">
  <link rel="stylesheet" href="plugins/line-icons/line-icons.css">
  <link rel="stylesheet" href="plugins/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="plugins/pace/pace-flash.css">
  <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css">
  <link rel="stylesheet" href="plugins/cube-portfolio/cubeportfolio/css/cubeportfolio.min.css">
  <link rel="stylesheet" href="plugins/cube-portfolio/cubeportfolio/custom/custom-cubeportfolio.css">
  <link rel="stylesheet" href="plugins/revolution-slider/rs-plugin/css/settings.css" type="text/css" media="screen">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" href="css/home/plugins/style-switcher.css">

  <link rel="stylesheet" href="css/home/theme-colors/default.css" id="style_color">

  <link rel="stylesheet" href="css/home/custom.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
          Toggle navigation

        </button>

          vator

              StartUps

              Investors

              VatorX

              VatorNews

              Register

              Log In

              The Startup and Investor Network

                 Join other investors

                 Add you startup

Get Your Startup Noticed

Be the best innovator you can be.

For Startups!

Join our network of entrepreneurs and apply for admission to top startup programs, with one application.

                   Join Today

Invest in the Best Startups

A simple way to diversify your startup portfolio

For Investors!

The Vator Investment Club lets you invest as little as $2500 alongside blue-chip investors in top deals, and Splash Winners.

                  Join VIC

Vator Splash Alumni

Stay Informed with Analysis and Events

As one of the first online networks dedicated to startups and investors, Vator has brought to you in-depth
      interviews
 with some of today's most celebrated entrepreneurs, before they became household names.
Check out some below.

 Visit our newsroom

Brian Chesky, Founder & CEO of Airbnb

Airbnb airs on VatorNews in 2009, while founders were still working in their apartment. Check out Startup Sessions.

Elon Musk, Founder & CEO of SpaceX, Tesla

Musk sits down in an in-depth interview with Bambi Francisco.

Jack Dorsey, Founder & CEO of Twitter

Bambi Francisco sits down with Dorsey during his first stint as CEO in 2008.

Vator.co

Our community for entrepreneurs and investors.
                Add your startup and/or join other investors.

VatorX

Our platform to help filter startup applications and manage deal flow.

              Create your own program.

Vator Media

Events, news and analysis  for and by our community.

                Check out the latest events and news.

                        10,000
                        Startups

                        100,000
                        Users

                        3000
                        Investors

                        100
                        Programs

Ian Ross

                  Founder & CEO, Oppsites; Principle at City Design Collective

We had no idea of the power of Vator Splash until we found the event packed with representatives from many of the region's most renowned
                  investment groups, journalists, elected officials, and professionals from tech and related fields. After OppSites was awarded
                  first prize, our schedule rapidly filled with meetings with top venture capital investors, interviews with local media
                  and offers of support from business development professionals. And that is to say nothing of the exposure from being on
                  Vator's vibrant online community and platform as well as the personal support and insight provided by Vator's founder and CEO Bambi Francisco.
                  Vator has put OppSites on a completely new course, and has accelerated our path to success.

Andres Fabris

                  Founder & CEO, Traxo

Vator Splash gives you a lot more than a fabulous evening of networking; it gives you access to an entire community of active
                  investors and inspiring entrepreneurs that are making it happen. The event generated significant exposure for our online travel
                  dashboard venture. Weeks after presenting we raised $100K from an investor who saw the online video of our Vator pitch.
                  Not only was winning Vator Splash NY a tremendous honor -- the event was THE catalyst that gave us the exposure,
                  momentum and legitimacy in the eyes of the investment community that we needed to complete our $4.2M Series A.
                  Thank you Bambi and team Vator for your inspiring passion and entrepreneurial spirit!

Aaron Hirschhorn

                  Founder & CEO, DogVacay

DogVacay.com won Vator Splash LA in June 2012. The competition allowed us an opportunity to meet and pitch against some of
                  the great Los Angeles startups and further foster our entrepreneurial community. There was such a positive energy with so
                  many great minds providing insightful feedback throughout the night. Two paws up, Vator!

Jeremy Liew

                  Partner,  Lightspeed Venture Partners

Vator's competition platform made it simple to judge contestants by accessing video, PPT, ratings, executive summaries
                  all in one place. It's the most efficient solution to judging competitions and it makes the process of judging a
                  lot more fun! And the Vator Splash competition makes it easy and efficient to review a large number of early-stage
                  startups that I would not otherwise have been exposed to.

Gagan Biyani

                  Co-Founder, Udemy

Udemy was the winner of the May 2010 Vator Splash, and it was perhaps the most important award we've won to-date.
                  Vator Splash is an incredible event in which entrepreneurs are given a chance to showcase their wares in front of a
                  huge crowd of investors, advisors, executives and fellow entrepreneurs. Bambi and team do a great job running the event
                  and bring in top-quality speakers and judges. The event provides results: a significant number of investors, advisors
                  and business development opportunities arose after we won Vator Splash in front of a crowd of more than 200.
                  Furthermore, one of the judges - Dave McClure - ended up investing in our company. Finally, VatorSplash was a great
                  momentum-builder for us as we were getting ready to fundraise. The victory provided social proof to prospective investors
                  and increased our chances of successfully attracting investment. We went on to raise $1M from a great group of angel investors!

Lisa Maki

                  Co-Founder & CEO, PokitDok

The Vator community and its Splash event provided the perfect launch pad to generate exposure for our company.
                  Winning Vator Splash 2013 SF gave us the exposure, quality venture capital meetings and network effect every startup
                  needs to initiate and complete a successful round. The very next quarter, we raised a $4M Series A. Thanks Vator!

Jed Katz

                  Managing Partner, Javelin Venture Partners

The Vator platform is a very well organized tool for learning about new start-ups, reviewing their materials, viewing
                  their media, and helping the best ones get more exposure.

Company

                          About

                          Events

                          Contact Us

For Organizations

VatorX

For Fundraising

Vator Investment Club

2015 © All Rights Reserved. Unify Theme by Htmlstream


text:
namespace DDDSouthWest.Domain.Features.Account.Admin.ManageTalks.ViewTalkDetail
{
    public class ViewTalkDetailModel
    {
        public int Id { get; set; }

        public string TalkTitle { get; set; }

        public string TalkBodyHtml { get; set; }

        public string TalkBodyMarkdown { get; set; }

        public string TalkSummary { get; set; }

        public string SpeakerGivenName { get; set; }

        public string SpeakerFamilyName { get; set; }

        public string SpeakerFullName => $"{SpeakerGivenName} {SpeakerFamilyName}";

        public bool IsApproved { get; set; }

        public bool IsSubmitted { get; set; }
    }
}


text:
package MailChimpClone::Form::Config::Edit;
use HTML::FormHandler::Types ':all';
use HTML::FormHandler::Moose;
extends 'HTML::FormHandler';
with 'HTML::FormHandler::Widget::Theme::Bootstrap3';
extends 'HTML::FormHandler::Model::DBIC';

sub build_form_element_class {['form-inline']}

#forms

has_field 'config_key' => (
    type             => 'Text',
    required         => 1,
    required_message => 'Please enter config_key.',
    label            => 'config_key',
    wrapper_class	 => ['col-md-6'],
);

has_field 'description' => (
    type             => 'Text',
    required         => 1,
    required_message => 'Please enter description.',
    label            => 'description',
    wrapper_class	 => ['col-md-6'],
);

has_field 'config_value' => (
    type             => 'Text',
    required         => 1,
    required_message => 'Please enter config_value.',
    label            => 'config_value',
    wrapper_class	 => ['col-md-6'],
);

#relationships
#submit
has_field 'submit'  => ( type => 'Submit', value => 'Submit', element_class => ['btn btn-default'], wrapper_class => 'form-actions col-xs-12' );

__PACKAGE__->meta->make_immutable;
no HTML::FormHandler::Moose;
1;

#functions


text:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <!--
    (c) Copyright 2014 WibiData, Inc.
  -->
  <id>dir</id>
  <formats>
    <format>dir</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <outputDirectory>/</outputDirectory>
      <useProjectArtifact>false</useProjectArtifact>
      <includes>
        <include>*:release</include>
      </includes>
      <unpack>true</unpack>
      <scope>runtime</scope>
      <useTransitiveDependencies>false</useTransitiveDependencies>
    </dependencySet>
  </dependencySets>
</assembly>


text:
package org.apache.sshd.common.config.keys;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collection;
import java.util.List;

public interface OpenSshCertificate extends PrivateKey, PublicKey
{
    Collection<String> getPrincipals();
    List<OpenSshCertificate.CertificateOption> getCriticalOptions();
    List<OpenSshCertificate.CertificateOption> getExtensions();
    OpenSshCertificate.Type getType();
    PublicKey getCaPubKey();
    PublicKey getCertPubKey();
    String getId();
    String getKeyType();
    String getRawKeyType();
    String getReserved();
    String getSignatureAlgorithm();
    byte[] getMessage();
    byte[] getNonce();
    byte[] getRawSignature();
    byte[] getSignature();
    long getSerial();
    long getValidAfter();
    long getValidBefore();
    static boolean isValidNow(OpenSshCertificate p0){ return false; }
    static long INFINITY = 0;
    static long MIN_EPOCH = 0;
    static public class CertificateOption
    {
        protected CertificateOption() {}
        public CertificateOption(String p0){}
        public CertificateOption(String p0, String p1){}
        public String toString(){ return null; }
        public boolean equals(Object p0){ return false; }
        public final String getData(){ return null; }
        public final String getName(){ return null; }
        public int hashCode(){ return 0; }
    }
    static public enum Type
    {
        HOST, USER;
        private Type() {}
        public int getCode(){ return 0; }
        public static OpenSshCertificate.Type fromCode(int p0){ return null; }
    }
}


text:
using ::tensorflow::strings::Scanner;
using ::tensorflow::strings::StrCat;

namespace tensorflow {

string ProtoDebugString(
    const ::tensorflow::GraphDef& msg) {
  string s;
  ::tensorflow::strings::ProtoTextOutput o(&s, false);
  internal::AppendProtoDebugString(&o, msg);
  o.CloseTopMessage();
  return s;
}

string ProtoShortDebugString(
    const ::tensorflow::GraphDef& msg) {
  string s;
  ::tensorflow::strings::ProtoTextOutput o(&s, true);
  internal::AppendProtoDebugString(&o, msg);
  o.CloseTopMessage();
  return s;
}

namespace internal {

void AppendProtoDebugString(
    ::tensorflow::strings::ProtoTextOutput* o,
    const ::tensorflow::GraphDef& msg) {
  for (int i = 0; i < msg.node_size(); ++i) {
    o->OpenNestedMessage("node");
    ::tensorflow::internal::AppendProtoDebugString(o, msg.node(i));
    o->CloseNestedMessage();
  }
  if (msg.has_library()) {
    o->OpenNestedMessage("library");
    ::tensorflow::internal::AppendProtoDebugString(o, msg.library());
    o->CloseNestedMessage();
  }
  o->AppendNumericIfNotZero("version", msg.version());
  if (msg.has_versions()) {
    o->OpenNestedMessage("versions");
    ::tensorflow::internal::AppendProtoDebugString(o, msg.versions());
    o->CloseNestedMessage();
  }
}

}  // namespace internal

bool ProtoParseFromString(
    const string& s,
    ::tensorflow::GraphDef* msg) {
  msg->Clear();
  Scanner scanner(s);
  if (!internal::ProtoParseFromScanner(&scanner, false, false, msg)) return false;
  scanner.Eos();
  return scanner.GetResult();
}

namespace internal {

bool ProtoParseFromScanner(
    ::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
    ::tensorflow::GraphDef* msg) {
  std::vector<bool> has_seen(4, false);
  while(true) {
    ProtoSpaceAndComments(scanner);
    if (nested && (scanner->Peek() == (close_curly ? '}' : '>'))) {
      scanner->One(Scanner::ALL);
      ProtoSpaceAndComments(scanner);
      return true;
    }
    if (!nested && scanner->empty()) { return true; }
    scanner->RestartCapture()
        .Many(Scanner::LETTER_DIGIT_UNDERSCORE)
        .StopCapture();
    StringPiece identifier;
    if (!scanner->GetResult(nullptr, &identifier)) return false;
    bool parsed_colon = false;
    (void)parsed_colon;
    ProtoSpaceAndComments(scanner);
    if (scanner->Peek() == ':') {
      parsed_colon = true;
      scanner->One(Scanner::ALL);
      ProtoSpaceAndComments(scanner);
    }
    if (identifier == "node") {
      const bool is_list = (scanner->Peek() == '[');
      do {
        if (is_list) {
          scanner->One(Scanner::ALL);
          ProtoSpaceAndComments(scanner);
        }
        const char open_char = scanner->Peek();
        if (open_char != '{' && open_char != '<') return false;
        scanner->One(Scanner::ALL);
        ProtoSpaceAndComments(scanner);
        if (!::tensorflow::internal::ProtoParseFromScanner(
            scanner, true, open_char == '{', msg->add_node())) return false;
      } while (is_list && scanner->Peek() == ',');
      if (is_list && !scanner->OneLiteral("]").GetResult()) return false;
    }
    else if (identifier == "versions") {
      if (has_seen[1]) return false;
      has_seen[1] = true;
      const char open_char = scanner->Peek();
      if (open_char != '{' && open_char != '<') return false;
      scanner->One(Scanner::ALL);
      ProtoSpaceAndComments(scanner);
      if (!::tensorflow::internal::ProtoParseFromScanner(
          scanner, true, open_char == '{', msg->mutable_versions())) return false;
    }
    else if (identifier == "version") {
      if (has_seen[2]) return false;
      has_seen[2] = true;
      int32 value;
      if (!parsed_colon || !::tensorflow::strings::ProtoParseNumericFromScanner(scanner, &value)) return false;
      msg->set_version(value);
    }
    else if (identifier == "library") {
      if (has_seen[3]) return false;
      has_seen[3] = true;
      const char open_char = scanner->Peek();
      if (open_char != '{' && open_char != '<') return false;
      scanner->One(Scanner::ALL);
      ProtoSpaceAndComments(scanner);
      if (!::tensorflow::internal::ProtoParseFromScanner(
          scanner, true, open_char == '{', msg->mutable_library())) return false;
    }
  }
}

}  // namespace internal

}  // namespace tensorflow


text:
'''
Created on Dec 16, 2015

@author: MLS
'''
from collections import defaultdict
import logging
import json, re, socket
from apscheduler.dispatchers.base import BaseDispatcher,DispatchCode
from apscheduler.history import add_log, add_result
from kazoo.client import KazooClient, KazooState
from tzlocal import get_localzone
from datetime import datetime
from apscheduler.util import local_timestamp_to_datetime, datetime_to_utc_timestamp
from _mysql import result
# tz.localize(datetime.datetime.fromtimestamp(timestamp))

# import six
# from datetime import datetime, timedelta
# from pytz import utc
# from traceback import format_tb
# import os, sys, commands, subprocess
# from threading import Event
# from apscheduler.events import JobExecutionEvent, EVENT_SCHEDULER_START, EVENT_SCHEDULER_SHUTDOWN,EVENT_JOBSTORE_ADDED,EVENT_JOBSTORE_REMOVED, EVENT_JOB_ADDED, EVENT_JOB_REMOVED, EVENT_JOB_MODIFIED, EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, EVENT_JOB_MISSED

class ZkDispather(BaseDispatcher):
    '''
    """Abstract base class that defines the interface that every dispatcher must implement."""
    '''
    _state = None

    def __init__(self, scheduler, executor, zk_hosts='127.0.0.1:2181', zk_root='/windmill'):
        super(ZkDispather, self).__init__(scheduler, executor)
        self._state = defaultdict(lambda: [])
        self._zk_hosts = zk_hosts
        self._zk = KazooClient(hosts=zk_hosts)
        self._zk_root = zk_root
        self._local_hostname = socket.gethostname()

    def start(self):
        BaseDispatcher.start(self)
        self._zk.start()
        return self._zk.state == KazooState.CONNECTED

    def shutdown(self):
        BaseDispatcher.shutdown(self)
        self._state.clear()
        self._zk.stop()

    def dispatch(self, job, run_times):
        # none sense to run in repeat
        if len(run_times) > 1:
            run_times = run_times[-1:]
        run_time = run_times[0]

        # allow hosts
        hosts = re.split('[,;,; \\r\\n]', job.conf.hosts) # 里面有两个中文字符, 2 chinese symbol included
        if self._local_hostname not in hosts:
            logging.error('jog ignored. local ip %s not in hosts %s' % (self._local_hostname, job.conf.hosts ))
            return DispatchCode.IGNORED

        #logging.error('run_time %s' % run_time)
        # run in just one of these hosts
        if job.conf.host_strategy == 1:
            if not self._zk.client_state == KazooState.CONNECTED:
                msg = 'zk state is %s at host %s' % (self._zk.client_state, self.ip )
                logging.error(msg)
                add_log(job.conf, run_time=datetime_to_utc_timestamp(run_time), output=msg)
                return DispatchCode.FAIL_TO_DISPATCH

            else:
                if self._zk.exists(self._get_job_running_path(job)):
                    data, stat = self._zk.get(self._get_job_running_path(job))
                    logging.info('job ignored cause of exist_strategy=1 and the last running still going on. id=%s name=%s run_time=%s host=%s zk data:%s' % (job.id, job.conf.name, run_time, self.ip, data.decode("utf-8") ))
                    run_time = None
                    return DispatchCode.IGNORED
                else:
                    try:
                        self._zk.ensure_path(self._zk_root)
                        self._zk.create(self._get_job_running_path(job), json.dumps({'job': job.id, 'host': self._local_hostname , 'run_time': run_time}), ephemeral=True)
                    except Exception, e:
                        logging.error('job ignored cause of fail to create zk ephemeral node. id=%s name=%s run_time=%s host=%s zk path:%s' % (job.id, job.conf.name, run_time, self.ip, self._get_job_running_path(job) ))
                        run_time = None
                        return DispatchCode.FAIL_TO_DISPATCH

        # local instance
        with self._lock:
            if job.conf.exist_strategy == 1 and len(self._state[job.id]) > 0:
                logging.info('job ignored cause of exist_strategy=1 and the last running in local host still going on. id=%s name=%s run_time=%s host=%s' % (job.id, job.conf.name, run_time, self.ip ))
                run_time = None

        def callback(f):
            exc, tb = (f.exception_info() if hasattr(f, 'exception_info') else
                       (f.exception(), getattr(f.exception(), '__traceback__', None)))
            if exc:
                self._run_job_error(job, run_time, exc, tb)
            else:
                self._run_job_success(job, run_time, f.result())

            with self._lock:
                self._state[job.id].remove((f, run_time))

        #f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
        #f = self._pool.submit(self.run_job, job, job._jobstore_alias, run_times, None)
        if run_time:
            with self._lock:
                logging.info('commiting ')
                f = self._executor.submit_job(job, run_time)
                self._state[job.id].append((f, run_time))
                f.add_done_callback(callback)
        return DispatchCode.DONE

    def _run_job_success(self, job, run_time, events):
        """Called by the dispatcher with the list of generated events when `run_job` has been successfully called."""
#         with self._lock:
#             #self._state[job.id].remove((f, run_time))
#             indices = [i for i, (f, rt) in enumerate(self._state[job.id]) if rt == run_time]
#             for i in indices:
#                 del self._state[job.id][i]

        cost_ms = int ((datetime_to_utc_timestamp(datetime.now( get_localzone())) - datetime_to_utc_timestamp(run_time)) * 1000)
        for event in events:
            self._scheduler._dispatch_event(event)

        add_result(job.conf, datetime_to_utc_timestamp(run_time), result=0, output='ok', cost_ms=cost_ms)

    def _run_job_error(self, job, run_time, exc, traceback=None):
        """Called by the dispatcher with the exception if there is an error calling `run_job`."""
#         with self._lock:
#             indices = [i for i, (f, rt) in enumerate(self._state[job.id]) if rt == run_time]
#             for i in indices:
#                 del self._state[job.id][i]

        exc_info = (exc.__class__, exc, traceback)
        logging.error('Error running job %s run_time %s' % (job.id, run_time), exc_info=exc_info)

        cost_ms = int ((datetime_to_utc_timestamp(datetime.now( get_localzone())) - datetime_to_utc_timestamp(run_time)) * 1000)
        add_result(job.conf, datetime_to_utc_timestamp(run_time), result=1, output=exc_info, cost_ms=cost_ms)

    def _get_job_running_path(self, job):
        return self._zk_root + '/' + str(job.id)


text:
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVInvokedUrlCommand.h>

@interface CDVInAppBrowser : CDVPlugin {}

@property (nonatomic, assign) BOOL wkwebviewavailable;
@property (nonatomic, assign) BOOL usewkwebview;

- (void)open:(CDVInvokedUrlCommand*)command;
- (void)close:(CDVInvokedUrlCommand*)command;
- (void)injectScriptCode:(CDVInvokedUrlCommand*)command;
- (void)show:(CDVInvokedUrlCommand*)command;
- (void)hide:(CDVInvokedUrlCommand*)command;
- (void)loadAfterBeforeload:(CDVInvokedUrlCommand*)command;

@end


text:
module.exports = function customStock (options) {
  const processFn = processStream
  return [ options, 'stocks.*', processFn, finishFn ]
}

function processStream (data, next) {
  return new Promise(function (/* resolve, reject */) {
    setTimeout(function () {
      console.log(data)
      next()
    }, 500)
  })
}

function finishFn () {
  return console.log('Finished')
}