text:
#import "Diagnostic.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

#import <arpa/inet.h> // For AF_INET, etc.
#import <ifaddrs.h> // For getifaddrs()
#import <net/if.h> // For IFF_LOOPBACK

@implementation Diagnostic

- (void)pluginInitialize {

    [super pluginInitialize];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    self.bluetoothManager = [[CBCentralManager alloc]
                             initWithDelegate:self
                             queue:dispatch_get_main_queue()
                             options:@{CBCentralManagerOptionShowPowerAlertKey: @(NO)}];
    [self centralManagerDidUpdateState:self.bluetoothManager]; // Show initial state
}

/*************
 * Plugin API
 *************/

// Location
- (void) isLocationEnabled: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([CLLocationManager locationServicesEnabled] && [self isLocationAuthorized]) {
            NSLog(@"Location is enabled.");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            NSLog(@"Location is disabled.");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) isLocationEnabledSetting: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([CLLocationManager locationServicesEnabled]) {
            NSLog(@"Location Services is enabled");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            NSLog(@"Location Services is disabled");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

}

- (void) isLocationAuthorized: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([self isLocationAuthorized]) {
            NSLog(@"This app is authorized to use location.");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        } else {
            NSLog(@"This app is not authorized to use location.");
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

}

- (void) getLocationAuthorizationStatus: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        NSString* status = [self getLocationAuthorizationStatusAsString:[CLLocationManager authorizationStatus]];
        NSLog([NSString stringWithFormat:@"Location authorization status is: %@", status]);
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

}

- (void) requestLocationAuthorization: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)])
        {
            BOOL always = [[command argumentAtIndex:0] boolValue];
            if(always){
                NSAssert([[[NSBundle mainBundle] infoDictionary] valueForKey:@"NSLocationAlwaysUsageDescription"], @"For iOS 8 and above, your app must have a value for NSLocationAlwaysUsageDescription in its Info.plist");
                [self.locationManager requestAlwaysAuthorization];
                NSLog(@"Requesting location authorization: always");
            }else{
                NSAssert([[[NSBundle mainBundle] infoDictionary] valueForKey:@"NSLocationWhenInUseUsageDescription"], @"For iOS 8 and above, your app must have a value for NSLocationWhenInUseUsageDescription in its Info.plist");
                [self.locationManager requestWhenInUseAuthorization];
                NSLog(@"Requesting location authorization: when in use");
            }
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    self.locationRequestCallbackId = command.callbackId;
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

// Camera
- (void) isCameraEnabled: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([self isCameraPresent] && [self isCameraAuthorized]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) isCameraPresent: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([self isCameraPresent]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) isCameraAuthorized: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([self isCameraAuthorized]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) getCameraAuthorizationStatus: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        NSString* status = @"unknown";
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

        if(authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted){
            status = @"denied";
        }else if(authStatus == AVAuthorizationStatusNotDetermined){
            status = @"not_determined";
        }else if(authStatus == AVAuthorizationStatusAuthorized){
            status = @"authorized";
        }
        NSLog([NSString stringWithFormat:@"Camera authorization status is: %@", status]);
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) requestCameraAuthorization: (CDVInvokedUrlCommand*)command
{
    @try {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            CDVPluginResult* pluginResult;
            if(granted){
                NSLog(@"Granted access to camera");
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
            } else {
                NSLog(@"Not granted access to camera");
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
            }
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
    }
    @catch (NSException *exception) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

- (void) isCameraRollAuthorized: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([[self getCameraRollAuthorizationStatus]  isEqual: @"authorized"]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) getCameraRollAuthorizationStatus: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        NSString* status = [self getCameraRollAuthorizationStatus];

        NSLog([NSString stringWithFormat:@"Camera Roll authorization status is: %@", status]);
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) requestCameraRollAuthorization: (CDVInvokedUrlCommand*)command
{
    @try {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus authStatus) {
            NSString* status = [self getCameraRollAuthorizationStatusAsString:authStatus];
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
    }
    @catch (NSException *exception) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

// Wifi
- (void) isWifiEnabled: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if([self connectedToWifi]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

// Bluetooth
- (void) isBluetoothEnabled: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if(self.bluetoothEnabled) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];

        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];

        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) getBluetoothState: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        NSString* state = self.bluetoothState;
        NSLog([NSString stringWithFormat:@"Bluetooth state is: %@", state]);
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:state];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

}

// Settings
- (void) switchToSettings: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
        if (UIApplicationOpenSettingsURLString != nil && &UIApplicationOpenSettingsURLString != NULL){
            [[UIApplication sharedApplication] openURL: [NSURL URLWithString: UIApplicationOpenSettingsURLString]];
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        }else{
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported below iOS 8"];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

// Audio
- (void) isMicrophoneAuthorized: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
#ifdef __IPHONE_8_0
        AVAudioSessionRecordPermission recordPermission = [AVAudioSession sharedInstance].recordPermission;

        if(recordPermission == AVAudioSessionRecordPermissionGranted) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        }
        else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
#else
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Only supported on iOS 8 and higher"];
#endif
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) getMicrophoneAuthorizationStatus: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    @try {
#ifdef __IPHONE_8_0
        NSString* status = @"unknown";
        AVAudioSessionRecordPermission recordPermission = [AVAudioSession sharedInstance].recordPermission;
        switch(recordPermission){
            case AVAudioSessionRecordPermissionDenied:
                status = @"denied";
            case AVAudioSessionRecordPermissionGranted:
                status = @"granted";
            case AVAudioSessionRecordPermissionUndetermined:
                status = @"not_determined";
        }

        NSLog([NSString stringWithFormat:@"Microphone authorization status is: %@", status]);
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
#else
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Only supported on iOS 8 and higher"];
#endif
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) requestMicrophoneAuthorization: (CDVInvokedUrlCommand*)command
{
    @try {
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            NSLog(@"HAs access to microphone: %d", granted);
            CDVPluginResult* pluginResult;
            if(granted) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
            } else {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
            }
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
    }
    @catch (NSException *exception) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

// Remote (Push) Notifications
- (void) isRemoteNotificationsEnabled: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    BOOL isEnabled;
    @try {
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            // iOS8+
            BOOL remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
            UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;
            isEnabled = remoteNotificationsEnabled && userNotificationSettings.types != UIUserNotificationTypeNone;
        } else {
            // iOS7 and below
            UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
            isEnabled = enabledRemoteNotificationTypes != UIRemoteNotificationTypeNone;
        }

        if(isEnabled) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) getRemoteNotificationTypes: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    BOOL noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;
    @try {
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            // iOS8+
            UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;
            noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
            alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
            badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
            soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;
        } else {
            // iOS7 and below
            UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
            noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
            alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
            badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
            soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
        }

        NSMutableDictionary* types = [[NSMutableDictionary alloc]init];
        if(alertsEnabled) {
            [types setValue:@"1" forKey:@"alert"];
        } else {
            [types setValue:@"0" forKey:@"alert"];
        }
        if(badgesEnabled) {
            [types setValue:@"1" forKey:@"badge"];
        } else {
            [types setValue:@"0" forKey:@"badge"];
        }
        if(soundsEnabled) {
            [types setValue:@"1" forKey:@"sound"];
        } else {;
            [types setValue:@"0" forKey:@"sound"];
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self objectToJsonString:types]];
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void) isRegisteredForRemoteNotifications: (CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult;
    BOOL registered;
    @try {
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            // iOS8+
            registered = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
        } else {
            // iOS7 and below
            UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
            registered = enabledRemoteNotificationTypes != UIRemoteNotificationTypeNone;
        }
        if(registered) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:1];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:0];
        }
    }
    @catch (NSException *exception) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

/*********************
 * Internal functions
 *********************/
- (void)jsCallback: (NSString*)jsString
{
    [self.commandDelegate evalJs:jsString];
}

- (NSString*) getLocationAuthorizationStatusAsString: (CLAuthorizationStatus)authStatus
{
    NSString* status = @"unknown";
    if(authStatus == kCLAuthorizationStatusDenied || authStatus == kCLAuthorizationStatusRestricted){
        status = @"denied";
    }else if(authStatus == kCLAuthorizationStatusNotDetermined){
        status = @"not_determined";
    }else if(authStatus == kCLAuthorizationStatusAuthorizedAlways){
        status = @"authorized_always";
    }else if(authStatus == kCLAuthorizationStatusAuthorizedWhenInUse){
        status = @"authorized_when_in_use";
    }
    return status;
}

- (BOOL) isLocationAuthorized
{
    CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
    NSString* status = [self getLocationAuthorizationStatusAsString:authStatus];
    if([status  isEqual: @"authorized_always"] || [status  isEqual: @"authorized_when_in_use"]) {
        return true;
    } else {
        return false;
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)authStatus {
    NSString* status = [self getLocationAuthorizationStatusAsString:authStatus];
    NSLog([NSString stringWithFormat:@"Location authorization status changed to: %@", status]);

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:status];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.locationRequestCallbackId];

    [self onLocationAuthorizationStatusChange:status]; // Deprecated
}

-(void)onLocationAuthorizationStatusChange:(NSString *)status __attribute__((deprecated))
{
    NSString* jsString = [NSString stringWithFormat:@"cordova.plugins.diagnostic._onLocationAuthorizationStatusChange(\"%@\");", status];
    [self jsCallback:jsString];
}

- (BOOL) isCameraPresent
{
    BOOL cameraAvailable =
    [UIImagePickerController
     isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if(cameraAvailable) {
        NSLog(@"Camera available");
        return true;
    }
    else {
        NSLog(@"Camera unavailable");
        return false;
    }
}

- (BOOL) isCameraAuthorized
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        return true;
    } else {
        return false;
    }
}

- (NSString*) getCameraRollAuthorizationStatus
{
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    return [self getCameraRollAuthorizationStatusAsString:authStatus];

}

