text:
//
//  NSObject+DB.m
//  sqlite
//
//  Created by Jay on 7/9/18.
//  Copyright © 2018年 FEIWU888. All rights reserved.
//

#import "NSObject+DB.h"
#import <sqlite3.h>
#import <objc/runtime.h>// 导入运行时文件

/**
 开始事务.
 */

#define Begin_Transcation \
if(![DB sharedInstance].inTransaction){\
[DB sharedInstance].inTransaction = [[DB sharedInstance] execSql:@"begin transaction"];\
}

/**
 提交事务.
 */
#define Commit_Transcation \
if([DB sharedInstance].inTransaction){\
[[DB sharedInstance] execSql:@"commit transaction"];\
[DB sharedInstance].inTransaction = NO;\
}
/**
 回滚事务.
 */
#define Rollback_Transcation \
if([DB sharedInstance].inTransaction){\
[[DB sharedInstance] execSql:@"rollback transaction"];\
[DB sharedInstance].inTransaction=NO;\
}

static DB * instance = nil;
static sqlite3 *db = nil;

@interface DB()
@property (nonatomic, copy) NSString *dbPath;
@property (nonatomic, assign) BOOL inTransaction;//事务标志

@end

@implementation DB
+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
        instance.dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.db"];
    });
    return instance;
}

- (BOOL)openDB{

    int result = sqlite3_open(self.dbPath.UTF8String, &db);

    if (result == SQLITE_OK) {
        //NSLog(@"打开成功");
        return YES;
    } else {
        NSLog(@"打开失败");
        return NO;
    }
}

- (BOOL)closeDB{
    // 打开数据库的函数
    // 在数据库里面 所有的字符串都要变成utf-8的编码格式
    int result = sqlite3_close(db);
    if (result == SQLITE_OK) {
        //NSLog(@"关闭成功");
        return YES;
    } else {
        NSLog(@"关闭失败");
        return NO;
    }
}

- (BOOL)execSql:(NSString *)sql {
    char *errmsg = nil;
    BOOL result = sqlite3_exec(db, [sql UTF8String], nil, nil, &errmsg) == SQLITE_OK;
    if (!result) {
        if (errmsg) {
            NSString* sqlError = [NSString stringWithFormat:@"SQL语句执行错误: %s", errmsg];
            NSLog(@"%s--%@", __func__,sqlError);
            sqlite3_free(errmsg);
        }
    }
    return result;
}

- (BOOL)createTable:(Class)class{

    NSString *tableName = NSStringFromClass(class);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    id primaryKey = [self isRespondsToSelector:@selector(primaryKey) forClass:class];
#pragma clang diagnostic pop
    NSArray <NSDictionary *> *infos = [self getProperties:class contains:YES];

    NSMutableArray *info = [NSMutableArray array];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([primaryKey isEqualToString:obj.allKeys.firstObject]) {
            [info addObject:[NSString stringWithFormat:@"%@ INTEGER primary key autoincrement not null",obj.allKeys.firstObject]];
        }else
        {
            [info addObject:[NSString stringWithFormat:@"%@ %@",obj.allKeys.firstObject,obj.allValues.firstObject]];
        }
    }];

    NSMutableString *createString = [NSMutableString stringWithFormat:@"create table if not exists %@ (",tableName];

    [createString appendString:[info componentsJoinedByString:@","]];

    [createString appendString:@")"];
    // 创建一个person表, 要求字段:UID integer 主键,自增 name text, gender text, age integer
    // 创建表的sql语句
    // NSString *createString = @"create table if not exists dog (uid integer primary key autoincrement not null, name text, gender text, age integer)";

    // 第一个参数:数据库
    // 第二个参数:sql语句,要用utf-8的格式
    // 第三个参数:结果的回调函数
    // 第四个参数:回调函数的参数
    // 第五个参数:错误信息
    BOOL result = [self execSql:createString];//sqlite3_exec(db, createString.UTF8String, NULL, NULL, NULL);
    // 打印数据库的地址
    NSLog(@"_dbPath ==== %@", _dbPath);
    // 判断是否创建成功
    if (result) {
        //NSLog(@"创建表成功");
        return YES;
    } else {
        NSLog(@"创建表失败 %d", result);
        return NO;
    }

}

- (void)insertDatas:(NSArray <id>*)models{

    [self openDB];
    [self createTable:[models.firstObject class]];

    NSString *tableName = NSStringFromClass([models.firstObject class]);

    NSArray <NSDictionary *> *infos = [self getProperties:[models.firstObject class] contains:NO];

    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        info[obj.allKeys.firstObject] = obj.allValues.firstObject;
    }];

    NSMutableString *insertString = [NSMutableString stringWithFormat:@"insert into %@ (",tableName];

    [insertString appendFormat:@"%@ )",[info.allKeys componentsJoinedByString:@","]];
    [insertString appendString:@" values (?"];
    for (NSInteger i = 0; i < info.allKeys.count - 1; i ++) {
        [insertString appendString:@", ?"];
    }
    [insertString appendString:@")"];

    Begin_Transcation
    [models enumerateObjectsUsingBlock:^(id  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {

        // 插入数据的sql语句,数据不确定,所以在values里面使用?代替,之后向里面绑定
        //NSString *insertString = @"insert into person (name, gender, age) values (?, ?, ?)";
        // sqlite的伴随指针
        sqlite3_stmt *stmt = nil;

        // 预执行sql语句
        // 第一个参数:数据库
        // 第二个参数:sql语句
        // 第三个参数:如果为正,例如 : 1, 表示在取参数的时候,只取一个字节;使用负数表示取值取到碰到结束符号('\000','u000')。
        // 第四个参数:伴随指针,会伴随着数据库的操作,获取值或绑定值
        // 第五个参数:取值的时候如果取的不全,那么剩下的都存在这里。
        int result = sqlite3_prepare(db, insertString.UTF8String, -1, &stmt, NULL);
        // 如果预执行成功的话,那么就要往里面放数据了
        if (result == SQLITE_OK) {
            // 向预执行的sql语句里面插入参数 (取代'?'的位置)
            // 第一个参数:伴随指针
            // 第二个参数:'?'的位置,从1开始
            // 第三个参数:插入的数据
            // 第四个参数:和上面的-1是一样的
            // 第五个参数:回调函数

            for (int i = 0; i < info.allKeys.count; i ++) {

                NSString *key = info.allKeys[i];
                NSString *type = info.allValues[i];
                if ([type isEqualToString:@"INTEGER"]) {
                    sqlite3_bind_int64(stmt, i+1, [[model valueForKey:key] integerValue]);
                }else if ([type isEqualToString:@"float"]) {
                    sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] floatValue]);
                }if ([type isEqualToString:@"double"]) {
                    sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] doubleValue]);
                }if ([type isEqualToString:@"TEXT"]) {
                    sqlite3_bind_text(stmt, i+1, ((NSString *)[model valueForKey:key]).UTF8String, -1, NULL);
                }
            }

            // sql语句已经全了
            // 执行伴随指针,如果为SQLITE_DONE 代表执行成功,并且成功的插入数据。
            if (sqlite3_step(stmt) == SQLITE_DONE) {
                //NSLog(@"插入成功");
            } else {
                NSLog(@"插入失败");
            }
        } else {
            NSLog(@"插入失败%d", result);
        }

        // 一定要记得释放掉伴随指针
        sqlite3_finalize(stmt);
    }];

    Commit_Transcation

    [self closeDB];
}

- (void)insertData:(id)model{

    [self openDB];
    [self createTable:[model class]];

    NSString *tableName = NSStringFromClass([model class]);

    NSArray <NSDictionary *> *infos = [self getProperties:[model class] contains:NO];

    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        info[obj.allKeys.firstObject] = obj.allValues.firstObject;
    }];

    NSMutableString *insertString = [NSMutableString stringWithFormat:@"insert into %@ (",tableName];

    [insertString appendFormat:@"%@ )",[info.allKeys componentsJoinedByString:@","]];
    [insertString appendString:@" values (?"];
    for (NSInteger i = 0; i < info.allKeys.count - 1; i ++) {
        [insertString appendString:@", ?"];
    }
    [insertString appendString:@")"];

    // 插入数据的sql语句,数据不确定,所以在values里面使用?代替,之后向里面绑定
    //NSString *insertString = @"insert into person (name, gender, age) values (?, ?, ?)";
    // sqlite的伴随指针
    sqlite3_stmt *stmt = nil;

    // 预执行sql语句
    // 第一个参数:数据库
    // 第二个参数:sql语句
    // 第三个参数:如果为正,例如 : 1, 表示在取参数的时候,只取一个字节;使用负数表示取值取到碰到结束符号('\000','u000')。
    // 第四个参数:伴随指针,会伴随着数据库的操作,获取值或绑定值
    // 第五个参数:取值的时候如果取的不全,那么剩下的都存在这里。
    int result = sqlite3_prepare(db, insertString.UTF8String, -1, &stmt, NULL);
    // 如果预执行成功的话,那么就要往里面放数据了
    if (result == SQLITE_OK) {
        // 向预执行的sql语句里面插入参数 (取代'?'的位置)
        // 第一个参数:伴随指针
        // 第二个参数:'?'的位置,从1开始
        // 第三个参数:插入的数据
        // 第四个参数:和上面的-1是一样的
        // 第五个参数:回调函数

        for (int i = 0; i < info.allKeys.count; i ++) {

            NSString *key = info.allKeys[i];
            NSString *type = info.allValues[i];
            if ([type isEqualToString:@"INTEGER"]) {
                sqlite3_bind_int64(stmt, i+1, [[model valueForKey:key] integerValue]);
            }else if ([type isEqualToString:@"float"]) {
                sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] floatValue]);
            }if ([type isEqualToString:@"double"]) {
                sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] doubleValue]);
            }if ([type isEqualToString:@"TEXT"]) {
                sqlite3_bind_text(stmt, i+1, ((NSString *)[model valueForKey:key]).UTF8String, -1, NULL);
            }
        }

        // sql语句已经全了
        // 执行伴随指针,如果为SQLITE_DONE 代表执行成功,并且成功的插入数据。
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            //NSLog(@"插入成功");
        } else {
            NSLog(@"插入失败");
        }
    } else {
        NSLog(@"插入失败%d", result);
    }

    // 一定要记得释放掉伴随指针
    sqlite3_finalize(stmt);

    [self closeDB];
}
//UPDATE table_name
//SET column1 = value1, column2 = value2...., columnN = valueN
//WHERE [condition];
- (void)updateWithModel:(id)model where:(NSString *)condition{

    NSString *tableName = NSStringFromClass([model class]);
    NSArray <NSDictionary *> *infos = [self getProperties:[model class] contains:NO];

    NSMutableString *updateString = [NSMutableString stringWithFormat:@"update %@ set ",tableName];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [updateString appendFormat:@"%@ = '%@',",obj.allKeys.firstObject,[model valueForKey:obj.allKeys.firstObject]];
    }];

    NSString * updateSQL = [NSString stringWithFormat:@"%@ %@",[updateString substringToIndex:updateString.length-1],condition];

    // 伴随指针
    sqlite3_stmt *stmt = nil;

    int result = sqlite3_prepare(db, updateSQL.UTF8String, -1, &stmt, NULL);

    if (result == SQLITE_OK) {

        for (int i = 0; i < infos.count; i ++) {

            NSString *key = infos[i].allKeys.firstObject;
            NSString *type = infos[i].allValues.firstObject;
            if ([type isEqualToString:@"INTEGER"]) {
                sqlite3_bind_int64(stmt, i+1, [[model valueForKey:key] integerValue]);
            }else if ([type isEqualToString:@"float"]) {
                sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] floatValue]);
            }if ([type isEqualToString:@"double"]) {
                sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] doubleValue]);
            }if ([type isEqualToString:@"TEXT"]) {
                sqlite3_bind_text(stmt, i+1, ((NSString *)[model valueForKey:key]).UTF8String, -1, NULL);
            }
        }
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            //NSLog(@"修改成功");
        }
    }else{
        NSLog(@"更新失败%d", result);

    }

    sqlite3_finalize(stmt);
}