- (NSString*) getCameraRollAuthorizationStatusAsString: (PHAuthorizationStatus)authStatus
{
    NSString* status = @"unknown";
    if(authStatus == PHAuthorizationStatusDenied || authStatus == PHAuthorizationStatusRestricted){
        status = @"denied";
    }else if(authStatus == PHAuthorizationStatusNotDetermined ){
        status = @"not_determined";
    }else if(authStatus == PHAuthorizationStatusAuthorized){
        status = @"authorized";
    }
    return status;
}

- (BOOL) connectedToWifi  // Don't work on iOS Simulator, only in the device
{
    struct ifaddrs *addresses;
    struct ifaddrs *cursor;
    BOOL wiFiAvailable = NO;

    if (getifaddrs(&addresses) != 0) {
        return NO;
    }

    cursor = addresses;
    while (cursor != NULL)  {
        if (cursor -> ifa_addr -> sa_family == AF_INET && !(cursor -> ifa_flags & IFF_LOOPBACK)) // Ignore the loopback address
        {
            // Check for WiFi adapter
            if (strcmp(cursor -> ifa_name, "en0") == 0) {

                NSLog(@"Wifi ON");
                wiFiAvailable = YES;
                break;
            }
        }
        cursor = cursor -> ifa_next;
    }
    freeifaddrs(addresses);
    return wiFiAvailable;
}

- (NSString*) arrayToJsonString:(NSArray*)inputArray
{
    NSError* error;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:inputArray options:NSJSONWritingPrettyPrinted error:&error];
    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

- (NSString*) objectToJsonString:(NSDictionary*)inputObject
{
    NSError* error;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:inputObject options:NSJSONWritingPrettyPrinted error:&error];
    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

#pragma mark - CBCentralManagerDelegate

- (void) centralManagerDidUpdateState:(CBCentralManager *)central {
    NSString* state;
    NSString* description;

    switch(self.bluetoothManager.state)
    {
        case CBCentralManagerStateResetting:
            state = @"resetting";
            description =@"The connection with the system service was momentarily lost, update imminent.";
            break;

        case CBCentralManagerStateUnsupported:
            state = @"unsupported";
            description = @"The platform doesn't support Bluetooth Low Energy.";
            break;

        case CBCentralManagerStateUnauthorized:
            state = @"unauthorized";
            description = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"powered_off";
            description = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
            state = @"powered_on";
            description = @"Bluetooth is currently powered on and available to use.";
            break;
        default:
            state = @"unknown";
            description = @"State unknown, update imminent.";
            break;
    }
    NSLog(@"Bluetooth state changed: %@",description);

    self.bluetoothState = state;
    if([state  isEqual: @"powered_on"]){
        self.bluetoothEnabled = true;
    }else{
        self.bluetoothEnabled = false;
    }

    NSString* jsString = [NSString stringWithFormat:@"cordova.plugins.diagnostic._onBluetoothStateChange(\"%@\");", state];
    [self jsCallback:jsString];
}

@end


text:
package org.apache.skywalking.oap.server.core.analysis.metrics;

import lombok.Getter;
import lombok.Setter;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.Entrance;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.MetricsFunction;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.SourceFrom;
import org.apache.skywalking.oap.server.core.query.sql.Function;
import org.apache.skywalking.oap.server.core.storage.annotation.Column;

@MetricsFunction(functionName = "sum")
public abstract class SumMetrics extends Metrics implements LongValueHolder {

    protected static final String VALUE = "value";

    @Getter
    @Setter
    @Column(columnName = VALUE, dataType = Column.ValueDataType.COMMON_VALUE, function = Function.Sum)
    private long value;

    @Entrance
    public final void combine(@SourceFrom long count) {
        this.value += count;
    }

    @Override
    public final boolean combine(Metrics metrics) {
        SumMetrics sumMetrics = (SumMetrics) metrics;
        combine(sumMetrics.value);
        return true;
    }

    @Override
    public void calculate() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Italia Interactive Map</title>
    <script src="js/jquery-2.2.2.min.js" type="text/javascript"></script>
    <script src="js/jquery.browser.min.js" type="text/javascript"></script>
    <script src="js/snap.svg-min.js" type="text/javascript"></script>
    <script src="js/main.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <svg id="svgMap"></svg>
</body>
</html>


text:
require 'test_helper'

class PlatoonsHelperTest < ActionView::TestCase
end


text:
package com.runearrow.npcdefdumper;

import java.io.IOException;

import com.runearrow.utilities.FileOperations;
import com.runearrow.utilities.Stream;

/**
 * Class that unpacks the definitions - copied from a 317 client.
 */
public class NPCDefDumper {

	public static NPCDefDumper forID(int i) {
		for (int j = 0; j < 20; j++)
			if (cache[j].typeId == (long) i)
				return cache[j];

		anInt56 = (anInt56 + 1) % 20;
		NPCDefDumper entityDef = cache[anInt56] = new NPCDefDumper();
		stream.currentOffset = streamIndices[i];
		entityDef.typeId = i;
		entityDef.readValues(stream);

		return entityDef;
	}
	public static void run() {
		System.out.println("Dumping NPC Definitions...");
		stream = new Stream(FileOperations.ReadFile("./data/npc.dat"));
		Stream stream2 = new Stream(FileOperations.ReadFile("./data/npc.idx"));
		int totalNPCs = stream2.readUnsignedWord();

		NPCDefDumperPanel.npcData = new Object[totalNPCs][5];
		System.out.println(totalNPCs+" npcs loaded.");

		streamIndices = new int[totalNPCs];
		int i = 2;
		for (int j = 0; j < totalNPCs; j++) {
			streamIndices[j] = i;
			i += stream2.readUnsignedWord();
		}
		cache = new NPCDefDumper[20];
		for (int k = 0; k < 20; k++)
			cache[k] = new NPCDefDumper();
		for (int index = 0; index < totalNPCs; index++) {
			NPCDefDumper ed = forID(index);
			if (ed == null)
				continue;
			if (ed.name == null)
				continue;

		}
	}
	public void readValues(Stream stream) {
		do {
			int i = stream.readUnsignedByte();
			if (i == 0)
				return;
			if (i == 1) {
				int j = stream.readUnsignedByte();
				anIntArray94 = new int[j];
				for (int j1 = 0; j1 < j; j1++)
					anIntArray94[j1] = stream.readUnsignedWord();

			} else if (i == 2) {
				name = stream.readString();
			} else if (i == 3) {
				description = stream.readBytes();
			} else if (i == 12)
				aByte68 = stream.readSignedByte();
			else if (i == 13) {
				standAnim = stream.readUnsignedWord();
			} else if (i == 14)
				walkAnim = stream.readUnsignedWord();
			else if (i == 17) {
				walkAnim = stream.readUnsignedWord();
				anInt58 = stream.readUnsignedWord();
				anInt83 = stream.readUnsignedWord();
				anInt55 = stream.readUnsignedWord();
			} else if (i >= 30 && i < 40) {
				if (actions == null)
					actions = new String[5];
				actions[i - 30] = stream.readString();
				if (actions[i - 30].equalsIgnoreCase("hidden"))
					actions[i - 30] = null;
			} else if (i == 40) {
				int k = stream.readUnsignedByte();
				anIntArray76 = new int[k];
				anIntArray70 = new int[k];
				for (int k1 = 0; k1 < k; k1++) {
					anIntArray76[k1] = stream.readUnsignedWord();
					anIntArray70[k1] = stream.readUnsignedWord();
				}

			} else if (i == 60) {
				int l = stream.readUnsignedByte();
				anIntArray73 = new int[l];
				for (int l1 = 0; l1 < l; l1++)
					anIntArray73[l1] = stream.readUnsignedWord();

			} else if (i == 90)
				stream.readUnsignedWord();
			else if (i == 91)
				stream.readUnsignedWord();
			else if (i == 92)
				stream.readUnsignedWord();
			else if (i == 93)
				aBoolean87 = false;
			else if (i == 95) {
				combatLevel = stream.readUnsignedWord();

				int indexId = (int) typeId;

				NPCDefDumperPanel.npcData[indexId][0] = name;
				NPCDefDumperPanel.npcData[indexId][1] = combatLevel;
				try {
					NPCDefDumperPanel.npcData[indexId][2] = WikiScraper.dumpHealthFrom2007RSWiki(name, combatLevel); //health
				} catch (IOException e) {
					NPCDefDumperPanel.npcData[indexId][2] = 0;
				}
				NPCDefDumperPanel.npcData[indexId][3] = 16; //respawn timer
				NPCDefDumperPanel.npcData[indexId][4] = aByte68; //size

				System.out.println("Id : "+typeId+", Name: "+NPCDefDumperPanel.npcData[indexId][0]+", Combat: "+NPCDefDumperPanel.npcData[indexId][1]+","
							+ " Health: "+NPCDefDumperPanel.npcData[indexId][2]+", Respawn: "+NPCDefDumperPanel.npcData[indexId][3]+" ,"
									+ " Size: "+NPCDefDumperPanel.npcData[indexId][4]);
			} else if (i == 97)
				anInt91 = stream.readUnsignedWord();
			else if (i == 98)
				anInt86 = stream.readUnsignedWord();
			else if (i == 99)
				aBoolean93 = true;
			else if (i == 100)
				anInt85 = stream.readSignedByte();
			else if (i == 101)
				anInt92 = stream.readSignedByte() * 5;
			else if (i == 102)
				anInt75 = stream.readUnsignedWord();
			else if (i == 103)
				anInt79 = stream.readUnsignedWord();
			else if (i == 106) {
				anInt57 = stream.readUnsignedWord();
				if (anInt57 == 65535)
					anInt57 = -1;
				anInt59 = stream.readUnsignedWord();
				if (anInt59 == 65535)
					anInt59 = -1;
				int i1 = stream.readUnsignedByte();
				childrenIDs = new int[i1 + 1];
				for (int i2 = 0; i2 <= i1; i2++) {
					childrenIDs[i2] = stream.readUnsignedWord();
					if (childrenIDs[i2] == 65535)
						childrenIDs[i2] = -1;
				}

			} else if (i == 107) {
				aBoolean84 = false;
			}

		} while (true);
	}
	public NPCDefDumper() {
		anInt55 = -1;
		anInt57 = -1;
		anInt58 = -1;
		anInt59 = -1;
		combatLevel = -1;
		anInt64 = 1834;
		walkAnim = -1;
		aByte68 = 1;
		anInt75 = -1;
		standAnim = -1;
		typeId = -1L;
		anInt79 = 32;
		anInt83 = -1;
		aBoolean84 = true;
		anInt86 = 128;
		aBoolean87 = true;
		anInt91 = 128;
		aBoolean93 = false;
	}

	public int anInt55;
	public static int anInt56;
	public int anInt57;
	public int anInt58;
	public int anInt59;
	public static Stream stream;
	public int combatLevel;
	public final int anInt64;
	public String name;
	public String actions[];
	public int walkAnim;
	public byte aByte68;
	public int[] anIntArray70;
	public static int[] streamIndices;
	public int[] anIntArray73;
	public int anInt75;
	public int[] anIntArray76;
	public int standAnim;
	public long typeId;
	public int anInt79;
	public static NPCDefDumper[] cache;
	//public static Client clientInstance;
	public int anInt83;
	public boolean aBoolean84;
	public int anInt85;
	public int anInt86;
	public boolean aBoolean87;
	public int childrenIDs[];
	public byte description[];
	public int anInt91;
	public int anInt92;
	public boolean aBoolean93;
	public int[] anIntArray94;
}


text:
using BrumWithMe.Data.Models.CompositeModels.Trip;
using BrumWithMe.Services.Data.Contracts;
using BrumWithMe.Services.Providers.Mapping.Contracts;
using BrumWithMe.Web.Models.Areas.Admin;
using BrumWithMe.Web.Models.Trip;
using Bytes2you.Validation;
using System.Collections.Generic;
using System.Web.Mvc;

namespace BrumWithMe.MVC.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        private readonly IReportService reportService;
        private readonly IMappingProvider mappingProvider;
        private readonly ITripService tripService;

        public AdminController(IReportService reportService, IMappingProvider mappingProvider, ITripService tripService)
        {
            Guard.WhenArgument(reportService, nameof(reportService)).IsNull().Throw();
            Guard.WhenArgument(mappingProvider, nameof(mappingProvider)).IsNull().Throw();
            Guard.WhenArgument(tripService, nameof(tripService)).IsNull().Throw();

            this.reportService = reportService;
            this.mappingProvider = mappingProvider;
            this.tripService = tripService;
        }

        public ActionResult Dashboard()
        {
            return this.View();
        }

        public ActionResult ReportedTrips()
        {
            var model = new ReportedTripsViewModel();
            var trips = this.reportService.GetReportedTrips();
            var tripsvmodel = this.mappingProvider.Map<IEnumerable<TripBasicInfo>, IEnumerable<TripBasicInfoViewModel>>(trips);

            model.ReportedTrips = tripsvmodel;
            return this.PartialView("_ReportedTrips", model);
        }

        public ActionResult DeletedTrips()
        {
            var deletedTrips = this.tripService.GetDeletedTrips();
            var tripsvmodel = this.mappingProvider.Map<IEnumerable<TripBasicInfo>, IEnumerable<TripBasicInfoViewModel>>(deletedTrips);

            return this.PartialView("_DeletedTrips", tripsvmodel);

        }

        [HttpPost]
        public ActionResult DeleteTrip(int tripId)
        {
            this.tripService.DeleteTrip(tripId);

            return this.RedirectToAction(nameof(AdminController.ReportedTrips));
        }

        [HttpPost]
        public ActionResult RestoreTrip(int tripId)
        {
            this.tripService.RecoverTrip(tripId);

            return this.RedirectToAction(nameof(AdminController.DeletedTrips));
        }

        [HttpPost]
        public ActionResult UnReportTrip(int tripId)
        {
            this.reportService.UnReportTrip(tripId);

            return this.RedirectToAction(nameof(AdminController.ReportedTrips));
        }
    }
}


text:
var GameOfLifeWorlds = GameOfLifeWorlds || new Campaign();
var GameOfLifeCultures = GameOfLifeCultures || {};
var GameOfLifeModule = GameOfLifeModule || {};

/**
 * Register the default agent types
 */
(function () {

    this.init = function () {
        var switchStateCapability = {} ;
        switchStateCapability.exercise = function(agent, world) {
            var x = agent.x;
            var y = agent.y;

            var positions = world.getMooreNeighbourhood(x, y, false);
            var agentCounter = 0;
            positions.forEach(function(position) {
                var pX = position.x, pY = position.y;
                var agents = world.getAgentsAtCell(pX, pY);
                if (agents && agents.length > 0 && agents[0].isLiving)
                    agentCounter++;
            })
            agent.isDirty = false;
            if (! agent.isLiving) {
                if (agentCounter == 3) {
                    agent.isLiving = true;
                    agent.isDirty = true;
                }
            }
            else  {
                if (agentCounter < 2 || agentCounter > 3) {
                    agent.isLiving = false;
                    agent.isDirty = true;
                }
            }
        };

        this.CELLULAR_AGENT_TYPE = new Culture("Cell", "000", ModuleManager.currentModule.resourceSet.categories);
        this.CELLULAR_AGENT_TYPE.birthProbability = 0.0;
        this.CELLULAR_AGENT_TYPE.reproductionAge = 15;
        this.CELLULAR_AGENT_TYPE.moveCost = 0;
        this.CELLULAR_AGENT_TYPE.waveNumber = 50;
        this.CELLULAR_AGENT_TYPE.speed = 1;
        this.CELLULAR_AGENT_TYPE.characteristics = {
            isLiving: false, isDirty: true
        };
        this.CELLULAR_AGENT_TYPE.beliefs = [
//            Beliefs.BeliefsAboutPaths
        ];
        this.CELLULAR_AGENT_TYPE.desires = [
        ];
        this.CELLULAR_AGENT_TYPE.capabilities = [
            switchStateCapability
        ];
        this.CELLULAR_AGENT_TYPE.drawFunction = (function (ctx, agent, x, y, pieceWidth, pieceHeight, newColor, counter, direction) {
            if (agent.isLiving) {
                var __ret = FiercePlanet.Drawing.getDrawingPosition(agent, Lifecycle.waveCounter);
                var xPos = __ret.intX;
                var yPos = __ret.intY;
                var nx = xPos * FiercePlanet.Orientation.cellWidth;
                var ny = yPos * FiercePlanet.Orientation.cellHeight;

                var color = (agent.isLiving ? "#fff" : "#000");
                ctx.fillStyle = color;
                if ((Universe.settings.isometricView || Lifecycle.currentWorld.isometricView)) {
                    var newOrigin = FiercePlanet.Isometric.doIsometricOffset(xPos, yPos);
                    nx = newOrigin.x;
                    ny = newOrigin.y;
                    var originXp = newOrigin.x + FiercePlanet.Orientation.cellWidth / 2;
                    var originYp = newOrigin.y + FiercePlanet.Orientation.cellHeight;

                    // Rotation logic here - TODO: Refactor out
                    originXp = originXp - (FiercePlanet.Orientation.halfWorldWidth);
                    originYp = originYp - (FiercePlanet.Orientation.halfWorldHeight);

                    FiercePlanet.Isometric.draw3DTile(ctx, [originXp, originYp], FiercePlanet.Orientation.cellHeight);
                    ctx.fill();
                }
                else {
                    nx = nx - (FiercePlanet.Orientation.worldWidth) / 2;
                    ny = ny - (FiercePlanet.Orientation.worldHeight) / 2;
                    nx = Math.floor(nx);
                    ny = Math.floor(ny);

                    ctx.fillRect(nx, ny, FiercePlanet.Orientation.cellWidth, FiercePlanet.Orientation.cellHeight);
                }
            }
        });
        this.CELLULAR_AGENT_TYPE.initFunction = function (agent, world) {
            var r = Math.random();
            agent.gender = (r < 0.5 ? 'm' : 'f');
        }

        this.id = 'GOL-Agents';
        this.cultures = [GameOfLifeCultures.CELLULAR_AGENT_TYPE];
    }

}).apply(GameOfLifeCultures);