- (void)deleteWithModel:(Class)class where:(NSString *)condition{

    NSString *tableName = NSStringFromClass(class);

    NSString *deleteString = [NSString stringWithFormat:@"delete from %@ %@", tableName,condition];

    BOOL result = [self execSql:deleteString];//sqlite3_exec(db, deleteString.UTF8String, NULL, NULL, NULL);

    if (result) {
        //NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }
}

- (NSArray <id>*)searchAllModel:(Class)class where:(NSString *)condition {

    [self openDB];
    NSString *tableName = NSStringFromClass(class);

    NSString *searchString = [NSString stringWithFormat:@"select * from %@ %@", tableName,condition];

    sqlite3_stmt *stmt = nil;

    int result = sqlite3_prepare(db, searchString.UTF8String, -1, &stmt, NULL);
    NSMutableArray *models = [NSMutableArray array];

    if (result == SQLITE_OK) {

        NSArray <NSDictionary *> *infos = [self getProperties:class contains:YES];

        // 当sqlite3_step(stmt) == SQLITE_ROW 的时候,代表还有下一条数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {

            id model = [class new];
            for (int i = 0 ; i < infos.count; i++) {
                NSString *type = infos[i].allValues.firstObject;
                NSString *key = infos[i].allKeys.firstObject;

                if ([type isEqualToString:@"INTEGER"]) {

                    int uid = sqlite3_column_int(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }else if ([type isEqualToString:@"float"]) {

                    float uid = sqlite3_column_double(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }if ([type isEqualToString:@"double"]) {

                    double uid = sqlite3_column_double(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }if ([type isEqualToString:@"TEXT"]) {
                    NSString *name = [NSString stringWithUTF8String:(const char *) sqlite3_column_text(stmt, i)];
                    [model setValue:name forKey:key];

                }

            }
            [models addObject:model];
        }
        NSLog(@"%s--%@", __func__,models);
    }

    sqlite3_finalize(stmt);
    [self closeDB];
    return models;
}

-(id)isRespondsToSelector:(SEL)selector forClass:(Class)cla{
    id obj = nil;
    if([cla respondsToSelector:selector]){
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        obj = [cla performSelector:selector];
#pragma clang diagnostic pop
    }else{
        //抛出异常
        NSException *exc = [NSException exceptionWithName:@"请在保存的模型中实现 +(NSString *)primaryKey" reason:@"请在保存的模型中实现 +(NSString *)primaryKey" userInfo:nil];
        //抛出异常
        [exc raise];
    }
    return obj;
}

-(NSArray <NSDictionary *>*)getProperties:(Class)cls contains:(BOOL)isc{

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    NSString * primaryKey = [self isRespondsToSelector:@selector(primaryKey) forClass:cls];
#pragma clang diagnostic pop
    unsigned int outCount = 0;

    NSMutableArray *array = [NSMutableArray array];

    Ivar * ivars = class_copyIvarList([cls class], &outCount);
    for (unsigned int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        const char * cName = ivar_getName(ivar);
        const char * cType = ivar_getTypeEncoding(ivar);
        NSString *name = [[NSString stringWithCString:cName encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"_" withString:@""];
        NSString *type = [NSString stringWithCString:cType encoding:NSUTF8StringEncoding];
        //NSLog(@"类型为 %@ 的 %@ ",type, name);

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        if([name isEqualToString:primaryKey] && !isc) continue;

        if ([type isEqualToString:@"B"]) {
            dict[name] = @"INTEGER";

        }else if ([type isEqualToString:@"@\"NSString\""]) {
            dict[name] = @"TEXT";

        }else if ([type isEqualToString:@"q"]) {
            dict[name] = @"INTEGER";

        }else if ([type isEqualToString:@"d"]) {
            dict[name] = @"double";

        }else if ([type isEqualToString:@"i"]) {
            dict[name] = @"INTEGER";

        }else if ([type isEqualToString:@"f"]) {
            dict[name] = @"float";

        }else if ([type isEqualToString:@"Q"]) {
            dict[name] = @"INTEGER";

        }else
        {
            continue;
        }
        [array addObject:dict];

    }
    free(ivars);

    return array;
}

@end

@implementation NSObject (DB)

- (BOOL)insert{

    BOOL isOk = NO;

    [[DB sharedInstance] openDB];
    [[DB sharedInstance] createTable:[self class]];

    NSString *tableName = NSStringFromClass([self class]);

    NSArray <NSDictionary *> *infos = [[DB sharedInstance] getProperties:[self class] contains:NO];

    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        info[obj.allKeys.firstObject] = obj.allValues.firstObject;
    }];

    NSMutableString *insertString = [NSMutableString stringWithFormat:@"insert into %@ (",tableName];

    [insertString appendFormat:@"%@ )",[info.allKeys componentsJoinedByString:@","]];
    [insertString appendString:@" values (?"];
    for (NSInteger i = 0; i < info.allKeys.count - 1; i ++) {
        [insertString appendString:@", ?"];
    }
    [insertString appendString:@")"];

    // 插入数据的sql语句,数据不确定,所以在values里面使用?代替,之后向里面绑定
    //NSString *insertString = @"insert into person (name, gender, age) values (?, ?, ?)";
    // sqlite的伴随指针
    sqlite3_stmt *stmt = nil;

    // 预执行sql语句
    // 第一个参数:数据库
    // 第二个参数:sql语句
    // 第三个参数:如果为正,例如 : 1, 表示在取参数的时候,只取一个字节;使用负数表示取值取到碰到结束符号('\000','u000')。
    // 第四个参数:伴随指针,会伴随着数据库的操作,获取值或绑定值
    // 第五个参数:取值的时候如果取的不全,那么剩下的都存在这里。
    int result = sqlite3_prepare(db, insertString.UTF8String, -1, &stmt, NULL);
    // 如果预执行成功的话,那么就要往里面放数据了
    if (result == SQLITE_OK) {
        // 向预执行的sql语句里面插入参数 (取代'?'的位置)
        // 第一个参数:伴随指针
        // 第二个参数:'?'的位置,从1开始
        // 第三个参数:插入的数据
        // 第四个参数:和上面的-1是一样的
        // 第五个参数:回调函数

        for (int i = 0; i < info.allKeys.count; i ++) {

            NSString *key = info.allKeys[i];
            NSString *type = info.allValues[i];
            if ([type isEqualToString:@"INTEGER"]) {
                sqlite3_bind_int64(stmt, i+1, [[self valueForKey:key] integerValue]);
            }else if ([type isEqualToString:@"float"]) {
                sqlite3_bind_double(stmt, i+1, [[self valueForKey:key] floatValue]);
            }if ([type isEqualToString:@"double"]) {
                sqlite3_bind_double(stmt, i+1, [[self valueForKey:key] doubleValue]);
            }if ([type isEqualToString:@"TEXT"]) {
                sqlite3_bind_text(stmt, i+1, ((NSString *)[self valueForKey:key]).UTF8String, -1, NULL);
            }
        }

        // sql语句已经全了
        // 执行伴随指针,如果为SQLITE_DONE 代表执行成功,并且成功的插入数据。
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            //NSLog(@"插入成功");
            isOk = YES;
        } else {
            NSLog(@"插入失败");
            isOk = NO;
        }
    } else {
        NSLog(@"插入失败%d", result);
        isOk = NO;
    }

    // 一定要记得释放掉伴随指针
    sqlite3_finalize(stmt);

    [[DB sharedInstance] closeDB];
    return isOk;
}

+ (BOOL)insertDatas:(NSArray <id>*)models{

    __block BOOL isOK = NO;

    [[DB sharedInstance] openDB];
    [[DB sharedInstance] createTable:[models.firstObject class]];

    NSString *tableName = NSStringFromClass([models.firstObject class]);

    NSArray <NSDictionary *> *infos = [[DB sharedInstance] getProperties:[models.firstObject class] contains:NO];

    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        info[obj.allKeys.firstObject] = obj.allValues.firstObject;
    }];

    NSMutableString *insertString = [NSMutableString stringWithFormat:@"insert into %@ (",tableName];

    [insertString appendFormat:@"%@ )",[info.allKeys componentsJoinedByString:@","]];
    [insertString appendString:@" values (?"];
    for (NSInteger i = 0; i < info.allKeys.count - 1; i ++) {
        [insertString appendString:@", ?"];
    }
    [insertString appendString:@")"];

    Begin_Transcation
    [models enumerateObjectsUsingBlock:^(id  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {

        // 插入数据的sql语句,数据不确定,所以在values里面使用?代替,之后向里面绑定
        //NSString *insertString = @"insert into person (name, gender, age) values (?, ?, ?)";
        // sqlite的伴随指针
        sqlite3_stmt *stmt = nil;

        // 预执行sql语句
        // 第一个参数:数据库
        // 第二个参数:sql语句
        // 第三个参数:如果为正,例如 : 1, 表示在取参数的时候,只取一个字节;使用负数表示取值取到碰到结束符号('\000','u000')。
        // 第四个参数:伴随指针,会伴随着数据库的操作,获取值或绑定值
        // 第五个参数:取值的时候如果取的不全,那么剩下的都存在这里。
        int result = sqlite3_prepare(db, insertString.UTF8String, -1, &stmt, NULL);
        // 如果预执行成功的话,那么就要往里面放数据了
        if (result == SQLITE_OK) {
            // 向预执行的sql语句里面插入参数 (取代'?'的位置)
            // 第一个参数:伴随指针
            // 第二个参数:'?'的位置,从1开始
            // 第三个参数:插入的数据
            // 第四个参数:和上面的-1是一样的
            // 第五个参数:回调函数

            for (int i = 0; i < info.allKeys.count; i ++) {

                NSString *key = info.allKeys[i];
                NSString *type = info.allValues[i];
                if ([type isEqualToString:@"INTEGER"]) {
                    sqlite3_bind_int64(stmt, i+1, [[model valueForKey:key] integerValue]);
                }else if ([type isEqualToString:@"float"]) {
                    sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] floatValue]);
                }if ([type isEqualToString:@"double"]) {
                    sqlite3_bind_double(stmt, i+1, [[model valueForKey:key] doubleValue]);
                }if ([type isEqualToString:@"TEXT"]) {
                    sqlite3_bind_text(stmt, i+1, ((NSString *)[model valueForKey:key]).UTF8String, -1, NULL);
                }
            }

            // sql语句已经全了
            // 执行伴随指针,如果为SQLITE_DONE 代表执行成功,并且成功的插入数据。
            if (sqlite3_step(stmt) == SQLITE_DONE) {
                //NSLog(@"插入成功");
                isOK = YES;
            } else {
                NSLog(@"插入失败");
                isOK = NO;
            }
        } else {
            NSLog(@"插入失败%d", result);
              isOK = NO;
        }

        // 一定要记得释放掉伴随指针
        sqlite3_finalize(stmt);
    }];

    Commit_Transcation

    [[DB sharedInstance] closeDB];

    return isOK;
}