(function () {

    this.init = function () {
        this.gameOfLifeWorld = new World();
        (function () {
            this.id = 1;
            this.isometricView = false;
            this.allowResourcesOnPath = true;
            this.allowOffscreenCycling = true;
            this.initialResourceStore = 10000;
            this.isPresetWorld = true;
            this.placeAgentsOnAllCells = true;
//            this.randomiseAgents = true;
            this.randomiseResources = true;
//            this.addEntryPoint(19, 0);
//                this.addExitPoint(10, 10);
            this.scaleFactor = 1;
            this.cellsAcross = 50;
            this.cellsDown = 50;
            this.initialAgentNumber = 1;
            this.generateWaveAgentsAutomatically = true;
            this.incrementAgentsEachWave = 1;
//                this.distributeAgentsNormally = true;
//                this.distributeAgentsSigma = 4;
//                this.distributeAgentsHealthNormally = false;
//                this.distributeAgentsHealthSigma = 4;
            this.noWander = true;
            this.noSpeedChange = true;
            this.resourcesOwnTilesExclusively = false;
            this.agentsOwnTilesExclusively = true;
            this.allowOffscreenCycling = false;
            this.waveNumber = 1;
            this.expiryLimit = 1;
            this.initialResourceNumber = 0;
            this.name = ("Testing parameters...");
            this.isTerminalWorld = true;
            this.dontClearCanvas = false;
            this.scrollingImageVisible = false;
            this.introduction =
                "
Size of world:

<input class='world-parameters' name='SizeOfWorld' value='130'/>
" +
                    "
Enter number of live agents to start with:

<input class='world-parameters' name='NumberOfLiveAgents' value='2000'/>
" +
                    ""
            ;
            this.conclusion = ("Well done.");
            this.currentAgentsFunction = function(agent) {
                return agent;//.isDirty;
            };

            this.setup = function () {
                if (FiercePlanet.Parameters.SizeOfWorld) {
                    this.cellsAcross = this.cellsDown = parseInt(FiercePlanet.Parameters.SizeOfWorld);
                    this.setCurrentAgents([]);
                    this.expiredAgents = [];
                }

                var bg = new Terrain(one.color('#000').alpha(0.9));
                this.addTerrainToPath(bg);
//                this.generatePath();
//                for (var i = 0; i < this.cellsAcross; i++) {
//                    for (var j = 0; j < this.cellsDown; j++) {
//                        this.terrainMap[[i, j]] = bg;
//                    }
//                }

                if (FiercePlanet.Parameters.SizeOfWorld) {
                    this.initialiseCells();
                    this.waves = undefined;
                    this.initialiseWaves(this.waveNumber);
                }

                // Get pathway length
                var pl = this.pathway.length;
                if (FiercePlanet.Parameters.NumberOfLiveAgents) {
                    var nola = parseInt(FiercePlanet.Parameters.NumberOfLiveAgents);
                    for (var i = 0; i < nola; i ++) {
                        // Generate a random tile position
                        var tp = Math.floor(Math.random() * pl);
                        var pathCell = this.pathway[tp];
                        var agents = this.getAgentsAtCell(pathCell[0], pathCell[1]);
                        if (agents && agents.length > 0)
                            agents[0].isLiving = true;
                    }
                }
            };

        }).apply(this.gameOfLifeWorld);

        // Prepare as a module
        this.id = "GOL";
        this.name = "GOL";
        this.position = 1;
        this.worlds = [this.gameOfLifeWorld ];
    }

    this.init();
}).apply(GameOfLifeWorlds);

(function() {
    this.init = function() {
        GameOfLifeCultures.init();

        var module = new Module();
        module.id = 'GOL';
        module.registerSelf();
        module.registerCampaign(GameOfLifeWorlds);
        module.registerCulture(GameOfLifeCultures.CELLULAR_AGENT_TYPE);
        module.registerResourceSet(TBL);

		Universe.settings.isometricView = false;
        Universe.settings.hidePathBorder = true;
        Universe.settings.scrollingImageVisible = localStorage.scrollingImageVisible = false;
        Universe.settings.showGraph = true;
        Universe.settings.showEditor = true;
        Universe.settings.store();
        Lifecycle.currentCampaignID = 'GOL';
        Lifecycle.currentWorldNumber = localStorage.currentWorldNumber = 0;
        Lifecycle.currentWorldPreset = true;
        Lifecycle.interval = 10;
        Lifecycle.worldDelay = 300;

        FiercePlanet.ModuleEditor.buildEditorFromUrl('/javascripts/fp/modules/gol/game-of-life-module.js', 'GameOfLifeModule.init(); FiercePlanet.Game.loadGame();');
    };
}).apply(GameOfLifeModule);

if (typeof exports !== "undefined") {
    exports.GameOfLifeCultures = GameOfLifeCultures;
    exports.GameOfLifeWorlds = GameOfLifeWorlds;
    exports.GameOfLifeModule = GameOfLifeModule;
}


text:
package es.upv.grycap.coreutils.fiber.test.mockserver;

import static java.util.Collections.emptyMap;

import java.util.Map;

/**
 * Defines expectation responses for requests made with the HTTP POST method.
 * @author Erik Torres
 * @since 0.1.0
 */
public class ExpectationHttpPostResponse extends AbstractExpectationResponse {

	/**
	 * Convenient constructor that can be used to create expectations where the server where the server responds
	 * to all correct requests with the HTTP status code CREATED (201) to the proper requests and no query parameters
	 * are submitted. This pattern is commonly used in REST and REST-like APIs.
	 * @param path - the path where clients expect the server is listening for incoming requests
	 * @param contentType - the content type of the server response
	 * @param body - the content of the body sent with the server response
	 * @param delay - the server will wait this time before sending a response to the client
	 */
	public ExpectationHttpPostResponse(final String path, final String contentType, final String body, final long delay) {
		super(path, emptyMap(), 201, contentType, body, delay);
	}

	/**
	 * Convenient constructor that can be used to create expectations where the server responds
	 * to all correct requests with the HTTP status code CREATED (201).
	 * @param path - the path where clients expect the server is listening for incoming requests
	 * @param parameters - query parameters accompanying the request
	 * @param contentType - the content type of the server response
	 * @param body - the content of the body sent with the server response
	 * @param delay - the server will wait this time before sending a response to the client
	 */
	public ExpectationHttpPostResponse(final String path, final Map<String, String> parameters, final String contentType, final String body, final long delay) {
		super(path, parameters, 201, contentType, body, delay);
	}

	/**
	 * Convenient constructor that receives initial values for all the parameters of this class.
	 * @param path - the path where clients expect the server is listening for incoming requests
	 * @param parameters - query parameters accompanying the request
	 * @param statusCode - the response status code after the request is processed in the server
	 * @param contentType - the content type of the server response
	 * @param body - the content of the body sent with the server response
	 * @param delay - the server will wait this time before sending a response to the client
	 */
	public ExpectationHttpPostResponse(final String path, final Map<String, String> parameters, final int statusCode, final String contentType, final String body, final long delay) {
		super(path, parameters, statusCode, contentType, body, delay);
	}

}


text:
export BIGIP_Addrs="10.147.29.214"
#export BIGIP_Addrs="10.147.185.205"
export BIGIP_User="admin"
export BIGIP_Passwd="admin"

##
## Modify these arrays to reflect the names of configuration objects you need
##   removed from the BIGIP configuration.
##
export GRPNAMES=("URL_Block_List")
export VSNAMES=("filt_in_HTTP" "HTTPS_Passthrough" "DNS_Traffic_Passthrough" "lb_urlfilter" \
  "TrafficListener" "TrafficPassthrough" "DNS_Traffic_Passthrough_With_Cache")
export POLICYNAMES=("CPE_Security_Policy")
export IRULE_NAMES=("URL_Filter" "Assign_BWC_Policy")
export POOLNAMES=("urlfilter_pool")
export DNSCACHENAMES=("DNS_Cache")
export PROFILENAMES=("dns/dns_cache")
export BWCNAMES=("Base_Traffic_BWC")

## Programs
#export CURL="/opt/vagrant/embedded/bin/curl"
export CURL="/usr/bin/curl"
export LOGFILE='./f5_reset.log'
if [ -e $LOGFILE ]; then
  echo "Removing old Log file."
  rm $LOGFILE
fi

# Initial Curl connection timeout value in seconds.
TIMEOUT=5
## Maximum time for an API call to return. Depending on what you are doing,
##  this value should be quite large as some calls take a long time to
##  complete!  Testing your script should provide you with a good ideal
##  about what is too long.  I usually start at 120 seconds and go up from there.
MAXTIMEOUT=500

source ./F5CommonRESTAPIs.sh
log "** Adding Common iControl REST API Function **"

#-------------------------------------------------------
# Function: listActiveModules()
#-------------------------------------------------------
listActiveModules() {
  LIST=$(restCall "GET" "/tm/sys/provision/?\$select=name,level")
  CNT=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print len(input['items'])")
  I=0
  local -a ARR=()
  while [[ $I != $CNT ]]; do
    LVL=$(echo $LIST | jsonq "[\"items\"][${I}][\"level\"]")
    if [[ $LVL != "none" ]]; then
      ARR[$I]=$(echo $LIST | jsonq "[\"items\"][${I}][\"name\"]")
    fi
    I=$((I+1))
  done
  echo ${ARR[@]}
}

#-----------------------------------------------------------------------
#-----------------------------[  MAIN  ]--------------------------------
#-----------------------------------------------------------------------
log "*** Program Start ***"

# Check to make sure defined BIGIP is up and available for API calls
echo "Checking to see if we can talk to BIGIP..."
log "---Checking to see if we can talk to BIGIP..."
if (! whenAvailable); then
  echo "ERROR: BIGIP Not responding... Please check to see if it is running!"
  exit 1
fi

# Get the BIGIP Version
echo "Retrieving BIGIP Version number..."
log "---Retrieving BIGIP Version number..."
BIGIPVERSION=$(getVersion)
echo "    ${BIGIPVERSION}"

# Remove Default Route
echo "Remove Default Route"
log "---Remove Default Route"
OUT=$(restCall "DELETE" "/tm/net/route/~Common~DefaultRoute")
if [[ $OUT != "" ]]; then
  log "Remove DefaultRoute: `echo $OUT | python -mjson.tool`"
fi