+ (NSArray <id>*)searchDataWhere:(NSString *)condition{

    [[DB sharedInstance] openDB];
    NSString *tableName = NSStringFromClass(self);

    NSString *searchString = [NSString stringWithFormat:@"select * from %@ %@", tableName,condition];

    sqlite3_stmt *stmt = nil;

    int result = sqlite3_prepare(db, searchString.UTF8String, -1, &stmt, NULL);
    NSMutableArray *models = [NSMutableArray array];

    if (result == SQLITE_OK) {

        NSArray <NSDictionary *> *infos = [[DB sharedInstance] getProperties:self contains:YES];

        // 当sqlite3_step(stmt) == SQLITE_ROW 的时候,代表还有下一条数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {

            id model = [self new];
            for (int i = 0 ; i < infos.count; i++) {
                NSString *type = infos[i].allValues.firstObject;
                NSString *key = infos[i].allKeys.firstObject;

                if ([type isEqualToString:@"INTEGER"]) {

                    int uid = sqlite3_column_int(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }else if ([type isEqualToString:@"float"]) {

                    float uid = sqlite3_column_double(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }if ([type isEqualToString:@"double"]) {

                    double uid = sqlite3_column_double(stmt, i);
                    [model setValue:@(uid) forKey:key];

                }if ([type isEqualToString:@"TEXT"]) {
                    NSString *name = [NSString stringWithUTF8String:(const char *) sqlite3_column_text(stmt, i)];
                    [model setValue:name forKey:key];

                }

            }
            [models addObject:model];
        }
        NSLog(@"%s--%@", __func__,models);
    }

    sqlite3_finalize(stmt);
    [[DB sharedInstance] closeDB];
    return models;
}

+ (BOOL)deleteDataWhere:(NSString *)condition{
    [[DB sharedInstance] openDB];
    NSString *tableName = NSStringFromClass(self);

    NSString *deleteString = [NSString stringWithFormat:@"delete from %@ %@", tableName,condition];

    BOOL result = [[DB sharedInstance] execSql:deleteString];//sqlite3_exec(db, deleteString.UTF8String, NULL, NULL, NULL);

    if (result) {
        //NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }
    [[DB sharedInstance] closeDB];
    return result;
}

//UPDATE table_name
//SET column1 = value1, column2 = value2...., columnN = valueN
//WHERE [condition];
- (BOOL)update{
    BOOL isOK = NO;
        [[DB sharedInstance] openDB];
    NSString *tableName = NSStringFromClass([self class]);
    NSArray <NSDictionary *> *infos = [[DB sharedInstance] getProperties:[self class] contains:NO];

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    id primaryKeyType = [[DB sharedInstance] isRespondsToSelector:@selector(primaryKey) forClass:[self class]];
#pragma clang diagnostic pop

    id primaryKeyValue = [self valueForKey:primaryKeyType];

    NSMutableString *updateString = [NSMutableString stringWithFormat:@"update %@ set ",tableName];
    [infos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [updateString appendFormat:@"%@ = '%@',",obj.allKeys.firstObject,[self valueForKey:obj.allKeys.firstObject]];
    }];

    NSString * updateSQL = [NSString stringWithFormat:@"%@ where %@ = %@",[updateString substringToIndex:updateString.length-1],primaryKeyType,primaryKeyValue];

    // 伴随指针
    sqlite3_stmt *stmt = nil;

    int result = sqlite3_prepare(db, updateSQL.UTF8String, -1, &stmt, NULL);

    if (result == SQLITE_OK) {

        for (int i = 0; i < infos.count; i ++) {

            NSString *key = infos[i].allKeys.firstObject;
            NSString *type = infos[i].allValues.firstObject;
            if ([type isEqualToString:@"INTEGER"]) {
                sqlite3_bind_int64(stmt, i+1, [[self valueForKey:key] integerValue]);
            }else if ([type isEqualToString:@"float"]) {
                sqlite3_bind_double(stmt, i+1, [[self valueForKey:key] floatValue]);
            }if ([type isEqualToString:@"double"]) {
                sqlite3_bind_double(stmt, i+1, [[self valueForKey:key] doubleValue]);
            }if ([type isEqualToString:@"TEXT"]) {
                sqlite3_bind_text(stmt, i+1, ((NSString *)[self valueForKey:key]).UTF8String, -1, NULL);
            }
        }
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            //NSLog(@"修改成功");
            isOK = YES;
        }
    }else{
        NSLog(@"更新失败%d", result);
        isOK = NO;
    }

    sqlite3_finalize(stmt);
        [[DB sharedInstance] closeDB];
    return isOK;
}

@end


text:
/* Dynamic top menu positioning
 *
 */

var num = 1950; //number of pixels before modifying styles

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > num) {
        $('.menu').addClass('fixed');
    } else {
        $('.menu').removeClass('fixed');
    }
});

//USE SCROLL WHEEL FOR THIS FIDDLE DEMO

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Attentra\ResourceBundle\Controller;

use Attentra\CoreBundle\Form\Type\LinkButtonType;
use Attentra\ResourceBundle\Entity\Resource;
use Attentra\ResourceBundle\Form\ResourceType;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * Manage Attentra resource entities
 *
 * @Route("/resource")
 *
 */
class ResourceController extends Controller
{
    /**
     * Lists all entities.
     *
     * @Route("/", name="attentra_resource")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        return array(
            'entities' => $em->getRepository('AttentraResourceBundle:Resource')->findBy([], ['name' => 'asc']),
        );
    }

    /**
     * Displays a form to create a new entity.
     *
     * @Route("/new", name="attentra_resource_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Resource();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new entity.
     *
     * @Route("/", name="attentra_resource_create")
     * @Method("POST")
     * @Template("AttentraResourceBundle:Resource:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Resource();
        $form   = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('attentra_resource_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays an entity.
     *
     * @Route("/{id}", name="attentra_resource_show", requirements={"id" = "\d+"})
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AttentraResourceBundle:Resource')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find the entity.');
        }

        return array(
            'entity' => $entity,
        );
    }

    /**
     * Displays a form to edit an existing entity.
     *
     * @Route("/{id}/edit", name="attentra_resource_edit", requirements={"id" = "\d+"})
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AttentraResourceBundle:Resource')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find the entity.');
        }

        $editForm   = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing entity.
     *
     * @Route("/{id}", name="attentra_resource_update")
     * @Method({"PUT", "DELETE"})
     * @Template("AttentraResourceBundle:Resource:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AttentraResourceBundle:Resource')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find the entity.');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('attentra_resource'));
        }

        $deleteForm = $this->createDeleteForm($id);
        $deleteForm->handleRequest($request);
        if ($deleteForm->isValid()) {

            $em->remove($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('attentra_resource'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Find a resource by the identifier key
     *
     * @Route("/byidentifier/{identifier}", name="attentra_resource_byidentifier")
     * @Method("GET")
     */
    public function showByIdentifier($identifier)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AttentraResourceBundle:Resource')->findOneBy(array('identifier' => $identifier));

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find the entity.');
        }

        return new RedirectResponse($this->generateUrl('attentra_resource_show', array('id' => $entity->getId())));
    }

    // ======================================

    /**
     * Creates a form to create an entity.
     *
     * @param \Attentra\ResourceBundle\Entity\Resource|Resource $entity The entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Resource $entity)
    {
        $form = $this->createForm(
            new ResourceType(),
            $entity,
            array(
                'action' => $this->generateUrl('attentra_resource_create'),
                'method' => 'POST'
            )
        );

        $form->add('submit', 'submit', array('label' => 'Create', 'attr' => ['icon' => 'ok']));
        $form->add('return', new LinkButtonType(), array('link' => $this->generateUrl('attentra_resource')));

        return $form;
    }

    /**
     * Creates a form to edit an entity.
     *
     * @param \Attentra\ResourceBundle\Entity\Resource|Resource $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createEditForm(Resource $entity)
    {
        $form = $this->createForm(
            new ResourceType(),
            $entity,
            array(
                'action' => $this->generateUrl('attentra_resource_update', array('id' => $entity->getId())),
                'method' => 'PUT',
            )
        );

        $form->add('submit', 'submit', array('label' => 'Update', 'attr' => ['icon' => 'ok']));
        $form->add('return', new LinkButtonType(), array('link' => $this->generateUrl('attentra_resource')));

        return $form;
    }

    /**
     * Creates a form to delete an entity by id.
     *
     * @param mixed $id The entity id
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id, Request $request = null)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('attentra_resource_update', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('previous_page', 'hidden', ['data' => $request !== null ? $request->getUri() : ''])
            ->add('confirm', 'checkbox', ['label' => 'I confirm the complete deletion of this item and all relatives items', 'constraints' => new NotBlank()])
            ->add('submit', 'submit', ['label' => 'Delete', 'attr' => ['class' => 'btn-danger', 'icon' => 'remove']])
            ->getForm();
    }

}


text:
/**
 * @since 2019-04-23 11:08
 * @author vivaxy
 */