# Remove all named Virtual Servers
echo "Removing Virtual Servers..."
log "---Removing Virtual Servers..."
I=0
while [[ ${VSNAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/virtual/${VSNAMES[$I]}" )
  if [[ $OUT == "" ]]; then
    echo "   ${VSNAMES[$I]}"
  else
    log "Remove VS: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Disable any Global Security Policy
echo "Disable Global Secuirity Policy"
log "---Disable Global Secuirity Policy"
OUT=$(restCall "PATCH" "/tm/security/firewall/globalRules" "{ \"enforcedPolicy\": \"none\" }")
log "Disable Global security Policy: `echo $OUT | python -mjson.tool`"

# Remove any Security Policies
echo "Removing Security Policies..."
log "---Removing Security Policies..."
I=0
while [[ ${POLICYNAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/security/firewall/policy/${POLICYNAMES[$I]}" )
  if [[ $OUT == "" ]]; then
    echo "   ${POLICYNAMES[$I]}"
  else
    log "Remove Security Policy: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove any Pools
echo "Remove Pools..."
log "---Remove Pools..."
I=0
while [[ ${POOLNAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/pool/${POOLNAMES[$I]}")
  #log "Remove Pool: `echo $OUT | python -mjson.tool`"
  if [[ $OUT == "" ]]; then
    echo "   ${POOLNAMES[$I]}"
  else
    log "Remove Pool: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove all Nodes from list
echo "Remove all Nodes from List..."
log "---Remove all Nodes from List..."
LIST=$(restCall "GET" "/tm/ltm/node?\$select=name")
TEST=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print('yes' if 'items' in input else 'no')")
if [[ $TEST == 'yes' ]]; then
  CNT=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print len(input['items'])")
  I=0
  while [[ $I != $CNT ]]; do
    AA=$(echo $LIST | jsonq "[\"items\"][${I}][\"name\"]")
    # Remove the node
    OUT=$(restCall "DELETE" "/tm/ltm/node/~Common~${AA}")
    #log "Remove Node: `echo $OUT | python -mjson.tool`"
    echo "    ${AA}"
    I=$((I+1))
  done
fi

# Remove any iRules
echo "Remove iRules..."
log "---Remove iRules..."
I=0
while [[ ${IRULE_NAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/rule/~Common~${IRULE_NAMES[$I]}")
  #log "Remove iRule: `echo $OUT | python -mjson.tool`"
  if [[ $OUT == "" ]]; then
    echo "    ${IRULE_NAMES[$I]}"
  else
    log "Remove iRule: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove any Data Groups
echo "Remove Data Groups..."
log "---Remove Data Groups..."
I=0
while [[ ${GRPNAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/data-group/internal/~Common~${GRPNAMES[$I]}")
  #log "Remove DataGroup: `echo $OUT | python -mjson.tool`"
  if [[ $OUT == "" ]]; then
    echo "    ${GRPNAMES[$I]}"
  else
    log "Remove DataGroup: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove any Profiles
echo "Remove Profiles..."
log "---Remove Profiles..."
I=0
while [[ ${PROFILENAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/profile/${PROFILENAMES[$I]}")
  #log "Remove Profile: `echo $OUT | python -mjson.tool`"
  if [[ $OUT == "" ]]; then
    echo "    ${PROFILENAMES[$I]}"
  else
    log "Remove Profile: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove any DNS Caches
echo "Remove DNS Caches..."
log "---Remove DNS Caches..."
I=0
while [[ ${DNSCACHENAMES[$I]} != "" ]]; do
  OUT=$(restCall "DELETE" "/tm/ltm/dns/cache/transparent/~Common~${DNSCACHENAMES[$I]}")
  #log "Remove DNS Cache: `echo $OUT | python -mjson.tool`"
  if [[ $OUT == "" ]]; then
    echo "    ${DNSCACHENAMES[$I]}"
  else
    log "Remove DNS Cache: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove any BWC Policies
echo "Remove BWC Policies..."
log "---Remove BWC Policies..."
I=0
while [[ ${BWCNAMES[$I]} != "" ]]; do
  if [[ $BIGIPVERSION == "12.0" ]]; then
    OUT=$(restCall "DELETE" "/tm/net/bwc/policy/~Common~${BWCNAMES[$I]}")
  fi
  if [[ $BIGIPVERSION == "11.6" ]]; then
    OUT=$(restCall "DELETE" "/tm/net/bwc-policy/~Common~${BWCNAMES[$I]}")
  fi
  if [[ $OUT == "" ]]; then
    echo "    ${BWCNAMES[$I]}"
  else
    log "Remove BWC Policies: `echo $OUT | python -mjson.tool`"
  fi
  I=$((I+1))
done

# Remove SelfIPs
echo "Remove SelfIPs..."
log "---Remove SelfIPs..."
LIST=$(restCall "GET" "/tm/net/self?\$select=name")
TEST=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print('yes' if 'items' in input else 'no')")
if [[ $TEST == 'yes' ]]; then
  CNT=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print len(input['items'])")
  I=0
  while [[ $I != $CNT ]]; do
    AA=$(echo $LIST | jsonq "[\"items\"][${I}][\"name\"]")
    # Remove the node
    OUT=$(restCall "DELETE" "/tm/net/self/~Common~${AA}")
    if [[ $OUT == "" ]]; then
      echo "    ${AA}"
    else
      log "Remove SelfIPs: `echo $OUT | python -mjson.tool`"
    fi
    I=$((I+1))
  done
fi

# Remove vlans
echo "Remove VLANs..."
log "---Remove VLANs..."
LIST=$(restCall "GET" "/tm/net/vlan?\$select=name")
TEST=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print('yes' if 'items' in input else 'no')")
if [[ $TEST == 'yes' ]]; then
  CNT=$(echo $LIST | python -c "import sys,json; input=json.load(sys.stdin); print len(input['items'])")
  I=0
  while [[ $I != $CNT ]]; do
    AA=$(echo $LIST | jsonq "[\"items\"][${I}][\"name\"]")
    # Remove the node
    OUT=$(restCall "DELETE" "/tm/net/vlan/~Common~${AA}")
    if [[ $OUT == "" ]]; then
      echo "    ${AA}"
    else
      log "Remove SelfIPs: `echo $OUT | python -mjson.tool`"
    fi
    I=$((I+1))
  done
fi

# If AFM is enabled, disable and reboot
echo "Check to see if AFM is enabled..."
log "---Check to see if AFM is enabled..."
declare -a LIST=()
LIST=$(listActiveModules)
for MOD in ${LIST[@]}; do
  if [[ $MOD == "afm" ]]; then
    echo "AFM is Enabled, Disabling..."
    log "---AFM is Enabled, Disabling..."
    OUT=$(restCall "PUT" "/tm/sys/provision/afm" "{ \"level\": \"none\" }")
    sleep 10
    if (! waitForActiveStatus); then
      echo "ERROR: BIGIP Not in 'Active' status after disabling AFM module!!!"
      exit 1
    fi
    if (! whenAvailable); then
      echo "ERROR: BIGIP Not responding... Please check to see if it is running!"
      exit 1
    fi
    echo "Save Configuration..."
    log "---Save Configuration..."
    SAVE=$(saveConfig)
    echo "Rebooting BIGIP to complete AFM cleanup..."
    log "---Rebooting BIGIP to complete AFM cleanup..."
    rebootBIGIP
    sleep 60
    echo "Waiting for the BIGIP to come back up into an 'ACTIVE' state..."
    if (! whenAvailable ); then
      echo "BIGIP not responding within ${MAXTIMEOUT} seconds. Aborting..."
      exit 1
    fi
    if ( ! waitForActiveStatus ); then
      echo "BIGIP did not return to an 'ACTIVE' state after the reboot. Aborting..."
      exit 1
    fi
  fi
done

# Save Config
echo "Saving the new Configuration..."
log "----Saving the new Configuration..."
OUT=$(saveConfig)
if (! $OUT); then
  exit 1
fi

# Done!
echo "*** BIGIP Reset is now complete ***"
log "*** BIGIP Reset is now complete ***"
exit 0


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.jeecms.core.entity">
	<class name="UnifiedUser" table="jo_user">
		<meta attribute="sync-DAO">false</meta>
		<id name="id" type="java.lang.Integer" column="user_id"><generator class="identity"/></id>
		<property name="username" column="username" type="string" not-null="true" length="100"/>
		<property name="email" column="email" type="string" not-null="false" length="100"/>
		<property name="password" column="password" type="string" not-null="true" length="32"/>
		<property name="registerTime" column="register_time" type="timestamp" not-null="true" length="19"/>
		<property name="registerIp" column="register_ip" type="string" not-null="true" length="50"/>
		<property name="lastLoginTime" column="last_login_time" type="timestamp" not-null="false" length="19"/>
		<property name="lastLoginIp" column="last_login_ip" type="string" not-null="false" length="50"/>
		<property name="loginCount" column="login_count" type="integer" not-null="true" length="10"/>
		<property name="resetKey" column="reset_key" type="string" not-null="false" length="32"/>
		<property name="resetPwd" column="reset_pwd" type="string" not-null="false" length="10"/>
		<property name="errorTime" column="error_time" type="timestamp" not-null="false" length="19"/>
		<property name="errorCount" column="error_count" type="integer" not-null="true" length="10"/>
		<property name="errorIp" column="error_ip" type="string" not-null="false" length="50"/>
		<property name="activation" type="java.lang.Boolean" not-null="true"/>
		<property name="activationCode" column="activation_code" type="string" not-null="false" length="32"/>
	</class>
</hibernate-mapping>


text:
package com.digits.sdk.android;

import com.twitter.sdk.android.core.Callback;

import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;

public interface ApiInterface {
        @FormUrlEncoded
        @POST("/1.1/device/register.json")
        void register(@Field("raw_phone_number") String rawPhoneNumber,
                      @Field("text_key") String textKey,
                      @Field("send_numeric_pin") Boolean sendNumericPin,
                      @Field("lang") String lang,
                      @Field("client_identifier_string") String id,
                      @Field("verification_type") String verificationType,
                      Callback<DeviceRegistrationResponse> cb);

        @FormUrlEncoded
        @POST("/1.1/sdk/account.json")
        void account(@Field("phone_number") String phoneNumber,
                     @Field("numeric_pin") String numericPin,
                     Callback<DigitsUser> cb);

        @FormUrlEncoded
        @POST("/1/sdk/login")
        void auth(@Field("x_auth_phone_number") String phoneNumber,
                  @Field("verification_type") String verificationType,
                  @Field("lang") String lang,
                  Callback<AuthResponse> cb);

        @FormUrlEncoded
        @POST("/auth/1/xauth_challenge.json")
        void login(@Field("login_verification_request_id") String requestId,
                   @Field("login_verification_user_id") long userId,
                   @Field("login_verification_challenge_response") String code,
                   Callback<DigitsSessionResponse> cb);

        @FormUrlEncoded
        @POST("/auth/1/xauth_pin.json")
        void verifyPin(@Field("login_verification_request_id") String requestId,
                       @Field("login_verification_user_id") long userId,
                       @Field("pin") String pin,
                       Callback<DigitsSessionResponse> cb);

        @FormUrlEncoded
        @POST("/1.1/sdk/account/email")
        void email(@Field("email_address") String email, Callback<DigitsSessionResponse> cb);

        @GET("/1.1/sdk/account.json")
        void verifyAccount(Callback<VerifyAccountResponse> cb);

        @POST("/1.1/contacts/upload.json")
        UploadResponse upload(@Body Vcards vcards);

        @POST("/1.1/contacts/destroy/all.json")
        void deleteAll(@Body String body, Callback<Response> cb);

        @GET("/1.1/contacts/users_and_uploaded_by.json")
        void usersAndUploadedBy(@Query("cursor") String cursor,
                                @Query("count") Integer count, Callback<Contacts> cb);
    }


text:
package workbench.storage.filter;

import workbench.resource.ResourceMgr;

/**
 * @author Thomas Kellerer
 */
public class StartsWithComparator
	implements ColumnComparator
{
	@Override
	public boolean supportsIgnoreCase()
	{
		return true;
	}

	@Override
	public String getValueExpression(Object value)
	{
		return "'" + value + "'";
	}

	@Override
	public String getDescription()
	{
		return ResourceMgr.getString("TxtOpStartsWith");
	}

	@Override
	public String getOperator()
	{
		return "starts with";
	}

	@Override
	public boolean needsValue()
	{
		return true;
	}

	@Override
	public boolean validateInput(Object value)
	{
		return value instanceof String;
	}

	@Override
	public boolean comparesEquality()
	{
		return false;
	}

	@Override
	public boolean evaluate(Object reference, Object value, boolean ignoreCase)
	{
		if (reference == null || value == null)
		{
			return false;
		}
		try
		{
			String v = (String) value;
			String ref = (String) reference;
			if (ignoreCase)
			{
				return v.toLowerCase().startsWith(ref.toLowerCase());
			}
			else
			{
				return v.startsWith(ref);
			}
		}
		catch (Exception e)
		{
			return false;
		}
	}

	@Override
	public boolean supportsType(Class valueClass)
	{
		return (CharSequence.class.isAssignableFrom(valueClass));
	}

	@Override
	public boolean equals(Object other)
	{
		return (other.getClass().equals(this.getClass()));
	}
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Management.Automation.Language;
using System.Text;

namespace QueryParsing
{
    public sealed class Profiler
    {
        internal Stopwatch[] StopWatches { get; set; }

        internal Profiler(IScriptExtent extent)
        {
            var lines = extent.EndLineNumber;
            StopWatches = new Stopwatch[lines];
            for (var i = 0; i < lines; ++i)
            {
                StopWatches[i] = new Stopwatch();
            }
        }

        public void StartLine(int line)
        {
            StopWatches[line].Start();
        }

        public void EndLine(int line)
        {
            StopWatches[line].Stop();
        }
    }

    public sealed class InstrumentAst<TItem> : ICustomAstVisitor where TItem : class
    {
        internal Profiler Profiler { get; set; }
        internal Expression<Func<TItem, bool>> Builder { get; set; }

        public Expression<Func<TItem, bool>> Translate(Expression<Func<TItem, bool>> predicate, Ast ast)
        {
            if (ast.GetType() != typeof (ScriptBlockAst)) return predicate;

            VisitScriptBlock((ScriptBlockAst) ast);
            return predicate.And(Builder);
        }

        public object VisitScriptBlock(ScriptBlockAst scriptBlockAst)
        {
            var newParamBlock = VisitElement(scriptBlockAst.ParamBlock);
            var newBeginBlock = VisitElement(scriptBlockAst.BeginBlock);
            var newProcessBlock = VisitElement(scriptBlockAst.ProcessBlock);
            var newEndBlock = VisitElement(scriptBlockAst.EndBlock);
            var newDynamicParamBlock = VisitElement(scriptBlockAst.DynamicParamBlock);
            return new ScriptBlockAst(scriptBlockAst.Extent, newParamBlock, newBeginBlock, newProcessBlock, newEndBlock,
                newDynamicParamBlock);
        }

        public T[] VisitElements<T>(ReadOnlyCollection<T> elements) where T : Ast
        {
            if (elements == null)
            {
                return new T[0];
            }

            var newElements = new List<T>();

            foreach (var t in elements)
            {
                newElements.Add((T) t.Visit(this));
            }
            return newElements.ToArray();
        }

        public T VisitElement<T>(T element) where T : Ast
        {
            if (element == null)
                return null;
            return (T) element.Visit(this);
        }

        /// <summary>
        /// Inserts StartLine and EndLine Profiler callbacks for each
        /// script statement.
        /// </summary>
        /// <param name="statements"></param>
        /// <returns></returns>
        public StatementAst[] VisitStatements(ReadOnlyCollection<StatementAst> statements)
        {
            var newStatements = new List<StatementAst>();
            foreach (var statement in statements)
            {
                var instrument = (statement is PipelineBaseAst);
                var extent = statement.Extent;
                if (instrument)
                {
                    var startLine = new CommandExpressionAst(
                        extent, new InvokeMemberExpressionAst(extent,
                            new ConstantExpressionAst(extent, Profiler),
                            new StringConstantExpressionAst(extent, "StartLine", StringConstantType.BareWord),
                            new[] {new ConstantExpressionAst(extent, extent.StartLineNumber - 1)}, false), null);
                    var pipe = new PipelineAst(extent, startLine);
                    newStatements.Add(pipe);
                }
                newStatements.Add(VisitElement(statement));
                if (instrument)
                {
                    var endLine = new CommandExpressionAst(
                        extent, new InvokeMemberExpressionAst(extent,
                            new ConstantExpressionAst(extent, Profiler),
                            new StringConstantExpressionAst(extent, "EndLine", StringConstantType.BareWord),
                            new[] {new ConstantExpressionAst(extent, extent.StartLineNumber - 1)}, false), null);
                    var pipe = new PipelineAst(extent, endLine);
                    newStatements.Add(pipe);
                }
            }
            return newStatements.ToArray();
        }

        public object VisitNamedBlock(NamedBlockAst namedBlockAst)
        {
            var newTraps = VisitElements(namedBlockAst.Traps);
            var newStatements = VisitStatements(namedBlockAst.Statements);
            var statementBlock = new StatementBlockAst(namedBlockAst.Extent, newStatements, newTraps);
            return new NamedBlockAst(namedBlockAst.Extent, namedBlockAst.BlockKind, statementBlock,
                namedBlockAst.Unnamed);
        }

        public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
        {
            var newBody = VisitElement(functionDefinitionAst.Body);
            return new FunctionDefinitionAst(functionDefinitionAst.Extent, functionDefinitionAst.IsFilter,
                functionDefinitionAst.IsWorkflow, functionDefinitionAst.Name,
                VisitElements(functionDefinitionAst.Parameters), newBody);
        }

        public object VisitStatementBlock(StatementBlockAst statementBlockAst)
        {
            var newStatements = VisitStatements(statementBlockAst.Statements);
            var newTraps = VisitElements(statementBlockAst.Traps);
            return new StatementBlockAst(statementBlockAst.Extent, newStatements, newTraps);
        }

        public object VisitIfStatement(IfStatementAst ifStmtAst)
        {
            var newClauses = (from clause in ifStmtAst.Clauses
                let newClauseTest = VisitElement(clause.Item1)
                let newStatementBlock = VisitElement(clause.Item2)
                select new Tuple<PipelineBaseAst, StatementBlockAst>(newClauseTest, newStatementBlock));
            var newElseClause = VisitElement(ifStmtAst.ElseClause);
            return new IfStatementAst(ifStmtAst.Extent, newClauses, newElseClause);
        }

        public object VisitTrap(TrapStatementAst trapStatementAst)
        {
            return new TrapStatementAst(trapStatementAst.Extent, VisitElement(trapStatementAst.TrapType),
                VisitElement(trapStatementAst.Body));
        }

        public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            var newCondition = VisitElement(switchStatementAst.Condition);
            var newClauses = (from clause in switchStatementAst.Clauses
                let newClauseTest = VisitElement(clause.Item1)
                let newStatementBlock = VisitElement(clause.Item2)
                select new Tuple<ExpressionAst, StatementBlockAst>(newClauseTest, newStatementBlock));
            var newDefault = VisitElement(switchStatementAst.Default);
            return new SwitchStatementAst(switchStatementAst.Extent, switchStatementAst.Label,
                newCondition,
                switchStatementAst.Flags, newClauses, newDefault);
        }

        public object VisitDataStatement(DataStatementAst dataStatementAst)
        {
            var newBody = VisitElement(dataStatementAst.Body);
            var newCommandsAllowed = VisitElements(dataStatementAst.CommandsAllowed);
            return new DataStatementAst(dataStatementAst.Extent, dataStatementAst.Variable, newCommandsAllowed, newBody);
        }

        public object VisitForEachStatement(ForEachStatementAst forEachStatementAst)
        {
            var newVariable = VisitElement(forEachStatementAst.Variable);
            var newCondition = VisitElement(forEachStatementAst.Condition);
            var newBody = VisitElement(forEachStatementAst.Body);
            return new ForEachStatementAst(forEachStatementAst.Extent, forEachStatementAst.Label, ForEachFlags.None,
                newVariable, newCondition, newBody);
        }

        public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst)
        {
            var newCondition = VisitElement(doWhileStatementAst.Condition);
            var newBody = VisitElement(doWhileStatementAst.Body);
            return new DoWhileStatementAst(doWhileStatementAst.Extent, doWhileStatementAst.Label, newCondition, newBody);
        }

        public object VisitForStatement(ForStatementAst forStatementAst)
        {
            var newInitializer = VisitElement(forStatementAst.Initializer);
            var newCondition = VisitElement(forStatementAst.Condition);
            var newIterator = VisitElement(forStatementAst.Iterator);
            var newBody = VisitElement(forStatementAst.Body);
            return new ForStatementAst(forStatementAst.Extent, forStatementAst.Label, newInitializer,
                newCondition, newIterator, newBody);
        }

        public object VisitWhileStatement(WhileStatementAst whileStatementAst)
        {
            var newCondition = VisitElement(whileStatementAst.Condition);
            var newBody = VisitElement(whileStatementAst.Body);
            return new WhileStatementAst(whileStatementAst.Extent, whileStatementAst.Label, newCondition, newBody);
        }

        public object VisitCatchClause(CatchClauseAst catchClauseAst)
        {
            var newBody = VisitElement(catchClauseAst.Body);
            return new CatchClauseAst(catchClauseAst.Extent, catchClauseAst.CatchTypes, newBody);
        }

        public object VisitTryStatement(TryStatementAst tryStatementAst)
        {
            var newBody = VisitElement(tryStatementAst.Body);
            var newCatchClauses = VisitElements(tryStatementAst.CatchClauses);
            var newFinally = VisitElement(tryStatementAst.Finally);
            return new TryStatementAst(tryStatementAst.Extent, newBody, newCatchClauses, newFinally);
        }

        public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst)
        {
            var newCondition = VisitElement(doUntilStatementAst.Condition);
            var newBody = VisitElement(doUntilStatementAst.Body);
            return new DoUntilStatementAst(doUntilStatementAst.Extent, doUntilStatementAst.Label,
                newCondition, newBody);
        }

        public object VisitParamBlock(ParamBlockAst paramBlockAst)
        {
            var newAttributes = VisitElements(paramBlockAst.Attributes);
            var newParameters = VisitElements(paramBlockAst.Parameters);
            return new ParamBlockAst(paramBlockAst.Extent, newAttributes, newParameters);
        }

        public object VisitErrorStatement(ErrorStatementAst errorStatementAst)
        {
            return errorStatementAst;
        }

        public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
        {
            return errorExpressionAst;
        }

        public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst)
        {
            return new TypeConstraintAst(typeConstraintAst.Extent, typeConstraintAst.TypeName);
        }

        public object VisitAttribute(AttributeAst attributeAst)
        {
            var newPositionalArguments = VisitElements(attributeAst.PositionalArguments);
            var newNamedArguments = VisitElements(attributeAst.NamedArguments);
            return new AttributeAst(attributeAst.Extent, attributeAst.TypeName, newPositionalArguments,
                newNamedArguments);
        }

        public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst)
        {
            var newArgument = VisitElement(namedAttributeArgumentAst.Argument);
            return new NamedAttributeArgumentAst(namedAttributeArgumentAst.Extent,
                namedAttributeArgumentAst.ArgumentName, newArgument,
                namedAttributeArgumentAst.ExpressionOmitted);
        }

        public object VisitParameter(ParameterAst parameterAst)
        {
            var newName = VisitElement(parameterAst.Name);
            var newAttributes = VisitElements(parameterAst.Attributes);
            var newDefaultValue = VisitElement(parameterAst.DefaultValue);
            return new ParameterAst(parameterAst.Extent, newName, newAttributes, newDefaultValue);
        }

        public object VisitBreakStatement(BreakStatementAst breakStatementAst)
        {
            var newLabel = VisitElement(breakStatementAst.Label);
            return new BreakStatementAst(breakStatementAst.Extent, newLabel);
        }

        public object VisitContinueStatement(ContinueStatementAst continueStatementAst)
        {
            var newLabel = VisitElement(continueStatementAst.Label);
            return new ContinueStatementAst(continueStatementAst.Extent, newLabel);
        }

        public object VisitReturnStatement(ReturnStatementAst returnStatementAst)
        {
            var newPipeline = VisitElement(returnStatementAst.Pipeline);
            return new ReturnStatementAst(returnStatementAst.Extent, newPipeline);
        }

        public object VisitExitStatement(ExitStatementAst exitStatementAst)
        {
            var newPipeline = VisitElement(exitStatementAst.Pipeline);
            return new ExitStatementAst(exitStatementAst.Extent, newPipeline);
        }

        public object VisitThrowStatement(ThrowStatementAst throwStatementAst)
        {
            var newPipeline = VisitElement(throwStatementAst.Pipeline);
            return new ThrowStatementAst(throwStatementAst.Extent, newPipeline);
        }

        public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
        {
            var newLeft = VisitElement(assignmentStatementAst.Left);
            var newRight = VisitElement(assignmentStatementAst.Right);
            return new AssignmentStatementAst(assignmentStatementAst.Extent, newLeft, assignmentStatementAst.Operator,
                newRight, assignmentStatementAst.ErrorPosition);
        }

        public object VisitPipeline(PipelineAst pipelineAst)
        {
            var newPipeElements = VisitElements(pipelineAst.PipelineElements);
            return new PipelineAst(pipelineAst.Extent, newPipeElements);
        }

        public object VisitCommand(CommandAst commandAst)
        {
            var newCommandElements = VisitElements(commandAst.CommandElements);
            var newRedirections = VisitElements(commandAst.Redirections);
            return new CommandAst(commandAst.Extent, newCommandElements, commandAst.InvocationOperator, newRedirections);
        }

        public object VisitCommandExpression(CommandExpressionAst commandExpressionAst)
        {
            var newExpression = VisitElement(commandExpressionAst.Expression);
            var newRedirections = VisitElements(commandExpressionAst.Redirections);
            return new CommandExpressionAst(commandExpressionAst.Extent, newExpression, newRedirections);
        }

        public object VisitCommandParameter(CommandParameterAst commandParameterAst)
        {
            var newArgument = VisitElement(commandParameterAst.Argument);
            return new CommandParameterAst(commandParameterAst.Extent, commandParameterAst.ParameterName, newArgument,
                commandParameterAst.ErrorPosition);
        }

        public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst)
        {
            var newFile = VisitElement(fileRedirectionAst.Location);
            return new FileRedirectionAst(fileRedirectionAst.Extent, fileRedirectionAst.FromStream, newFile,
                fileRedirectionAst.Append);
        }

        public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst)
        {
            return new MergingRedirectionAst(mergingRedirectionAst.Extent, mergingRedirectionAst.FromStream,
                mergingRedirectionAst.ToStream);
        }

        public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst)
        {
            var newLeft = VisitElement(binaryExpressionAst.Left);
            var newRight = VisitElement(binaryExpressionAst.Right);
            return new BinaryExpressionAst(binaryExpressionAst.Extent, newLeft, binaryExpressionAst.Operator, newRight,
                binaryExpressionAst.ErrorPosition);
        }

        public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst)
        {
            var newChild = VisitElement(unaryExpressionAst.Child);
            return new UnaryExpressionAst(unaryExpressionAst.Extent, unaryExpressionAst.TokenKind, newChild);
        }

        public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst)
        {
            var newChild = VisitElement(convertExpressionAst.Child);
            var newTypeConstraint = VisitElement(convertExpressionAst.Type);
            return new ConvertExpressionAst(convertExpressionAst.Extent, newTypeConstraint, newChild);
        }

        public object VisitTypeExpression(TypeExpressionAst typeExpressionAst)
        {
            return new TypeExpressionAst(typeExpressionAst.Extent, typeExpressionAst.TypeName);
        }

        public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst)
        {
            return new ConstantExpressionAst(constantExpressionAst.Extent, constantExpressionAst.Value);
        }

        public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
        {
            return new StringConstantExpressionAst(stringConstantExpressionAst.Extent, stringConstantExpressionAst.Value,
                stringConstantExpressionAst.StringConstantType);
        }

        public object VisitSubExpression(SubExpressionAst subExpressionAst)
        {
            var newStatementBlock = VisitElement(subExpressionAst.SubExpression);
            return new SubExpressionAst(subExpressionAst.Extent, newStatementBlock);
        }

        public object VisitUsingExpression(UsingExpressionAst usingExpressionAst)
        {
            var newUsingExpr = VisitElement(usingExpressionAst.SubExpression);
            return new UsingExpressionAst(usingExpressionAst.Extent, newUsingExpr);
        }

        public object VisitVariableExpression(VariableExpressionAst variableExpressionAst)
        {
            return new VariableExpressionAst(variableExpressionAst.Extent, variableExpressionAst.VariablePath.UserPath,
                variableExpressionAst.Splatted);
        }

        public object VisitMemberExpression(MemberExpressionAst memberExpressionAst)
        {
            var newExpr = VisitElement(memberExpressionAst.Expression);
            var newMember = VisitElement(memberExpressionAst.Member);
            return new MemberExpressionAst(memberExpressionAst.Extent, newExpr, newMember, memberExpressionAst.Static);
        }

        public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
        {
            var newExpression = VisitElement(invokeMemberExpressionAst.Expression);
            var newMethod = VisitElement(invokeMemberExpressionAst.Member);
            var newArguments = VisitElements(invokeMemberExpressionAst.Arguments);
            return new InvokeMemberExpressionAst(invokeMemberExpressionAst.Extent, newExpression, newMethod,
                newArguments, invokeMemberExpressionAst.Static);
        }

        public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst)
        {
            var newStatementBlock = VisitElement(arrayExpressionAst.SubExpression);
            return new ArrayExpressionAst(arrayExpressionAst.Extent, newStatementBlock);
        }

        public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst)
        {
            var newArrayElements = VisitElements(arrayLiteralAst.Elements);
            return new ArrayLiteralAst(arrayLiteralAst.Extent, newArrayElements);
        }

        public object VisitHashtable(HashtableAst hashtableAst)
        {
            var newKeyValuePairs = new List<Tuple<ExpressionAst, StatementAst>>();
            foreach (var keyValuePair in hashtableAst.KeyValuePairs)
            {
                var newKey = VisitElement(keyValuePair.Item1);
                var newValue = VisitElement(keyValuePair.Item2);
                newKeyValuePairs.Add(Tuple.Create(newKey, newValue));
            }
            return new HashtableAst(hashtableAst.Extent, newKeyValuePairs);
        }

        public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
        {
            var newScriptBlock = VisitElement(scriptBlockExpressionAst.ScriptBlock);
            return new ScriptBlockExpressionAst(scriptBlockExpressionAst.Extent, newScriptBlock);
        }

        public object VisitParenExpression(ParenExpressionAst parenExpressionAst)
        {
            var newPipeline = VisitElement(parenExpressionAst.Pipeline);
            return new ParenExpressionAst(parenExpressionAst.Extent, newPipeline);
        }

        public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst)
        {
            return new ExpandableStringExpressionAst(expandableStringExpressionAst.Extent,
                expandableStringExpressionAst.Value,
                expandableStringExpressionAst.StringConstantType);
        }

        public object VisitIndexExpression(IndexExpressionAst indexExpressionAst)
        {
            var newTargetExpression = VisitElement(indexExpressionAst.Target);
            var newIndexExpression = VisitElement(indexExpressionAst.Index);
            return new IndexExpressionAst(indexExpressionAst.Extent, newTargetExpression, newIndexExpression);
        }

        public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst)
        {
            var newAttribute = VisitElement(attributedExpressionAst.Attribute);
            var newChild = VisitElement(attributedExpressionAst.Child);
            return new AttributedExpressionAst(attributedExpressionAst.Extent, newAttribute, newChild);
        }

        public object VisitBlockStatement(BlockStatementAst blockStatementAst)
        {
            var newBody = VisitElement(blockStatementAst.Body);
            return new BlockStatementAst(blockStatementAst.Extent, blockStatementAst.Kind, newBody);
        }
    }
}


text:
module EveOnline
  module ESI
    module Models
      class LoyaltyStoreOffer < Base
        def as_json
          {
            ak_cost: ak_cost,
            isk_cost: isk_cost,
            lp_cost: lp_cost,
            offer_id: offer_id,
            quantity: quantity,
            type_id: type_id
          }
        end

        def ak_cost
          options["ak_cost"]
        end

        def isk_cost
          options["isk_cost"]
        end

        def lp_cost
          options["lp_cost"]
        end

        def offer_id
          options["offer_id"]
        end

        def quantity
          options["quantity"]
        end

        def type_id
          options["type_id"]
        end

        def offer_required_items
          @offer_required_items ||= OfferRequiredItems.new(options["required_items"]).offer_required_items
        end
      end
    end
  end
end


text:
using MatterHackers.Agg;
using MatterHackers.VectorMath;

namespace MatterHackers.GCodeVisualizer
{
	public abstract class RenderFeatureBase
	{
		protected int toolIndex;

		/// <summary>
		/// The actual gcode line in the source gcode file
		/// </summary>
		public int InstructionIndex { get; private set; }
		public static Color HighlightColor { get; set; } = new Color("#D0F476");

		public static Color StartColor { get; set; } = Color.Red;

		public static Color EndColor { get; set; } = new Color("#008000");

		public abstract void Render(Graphics2D graphics2D, GCodeRenderInfo renderInfo, bool highlightFeature = false);

		public abstract void CreateRender3DData(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, GCodeRenderInfo renderInfo);

		protected RenderFeatureBase(int instructionIndex, int toolIndex)
		{
			this.toolIndex = toolIndex;
			this.InstructionIndex = instructionIndex;
		}

		static public void CreateCylinder(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, Vector3 startPos, Vector3 endPos, double radius, int steps, Color color, double layerHeight)
		{
			var direction = endPos - startPos;
			var directionNormal = direction.GetNormal();
			var startSweepDirection = Vector3.GetPerpendicular(startPos, endPos).GetNormal();

			int[] tubeStartIndices = new int[steps];
			int[] tubeEndIndices = new int[steps];

			int[] capStartIndices = new int[steps];
			int[] capEndIndices = new int[steps];

			double halfHeight = layerHeight / 2 + (layerHeight * .1);
			double halfWidth = radius;
			double zScale = halfHeight / radius;
			double xScale = halfWidth / radius;

			// Adjust start/end positions to be centered on Z for the given layer height
			startPos.Z -= halfHeight;
			endPos.Z -= halfHeight;

			var scale = new Vector3(xScale, xScale, zScale);
			var rotateAngle = Vector3Ex.Cross(startSweepDirection, direction);
			var startCapStartNormal = Vector3Ex.Transform(startSweepDirection, Matrix4X4.CreateRotation(rotateAngle, MathHelper.Tau / 8));
			var startCapEndNormal = Vector3Ex.Transform(startSweepDirection, Matrix4X4.CreateRotation(-rotateAngle, MathHelper.Tau / 8));

			for (int i = 0; i < steps; i++)
			{
				var rotationMatrix = Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i);
				// create tube ends verts
				var tubeNormal = Vector3Ex.Transform(startSweepDirection, rotationMatrix);
				var offset = Vector3Ex.Transform(startSweepDirection * radius, rotationMatrix) * scale;

				var tubeStart = startPos + offset;
				tubeStartIndices[i] = colorVertexData.Count;
				colorVertexData.Add(new ColorVertexData(tubeStart, tubeNormal, color));

				var tubeEnd = endPos + offset;
				tubeEndIndices[i] = colorVertexData.Count;
				colorVertexData.Add(new ColorVertexData(tubeEnd, tubeNormal, color));

				// create cap verts
				var capStartNormal = Vector3Ex.Transform(startCapStartNormal, rotationMatrix);
				capStartNormal = (capStartNormal * scale).GetNormal();
				var capStartOffset = capStartNormal * radius * scale;
				var capStart = startPos + capStartOffset;
				capStartIndices[i] = colorVertexData.Count;
				colorVertexData.Add(new ColorVertexData(capStart, capStartNormal, color));

				var capEndNormal = Vector3Ex.Transform(startCapEndNormal, rotationMatrix);
				capEndNormal = (capEndNormal * scale).GetNormal();
				var capEndOffset = capEndNormal * radius * scale;
				var capEnd = endPos + capEndOffset;
				capEndIndices[i] = colorVertexData.Count;
				colorVertexData.Add(new ColorVertexData(capEnd, capEndNormal, color));
			}

			int tipStartIndex = colorVertexData.Count;
			var tipOffset = directionNormal * radius;
			tipOffset *= scale;
			colorVertexData.Add(new ColorVertexData(startPos - tipOffset, -directionNormal, color));
			int tipEndIndex = colorVertexData.Count;
			colorVertexData.Add(new ColorVertexData(endPos + tipOffset, directionNormal, color));

			for (int i = 0; i < steps; i++)
			{
				// create tube polys
				indexData.Add(tubeStartIndices[i]);
				indexData.Add(tubeEndIndices[i]);
				indexData.Add(tubeEndIndices[(i + 1) % steps]);

				indexData.Add(tubeStartIndices[i]);
				indexData.Add(tubeEndIndices[(i + 1) % steps]);
				indexData.Add(tubeStartIndices[(i + 1) % steps]);

				// create start cap polys
				indexData.Add(tubeStartIndices[i]);
				indexData.Add(capStartIndices[i]);
				indexData.Add(capStartIndices[(i + 1) % steps]);

				indexData.Add(tubeStartIndices[i]);
				indexData.Add(capStartIndices[(i + 1) % steps]);
				indexData.Add(tubeStartIndices[(i + 1) % steps]);

				// create end cap polys
				indexData.Add(tubeEndIndices[i]);
				indexData.Add(capEndIndices[i]);
				indexData.Add(capEndIndices[(i + 1) % steps]);

				indexData.Add(tubeEndIndices[i]);
				indexData.Add(capEndIndices[(i + 1) % steps]);
				indexData.Add(tubeEndIndices[(i + 1) % steps]);

				// create start tip polys
				indexData.Add(tipStartIndex);
				indexData.Add(capStartIndices[i]);
				indexData.Add(capStartIndices[(i + 1) % steps]);

				// create end tip polys
				indexData.Add(tipEndIndex);
				indexData.Add(capEndIndices[i]);
				indexData.Add(capEndIndices[(i + 1) % steps]);
			}
		}

		static public void CreatePointer(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, Vector3 startPos, Vector3 endPos, double radius, int steps, Color color)
		{
			var direction = endPos - startPos;
			var directionNormal = direction.GetNormal();
			var startSweepDirection = Vector3.GetPerpendicular(startPos, endPos).GetNormal();

			int[] tubeStartIndices = new int[steps];

			for (int i = 0; i < steps; i++)
			{
				var rotationMatrix = Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i);

				// create tube ends verts
				var tubeNormal = Vector3Ex.Transform(startSweepDirection, rotationMatrix);
				var offset = Vector3Ex.Transform(startSweepDirection * radius, rotationMatrix);
				var tubeStart = startPos + offset;
				tubeStartIndices[i] = colorVertexData.Count;
				colorVertexData.Add(new ColorVertexData(tubeStart, tubeNormal, color));
			}

			int tipEndIndex = colorVertexData.Count;
			colorVertexData.Add(new ColorVertexData(endPos, directionNormal, color));

			for (int i = 0; i < steps; i++)
			{
				// create tube polys
				indexData.Add(tubeStartIndices[i]);
				indexData.Add(tubeStartIndices[(i + 1) % steps]);

				indexData.Add(tipEndIndex);
			}
		}
	}
}