class AnimalOfPrivate {
  private name: string;
  constructor(theName: string) {
    this.name = theName;
  }
}

new AnimalOfPrivate('Cat').name; // Property 'name' is private and only accessible within class 'Animal'.

class RhinoOfPrivate extends AnimalOfPrivate {
  constructor() {
    super('Rhino');
  }
}

class EmployeeOfPrivate {
  private name: string;
  constructor(theName: string) {
    this.name = theName;
  }
}

let animalOfPrivate = new AnimalOfPrivate('Goat');
let rhinoOfPrivate = new RhinoOfPrivate();
let employeeOfPrivate = new EmployeeOfPrivate('Bob');

animalOfPrivate = rhinoOfPrivate;
// Type 'Employee' is not assignable to type 'Animal'.
// Types have separate declarations of a private property 'name'.
animalOfPrivate = employeeOfPrivate;


text:
package example;

import java.util.function.Function;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class FunctionConfiguration {

	/*
	 * You need this main method or explicit <start-class>example.FunctionConfiguration</start-class>
	 * in the POM to ensure boot plug-in makes the correct entry
	 */
	public static void main(String[] args) {
		SpringApplication.run(FunctionConfiguration.class, args);
	}

	@Bean
	public Function<String, String> uppercase() {
		return value -> value.toUpperCase();
	}
}


text:
.class final Landroid/app/ActivityManager$RecentTaskInfo$1;
.super Ljava/lang/Object;
.source "ActivityManager.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/ActivityManager$RecentTaskInfo;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/app/ActivityManager$RecentTaskInfo;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 325
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/app/ActivityManager$RecentTaskInfo;
    .locals 2
    .parameter "source"

    .prologue
    .line 327
    new-instance v0, Landroid/app/ActivityManager$RecentTaskInfo;

    const/4 v1, 0x0

    invoke-direct {v0, p1, v1}, Landroid/app/ActivityManager$RecentTaskInfo;-><init>(Landroid/os/Parcel;Landroid/app/ActivityManager$1;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 325
    invoke-virtual {p0, p1}, Landroid/app/ActivityManager$RecentTaskInfo$1;->createFromParcel(Landroid/os/Parcel;)Landroid/app/ActivityManager$RecentTaskInfo;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/app/ActivityManager$RecentTaskInfo;
    .locals 1
    .parameter "size"

    .prologue
    .line 330
    new-array v0, p1, [Landroid/app/ActivityManager$RecentTaskInfo;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 325
    invoke-virtual {p0, p1}, Landroid/app/ActivityManager$RecentTaskInfo$1;->newArray(I)[Landroid/app/ActivityManager$RecentTaskInfo;

    move-result-object v0

    return-object v0
.end method


text:
package org.wildfly.apigen.test.invocation.datasources.subsystem.xaDataSource;

import org.wildfly.swarm.config.runtime.Address;
import org.wildfly.swarm.config.runtime.ModelNodeBinding;
import java.util.Map;
import java.util.List;
import org.wildfly.swarm.config.runtime.Subresource;
import org.wildfly.swarm.config.runtime.ModelNodeSubresources;
import org.wildfly.apigen.test.invocation.datasources.subsystem.xaDataSource.xaDatasourceProperties.XaDatasourceProperties;

/**
 * A JDBC XA data-source configuration
 */
@Address("/subsystem=datasources/xa-data-source=*")
public class XaDataSource<T extends XaDataSource> {

	private String key;
	private Integer allocationRetry;
	private Long allocationRetryWaitMillis;
	private Boolean allowMultipleUsers;
	private Boolean backgroundValidation;
	private Long backgroundValidationMillis;
	private Long blockingTimeoutWaitMillis;
	private String capacityDecrementerClass;
	private Map capacityDecrementerProperties;
	private String capacityIncrementerClass;
	private Map capacityIncrementerProperties;
	private String checkValidConnectionSql;
	private Boolean connectable;
	private String connectionListenerClass;
	private Map connectionListenerProperty;
	private String driverName;
	private Boolean enabled;
	private Boolean enlistmentTrace;
	private String exceptionSorterClassName;
	private Map exceptionSorterProperties;
	private String flushStrategy;
	private Long idleTimeoutMinutes;
	private Integer initialPoolSize;
	private Boolean interleaving;
	private String jndiName;
	private Integer maxPoolSize;
	private String mcp;
	private Integer minPoolSize;
	private String newConnectionSql;
	private Boolean noRecovery;
	private Boolean noTxSeparatePool;
	private Boolean padXid;
	private String password;
	private Boolean poolPrefill;
	private Boolean poolUseStrictMin;
	private Long preparedStatementsCacheSize;
	private Long queryTimeout;
	private String reauthPluginClassName;
	private Map reauthPluginProperties;
	private String recoveryPassword;
	private String recoveryPluginClassName;
	private Map recoveryPluginProperties;
	private String recoverySecurityDomain;
	private String recoveryUsername;
	private Boolean sameRmOverride;
	private String securityDomain;
	private Boolean setTxQueryTimeout;
	private Boolean sharePreparedStatements;
	private Boolean spy;
	private String staleConnectionCheckerClassName;
	private Map staleConnectionCheckerProperties;
	private Boolean statisticsEnabled;
	private String trackStatements;
	private Boolean tracking;
	private String transactionIsolation;
	private String urlDelimiter;
	private String urlProperty;
	private String urlSelectorStrategyClassName;
	private Boolean useCcm;
	private Boolean useFastFail;
	private Boolean useJavaContext;
	private Long useTryLock;
	private String userName;
	private String validConnectionCheckerClassName;
	private Map validConnectionCheckerProperties;
	private Boolean validateOnMatch;
	private Boolean wrapXaResource;
	private String xaDatasourceClass;
	private Integer xaResourceTimeout;
	private XaDataSourceResources subresources = new XaDataSourceResources();

	public XaDataSource(String key) {
		this.key = key;
	}

	public String getKey() {
		return this.key;
	}

	/**
	 * The allocation retry element indicates the number of times that allocating a connection should be tried before throwing an exception
	 */
	@ModelNodeBinding(detypedName = "allocation-retry")
	public Integer allocationRetry() {
		return this.allocationRetry;
	}

	/**
	 * The allocation retry element indicates the number of times that allocating a connection should be tried before throwing an exception
	 */
	@SuppressWarnings("unchecked")
	public T allocationRetry(Integer value) {
		this.allocationRetry = value;
		return (T) this;
	}

	/**
	 * The allocation retry wait millis element specifies the amount of time, in milliseconds, to wait between retrying to allocate a connection
	 */
	@ModelNodeBinding(detypedName = "allocation-retry-wait-millis")
	public Long allocationRetryWaitMillis() {
		return this.allocationRetryWaitMillis;
	}

	/**
	 * The allocation retry wait millis element specifies the amount of time, in milliseconds, to wait between retrying to allocate a connection
	 */
	@SuppressWarnings("unchecked")
	public T allocationRetryWaitMillis(Long value) {
		this.allocationRetryWaitMillis = value;
		return (T) this;
	}

	/**
	 * Specifies if multiple users will access the datasource through the getConnection(user, password) method and hence if the internal pool type should account for that
	 */
	@ModelNodeBinding(detypedName = "allow-multiple-users")
	public Boolean allowMultipleUsers() {
		return this.allowMultipleUsers;
	}

	/**
	 * Specifies if multiple users will access the datasource through the getConnection(user, password) method and hence if the internal pool type should account for that
	 */
	@SuppressWarnings("unchecked")
	public T allowMultipleUsers(Boolean value) {
		this.allowMultipleUsers = value;
		return (T) this;
	}

	/**
	 * An element to specify that connections should be validated on a background thread versus being validated prior to use. Changing this value can be done only on disabled datasource,  requires a server restart otherwise.
	 */
	@ModelNodeBinding(detypedName = "background-validation")
	public Boolean backgroundValidation() {
		return this.backgroundValidation;
	}

	/**
	 * An element to specify that connections should be validated on a background thread versus being validated prior to use. Changing this value can be done only on disabled datasource,  requires a server restart otherwise.
	 */
	@SuppressWarnings("unchecked")
	public T backgroundValidation(Boolean value) {
		this.backgroundValidation = value;
		return (T) this;
	}

	/**
	 * The background-validation-millis element specifies the amount of time, in milliseconds, that background validation will run. Changing this value can be done only on disabled datasource,  requires a server restart otherwise
	 */
	@ModelNodeBinding(detypedName = "background-validation-millis")
	public Long backgroundValidationMillis() {
		return this.backgroundValidationMillis;
	}

	/**
	 * The background-validation-millis element specifies the amount of time, in milliseconds, that background validation will run. Changing this value can be done only on disabled datasource,  requires a server restart otherwise
	 */
	@SuppressWarnings("unchecked")
	public T backgroundValidationMillis(Long value) {
		this.backgroundValidationMillis = value;
		return (T) this;
	}

	/**
	 * The blocking-timeout-millis element specifies the maximum time, in milliseconds, to block while waiting for a connection before throwing an exception. Note that this blocks only while waiting for locking a connection, and will never throw an exception if creating a new connection takes an inordinately long time
	 */
	@ModelNodeBinding(detypedName = "blocking-timeout-wait-millis")
	public Long blockingTimeoutWaitMillis() {
		return this.blockingTimeoutWaitMillis;
	}

	/**
	 * The blocking-timeout-millis element specifies the maximum time, in milliseconds, to block while waiting for a connection before throwing an exception. Note that this blocks only while waiting for locking a connection, and will never throw an exception if creating a new connection takes an inordinately long time
	 */
	@SuppressWarnings("unchecked")
	public T blockingTimeoutWaitMillis(Long value) {
		this.blockingTimeoutWaitMillis = value;
		return (T) this;
	}

	/**
	 * Class defining the policy for decrementing connections in the pool
	 */
	@ModelNodeBinding(detypedName = "capacity-decrementer-class")
	public String capacityDecrementerClass() {
		return this.capacityDecrementerClass;
	}

	/**
	 * Class defining the policy for decrementing connections in the pool
	 */
	@SuppressWarnings("unchecked")
	public T capacityDecrementerClass(String value) {
		this.capacityDecrementerClass = value;
		return (T) this;
	}

	/**
	 * Properties to inject in class defining the policy for decrementing connections in the pool
	 */
	@ModelNodeBinding(detypedName = "capacity-decrementer-properties")
	public Map capacityDecrementerProperties() {
		return this.capacityDecrementerProperties;
	}

	/**
	 * Properties to inject in class defining the policy for decrementing connections in the pool
	 */
	@SuppressWarnings("unchecked")
	public T capacityDecrementerProperties(Map value) {
		this.capacityDecrementerProperties = value;
		return (T) this;
	}

	/**
	 * Class defining the policy for incrementing connections in the pool
	 */
	@ModelNodeBinding(detypedName = "capacity-incrementer-class")
	public String capacityIncrementerClass() {
		return this.capacityIncrementerClass;
	}

	/**
	 * Class defining the policy for incrementing connections in the pool
	 */
	@SuppressWarnings("unchecked")
	public T capacityIncrementerClass(String value) {
		this.capacityIncrementerClass = value;
		return (T) this;
	}

	/**
	 * Properties to inject in class defining the policy for incrementing connections in the pool
	 */
	@ModelNodeBinding(detypedName = "capacity-incrementer-properties")
	public Map capacityIncrementerProperties() {
		return this.capacityIncrementerProperties;
	}

	/**
	 * Properties to inject in class defining the policy for incrementing connections in the pool
	 */
	@SuppressWarnings("unchecked")
	public T capacityIncrementerProperties(Map value) {
		this.capacityIncrementerProperties = value;
		return (T) this;
	}

	/**
	 * Specify an SQL statement to check validity of a pool connection. This may be called when managed connection is obtained from the pool
	 */
	@ModelNodeBinding(detypedName = "check-valid-connection-sql")
	public String checkValidConnectionSql() {
		return this.checkValidConnectionSql;
	}

	/**
	 * Specify an SQL statement to check validity of a pool connection. This may be called when managed connection is obtained from the pool
	 */
	@SuppressWarnings("unchecked")
	public T checkValidConnectionSql(String value) {
		this.checkValidConnectionSql = value;
		return (T) this;
	}

	/**
	 * Enable the use of CMR for this datasource. This feature means that a local resource can reliably participate in an XA transaction.
	 */
	@ModelNodeBinding(detypedName = "connectable")
	public Boolean connectable() {
		return this.connectable;
	}

	/**
	 * Enable the use of CMR for this datasource. This feature means that a local resource can reliably participate in an XA transaction.
	 */
	@SuppressWarnings("unchecked")
	public T connectable(Boolean value) {
		this.connectable = value;
		return (T) this;
	}

	/**
	 * Speciefies class name extending org.jboss.jca.adapters.jdbc.spi.listener.ConnectionListener that provides a possible to listen for connection activation and passivation in order to perform actions before the connection is returned to the application or returned to the pool.
	 */
	@ModelNodeBinding(detypedName = "connection-listener-class")
	public String connectionListenerClass() {
		return this.connectionListenerClass;
	}

	/**
	 * Speciefies class name extending org.jboss.jca.adapters.jdbc.spi.listener.ConnectionListener that provides a possible to listen for connection activation and passivation in order to perform actions before the connection is returned to the application or returned to the pool.
	 */
	@SuppressWarnings("unchecked")
	public T connectionListenerClass(String value) {
		this.connectionListenerClass = value;
		return (T) this;
	}

	/**
	 * Properties to be injected in class specified in connection-listener-class
	 */
	@ModelNodeBinding(detypedName = "connection-listener-property")
	public Map connectionListenerProperty() {
		return this.connectionListenerProperty;
	}

	/**
	 * Properties to be injected in class specified in connection-listener-class
	 */
	@SuppressWarnings("unchecked")
	public T connectionListenerProperty(Map value) {
		this.connectionListenerProperty = value;
		return (T) this;
	}

	/**
	 * Defines the JDBC driver the datasource should use. It is a symbolic name matching the the name of installed driver. In case the driver is deployed as jar, the name is the name of deployment unit
	 */
	@ModelNodeBinding(detypedName = "driver-name")
	public String driverName() {
		return this.driverName;
	}

	/**
	 * Defines the JDBC driver the datasource should use. It is a symbolic name matching the the name of installed driver. In case the driver is deployed as jar, the name is the name of deployment unit
	 */
	@SuppressWarnings("unchecked")
	public T driverName(String value) {
		this.driverName = value;
		return (T) this;
	}

	/**
	 * Specifies if the datasource should be enabled. Note this attribute will not be supported runtime in next versions.
	 */
	@ModelNodeBinding(detypedName = "enabled")
	public Boolean enabled() {
		return this.enabled;
	}

	/**
	 * Specifies if the datasource should be enabled. Note this attribute will not be supported runtime in next versions.
	 */
	@SuppressWarnings("unchecked")
	public T enabled(Boolean value) {
		this.enabled = value;
		return (T) this;
	}

	/**
	 * Defines if WildFly/IronJacamar should record enlistment traces
	 */
	@ModelNodeBinding(detypedName = "enlistment-trace")
	public Boolean enlistmentTrace() {
		return this.enlistmentTrace;
	}

	/**
	 * Defines if WildFly/IronJacamar should record enlistment traces
	 */
	@SuppressWarnings("unchecked")
	public T enlistmentTrace(Boolean value) {
		this.enlistmentTrace = value;
		return (T) this;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.ExceptionSorter that provides an isExceptionFatal(SQLException) method to validate if an exception should broadcast an error
	 */
	@ModelNodeBinding(detypedName = "exception-sorter-class-name")
	public String exceptionSorterClassName() {
		return this.exceptionSorterClassName;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.ExceptionSorter that provides an isExceptionFatal(SQLException) method to validate if an exception should broadcast an error
	 */
	@SuppressWarnings("unchecked")
	public T exceptionSorterClassName(String value) {
		this.exceptionSorterClassName = value;
		return (T) this;
	}

	/**
	 * The exception sorter properties
	 */
	@ModelNodeBinding(detypedName = "exception-sorter-properties")
	public Map exceptionSorterProperties() {
		return this.exceptionSorterProperties;
	}

	/**
	 * The exception sorter properties
	 */
	@SuppressWarnings("unchecked")
	public T exceptionSorterProperties(Map value) {
		this.exceptionSorterProperties = value;
		return (T) this;
	}

	/**
	 * Specifies how the pool should be flush in case of an error. Valid values are: FailingConnectionOnly (default), IdleConnections and EntirePool
	 */
	@ModelNodeBinding(detypedName = "flush-strategy")
	public String flushStrategy() {
		return this.flushStrategy;
	}

	/**
	 * Specifies how the pool should be flush in case of an error. Valid values are: FailingConnectionOnly (default), IdleConnections and EntirePool
	 */
	@SuppressWarnings("unchecked")
	public T flushStrategy(String value) {
		this.flushStrategy = value;
		return (T) this;
	}

	/**
	 * The idle-timeout-minutes elements specifies the maximum time, in minutes, a connection may be idle before being closed. The actual maximum time depends also on the IdleRemover scan time, which is half of the smallest idle-timeout-minutes value of any pool. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
	 */
	@ModelNodeBinding(detypedName = "idle-timeout-minutes")
	public Long idleTimeoutMinutes() {
		return this.idleTimeoutMinutes;
	}

	/**
	 * The idle-timeout-minutes elements specifies the maximum time, in minutes, a connection may be idle before being closed. The actual maximum time depends also on the IdleRemover scan time, which is half of the smallest idle-timeout-minutes value of any pool. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
	 */
	@SuppressWarnings("unchecked")
	public T idleTimeoutMinutes(Long value) {
		this.idleTimeoutMinutes = value;
		return (T) this;
	}

	/**
	 * The initial-pool-size element indicates the initial number of connections a pool should hold.
	 */
	@ModelNodeBinding(detypedName = "initial-pool-size")
	public Integer initialPoolSize() {
		return this.initialPoolSize;
	}

	/**
	 * The initial-pool-size element indicates the initial number of connections a pool should hold.
	 */
	@SuppressWarnings("unchecked")
	public T initialPoolSize(Integer value) {
		this.initialPoolSize = value;
		return (T) this;
	}

	/**
	 * An element to enable interleaving for XA connections
	 */
	@ModelNodeBinding(detypedName = "interleaving")
	public Boolean interleaving() {
		return this.interleaving;
	}

	/**
	 * An element to enable interleaving for XA connections
	 */
	@SuppressWarnings("unchecked")
	public T interleaving(Boolean value) {
		this.interleaving = value;
		return (T) this;
	}

	/**
	 * Specifies the JNDI name for the datasource
	 */
	@ModelNodeBinding(detypedName = "jndi-name")
	public String jndiName() {
		return this.jndiName;
	}

	/**
	 * Specifies the JNDI name for the datasource
	 */
	@SuppressWarnings("unchecked")
	public T jndiName(String value) {
		this.jndiName = value;
		return (T) this;
	}

	/**
	 * The max-pool-size element specifies the maximum number of connections for a pool. No more connections will be created in each sub-pool
	 */
	@ModelNodeBinding(detypedName = "max-pool-size")
	public Integer maxPoolSize() {
		return this.maxPoolSize;
	}

	/**
	 * The max-pool-size element specifies the maximum number of connections for a pool. No more connections will be created in each sub-pool
	 */
	@SuppressWarnings("unchecked")
	public T maxPoolSize(Integer value) {
		this.maxPoolSize = value;
		return (T) this;
	}

	/**
	 * Defines the ManagedConnectionPool implementation, f.ex. org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreArrayListManagedConnectionPool
	 */
	@ModelNodeBinding(detypedName = "mcp")
	public String mcp() {
		return this.mcp;
	}

	/**
	 * Defines the ManagedConnectionPool implementation, f.ex. org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreArrayListManagedConnectionPool
	 */
	@SuppressWarnings("unchecked")
	public T mcp(String value) {
		this.mcp = value;
		return (T) this;
	}

	/**
	 * The min-pool-size element specifies the minimum number of connections for a pool
	 */
	@ModelNodeBinding(detypedName = "min-pool-size")
	public Integer minPoolSize() {
		return this.minPoolSize;
	}

	/**
	 * The min-pool-size element specifies the minimum number of connections for a pool
	 */
	@SuppressWarnings("unchecked")
	public T minPoolSize(Integer value) {
		this.minPoolSize = value;
		return (T) this;
	}

	/**
	 * Specifies an SQL statement to execute whenever a connection is added to the connection pool
	 */
	@ModelNodeBinding(detypedName = "new-connection-sql")
	public String newConnectionSql() {
		return this.newConnectionSql;
	}

	/**
	 * Specifies an SQL statement to execute whenever a connection is added to the connection pool
	 */
	@SuppressWarnings("unchecked")
	public T newConnectionSql(String value) {
		this.newConnectionSql = value;
		return (T) this;
	}

	/**
	 * Specifies if the connection pool should be excluded from recovery
	 */
	@ModelNodeBinding(detypedName = "no-recovery")
	public Boolean noRecovery() {
		return this.noRecovery;
	}

	/**
	 * Specifies if the connection pool should be excluded from recovery
	 */
	@SuppressWarnings("unchecked")
	public T noRecovery(Boolean value) {
		this.noRecovery = value;
		return (T) this;
	}

	/**
	 * Oracle does not like XA connections getting used both inside and outside a JTA transaction. To workaround the problem you can create separate sub-pools for the different contexts
	 */
	@ModelNodeBinding(detypedName = "no-tx-separate-pool")
	public Boolean noTxSeparatePool() {
		return this.noTxSeparatePool;
	}

	/**
	 * Oracle does not like XA connections getting used both inside and outside a JTA transaction. To workaround the problem you can create separate sub-pools for the different contexts
	 */
	@SuppressWarnings("unchecked")
	public T noTxSeparatePool(Boolean value) {
		this.noTxSeparatePool = value;
		return (T) this;
	}

	/**
	 * Should the Xid be padded
	 */
	@ModelNodeBinding(detypedName = "pad-xid")
	public Boolean padXid() {
		return this.padXid;
	}

	/**
	 * Should the Xid be padded
	 */
	@SuppressWarnings("unchecked")
	public T padXid(Boolean value) {
		this.padXid = value;
		return (T) this;
	}

	/**
	 * Specifies the password used when creating a new connection
	 */
	@ModelNodeBinding(detypedName = "password")
	public String password() {
		return this.password;
	}

	/**
	 * Specifies the password used when creating a new connection
	 */
	@SuppressWarnings("unchecked")
	public T password(String value) {
		this.password = value;
		return (T) this;
	}

	/**
	 * Should the pool be prefilled. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
	 */
	@ModelNodeBinding(detypedName = "pool-prefill")
	public Boolean poolPrefill() {
		return this.poolPrefill;
	}

	/**
	 * Should the pool be prefilled. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
	 */
	@SuppressWarnings("unchecked")
	public T poolPrefill(Boolean value) {
		this.poolPrefill = value;
		return (T) this;
	}

	/**
	 * Specifies if the min-pool-size should be considered strictly
	 */
	@ModelNodeBinding(detypedName = "pool-use-strict-min")
	public Boolean poolUseStrictMin() {
		return this.poolUseStrictMin;
	}

	/**
	 * Specifies if the min-pool-size should be considered strictly
	 */
	@SuppressWarnings("unchecked")
	public T poolUseStrictMin(Boolean value) {
		this.poolUseStrictMin = value;
		return (T) this;
	}

	/**
	 * The number of prepared statements per connection in an LRU cache
	 */
	@ModelNodeBinding(detypedName = "prepared-statements-cache-size")
	public Long preparedStatementsCacheSize() {
		return this.preparedStatementsCacheSize;
	}

	/**
	 * The number of prepared statements per connection in an LRU cache
	 */
	@SuppressWarnings("unchecked")
	public T preparedStatementsCacheSize(Long value) {
		this.preparedStatementsCacheSize = value;
		return (T) this;
	}

	/**
	 * Any configured query timeout in seconds. If not provided no timeout will be set
	 */
	@ModelNodeBinding(detypedName = "query-timeout")
	public Long queryTimeout() {
		return this.queryTimeout;
	}

	/**
	 * Any configured query timeout in seconds. If not provided no timeout will be set
	 */
	@SuppressWarnings("unchecked")
	public T queryTimeout(Long value) {
		this.queryTimeout = value;
		return (T) this;
	}

	/**
	 * The fully qualified class name of the reauthentication plugin implementation
	 */
	@ModelNodeBinding(detypedName = "reauth-plugin-class-name")
	public String reauthPluginClassName() {
		return this.reauthPluginClassName;
	}

	/**
	 * The fully qualified class name of the reauthentication plugin implementation
	 */
	@SuppressWarnings("unchecked")
	public T reauthPluginClassName(String value) {
		this.reauthPluginClassName = value;
		return (T) this;
	}

	/**
	 * The properties for the reauthentication plugin
	 */
	@ModelNodeBinding(detypedName = "reauth-plugin-properties")
	public Map reauthPluginProperties() {
		return this.reauthPluginProperties;
	}

	/**
	 * The properties for the reauthentication plugin
	 */
	@SuppressWarnings("unchecked")
	public T reauthPluginProperties(Map value) {
		this.reauthPluginProperties = value;
		return (T) this;
	}

	/**
	 * The password used for recovery
	 */
	@ModelNodeBinding(detypedName = "recovery-password")
	public String recoveryPassword() {
		return this.recoveryPassword;
	}

	/**
	 * The password used for recovery
	 */
	@SuppressWarnings("unchecked")
	public T recoveryPassword(String value) {
		this.recoveryPassword = value;
		return (T) this;
	}

	/**
	 * The fully qualified class name of the recovery plugin implementation
	 */
	@ModelNodeBinding(detypedName = "recovery-plugin-class-name")
	public String recoveryPluginClassName() {
		return this.recoveryPluginClassName;
	}

	/**
	 * The fully qualified class name of the recovery plugin implementation
	 */
	@SuppressWarnings("unchecked")
	public T recoveryPluginClassName(String value) {
		this.recoveryPluginClassName = value;
		return (T) this;
	}

	/**
	 * The properties for the recovery plugin
	 */
	@ModelNodeBinding(detypedName = "recovery-plugin-properties")
	public Map recoveryPluginProperties() {
		return this.recoveryPluginProperties;
	}

	/**
	 * The properties for the recovery plugin
	 */
	@SuppressWarnings("unchecked")
	public T recoveryPluginProperties(Map value) {
		this.recoveryPluginProperties = value;
		return (T) this;
	}

	/**
	 * The security domain used for recovery
	 */
	@ModelNodeBinding(detypedName = "recovery-security-domain")
	public String recoverySecurityDomain() {
		return this.recoverySecurityDomain;
	}

	/**
	 * The security domain used for recovery
	 */
	@SuppressWarnings("unchecked")
	public T recoverySecurityDomain(String value) {
		this.recoverySecurityDomain = value;
		return (T) this;
	}

	/**
	 * The user name used for recovery
	 */
	@ModelNodeBinding(detypedName = "recovery-username")
	public String recoveryUsername() {
		return this.recoveryUsername;
	}

	/**
	 * The user name used for recovery
	 */
	@SuppressWarnings("unchecked")
	public T recoveryUsername(String value) {
		this.recoveryUsername = value;
		return (T) this;
	}

	/**
	 * The is-same-rm-override element allows one to unconditionally set whether the javax.transaction.xa.XAResource.isSameRM(XAResource) returns true or false
	 */
	@ModelNodeBinding(detypedName = "same-rm-override")
	public Boolean sameRmOverride() {
		return this.sameRmOverride;
	}

	/**
	 * The is-same-rm-override element allows one to unconditionally set whether the javax.transaction.xa.XAResource.isSameRM(XAResource) returns true or false
	 */
	@SuppressWarnings("unchecked")
	public T sameRmOverride(Boolean value) {
		this.sameRmOverride = value;
		return (T) this;
	}

	/**
	 * Specifies the security domain which defines the javax.security.auth.Subject that are used to distinguish connections in the pool
	 */
	@ModelNodeBinding(detypedName = "security-domain")
	public String securityDomain() {
		return this.securityDomain;
	}

	/**
	 * Specifies the security domain which defines the javax.security.auth.Subject that are used to distinguish connections in the pool
	 */
	@SuppressWarnings("unchecked")
	public T securityDomain(String value) {
		this.securityDomain = value;
		return (T) this;
	}

	/**
	 * Whether to set the query timeout based on the time remaining until transaction timeout. Any configured query timeout will be used if there is no transaction
	 */
	@ModelNodeBinding(detypedName = "set-tx-query-timeout")
	public Boolean setTxQueryTimeout() {
		return this.setTxQueryTimeout;
	}

	/**
	 * Whether to set the query timeout based on the time remaining until transaction timeout. Any configured query timeout will be used if there is no transaction
	 */
	@SuppressWarnings("unchecked")
	public T setTxQueryTimeout(Boolean value) {
		this.setTxQueryTimeout = value;
		return (T) this;
	}

	/**
	 * Whether to share prepared statements, i.e. whether asking for same statement twice without closing uses the same underlying prepared statement
	 */
	@ModelNodeBinding(detypedName = "share-prepared-statements")
	public Boolean sharePreparedStatements() {
		return this.sharePreparedStatements;
	}

	/**
	 * Whether to share prepared statements, i.e. whether asking for same statement twice without closing uses the same underlying prepared statement
	 */
	@SuppressWarnings("unchecked")
	public T sharePreparedStatements(Boolean value) {
		this.sharePreparedStatements = value;
		return (T) this;
	}

	/**
	 * Enable spying of SQL statements
	 */
	@ModelNodeBinding(detypedName = "spy")
	public Boolean spy() {
		return this.spy;
	}

	/**
	 * Enable spying of SQL statements
	 */
	@SuppressWarnings("unchecked")
	public T spy(Boolean value) {
		this.spy = value;
		return (T) this;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.StaleConnectionChecker that provides an isStaleConnection(SQLException) method which if it returns true will wrap the exception in an org.jboss.jca.adapters.jdbc.StaleConnectionException
	 */
	@ModelNodeBinding(detypedName = "stale-connection-checker-class-name")
	public String staleConnectionCheckerClassName() {
		return this.staleConnectionCheckerClassName;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.StaleConnectionChecker that provides an isStaleConnection(SQLException) method which if it returns true will wrap the exception in an org.jboss.jca.adapters.jdbc.StaleConnectionException
	 */
	@SuppressWarnings("unchecked")
	public T staleConnectionCheckerClassName(String value) {
		this.staleConnectionCheckerClassName = value;
		return (T) this;
	}

	/**
	 * The stale connection checker properties
	 */
	@ModelNodeBinding(detypedName = "stale-connection-checker-properties")
	public Map staleConnectionCheckerProperties() {
		return this.staleConnectionCheckerProperties;
	}

	/**
	 * The stale connection checker properties
	 */
	@SuppressWarnings("unchecked")
	public T staleConnectionCheckerProperties(Map value) {
		this.staleConnectionCheckerProperties = value;
		return (T) this;
	}

	/**
	 * define if runtime statistics is enabled or not
	 */
	@ModelNodeBinding(detypedName = "statistics-enabled")
	public Boolean statisticsEnabled() {
		return this.statisticsEnabled;
	}

	/**
	 * define if runtime statistics is enabled or not
	 */
	@SuppressWarnings("unchecked")
	public T statisticsEnabled(Boolean value) {
		this.statisticsEnabled = value;
		return (T) this;
	}

	/**
	 * Whether to check for unclosed statements when a connection is returned to the pool, result sets are closed, a statement is closed or return to the prepared statement cache. Valid values are: "false" - do not track statements, "true" - track statements and result sets and warn when they are not closed, "nowarn" - track statements but do not warn about them being unclosed
	 */
	@ModelNodeBinding(detypedName = "track-statements")
	public String trackStatements() {
		return this.trackStatements;
	}

	/**
	 * Whether to check for unclosed statements when a connection is returned to the pool, result sets are closed, a statement is closed or return to the prepared statement cache. Valid values are: "false" - do not track statements, "true" - track statements and result sets and warn when they are not closed, "nowarn" - track statements but do not warn about them being unclosed
	 */
	@SuppressWarnings("unchecked")
	public T trackStatements(String value) {
		this.trackStatements = value;
		return (T) this;
	}

	/**
	 * Defines if IronJacamar should track connection handles across transaction boundaries
	 */
	@ModelNodeBinding(detypedName = "tracking")
	public Boolean tracking() {
		return this.tracking;
	}

	/**
	 * Defines if IronJacamar should track connection handles across transaction boundaries
	 */
	@SuppressWarnings("unchecked")
	public T tracking(Boolean value) {
		this.tracking = value;
		return (T) this;
	}

	/**
	 * Set the java.sql.Connection transaction isolation level. Valid values are: TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE and TRANSACTION_NONE
	 */
	@ModelNodeBinding(detypedName = "transaction-isolation")
	public String transactionIsolation() {
		return this.transactionIsolation;
	}

	/**
	 * Set the java.sql.Connection transaction isolation level. Valid values are: TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE and TRANSACTION_NONE
	 */
	@SuppressWarnings("unchecked")
	public T transactionIsolation(String value) {
		this.transactionIsolation = value;
		return (T) this;
	}

	/**
	 * Specifies the delimiter for URLs in connection-url for HA datasources
	 */
	@ModelNodeBinding(detypedName = "url-delimiter")
	public String urlDelimiter() {
		return this.urlDelimiter;
	}

	/**
	 * Specifies the delimiter for URLs in connection-url for HA datasources
	 */
	@SuppressWarnings("unchecked")
	public T urlDelimiter(String value) {
		this.urlDelimiter = value;
		return (T) this;
	}

	/**
	 * Specifies the property for the URL property in the xa-datasource-property values
	 */
	@ModelNodeBinding(detypedName = "url-property")
	public String urlProperty() {
		return this.urlProperty;
	}

	/**
	 * Specifies the property for the URL property in the xa-datasource-property values
	 */
	@SuppressWarnings("unchecked")
	public T urlProperty(String value) {
		this.urlProperty = value;
		return (T) this;
	}

	/**
	 * A class that implements org.jboss.jca.adapters.jdbc.URLSelectorStrategy
	 */
	@ModelNodeBinding(detypedName = "url-selector-strategy-class-name")
	public String urlSelectorStrategyClassName() {
		return this.urlSelectorStrategyClassName;
	}

	/**
	 * A class that implements org.jboss.jca.adapters.jdbc.URLSelectorStrategy
	 */
	@SuppressWarnings("unchecked")
	public T urlSelectorStrategyClassName(String value) {
		this.urlSelectorStrategyClassName = value;
		return (T) this;
	}

	/**
	 * Enable the use of a cached connection manager
	 */
	@ModelNodeBinding(detypedName = "use-ccm")
	public Boolean useCcm() {
		return this.useCcm;
	}

	/**
	 * Enable the use of a cached connection manager
	 */
	@SuppressWarnings("unchecked")
	public T useCcm(Boolean value) {
		this.useCcm = value;
		return (T) this;
	}

	/**
	 * Whether to fail a connection allocation on the first try if it is invalid (true) or keep trying until the pool is exhausted of all potential connections (false)
	 */
	@ModelNodeBinding(detypedName = "use-fast-fail")
	public Boolean useFastFail() {
		return this.useFastFail;
	}

	/**
	 * Whether to fail a connection allocation on the first try if it is invalid (true) or keep trying until the pool is exhausted of all potential connections (false)
	 */
	@SuppressWarnings("unchecked")
	public T useFastFail(Boolean value) {
		this.useFastFail = value;
		return (T) this;
	}

	/**
	 * Setting this to false will bind the datasource into global JNDI
	 */
	@ModelNodeBinding(detypedName = "use-java-context")
	public Boolean useJavaContext() {
		return this.useJavaContext;
	}

	/**
	 * Setting this to false will bind the datasource into global JNDI
	 */
	@SuppressWarnings("unchecked")
	public T useJavaContext(Boolean value) {
		this.useJavaContext = value;
		return (T) this;
	}

	/**
	 * Any configured timeout for internal locks on the resource adapter objects in seconds
	 */
	@ModelNodeBinding(detypedName = "use-try-lock")
	public Long useTryLock() {
		return this.useTryLock;
	}

	/**
	 * Any configured timeout for internal locks on the resource adapter objects in seconds
	 */
	@SuppressWarnings("unchecked")
	public T useTryLock(Long value) {
		this.useTryLock = value;
		return (T) this;
	}

	/**
	 * Specify the user name used when creating a new connection
	 */
	@ModelNodeBinding(detypedName = "user-name")
	public String userName() {
		return this.userName;
	}

	/**
	 * Specify the user name used when creating a new connection
	 */
	@SuppressWarnings("unchecked")
	public T userName(String value) {
		this.userName = value;
		return (T) this;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.ValidConnectionChecker that provides an isValidConnection(Connection) method to validate a connection. If an exception is returned that means the connection is invalid. This overrides the check-valid-connection-sql element
	 */
	@ModelNodeBinding(detypedName = "valid-connection-checker-class-name")
	public String validConnectionCheckerClassName() {
		return this.validConnectionCheckerClassName;
	}

	/**
	 * An org.jboss.jca.adapters.jdbc.ValidConnectionChecker that provides an isValidConnection(Connection) method to validate a connection. If an exception is returned that means the connection is invalid. This overrides the check-valid-connection-sql element
	 */
	@SuppressWarnings("unchecked")
	public T validConnectionCheckerClassName(String value) {
		this.validConnectionCheckerClassName = value;
		return (T) this;
	}

	/**
	 * The valid connection checker properties
	 */
	@ModelNodeBinding(detypedName = "valid-connection-checker-properties")
	public Map validConnectionCheckerProperties() {
		return this.validConnectionCheckerProperties;
	}

	/**
	 * The valid connection checker properties
	 */
	@SuppressWarnings("unchecked")
	public T validConnectionCheckerProperties(Map value) {
		this.validConnectionCheckerProperties = value;
		return (T) this;
	}

	/**
	 * The validate-on-match element specifies if connection validation should be done when a connection factory attempts to match a managed connection. This is typically exclusive to the use of background validation
	 */
	@ModelNodeBinding(detypedName = "validate-on-match")
	public Boolean validateOnMatch() {
		return this.validateOnMatch;
	}

	/**
	 * The validate-on-match element specifies if connection validation should be done when a connection factory attempts to match a managed connection. This is typically exclusive to the use of background validation
	 */
	@SuppressWarnings("unchecked")
	public T validateOnMatch(Boolean value) {
		this.validateOnMatch = value;
		return (T) this;
	}

	/**
	 * Should the XAResource instances be wrapped in an org.jboss.tm.XAResourceWrapper instance
	 */
	@ModelNodeBinding(detypedName = "wrap-xa-resource")
	public Boolean wrapXaResource() {
		return this.wrapXaResource;
	}

	/**
	 * Should the XAResource instances be wrapped in an org.jboss.tm.XAResourceWrapper instance
	 */
	@SuppressWarnings("unchecked")
	public T wrapXaResource(Boolean value) {
		this.wrapXaResource = value;
		return (T) this;
	}

	/**
	 * The fully qualified name of the javax.sql.XADataSource implementation
	 */
	@ModelNodeBinding(detypedName = "xa-datasource-class")
	public String xaDatasourceClass() {
		return this.xaDatasourceClass;
	}

	/**
	 * The fully qualified name of the javax.sql.XADataSource implementation
	 */
	@SuppressWarnings("unchecked")
	public T xaDatasourceClass(String value) {
		this.xaDatasourceClass = value;
		return (T) this;
	}

	/**
	 * The value is passed to XAResource.setTransactionTimeout(), in seconds. Default is zero
	 */
	@ModelNodeBinding(detypedName = "xa-resource-timeout")
	public Integer xaResourceTimeout() {
		return this.xaResourceTimeout;
	}

	/**
	 * The value is passed to XAResource.setTransactionTimeout(), in seconds. Default is zero
	 */
	@SuppressWarnings("unchecked")
	public T xaResourceTimeout(Integer value) {
		this.xaResourceTimeout = value;
		return (T) this;
	}

	public XaDataSourceResources subresources() {
		return this.subresources;
	}

	/**
	 * Add all XaDatasourceProperties objects to this subresource
	 * @return this
	 * @param value List of XaDatasourceProperties objects.
	 */
	@SuppressWarnings("unchecked")
	public T xaDatasourceProperties(List<XaDatasourceProperties> value) {
		this.subresources.xaDatasourceProperties.addAll(value);
		return (T) this;
	}

	/**
	 * Add the XaDatasourceProperties object to the list of subresources
	 * @param value The XaDatasourceProperties to add
	 * @return this
	 */
	@SuppressWarnings("unchecked")
	public T xaDatasourceProperties(XaDatasourceProperties value) {
		this.subresources.xaDatasourceProperties.add(value);
		return (T) this;
	}

	/**
	 * Child mutators for XaDataSource
	 */
	@ModelNodeSubresources
	public class XaDataSourceResources {
		/**
		 * List of xa-datasource-property
		 */
		private List<XaDatasourceProperties> xaDatasourceProperties = new java.util.ArrayList<>();

		/**
		 * Get the list of XaDatasourceProperties resources
		 * @return the list of resources
		 */
		@Subresource
		public List<XaDatasourceProperties> xaDatasourceProperties() {
			return this.xaDatasourceProperties;
		}
	}
}


text:
Portfolio::Application.routes.draw do

  devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
  scope ":locale" do
    resources :posts
  end
  resources :comments
  resources :projects

  get "welcome/index"
  root 'welcome#index'

end


text:
package com.heroku.kyokuhoku2;

import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Processor;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class HttpUtil {

    public static Processor urlEncode(final Expression fromExp, final String header) {
        return new Processor() {

            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(header, URLEncoder.encode(fromExp.evaluate(exchange, String.class), "UTF-8"));
            }
        };
    }

    public String getHtml(final String url) {
        Document document = HttpUtil.get(url);
        if (document == null) {
            return null;
        } else {
            return document.outerHtml();
        }
    }

    public static String getJson(String url) {
        int retry = 0;
        Connection.Response response = null;
        while (response == null && retry < 10) {
            try {
                response = Jsoup.connect(url).ignoreContentType(true).method(Connection.Method.GET).execute();
            } catch (Throwable t) {
                retry++;
            }
        }
        if (response != null) {
            return response.body();
        } else {
            return "{}";
        }
    }

    public static String[] getPages(final String url, final String query, final String param, final String attr) {
        Document doc = HttpUtil.get(url);
        ArrayList<String> pages = new ArrayList<>();
        while (true && doc != null) {
            pages.add(doc.outerHtml());
            Elements select = doc.select(query);
            if (select.isEmpty()) {
                break;
            } else {
                String cmcontinue = select.get(0).attr(attr);
                doc = HttpUtil.get(url + param + cmcontinue);
            }
        }
        return pages.toArray(new String[pages.size()]);
    }

    public static Document get(String url) {
        Document doc = null;
        int retry = 0;
        while (doc == null && retry < 10) {
            try {
                System.out.println("--> " + url);
                doc = Jsoup.connect(url).maxBodySize(Integer.MAX_VALUE).timeout(Integer.MAX_VALUE).get();
            } catch (Throwable t) {
                retry++;
            }
        }
        System.out.println("<-- " + url);
        return doc;
    }

    public static byte[] getBytes(String url) {
        Connection.Response response = null;
        int retry = 0;
        while (response == null & retry < 10) {
            try {
                response = Jsoup.connect(url).maxBodySize(Integer.MAX_VALUE).timeout(Integer.MAX_VALUE).ignoreContentType(true).execute();
            } catch (Throwable t) {
                retry++;
            }
        }
        if (response.bodyAsBytes().length != 0) {
            return response.bodyAsBytes();
        } else {
            return new byte[]{};
        }
    }
}


text:
using System;
using System.Runtime.Serialization;

namespace EliteTrader.ProgressReporting
{
	[Serializable]
	internal class ProgressDialogCancellationExcpetion : Exception
	{
		public ProgressDialogCancellationExcpetion()
			: base()
		{
		}

		public ProgressDialogCancellationExcpetion(string message)
			: base(message)
		{
		}

		public ProgressDialogCancellationExcpetion(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public ProgressDialogCancellationExcpetion(string format, params string[] arg)
			: base(string.Format(format, arg))
		{
		}

		protected ProgressDialogCancellationExcpetion(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
}


text:
import { mount } from '@vue/test-utils'
import Anchor from '@/components/Anchor'

const ANCHOR_ITEM = '.veui-anchor-item'

let componentOptions = {
  components: {
    'veui-anchor': Anchor
  },
  data () {
    return {
      coffees: [
        {
          label: 'Infused',
          value: '#infused',
          children: [
            {
              label: 'Breadcrumb',
              value: '/breadcrumb'
            }
          ]
        },
        {
          label: 'Boiled',
          value: '#boiled',
          children: [
            {
              label: 'Button',
              value: '/button'
            }
          ]
        },
        {
          label: 'Espresso',
          value: '#espresso'
        },
        {
          label: 'Milk coffee',
          value: '#milk-coffee'
        }
      ]
    }
  }
}

const debugInBrowser = {
  attachToDocument: true,
  sync: false
}

describe('components/Anchor', function () {
  it('should render items correctly', () => {
    let wrapper = mount(
      {
        ...componentOptions,
        template: '<veui-anchor :items="coffees"/>'
      },
      debugInBrowser
    )

    let items = wrapper.findAll(ANCHOR_ITEM)
    expect(items.length === 6).to.equal(true)
    wrapper.destroy()
  })

  it('should handle scroll correctly when container is window or falsy', async () => {
    let wrapper = mount(
      {
        ...componentOptions,
        template: `

            <veui-anchor :items="coffees" sticky/>
            <veui-anchor class="anchor-two" :items="coffees"/>

`
      },
      debugInBrowser
    )
    await wrapper.vm.$nextTick()
    // 滚动一下
    window.scrollTo(0, 100)
    await wrapper.vm.$nextTick()
    let stickyFirstAnchor = wrapper.find(ANCHOR_ITEM)
    await new Promise((resolve) => {
      setTimeout(() => {
        expect(stickyFirstAnchor.element.getBoundingClientRect().top).to.equal(
          0
        )
        let staticFirstAnchor = wrapper.find(`.anchor-two ${ANCHOR_ITEM}`)
        expect(
          staticFirstAnchor.element.getBoundingClientRect().top
        ).to.not.equal(0)
        resolve()
      }, 500)
    })

    // 滚动回来
    window.scrollTo(0, 0)
    await new Promise((resolve) => {
      setTimeout(() => {
        expect(
          stickyFirstAnchor.element.getBoundingClientRect().top
        ).to.not.equal(0)
        resolve()
      }, 500)
    })
    wrapper.destroy()
  })

  it('should handle scroll correctly when container is a element', async () => {
    // 先覆盖掉 body 的默认样式
    document.body.style.margin = '0px'
    let wrapper = mount(
      {
        ...componentOptions,
        template: `

            <veui-anchor ref="anchor" :items="coffees" container="wrapper" sticky/>
            <veui-anchor class="anchor-two" :items="coffees"/>

`
      },
      debugInBrowser
    )
    let { vm } = wrapper
    await wrapper.vm.$nextTick()
    // 滚动一下
    vm.$refs.wrapper.scrollTop = 100
    await vm.$nextTick()
    let stickyFirstAnchor = wrapper.find(ANCHOR_ITEM)
    await new Promise((resolve) => {
      setTimeout(() => {
        expect(stickyFirstAnchor.element.getBoundingClientRect().top).to.equal(
          0
        )
        let staticFirstAnchor = wrapper.find(`.anchor-two ${ANCHOR_ITEM}`)
        expect(
          staticFirstAnchor.element.getBoundingClientRect().top
        ).to.not.equal(0)
        resolve()
      }, 500)
    })

    // 滚动回来
    vm.$refs.wrapper.scrollTop = 0
    await new Promise((resolve) => {
      setTimeout(() => {
        expect(
          stickyFirstAnchor.element.getBoundingClientRect().top
        ).to.not.equal(0)
        resolve()
      }, 500)
    })
    document.body.style.margin = ''
    wrapper.destroy()
  })

  it('should handle click correctly', async () => {
    document.body.style.margin = '0px'
    let wrapper = mount(
      {
        ...componentOptions,
        template: `

            <veui-anchor ref="anchor" :items="coffees" container="wrapper" sticky/>

`
      },
      debugInBrowser
    )
    let { vm } = wrapper
    await vm.$nextTick()
    let stickyFirstAnchor = wrapper.find(ANCHOR_ITEM)
    stickyFirstAnchor.trigger('click')
    await new Promise((resolve) => {
      setTimeout(() => {
        expect(stickyFirstAnchor.element.getBoundingClientRect().top).to.equal(
          0
        )
        resolve()
      }, 500)
    })
    document.body.style.margin = ''
    wrapper.destroy()
  })
})


text:
package greetings {
  package object hello {
    def speak = println("Hello!!")
  }
}


text:
namespace Contentment.Api.Services
{
	public interface IIdGenerator
	{
		string Generate();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@drawable/ic_cancel_pressed" />
    <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/ic_cancel_focus" />
    <item android:state_enabled="true" android:drawable="@drawable/ic_cancel" />
    <item android:state_enabled="false" android:drawable="@drawable/ic_cancel_disable" />
</selector>


text:
if ($# != 2) then
    echo "Usage: $0 start end"
    echo "cleans the given object space"
    exit
endif

set excludedSpaces = "0"  # fake space used when not excluding
set excludeList = $adminArea/helpers/NetMaintOSExcludeList

# ensure that exclude file exists and is not empty
if (-e $excludeList) then
    if (-s $excludeList) then
        # change newlines into pipes for regex alternation
        set excludedSpaces = `sed ':a;N;$\\!ba;s/\n/|/g' < $excludeList`
    endif
else
    touch $excludeList
endif

set seqScript = 'BEGIN {for (i=ARGV[1]; i<=ARGV[2]; i++) print i; exit}'
awk "$seqScript" $1 $2 | egrep --invert-match --line-regexp $excludedSpaces


text:
@interface ExternalstorageFactoryBase : NSObject<IExternalstorageFactory> {
    NSMutableDictionary* mExternalstorageInstances;
    id<IExternalstorageSingleton> mExternalstorageSingleton;
}

-(id)init;

-(id<IExternalstorageSingleton>) getExternalstorageSingleton;
-(id<IExternalstorage>) getExternalstorageByID:(NSString*)ID;

-(void) destroyObjectByID:(NSString*)ID;

-(id<IExternalstorage>)createExternalstorageByID:(NSString*)ID;

-(void)dealloc;

@end


text:
(function() {
    'use strict';
    angular
        .module('money.priceRatio')
        .run(webRun);
    webRun.$inject = ['routerHelper'];
    /* @ngInject */
    function webRun(routerHelper) {
        routerHelper.configureStates(getStates());
    }

    function getStates() {
        return [{
            state: 'priceRatio',
            config: {
                url: '/priceRatio',
                templateUrl: 'price-ratio/price-ratio.view.html',
                controller: 'PriceRatioController',
                controllerAs: 'vm',
                fsBreadcrumb: {
                    label: '涨跌比率'
                }
            }
        }];
    }
})();