text:
@implementation EventManager

+(BOOL)clearData{
    BOOL result = YES;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSArray* events = nil;
    NSPredicate* predicate = nil;
    NSFetchRequest *request = nil;
    NSEntityDescription* entityDescription = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    // Clear event data
    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    events = [context executeFetchRequest:request error:&error];

    for (Event* event in events) {
        [context deleteObject:event];
    }

    [context save:&error];

    if (error) {
        result = NO;
    }

    // Clear calendar data
    entityDescription = [NSEntityDescription entityForName:CALENDAR_ENTITY inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    events = [context executeFetchRequest:request error:&error];

    for (MyCalendar* calendar in events) {
        [context deleteObject:calendar];
    }

    [context save:&error];

    if (error) {
        result = NO;
    }

    return result;
}

+(NSArray*)eventsByEventType:(EventType)eventType{
    NSArray* events = nil;
    NSPredicate* predicate = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSFetchRequest *request = nil;
    NSSortDescriptor* dateDescr = nil;
    NSSortDescriptor* timeDescr = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];

    predicate = [NSPredicate predicateWithFormat:@"eventType = %@", [NSNumber numberWithInt:eventType]];//@"%@ = %d", EVENT_ID_PROPERTY, [eventId intValue]];

    [request setEntity:entityDescription];
    [request setPredicate:predicate];

    events = [context executeFetchRequest:request error:&error];

    dateDescr = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    timeDescr = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];

    events = [events sortedArrayUsingDescriptors:@[dateDescr, timeDescr]];

    return ([events count] > 0 ? events : nil);
}

+(BOOL)clearDataByEventType:(EventType)eventType{
    BOOL result = YES;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    for (Event* event in [self eventsByEventType:eventType]) {
        [context deleteObject:event];
    }

    [context save:&error];

    if (error) {
        result = NO;
    }

    return result;
}

#pragma mark - Meeting points methods

+(BOOL)generateMeetingPoints{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    //if (![self meetingPoints]) {
    [self clearMeetingPoints];

        appDelegate = [[UIApplication sharedApplication] delegate];

        context = [appDelegate managedObjectContext];

        entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

        fileContents = [[NSBundle mainBundle] pathForResource:@"meetingPoints" ofType:@"json"];

        jsonEvents = [[NSMutableArray alloc] init];

        fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

        if (error) {
            result = NO;
        } else{
            data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

            jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {
                result = NO;
            } else{
                events = [jsonDict objectForKey:@"events"];

                formatter = [[NSDateFormatter alloc] init];

                for (NSObject* object in events) {
                    event = nil;

                    event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                    event.eventType = [NSNumber numberWithInt:EVENT_TYPE_MEETING_POINT];

                    event.name = [object valueForKey:@"summary"];

                    [formatter setDateFormat:@"dd/MM/yyyy"];

                    event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                    [formatter setDateFormat:@"HH:mm"];

                    event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                    event.place = [object valueForKey:@"place"];
                    event.summary = [object valueForKey:@"promotion"];

                    [context save:&error];
                }

            }
        }

    //}

    return result;
}

+(NSArray*)meetingPoints{
    return [self eventsByEventType:EVENT_TYPE_MEETING_POINT];
}

+(BOOL)clearMeetingPoints{
    return [self clearDataByEventType:EVENT_TYPE_MEETING_POINT];
}

#pragma mark - Workshop methods

+(BOOL)generateWorkshops{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    if (![self workshops]) {
        appDelegate = [[UIApplication sharedApplication] delegate];

        context = [appDelegate managedObjectContext];

        entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

        fileContents = [[NSBundle mainBundle] pathForResource:@"workshops" ofType:@"json"];

        jsonEvents = [[NSMutableArray alloc] init];

        fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

        if (error) {
            result = NO;
        } else{
            data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

            jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {
                result = NO;
            } else{
                events = [jsonDict objectForKey:@"events"];

                formatter = [[NSDateFormatter alloc] init];

                for (NSObject* object in events) {
                    event = nil;

                    event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                    event.eventType = [NSNumber numberWithInt:EVENT_TYPE_WORKSHOP];

                    event.name = [object valueForKey:@"name"];
                    event.summary = [NSString stringWithFormat:@"Ministrante: %@\n\n%@", [object valueForKey:@"owner"], [object valueForKey:@"summary"]];
                    event.sheet = [NSString stringWithFormat:@"%@ - %@", [object valueForKey:@"date"], [object valueForKey:@"time"]];

                    event.place = [object valueForKey:@"place"];
                    event.duration = [object valueForKey:@"duration"];
                    event.vacancys = [object valueForKey:@"vacancys"];
                    event.target = [object valueForKey:@"target"];
                    event.requirement = [object valueForKey:@"requirements"];

                    [context save:&error];
                }

            }
        }

    }

    return result;
}

+(NSArray*)workshops{
    return [self eventsByEventType:EVENT_TYPE_WORKSHOP];
}

+(BOOL)clearWorkshops{
    return [self clearDataByEventType:EVENT_TYPE_WORKSHOP];
}

#pragma mark - Storytelling methods

+(BOOL)generateStorytellings{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    if (![self storytellings]) {
        appDelegate = [[UIApplication sharedApplication] delegate];

        context = [appDelegate managedObjectContext];

        entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

        fileContents = [[NSBundle mainBundle] pathForResource:@"storytelling" ofType:@"json"];

        jsonEvents = [[NSMutableArray alloc] init];

        fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

        if (error) {
            result = NO;
        } else{
            data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

            jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {
                result = NO;
            } else{
                events = [jsonDict objectForKey:@"events"];

                formatter = [[NSDateFormatter alloc] init];

                for (NSObject* object in events) {
                    event = nil;

                    event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                    event.eventType = [NSNumber numberWithInt:EVENT_TYPE_STORYTELLING];

                    event.name = [object valueForKey:@"name"];
                    event.summary =  [object valueForKey:@"summary"];
                    event.sheet = [object valueForKey:@"sheet"];

                    [formatter setDateFormat:@"dd/MM/yyyy"];

                    event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                    [formatter setDateFormat:@"HH:mm"];

                    event.time = [formatter dateFromString:[object valueForKey:@"time"]];

                    event.place = [object valueForKey:@"place"];
                    event.duration = [object valueForKey:@"duration"];

                    [context save:&error];
                }

            }
        }

    }

    return result;
}

+(NSArray*)storytellings{
    return [self eventsByEventType:EVENT_TYPE_STORYTELLING];
}

+(BOOL)clearStorytellings{
    return [self clearDataByEventType:EVENT_TYPE_STORYTELLING];
}

#pragma mark - Specials methods

+(BOOL)generateExhibition{
    return [self generateAdult];// && [self generateChildren] && [self generateStreet] && [self generateUnicamp];
}

+(BOOL)generateAdult{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    if (![self exhibitions]) {
        appDelegate = [[UIApplication sharedApplication] delegate];

        context = [appDelegate managedObjectContext];

        entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

        fileContents = [[NSBundle mainBundle] pathForResource:@"adultShow" ofType:@"json"];

        jsonEvents = [[NSMutableArray alloc] init];

        fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

        if (error) {
            result = NO;
        } else{
            data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

            jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {
                result = NO;
            } else{
                events = [jsonDict objectForKey:@"events"];

                formatter = [[NSDateFormatter alloc] init];

                for (NSObject* object in events) {
                    event = nil;

                    event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                    event.eventType = [NSNumber numberWithInt:EVENT_TYPE_EXHIBITION];

                    event.name = [object valueForKey:@"name"];

                    [formatter setDateFormat:@"dd/MM/yyyy"];

                    event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                    [formatter setDateFormat:@"HH:mm"];

                    if ([object valueForKey:@"time"] && ((NSString*)[object valueForKey:@"time"]).length > 0) {
                        event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                    }

                    event.place = [object valueForKey:@"place"];
                    event.summary = [object valueForKey:@"summary"];
                    event.sheet = [object valueForKey:@"sheet"];

                    event.duration = [object valueForKey:@"duration"];
                    event.rating = [object valueForKey:@"rating"];
                    event.vacancys = @"Espetáculo Adulto";

                    [context save:&error];
                }

            }

        }

        result = result && [self generateChildren];

    }

    return result;
}

+(BOOL)generateChildren{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

    fileContents = [[NSBundle mainBundle] pathForResource:@"childrenShow" ofType:@"json"];

    jsonEvents = [[NSMutableArray alloc] init];

    fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

    if (error) {
        result = NO;
    } else{
        data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

        jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if (error) {
            result = NO;
        } else{
            events = [jsonDict objectForKey:@"events"];

            formatter = [[NSDateFormatter alloc] init];

            for (NSObject* object in events) {
                event = nil;

                event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                event.eventType = [NSNumber numberWithInt:EVENT_TYPE_EXHIBITION];

                event.name = [object valueForKey:@"name"];

                [formatter setDateFormat:@"dd/MM/yyyy"];

                event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                [formatter setDateFormat:@"HH:mm"];

                if ([object valueForKey:@"time"] && ((NSString*)[object valueForKey:@"time"]).length > 0) {
                    event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                }

                event.place = [object valueForKey:@"place"];
                event.summary = [object valueForKey:@"summary"];
                event.sheet = [object valueForKey:@"sheet"];

                event.duration = [object valueForKey:@"duration"];
                event.rating = [object valueForKey:@"rating"];
                event.vacancys = @"Espetáculo Infantil";

                [context save:&error];
            }

        }

    }

    result = result && [self generateStreet];

    return result;
}

+(BOOL)generateStreet{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

    fileContents = [[NSBundle mainBundle] pathForResource:@"streetShow" ofType:@"json"];

    jsonEvents = [[NSMutableArray alloc] init];

    fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

    if (error) {
        result = NO;
    } else{
        data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

        jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if (error) {
            result = NO;
        } else{
            events = [jsonDict objectForKey:@"events"];

            formatter = [[NSDateFormatter alloc] init];

            for (NSObject* object in events) {
                event = nil;

                event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                event.eventType = [NSNumber numberWithInt:EVENT_TYPE_EXHIBITION];

                event.name = [object valueForKey:@"name"];

                [formatter setDateFormat:@"dd/MM/yyyy"];

                event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                [formatter setDateFormat:@"HH:mm"];

                if ([object valueForKey:@"time"] && ((NSString*)[object valueForKey:@"time"]).length > 0) {
                    event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                }

                event.place = [object valueForKey:@"place"];
                event.summary = [object valueForKey:@"summary"];
                event.sheet = [object valueForKey:@"sheet"];

                event.duration = [object valueForKey:@"duration"];
                event.rating = [object valueForKey:@"rating"];
                event.vacancys = @"Espetáculo de Rua";

                [context save:&error];
            }

        }

    }

    result = result && [self generateUnicamp];

    return result;
}

+(BOOL)generateUnicamp{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

    fileContents = [[NSBundle mainBundle] pathForResource:@"unicamp" ofType:@"json"];

    jsonEvents = [[NSMutableArray alloc] init];

    fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

    if (error) {
        result = NO;
    } else{
        data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

        jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if (error) {
            result = NO;
        } else{
            events = [jsonDict objectForKey:@"events"];

            formatter = [[NSDateFormatter alloc] init];

            for (NSObject* object in events) {
                event = nil;

                event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                event.eventType = [NSNumber numberWithInt:EVENT_TYPE_EXHIBITION];

                event.name = [object valueForKey:@"name"];

                [formatter setDateFormat:@"dd/MM/yyyy"];

                event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                [formatter setDateFormat:@"HH:mm"];

                if ([object valueForKey:@"time"] && ((NSString*)[object valueForKey:@"time"]).length > 0) {
                    event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                }

                event.place = [object valueForKey:@"place"];
                event.summary = [object valueForKey:@"summary"];
                event.sheet = [object valueForKey:@"sheet"];

                event.duration = [object valueForKey:@"duration"];
                event.rating = [object valueForKey:@"rating"];
                event.vacancys = @"Mostra UNICAMP";

                [context save:&error];
            }

        }

    }

    return result;
}

+(NSArray*)exhibitions{
    return [self eventsByEventType:EVENT_TYPE_EXHIBITION];
}

+(BOOL)clearExhibition{
    return [self clearDataByEventType:EVENT_TYPE_EXHIBITION];
}

#pragma mark - Specials methods

+(BOOL)generateSpecials{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    if (![self specials]) {
        appDelegate = [[UIApplication sharedApplication] delegate];

        context = [appDelegate managedObjectContext];

        entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

        fileContents = [[NSBundle mainBundle] pathForResource:@"specialShow" ofType:@"json"];

        jsonEvents = [[NSMutableArray alloc] init];

        fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

        if (error) {
            result = NO;
        } else{
            data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

            jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {
                result = NO;
            } else{
                events = [jsonDict objectForKey:@"events"];

                formatter = [[NSDateFormatter alloc] init];

                for (NSObject* object in events) {
                    event = nil;

                    event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                    event.eventType = [NSNumber numberWithInt:EVENT_TYPE_SPECIAL];

                    event.name = [object valueForKey:@"name"];

                    [formatter setDateFormat:@"dd/MM/yyyy"];

                    event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                    [formatter setDateFormat:@"HH:mm"];

                    if ([object valueForKey:@"time"] && ((NSString*)[object valueForKey:@"time"]).length > 0) {
                        event.time = [formatter dateFromString:[object valueForKey:@"time"]];
                    }

                    event.place = [object valueForKey:@"place"];
                    //event.summary = [object valueForKey:@"promotion"];
                    event.summary = [object valueForKey:@"summary"];
                    event.sheet = [object valueForKey:@"sheet"];

                    event.duration = [object valueForKey:@"duration"];
                    event.rating = [object valueForKey:@"rating"];
                    event.vacancys = [object valueForKey:@"category"];

                    [context save:&error];
                }

            }

            result = result && [self generateSpecialsPocket];
        }

    }

    return result;
}

+(BOOL)generateSpecialsPocket{
    BOOL result = YES;
    NSArray* events = nil;
    NSMutableArray* jsonEvents = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSString* fileContents = nil;
    NSDictionary* jsonDict = nil;
    NSData* data = nil;
    Event* event = nil;
    NSDateFormatter* formatter = nil;

    //if (![self specials]) {
    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:EVENT_ENTITY inManagedObjectContext:context];

    fileContents = [[NSBundle mainBundle] pathForResource:@"pocketShow" ofType:@"json"];

    jsonEvents = [[NSMutableArray alloc] init];

    fileContents = [NSString stringWithContentsOfFile:fileContents encoding:NSUTF8StringEncoding error:&error];

    if (error) {
        result = NO;
    } else{
        data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

        jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if (error) {
            result = NO;
        } else{
            events = [jsonDict objectForKey:@"events"];

            formatter = [[NSDateFormatter alloc] init];

            for (NSObject* object in events) {
                event = nil;

                event = [[Event alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

                event.eventType = [NSNumber numberWithInt:EVENT_TYPE_SPECIAL];

                event.name = [object valueForKey:@"name"];

                [formatter setDateFormat:@"dd/MM/yyyy"];

                event.date = [formatter dateFromString:[object valueForKey:@"date"]];

                [formatter setDateFormat:@"HH:mm"];

                event.time = [formatter dateFromString:[object valueForKey:@"time"]];

                event.place = [NSString stringWithFormat:@"%@ - %@", [object valueForKey:@"place"], [object valueForKey:@"address"]];
                event.summary = [NSString stringWithFormat:@"Ministrante: %@\n\n%@", [object valueForKey:@"owner"], [object valueForKey:@"summary"]];
                event.sheet = [object valueForKey:@"sheet"];

                event.duration = [object valueForKey:@"duration"];
                event.rating = [object valueForKey:@"rating"];
                event.vacancys = @"Mostra de Bolso";

                [context save:&error];
            }

        }
    }

    //}

    return result;
}

+(NSArray*)specials{
    return [self eventsByEventType:EVENT_TYPE_SPECIAL];
}

+(BOOL)clearSpecials{
    return [self clearDataByEventType:EVENT_TYPE_SPECIAL];
}

#pragma mark - My Calendar methods

+(BOOL)isEventFavorited:(Event*)event{
    BOOL result = NO;

    NSArray* events = nil;
    NSPredicate* predicate = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSFetchRequest *request = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:CALENDAR_ENTITY inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];

    predicate = [NSPredicate predicateWithFormat:@"myEvent = %@", event];//@"%@ = %d", EVENT_ID_PROPERTY, [eventId intValue]];

    [request setEntity:entityDescription];
    [request setPredicate:predicate];

    events = [context executeFetchRequest:request error:&error];

    result = ([events count] > 0 ? YES : NO);

    return result;
}

+(void)setEventFavorited:(Event*)event isFavorited:(BOOL)isFavorited{
    NSArray* events = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    MyCalendar* calendar = nil;
    NSFetchRequest *request = nil;
    NSPredicate* predicate = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:CALENDAR_ENTITY inManagedObjectContext:context];

    if (isFavorited) {
        calendar = [[MyCalendar alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];

        calendar.myEvent = event;

        [context save:&error];

    } else{
        request = [[NSFetchRequest alloc] init];

        predicate = [NSPredicate predicateWithFormat:@"myEvent = %@", event];//@"%@ = %d", EVENT_ID_PROPERTY, [eventId intValue]];

        [request setEntity:entityDescription];
        [request setPredicate:predicate];

        events = [context executeFetchRequest:request error:&error];

        for (NSManagedObject* event in events) {
            [context deleteObject:event];

            [context save:&error];
        }
    }

}

+(NSArray*)myCalendarEvents{
    NSArray* events = nil;
    NSPredicate* predicate = nil;
    NSError *error = nil;
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSEntityDescription *entityDescription = nil;
    NSFetchRequest *request = nil;
    NSSortDescriptor* dateDescr = nil;
    NSSortDescriptor* timeDescr = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    entityDescription = [NSEntityDescription entityForName:CALENDAR_ENTITY inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];

    //predicate = [NSPredicate predicateWithFormat:@"eventType = %@", [NSNumber numberWithInt:eventType]];//@"%@ = %d", EVENT_ID_PROPERTY, [eventId intValue]];

    [request setEntity:entityDescription];
    //[request setPredicate:predicate];

    events = [context executeFetchRequest:request error:&error];

    dateDescr = [[NSSortDescriptor alloc] initWithKey:@"myEvent.date" ascending:YES];
    timeDescr = [[NSSortDescriptor alloc] initWithKey:@"myEvent.time" ascending:YES];

    events = [events sortedArrayUsingDescriptors:@[dateDescr, timeDescr]];

    return ([events count] > 0 ? events : nil);
}

#pragma mark - POG

+(void)fixEvents{
    AppDelegate *appDelegate = nil;
    NSManagedObjectContext *context = nil;
    NSError* error = nil;
    NSDateFormatter* formatter = nil;

    appDelegate = [[UIApplication sharedApplication] delegate];

    context = [appDelegate managedObjectContext];

    formatter = [[NSDateFormatter alloc] init];

    for (Event* e in [self eventsByEventType:EVENT_TYPE_EXHIBITION]) {
        if ([e.name containsString:@"Sala de Banho"]) {
            if ([e.place containsString:@"Terminal"]) {
                e.place = @"Terminal Barão Geraldo";
            } else{
                e.place = @"Coreto da Praça Castro Mendes";
            }

            [context save:&error];
        }
    }

    for (Event* e in [self eventsByEventType:EVENT_TYPE_SPECIAL]) {
        if ([e.name containsString:@"Quem com porcos se mistura"]) {
            e.name = @"Quem com porcos se mistura, farelo come, Grupo VÃO (São Paulo/SP)";

            [context save:&error];

        } else if ([e.name containsString:@"A natureza da vida"]){
            [formatter setDateFormat:@"HH:mm"];

            e.time = [formatter dateFromString:@"17:30"];
            e.place = @"Ciclo Básico Unicamp";

            [context save:&error];
        }
    }
}

@end


text:
all = mul mulh mulhu mulw mulhsu
all += rem remu remuw remw
all += div divu divuw divw

include ../common64.mk

redpajama_set_name: RedPajamaGithub


text:
;(function ( $ ) {

	$.fn.conditioner = function( options ){

		var opts = $.extend({
			events: '',
			conditions: [],
			onTrue: '',
			onFalse: '',
		}, options );

		function prepareConds( $ele ){

			$inputs = false;
			opts = $ele.data( 'conditioner-opts' );
			conds = [];

			// Inline options
			if( typeof $ele.data( 'condr-input' ) !== 'undefined' ){

				// data-condr-input="(closest::.wrap)(find::.myele)"
				inputAttr = $ele.data( 'condr-input' );

				$inputEle = $ele;
				if( inputAttr.indexOf( '(' ) != -1 ){ // Input selection is advanced as it has braces

					// Loop through the selectors and get the jQuery obj of input
					$.each( inputAttr.match( /\(.+?\)/g ), function( index, method ){
						method = method.replace( /[()]/g, '' );
						methodSplit = method.split( '::' );
						$inputEle = $inputEle[ methodSplit[0] ]( methodSplit[1] );
					});

				}else{
					$inputEle = $( inputAttr );
				}

				if( typeof $ele.data( 'condr-action' ) !== 'undefined' ){

					conds.push({
						input: $inputEle,
						value: $ele.data( 'condr-value' ),
						type: $ele.data( 'condr-action' ).split('?')[0]
					});

					// Add input to list
					$inputs = ( $inputs == false ) ? $inputEle : $inputs.add( $inputEle );
				}

			}

			// External options
			if( opts.conditions.length > 0 ){
				$.each( opts.conditions, function( index, cond ){

					if( cond.input != '' && typeof cond.input === 'function' ){
						$indInput = cond.input.call( $ele );
					}else if( typeof cond.input === 'string' ){
						$indInput = $( cond.input );
					}else{
						return true;
					}

					conds.push({
						input: $indInput,
						value: ( typeof cond.value === 'function' ) ? cond.value.call( $ele ) : cond.value,
						type: cond.type
					});

					$inputs = ( $inputs == false ) ? $indInput : $inputs.add( $indInput );

				});
			}

			// Attach the array which has all the conditions, value and type to the element
			$ele.data( 'conditioner-conds', conds );

			return $inputs;
		}

		function checkCondition( $ele ){

			conds = $ele.data( 'conditioner-conds' );
			finalCheck = null;

			// Loop through each condition
			$.each( conds, function( index, cond ){
				indCheck = checkValue( cond );
				finalCheck = ( finalCheck == null ) ? indCheck : ( finalCheck && indCheck );
			});

			// If inline options are set
			if( typeof $ele.data( 'condr-action' ) !== 'undefined' ){

				condrAction = $ele.data( 'condr-action' );
				actionSplit = condrAction.split( '?' );
				actions = actionSplit[1].split( ':' );

				if( finalCheck ){
					$ele[ actions[0] ]();
				}else{
					$ele[ actions[1] ]();
				}

				return true;
			}

			// If external options are set
			if( opts.onTrue != '' && opts.onFalse != '' ){

				if( finalCheck ){
					if( typeof opts.onTrue === 'function' )
						opts.onTrue.call( $ele );
				}else{
					if( typeof opts.onFalse === 'function' )
						opts.onFalse.call( $ele );
				}

				return true;

			}

		}

		function checkValue( cond ){

			var inputVal = '';
			var checkPassed = false;

			if( cond.input.attr( 'type' ) == 'radio'){
				inputVal = cond.input.filter(':checked').val();
			}else if( cond.input.attr( 'type' ) == 'checkbox' ){
				if( cond.input.is( ':checked' ) ) return true;
				else return false;
			}else{
				inputVal = cond.input.val();
			}

			if( typeof cond.type === 'undefined' ){
				cond.type = 'simple';
			}

			// Check didn't pass so try others
			if( typeof cond.value !== 'undefined' && typeof inputVal !== 'undefined' ){
				if( cond.type == 'pattern' ){
					checkPassed = ( inputVal.match( new RegExp( cond.value, 'g' ) ) !== null ) ? true : false;
				}else if( cond.type == 'simple' ){
					checkPassed = ( inputVal == cond.value ) ? true : false;
				}
			}

			return checkPassed;

		}

		return this.each(function(){

			$ele = $(this).data( 'conditioner-opts', opts );
			$inputs = prepareConds( $ele );
			events = ( typeof $ele.data( 'condr-events' ) !== 'undefined' ) ? $ele.data( 'condr-events' ) : opts.events;

			if( $inputs.length > 0 && events != '' ){

				if( typeof $inputs.data( 'conditioner-ele' ) === 'undefined' ){
					$inputs.data( 'conditioner-ele', $ele );
				}else{
					$eles = $inputs.data( 'conditioner-ele' ).add( $ele );
					$inputs.data( 'conditioner-ele', $eles );
				}

				$inputs.on( events, function(){
					$(this).data( 'conditioner-ele' ).each(function(){
						checkCondition( $(this) );
					});
				});

				// Check the conditions once
				checkCondition( $ele );
			}

		});

	}

})( jQuery );


text:
This README outlines the details of collaborating on this Ember application.

## Prerequisites

You will need the following things properly installed on your computer.

* [Git](https://git-scm.com/)
* [Node.js](https://nodejs.org/)
* [Yarn](https://yarnpkg.com/)
* [Ember CLI](https://cli.emberjs.com/release/)
* [Google Chrome](https://google.com/chrome/)

## Installation

* `git clone <repository-url>` this repository
* `cd packages/web-client`
* `yarn install`

## Running / Development

* `ember serve`
* Visit your app at [http://localhost:4200](http://localhost:4200).
* Visit your tests at [http://localhost:4200/tests](http://localhost:4200/tests).

Note that you will have to run the hub for some functionality of this app, see [the hub README](../hub/README.md#running).

### Required environment variables
Connecting to the Kovan Testnet with WalletConnect requires an Infura project id. This should be specified in a `.env` file in this package's root as:
```
INFURA_ID=<your infura project id here>
```

Deployed versions will use a "HUB_URL" env var, which is processed at the time ember-cl-deploy runs.

### Thread animation interval environment variable
As a convenience for development, you can set the `THREAD_ANIMATION_INTERVAL` environment variable to control how quickly messages in workflows are shown.

### Code Generators

Make use of the many generators for code, try `ember help generate` for more details

### Running Tests

* `ember test`
* `ember test --server`

### Linting

* `yarn lint`
* `yarn lint:fix`

### Building

* `ember build` (development)
* `ember build --environment production` (production)

### Deploying

This app is deployed using ember-cli-deploy. CI automatically deploys passing builds of the main branch to staging.

## Further Reading / Useful Links

* [ember.js](https://emberjs.com/)
* [ember-cli](https://cli.emberjs.com/release/)
* Development Browser Extensions
  * [ember inspector for chrome](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi)
  * [ember inspector for firefox](https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/)


text:
/**
 * glBegin/EndCondtionalRender functions
 *
 * \author Brian Paul
 */

#include "main/imports.h"
#include "main/context.h"

#include "pipe/p_context.h"
#include "pipe/p_defines.h"
#include "st_context.h"
#include "st_cb_queryobj.h"
#include "st_cb_condrender.h"

/**
 * Called via ctx->Driver.BeginConditionalRender()
 */
static void
st_BeginConditionalRender(GLcontext *ctx, struct gl_query_object *q,
                          GLenum mode)
{
   struct st_query_object *stq = st_query_object(q);
   struct pipe_context *pipe = st_context(ctx)->pipe;
   uint m;

   switch (mode) {
   case GL_QUERY_WAIT:
      m = PIPE_RENDER_COND_WAIT;
      break;
   case GL_QUERY_NO_WAIT:
      m = PIPE_RENDER_COND_NO_WAIT;
      break;
   case GL_QUERY_BY_REGION_WAIT:
      m = PIPE_RENDER_COND_BY_REGION_WAIT;
      break;
   case GL_QUERY_BY_REGION_NO_WAIT:
      m = PIPE_RENDER_COND_BY_REGION_NO_WAIT;
      break;
   default:
      assert(0 && "bad mode in st_BeginConditionalRender");
      m = PIPE_RENDER_COND_WAIT;
   }

   pipe->render_condition(pipe, stq->pq, m);
}

/**
 * Called via ctx->Driver.BeginConditionalRender()
 */
static void
st_EndConditionalRender(GLcontext *ctx, struct gl_query_object *q)
{
   struct pipe_context *pipe = st_context(ctx)->pipe;
   (void) q;
   pipe->render_condition(pipe, NULL, 0);
}

void st_init_cond_render_functions(struct dd_function_table *functions)
{
   functions->BeginConditionalRender = st_BeginConditionalRender;
   functions->EndConditionalRender = st_EndConditionalRender;
}


text:
using System;

namespace IAmNotified.ClientSDK.Notification
{
    public abstract class NotificationBase : INotification
    {
        abstract public String Message { get; }
        //TODO: not the right place for QueueName!
        public abstract String QueueName { get; }
        public TimeSpan? ExpirationTime { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace RoslynMapper.UnitTests
{
    public class TypeResolveTests : IClassFixture<MapEngineFixture>
    {
        private IMapEngine _mapper;
        public TypeResolveTests(MapEngineFixture fixture)
        {
            _mapper = fixture.Engine;
        }

        public class Source
        {
            public int Value { get; set; }
        }

        public class Destination
        {
            public int OtherValue { get; set; }
            public string OtherString { get; set; }
        }

        [Fact]
        public void Map_Type_using_Expression_Lambda_Resolver()
        {
            Guid guid = Guid.NewGuid();
            _mapper.SetMapper<Source, Destination>(guid.ToString()).Resolve((s, d) => d.OtherValue = s.Value * 4);
            _mapper.Build();

            var destination = _mapper.GetMapper<Source, Destination>(guid.ToString()).Map(new Source() { Value = 21 });
            Assert.Equal(destination.OtherValue, 84);
        }

        [Fact]
        public void Map_Type_using_Statement_Lambda_Resolver()
        {
            Guid guid = Guid.NewGuid();
            _mapper.SetMapper<Source, Destination>(guid.ToString()).Resolve((s, d) => { d.OtherValue = s.Value * 4; d.OtherString = (s.Value * 3).ToString(); });
            _mapper.Build();

            var destination = _mapper.GetMapper<Source, Destination>(guid.ToString()).Map(new Source() { Value = 21 });
            Assert.Equal(destination.OtherString, "63");
        }
    }
}


text:
using System;
using UnityEngine;

namespace NaughtyAttributes
{
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class AnimatorParamAttribute : DrawerAttribute
    {
        public string AnimatorName { get; private set; }
        public AnimatorControllerParameterType? AnimatorParamType { get; private set; }

        public AnimatorParamAttribute(string animatorName)
        {
            AnimatorName = animatorName;
            AnimatorParamType = null;
        }

        public AnimatorParamAttribute(string animatorName, AnimatorControllerParameterType animatorParamType)
        {
            AnimatorName = animatorName;
            AnimatorParamType = animatorParamType;
        }
    }
}


text:
  <form name="form" ng-submit="register()">
    <fieldset>
      <legend>Sign up form</legend>

        Email
        <input name="email" type="text" ng-model="user.email">

        Password
        <input name="password" type="password" ng-model="user.password">

        <button>Sign up</button>

    </fieldset>
  </form>


text:
package org.apache.cassandra.db;

import java.nio.ByteBuffer;
import java.util.UUID;

public abstract class TypeSizes
{
    public static final TypeSizes NATIVE = new NativeDBTypeSizes();
    //只看到org.apache.cassandra.cache.SerializingCache和一些测试例子中用到
    public static final TypeSizes VINT = new VIntEncodedTypeSizes();

    private static final int BOOL_SIZE = 1;
    private static final int SHORT_SIZE = 2;
    private static final int INT_SIZE = 4;
    private static final int LONG_SIZE = 8;
    private static final int UUID_SIZE = 16;

    public abstract int sizeof(boolean value);
    public abstract int sizeof(short value);
    public abstract int sizeof(int value);
    public abstract int sizeof(long value);
    public abstract int sizeof(UUID value);

    /** assumes UTF8 */
    public int sizeof(String value)
    {
        int length = encodedUTF8Length(value);
        assert length <= Short.MAX_VALUE;
        return sizeof((short) length) + length;
    }

    public static int encodedUTF8Length(String st)
    {
        int strlen = st.length();
        int utflen = 0;
        for (int i = 0; i < strlen; i++)
        {
            int c = st.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F))
                utflen++;
            else if (c > 0x07FF)
                utflen += 3;
            else
                utflen += 2;
        }
        return utflen;
    }

    public int sizeofWithShortLength(ByteBuffer value)
    {
        return sizeof((short) value.remaining()) + value.remaining();
    }

    public int sizeofWithLength(ByteBuffer value)
    {
        return sizeof(value.remaining()) + value.remaining();
    }

    public static class NativeDBTypeSizes extends TypeSizes
    {
        public int sizeof(boolean value)
        {
            return BOOL_SIZE;
        }

        public int sizeof(short value)
        {
            return SHORT_SIZE;
        }

        public int sizeof(int value)
        {
            return INT_SIZE;
        }

        public int sizeof(long value)
        {
            return LONG_SIZE;
        }

        public int sizeof(UUID value)
        {
            return UUID_SIZE;
        }
    }

    public static class VIntEncodedTypeSizes extends TypeSizes
    {
        private static final int BOOL_SIZE = 1;

        public int sizeofVInt(long i)
        {
            if (i >= -112 && i <= 127)
                return 1;

            int size = 0;
            int len = -112;
            if (i < 0)
            {
                i ^= -1L; // take one's complement'
                len = -120;
            }
            long tmp = i;
            while (tmp != 0)
            {
                tmp = tmp >> 8;
                len--;
            }
            size++;
            len = (len < -120) ? -(len + 120) : -(len + 112);
            size += len;
            return size;
        }

        public int sizeof(long i)
        {
            return sizeofVInt(i);
        }

        public int sizeof(boolean i)
        {
            return BOOL_SIZE;
        }

        public int sizeof(short i)
        {
            return sizeofVInt(i);
        }

        public int sizeof(int i)
        {
            return sizeofVInt(i);
        }

        public int sizeof(UUID value)
        {
            return sizeofVInt(value.getMostSignificantBits()) + sizeofVInt(value.getLeastSignificantBits());
        }
    }
}


text:
package org.elasticsearch.action.index;

import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;

/**
 * A response of an index operation,
 *
 * @see org.elasticsearch.action.index.IndexRequest
 * @see org.elasticsearch.client.Client#index(IndexRequest)
 */
public class IndexResponse extends DocWriteResponse {

    public IndexResponse(ShardId shardId, StreamInput in) throws IOException {
        super(shardId, in);
    }

    public IndexResponse(StreamInput in) throws IOException {
        super(in);
    }

    public IndexResponse(ShardId shardId, String id, long seqNo, long primaryTerm, long version, boolean created) {
        this(shardId, id, seqNo, primaryTerm, version, created ? Result.CREATED : Result.UPDATED);
    }

    private IndexResponse(ShardId shardId, String id, long seqNo, long primaryTerm, long version, Result result) {
        super(shardId, id, seqNo, primaryTerm, version, assertCreatedOrUpdated(result));
    }

    private static Result assertCreatedOrUpdated(Result result) {
        assert result == Result.CREATED || result == Result.UPDATED;
        return result;
    }

    @Override
    public RestStatus status() {
        return result == Result.CREATED ? RestStatus.CREATED : super.status();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("IndexResponse[");
        builder.append("index=").append(getIndex());
        builder.append(",id=").append(getId());
        builder.append(",version=").append(getVersion());
        builder.append(",result=").append(getResult().getLowercase());
        builder.append(",seqNo=").append(getSeqNo());
        builder.append(",primaryTerm=").append(getPrimaryTerm());
        builder.append(",shards=").append(Strings.toString(getShardInfo()));
        return builder.append("]").toString();
    }

    public static IndexResponse fromXContent(XContentParser parser) throws IOException {
        ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);

        Builder context = new Builder();
        while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
            parseXContentFields(parser, context);
        }
        return context.build();
    }

    /**
     * Parse the current token and update the parsing context appropriately.
     */
    public static void parseXContentFields(XContentParser parser, Builder context) throws IOException {
        DocWriteResponse.parseInnerToXContent(parser, context);
    }

    /**
     * Builder class for {@link IndexResponse}. This builder is usually used during xcontent parsing to
     * temporarily store the parsed values, then the {@link Builder#build()} method is called to
     * instantiate the {@link IndexResponse}.
     */
    public static class Builder extends DocWriteResponse.Builder {
        @Override
        public IndexResponse build() {
            IndexResponse indexResponse = new IndexResponse(shardId, id, seqNo, primaryTerm, version, result);
            indexResponse.setForcedRefresh(forcedRefresh);
            if (shardInfo != null) {
                indexResponse.setShardInfo(shardInfo);
            }
            return indexResponse;
        }
    }
}


text:
package demo;

/**
 *
 * @author Stephane Nicoll
 */
public class StringMachin implements Machin<String> {

	@Override
	public void doIt(String stuff) {

	}
}


text:
package org.sfs;

import com.fasterxml.jackson.core.JsonFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.http.HttpClient;
import org.sfs.auth.AuthProviderService;
import org.sfs.elasticsearch.Elasticsearch;
import org.sfs.encryption.AwsKms;
import org.sfs.encryption.AzureKms;
import org.sfs.encryption.ContainerKeys;
import org.sfs.encryption.MasterKeys;
import org.sfs.filesystem.temp.TempDirectoryCleaner;
import org.sfs.jobs.Jobs;
import org.sfs.nodes.ClusterInfo;
import org.sfs.nodes.NodeStats;
import org.sfs.nodes.Nodes;

import java.util.concurrent.ExecutorService;

public abstract class Server extends AbstractVerticle implements SfsVerticle {

    public abstract Context getContext();

    public abstract ExecutorService getIoPool();

    public abstract ExecutorService getBackgroundPool();

    public abstract VertxContext<Server> vertxContext();

    public abstract AuthProviderService authProviderService();

    public abstract TempDirectoryCleaner tempFileFactory();

    public abstract Elasticsearch elasticsearch();

    public abstract Nodes nodes();

    public abstract Jobs jobs();

    public abstract SfsFileSystem sfsFileSystem();

    public abstract JsonFactory jsonFactory();

    public abstract AwsKms awsKms();

    public abstract AzureKms azureKms();

    public abstract MasterKeys masterKeys();

    public abstract ContainerKeys containerKeys();

    public abstract HttpClient httpClient(boolean https);

    public abstract ClusterInfo getClusterInfo();

    public abstract NodeStats getNodeStats();

    public abstract byte[] getRemoteNodeSecret();
}


text:
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

__global__ void AddOneKernel(const int* in, const int N, int* out) {
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N;
       i += blockDim.x * gridDim.x) {
    out[i] = in[i] + 1;
  }
}

void AddOneKernelLauncher(const int* in, const int N, int* out) {
  AddOneKernel<<<32, 256>>>(in, N, out);
}

#endif


text:
package javax.json;

import javax.json.spi.JsonProvider;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParserFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;

public class Json {
    private Json() {
        // no-op
    }

    public static JsonParser createParser(Reader reader) {
        return JsonProvider.provider().createParser(reader);
    }

    public static JsonParser createParser(InputStream in) {
        return JsonProvider.provider().createParser(in);
    }

    public static JsonGenerator createGenerator(Writer writer) {
        return JsonProvider.provider().createGenerator(writer);
    }

    public static JsonGenerator createGenerator(OutputStream out) {
        return JsonProvider.provider().createGenerator(out);
    }

    public static JsonParserFactory createParserFactory(Map<String, ?> config) {
        return JsonProvider.provider().createParserFactory(config);
    }

    public static JsonGeneratorFactory createGeneratorFactory(Map<String, ?> config) {
        return JsonProvider.provider().createGeneratorFactory(config);
    }

    public static JsonWriter createWriter(Writer writer) {
        return JsonProvider.provider().createWriter(writer);
    }

    public static JsonWriter createWriter(OutputStream out) {
        return JsonProvider.provider().createWriter(out);
    }

    public static JsonReader createReader(Reader reader) {
        return JsonProvider.provider().createReader(reader);
    }

    public static JsonReader createReader(InputStream in) {
        return JsonProvider.provider().createReader(in);
    }

    public static JsonReaderFactory createReaderFactory(Map<String, ?> config) {
        return JsonProvider.provider().createReaderFactory(config);
    }

    public static JsonWriterFactory createWriterFactory(Map<String, ?> config) {
        return JsonProvider.provider().createWriterFactory(config);
    }

    public static JsonArrayBuilder createArrayBuilder() {
        return JsonProvider.provider().createArrayBuilder();
    }

    public static JsonObjectBuilder createObjectBuilder() {
        return JsonProvider.provider().createObjectBuilder();
    }

    public static JsonBuilderFactory createBuilderFactory(Map<String, ?> config) {
        return JsonProvider.provider().createBuilderFactory(config);
    }
}


text:
angular.module('confRegistrationWebApp').filter('unique', function () {
  return function (items, filterOn) {
    if (filterOn === false) {
      return items;
    }

    if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
      var newItems = [];

      var extractValueToCompare = function (item) {
        if (angular.isObject(item) && angular.isString(filterOn)) {
          return item[filterOn];
        } else {
          return item;
        }
      };

      angular.forEach(items, function (item) {
        var isDuplicate = false;

        for (var i = 0; i < newItems.length; i++) {
          if (
            angular.equals(
              extractValueToCompare(newItems[i]),
              extractValueToCompare(item),
            )
          ) {
            isDuplicate = true;
            newItems[i]._count++;
            break;
          }
        }
        if (!isDuplicate) {
          item._count = 1;
          newItems.push(item);
        }
      });
      items = newItems;
    }
    return items;
  };
});


text:
"""
Various utils for dealing with backward compatibility across Django
versions.
"""
from functools import wraps

import django
from django.conf import settings

# Middleware mixin for Django 1.10
try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    class MiddlewareMixin(object):
        pass

def get_middleware_setting_name():
    """
    Returns the name of the middleware setting.
    """
    if hasattr(settings, "MIDDLEWARE") and settings.MIDDLEWARE is not None:
        return "MIDDLEWARE"
    else:
        return "MIDDLEWARE_CLASSES"

def get_middleware_setting():
    """
    Returns the middleware setting.
    """
    return getattr(settings, get_middleware_setting_name())

def is_authenticated(user):
    """
    Returns True if the user is authenticated.
    """
    if django.VERSION < (1, 10):
        return user.is_authenticated()
    return user.is_authenticated

def get_related_model(field):
    """
    Returns the model on a relation field.
    """
    # We could skip the version check here and rely on AttributeError,
    # but that triggers all the deprecation warnings for this.
    if django.VERSION < (1, 9):
        try:
            return field.rel.to
        except AttributeError:
            pass
    else:
        try:
            return field.remote_field.model
        except AttributeError:
            pass

def mark_safe(s):
    from django.utils.safestring import mark_safe as django_safe
    if callable(s):
        @wraps(s)
        def wrapper(*args, **kwargs):
            return django_safe(s(*args, **kwargs))
        return wrapper
    return django_safe(s)


text:
package org.bricolages.streaming.stream;
import org.bricolages.streaming.exception.*;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.slf4j.Logger;
import lombok.*;

public interface StreamBundleRepository extends JpaRepository<StreamBundle, Long> {
    List<StreamBundle> findByStreamAndBucketAndPrefix(PacketStream stream, String bucket, String prefix);

    default StreamBundle findStreamBundle(PacketStream stream, String bucket, String prefix) {
        val list = findByStreamAndBucketAndPrefix(stream, bucket, prefix);
        if (list.isEmpty()) return null;
        if (list.size() > 1) {
            throw new ApplicationError("FATAL: multiple stream bundle matched: " + stream.id + ", " + prefix);
        }
        return list.get(0);
    }

    List<StreamBundle> findByBucketAndPrefix(String bucket, String prefix);

    default StreamBundle findStreamBundle(String bucket, String prefix) {
        val list = findByBucketAndPrefix(bucket, prefix);
        if (list.isEmpty()) return null;
        if (list.size() > 1) {
            throw new ApplicationError("FATAL: multiple stream bundle matched: bucket=" + bucket + ", prefix=" + prefix);
        }
        return list.get(0);
    }

    default StreamBundle findOrCreate(PacketStream stream, String bucket, String prefix, Logger log) {
        StreamBundle bundle = findStreamBundle(stream, bucket, prefix);
        if (bundle == null) {
            try {
                bundle = new StreamBundle(stream, bucket, prefix);
                save(bundle);
                logNewStreamBundle(log, stream.getId(), prefix);
            }
            catch (DataIntegrityViolationException ex) {
                bundle = findStreamBundle(stream, bucket, prefix);
            }
        }
        return bundle;
    }

    default void logNewStreamBundle(Logger log, long streamId, String streamPrefix) {
        log.warn("new stream bundle: stream_id={}, stream_prefix={}", streamId, streamPrefix);
    }
}


text:
package ru.retverd.jira.reporter.progress;

import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.domain.*;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import org.apache.log4j.Logger;
import org.apache.poi.POIXMLException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime;
import org.xml.sax.SAXException;
import ru.retverd.jira.reporter.progress.helpers.ExcelHelper;
import ru.retverd.jira.reporter.progress.types.ConfigType;
import ru.retverd.jira.reporter.progress.types.IssueColumnsType;
import ru.retverd.jira.reporter.progress.types.ReportType;

import javax.naming.ConfigurationException;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

public class ProgressReporter {
    // Divider between links prefix and issue number
    static private final String ISSUE_DIVIDER = "-";
    // String for subtasks
    static private final String SUBTASK_OF_VALUE = "subtask of";
    // String for subtasks
    static private final String SCHEMA_FILE = "progress_reporter.xsd";
    // Default dueDateFormat
    static private final String DUE_DATE_FORMAT = "dd.mm.yyyy";
    //
    static private final Integer AUTH_FAIL_STATUS = 401;
    //
    private static final Logger log = Logger.getLogger(ProgressReporter.class.getName());
    //
    private boolean saveFlag = false;
    // Relevant for whole report
    private ConfigType config;
    private XSSFWorkbook workbook;
    private JiraRestClient jiraClient;
    private Set<String> searchFields;
    private List<String> projects;
    private short dueDateFormat;
    // Relevant for one sheet only
    private String issueSummaryPrefixToHide;
    private Map<String, String> linksList;
    private List<String> affVersionsList;
    private List<String> componentsList;
    private List<String> labelsList;

    public void loadConfigFile(String configFile) throws ConfigurationException {
        log.info("Loading and parsing properties from " + configFile);
        try {
            Unmarshaller unmarshaller = JAXBContext.newInstance(ConfigType.class).createUnmarshaller();
            // Optional schema validation
            File schemaFile = new File(SCHEMA_FILE);
            if (schemaFile.exists()) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                Schema schema = schemaFactory.newSchema(schemaFile);
                unmarshaller.setSchema(schema);
            }
            config = (ConfigType) unmarshaller.unmarshal(new File(configFile));
        } catch (JAXBException e) {
            ConfigurationException ex;
            if (e.getMessage() == null) {
                ex = new ConfigurationException(JAXBException.class + " thrown with linked exception " + e.getLinkedException().getClass() + " and message: " + e.getLinkedException().getMessage());
                log.fatal(e.getLinkedException().getMessage(), e.getLinkedException());
            } else {
                ex = new ConfigurationException(JAXBException.class + " thrown with message: " + e.getMessage());
                log.fatal(e.getMessage(), e);
            }
            ex.setRootCause(e);
            throw ex;
        } catch (SAXException e) {
            ConfigurationException ex = new ConfigurationException("Something wrong happened during xsd-schema loading.");
            ex.setRootCause(e);
            log.fatal(ex.getMessage(), e);
            throw ex;
        }

        if (config.getReport().getUpdateDate() != null) {
            try {
                config.getReport().getUpdateDate().getUpdateTime(new DateTime(), config.getLocale());
            } catch (IllegalArgumentException e) {
                ConfigurationException ex = new ConfigurationException(e.getMessage() + " for field config -> report -> updateDate -> timePattern");
                ex.setRootCause(e);
                log.fatal(ex.getMessage(), e);
                throw ex;
            }
        }

        if (config.getReport().getReportName() != null) {
            String tempName;

            try {
                tempName = config.getReport().getReportName().getFullName(new DateTime(), config.getLocale());
            } catch (IllegalArgumentException e) {
                ConfigurationException ex = new ConfigurationException(e.getMessage() + " for field config -> report -> reportName -> timePattern");
                ex.setRootCause(e);
                log.fatal(ex.getMessage(), e);
                throw ex;
            }

            if (tempName.isEmpty()) {
                ConfigurationException ex = new ConfigurationException("At least one field for tag <reportName> should be filled!");
                log.fatal(ex.getMessage(), ex);
                throw ex;
            }
        }
    }

    public void connectToJira(String login, String pass) throws ConfigurationException {
        if (config.getJira().getProxy() != null) {
            System.setProperty("https.proxyHost", config.getJira().getProxy().getHost());
            System.setProperty("https.proxyPort", config.getJira().getProxy().getPort());
            log.info("Proxy server " + config.getJira().getProxy().getHost() + ":" + config.getJira().getProxy().getPort() + " is being used!");
        }

        String errorMessage;
        URI uri;

        try {
            uri = new URI(config.getJira().getUrl());
        } catch (URISyntaxException e) {
            ConfigurationException ex = new ConfigurationException(URISyntaxException.class + " thrown with message: " + e.getMessage());
            ex.setRootCause(e);
            log.fatal(ex.getMessage(), e);
            throw ex;
        }

        // Connect to Jira
        if (config.getJira().isAnonymous()) {
            JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
            jiraClient = factory.createWithAnonymousAccess(uri);
            log.info("Anonymous factory was used.");
            errorMessage = "Anonymous access is prohibited!";
        } else {
            // Request credentials for JIRA
            // TODO handle empty credentials!
            if (login == null && pass == null) {
                String loginPrompt = "Please enter your login: ";
                String passPrompt = "Please enter your password: ";
                Console console = System.console();
                System.out.print(loginPrompt);
                if (console == null) {
                    Scanner in = new Scanner(System.in);
                    login = in.next();
                    System.out.print(passPrompt);
                    pass = in.next();
                    in.close();
                } else {
                    login = console.readLine();
                    System.out.print(passPrompt);
                    pass = new String(console.readPassword());
                }
            }
            JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
            jiraClient = factory.createWithBasicHttpAuthentication(uri, login, pass);
            log.info("Basic http authentication factory was used.");
            errorMessage = "Authentication error! Please check your credentials!";
        }

        try {
            ServerInfo si = jiraClient.getMetadataClient().getServerInfo().claim();
            log.info("Successfully connected to Jira instance v." + si.getVersion());
        } catch (RestClientException e) {
            disconnect();
            com.google.common.base.Optional<Integer> statusCode = e.getStatusCode();
            if (statusCode.isPresent()) {
                // TODO handle incorrect credentials!
                // TODO handle missing access!
                if (statusCode.get().equals(AUTH_FAIL_STATUS)) {
                    ConfigurationException ex = new ConfigurationException(errorMessage);
                    ex.setRootCause(e);
                    log.fatal(errorMessage, e);
                    throw ex;
                }
                log.fatal(e.getMessage(), e);
                throw e;
            }
            log.fatal(e.getMessage(), e);
            throw e;
        } catch (RuntimeException e) {
            disconnect();
            throw e;
        }
    }

    public void initObjects() {
        this.searchFields = new HashSet<String>();
        searchFields.add("summary");
        searchFields.add("created");
        searchFields.add("updated");
        searchFields.add("links");
        searchFields.add("status");
        searchFields.add("issuetype");
        searchFields.add("assignee");
        searchFields.add("components");
        searchFields.add("timetracking");
        searchFields.add("labels");
        searchFields.add("versions");
        searchFields.add("project");
        searchFields.add("parent");
        searchFields.add("duedate");

        projects = config.getJira().getProjects();

        linksList = new HashMap<String, String>();
        if (config.getReport().getRootIssue() != null) {
            log.info("Getting IssueLinkTypes from server...");
            Iterable<IssuelinksType> issueLinkTypes = jiraClient.getMetadataClient().getIssueLinkTypes().claim();
            for (String link : config.getReport().getRootIssue().getLinks()) {
                for (IssuelinksType issueLinkType : issueLinkTypes) {
                    if (issueLinkType.getInward().equals(link)) {
                        linksList.put(link, issueLinkType.getOutward());
                        break;
                    } else if (issueLinkType.getOutward().equals(link)) {
                        linksList.put(link, issueLinkType.getInward());
                        break;
                    }
                }
                if (!linksList.containsKey(link)) {
                    log.error("Issue link type '" + link + "' is missing on server!");
                }
            }
        }
    }

    public void loadReportTemplate(String reportTemplate) throws ConfigurationException, IOException {
        // Load Excel file with report timePattern
        log.info("Reading report file " + reportTemplate);
        // OPCPackage is not used due to problems with saving results: org.apache.poi.openxml4j.exceptions.OpenXML4JException: The part /docProps/app.xml fail
        // to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@1c67c1a6
        FileInputStream fis;
        try {
            fis = new FileInputStream(reportTemplate);
        } catch (FileNotFoundException e) {
            ConfigurationException ex = new ConfigurationException(System.getProperty("user.dir") + "\\" + e.getMessage());
            ex.setRootCause(e);
            log.fatal(ex.getMessage(), e);
            throw ex;
        }
        try {
            workbook = new XSSFWorkbook(fis);
        } catch (POIXMLException e) {
            ConfigurationException ex = new ConfigurationException("Report template " + System.getProperty("user.dir") + "\\" + reportTemplate + " has wrong format.");
            ex.setRootCause(e);
            log.fatal(ex.getMessage(), e);
            throw ex;
        } catch (IOException e) {
            ConfigurationException ex = new ConfigurationException("Something wrong happened during load " + System.getProperty("user.dir") + "\\" + reportTemplate + ": " + e.getMessage());
            ex.setRootCause(e);
            log.fatal(ex.getMessage(), e);
            throw ex;
        } finally {
            fis.close();
        }

        if (config.getReport().getIssueColumns().getDueDate() != null) {
            dueDateFormat = workbook.createDataFormat().getFormat(config.getReport().getDueDateFormat() == null ? DUE_DATE_FORMAT : config.getReport().getDueDateFormat());
        }
    }

    static private Double toHours(Integer value) {
        return (double) (value == null ? 0 : value) / 60;
    }

    public void updateReport() {
        // Iterate through sheets
        for (XSSFSheet sheet : workbook) {
            String sheetName = sheet.getSheetName();
            if (sheetName.contains(config.getReport().getMarker())) {
                log.info("Processing sheet \"" + sheetName.replace(config.getReport().getMarker(), "") + "\"...");
                if (config.getReport().getUpdateDate() != null) {
                    XSSFRow updateRow = sheet.getRow(config.getReport().getUpdateDate().getCell().getRow());
                    if (updateRow == null) {
                        log.error("Row " + ExcelHelper.humanizeRow(config.getReport().getUpdateDate().getCell().getRow()) + " for update date is missing on sheet " + sheetName + ".");
                    } else {
                        updateRow.getCell(config.getReport().getUpdateDate().getCell().getCol(), Row.CREATE_NULL_AS_BLANK).setCellValue(config.getReport().getUpdateDate().getUpdateTime(new DateTime(), config.getLocale()));
                    }
                }
                // Prefix for issue summary to be hidden
                issueSummaryPrefixToHide = "";
                if (config.getReport().getToHide() != null) {
                    if (config.getReport().getToHide().getIssuePrefixCell() != null) {
                        XSSFRow row = sheet.getRow(config.getReport().getToHide().getIssuePrefixCell().getRow());
                        if (row != null) {
                            XSSFCell cell = row.getCell(config.getReport().getToHide().getIssuePrefixCell().getCol());
                            if (cell != null) {
                                issueSummaryPrefixToHide = cell.getStringCellValue();
                            }
                        }
                    }
                }
                // List of affVersions to be hidden
                affVersionsList = new ArrayList<String>();
                if (config.getReport().getToHide() != null) {
                    if (config.getReport().getToHide().getAffectedVersionCell() != null) {
                        XSSFRow row = sheet.getRow(config.getReport().getToHide().getAffectedVersionCell().getRow());
                        if (row != null) {
                            XSSFCell cell = row.getCell(config.getReport().getToHide().getAffectedVersionCell().getCol());
                            if (cell != null) {
                                String[] array = cell.getStringCellValue().split(",");
                                for (String s : array) {
                                    affVersionsList.add(s.trim());
                                }
                            }
                        }
                    }
                }
                // List of components to be hidden
                componentsList = new ArrayList<String>();
                if (config.getReport().getToHide() != null) {
                    if (config.getReport().getToHide().getComponentsCell() != null) {
                        XSSFRow row = sheet.getRow(config.getReport().getToHide().getComponentsCell().getRow());
                        if (row != null) {
                            XSSFCell cell = row.getCell(config.getReport().getToHide().getComponentsCell().getCol());
                            if (cell != null) {
                                String[] array = cell.getStringCellValue().split(",");
                                for (String s : array) {
                                    componentsList.add(s.trim());
                                }
                            }
                        }
                    }
                }
                // List of labels to be hidden
                labelsList = new ArrayList<String>();
                if (config.getReport().getToHide() != null) {
                    if (config.getReport().getToHide().getLabelsCell() != null) {
                        XSSFRow row = sheet.getRow(config.getReport().getToHide().getLabelsCell().getRow());
                        if (row != null) {
                            XSSFCell cell = row.getCell(config.getReport().getToHide().getLabelsCell().getCol());
                            if (cell != null) {
                                String[] array = cell.getStringCellValue().split(",");
                                for (String s : array) {
                                    labelsList.add(s.trim());
                                }
                            }
                        }
                    }
                }

                String jqlQuery = getJQLQuery(sheet);
                String rootIssueKey = getRootIssueKey(sheet);
                if (jqlQuery != null) {
                    // Remove all rows with issues
                    removeRows(sheet, config.getReport().getStartProcessingRow());
                    log.info("Processing of linked issues will be initiated, all rows starting from row " + ExcelHelper.humanizeRow(config.getReport().getStartProcessingRow()) + " were deleted.");

                    int searchPos = 0;
                    int searchStep = config.getReport().getJqlQuery().getSearchStep();
                    // Retrieve all issues from relevant projects with requested label(s)
                    log.info("Searching for issues using request: " + jqlQuery + "...");
                    SearchResult searchResult = jiraClient.getSearchClient().searchJql(jqlQuery, searchStep, searchPos, searchFields).claim();
                    int totalSearchResults = searchResult.getTotal();
                    log.info(totalSearchResults + " issue(s) found.");

                    if (totalSearchResults > 0) {
                        boolean flag = config.getReport().getProcessingFlags().isIssueSummaryUpdate();
                        config.getReport().getProcessingFlags().setIssueSummaryUpdate(true);
                        // Go through retrieved issues and publish details
                        do {
                            for (Issue issue : searchResult.getIssues()) {
                                XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

                                publishIssueDetails(row, issue, null, null);
                            }
                            searchPos += searchStep;
                            searchResult = jiraClient.getSearchClient().searchJql(jqlQuery, searchStep, searchPos, null).claim();
                        } while (searchPos < totalSearchResults);
                        config.getReport().getProcessingFlags().setIssueSummaryUpdate(flag);
                    }
                } else if (rootIssueKey != null) {
                    // Remove all rows with issues
                    removeRows(sheet, config.getReport().getStartProcessingRow());
                    log.info("Search for issues will be initiated, all rows starting from row " + ExcelHelper.humanizeRow(config.getReport().getStartProcessingRow()) + " were deleted.");
                    // Publish details for root issue
                    XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                    log.info("Retrieving issue " + rootIssueKey);
                    Issue rootIssue = getJiraIssue(rootIssueKey);
                    if (rootIssue != null) {
                        publishIssueDetails(row, rootIssue, null, null);
                        // Walk through linked issues and subtasks and add rows with details
                        boolean flag = config.getReport().getProcessingFlags().isIssueSummaryUpdate();
                        config.getReport().getProcessingFlags().setIssueSummaryUpdate(true);
                        publishDependentIssues(sheet, rootIssue);
                        config.getReport().getProcessingFlags().setIssueSummaryUpdate(flag);
                    }
                } else {
                    int rowNumber = config.getReport().getStartProcessingRow();
                    XSSFRow row = sheet.getRow(rowNumber++);
                    while (row != null) {
                        XSSFCell cell = row.getCell(config.getReport().getIssueColumns().getKey(), Row.CREATE_NULL_AS_BLANK);
                        if (cell != null) {
                            String issueKey = cell.getStringCellValue();
                            if (isIssueInScope(issueKey)) {
                                log.info("Retrieving issue " + issueKey);
                                Issue issue = getJiraIssue(issueKey);
                                if (issue != null) {
                                    publishIssueDetails(row, issue, null, null);
                                }
                            }
                        }
                        row = sheet.getRow(rowNumber++);
                    }
                }

                if (config.getReport().getProcessingFlags().isAutosizeColumns()) {
                    adjustCellsWidth(sheet);
                }
                log.info("Sheet \"" + sheetName.replace(config.getReport().getMarker(), "") + "\" processed!");
            } else {
                log.info("Sheet \"" + sheetName + "\" is skipped.");
            }

            // Refresh all formulas if required
            // Leads to exceptions on some Excel files with error message: Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)
            // See https://github.com/retverd/jira-progress-reporter/issues/1 (Problems with evaluateAllFormulaCells)
            if (config.getReport().getProcessingFlags().isRecalculateFormulas()) {
                log.info("Recalculating formulas...");
                XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
            }
        }

    }

    private void publishDependentIssues(XSSFSheet sheet, Issue rootIssue) {
        Iterable<IssueLink> issueLinks = rootIssue.getIssueLinks();
        if (issueLinks != null) {
            for (IssueLink issueLink : issueLinks) {
                if (linksList.containsKey(issueLink.getIssueLinkType().getDescription())) {
                    XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                    log.info("Retrieving issue " + issueLink.getTargetIssueKey());
                    Issue linkedIssue = getJiraIssue(issueLink.getTargetIssueKey());
                    if (linkedIssue != null) {
                        publishIssueDetails(row, linkedIssue, linksList.get(issueLink.getIssueLinkType().getDescription()), rootIssue.getKey());
                        publishDependentIssues(sheet, linkedIssue);
                    }
                }
            }
        }

        Iterable<Subtask> subTasks = rootIssue.getSubtasks();

        if (subTasks != null && config.getReport().getRootIssue().isUnfoldSubtasks()) {
            for (Subtask subtask : subTasks) {
                XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                log.info("Retrieving issue " + subtask.getIssueKey());
                Issue subTask = getJiraIssue(subtask.getIssueKey());
                if (subTask != null) {
                    publishIssueDetails(row, subTask, SUBTASK_OF_VALUE, rootIssue.getKey());
                }
            }
        }
    }

    private void publishIssueDetails(XSSFRow row, Issue issue, String relation, String parentKey) {
        ReportType report = config.getReport();

        if (report.getProcessingFlags().isIssueSummaryUpdate() && report.getIssueColumns().getSummary() != null) {
            row.getCell(report.getIssueColumns().getSummary(), Row.CREATE_NULL_AS_BLANK).setCellValue(issue.getSummary().replaceFirst(issueSummaryPrefixToHide, ""));
        }

        row.getCell(report.getIssueColumns().getKey(), Row.CREATE_NULL_AS_BLANK).setCellValue(issue.getKey());

        if (relation == null && parentKey == null && report.getIssueColumns().getRelation() != null && report.getIssueColumns().getParentKey() != null) {
            IssueField parent = issue.getField("parent");
            if (parent != null) {
                JSONObject parentValue = (JSONObject) parent.getValue();
                try {
                    parentKey = parentValue.getString("key");
                    relation = SUBTASK_OF_VALUE;
                } catch (JSONException e) {
                    log.error("For issue " + issue.getKey() + " " + e.getMessage(), e);
                }
            }
        }

        if (relation != null && report.getIssueColumns().getRelation() != null) {
            row.getCell(report.getIssueColumns().getRelation(), Row.CREATE_NULL_AS_BLANK).setCellValue(relation);
        }

        if (parentKey != null && report.getIssueColumns().getParentKey() != null) {
            row.getCell(report.getIssueColumns().getParentKey(), Row.CREATE_NULL_AS_BLANK).setCellValue(parentKey);
        }

        TimeTracking time = issue.getTimeTracking();
        publishTimeToCell(row, report.getIssueColumns().getEstimation(), time == null ? null : toHours(time.getOriginalEstimateMinutes()));
        publishTimeToCell(row, report.getIssueColumns().getSpentTime(), time == null ? null : toHours(time.getTimeSpentMinutes()));
        publishTimeToCell(row, report.getIssueColumns().getRemainingTime(), time == null ? null : toHours(time.getRemainingEstimateMinutes()));

        if (report.getIssueColumns().getStatus() != null) {
            row.getCell(report.getIssueColumns().getStatus(), Row.CREATE_NULL_AS_BLANK).setCellValue(issue.getStatus().getName());
        }

        if (report.getIssueColumns().getAfVersion() != null && issue.getAffectedVersions() != null) {
            Iterator<Version> iVersions = issue.getAffectedVersions().iterator();
            String versions = "";
            while (iVersions.hasNext()) {
                String iVersion = iVersions.next().getName();
                // Check for redundant affected versions
                if (!affVersionsList.contains(iVersion)) {
                    versions = versions + ", " + iVersion;
                }
            }
            versions = versions.replaceFirst(", ", "");
            row.getCell(report.getIssueColumns().getAfVersion(), Row.CREATE_NULL_AS_BLANK).setCellValue(versions);
        }

        if (report.getIssueColumns().getComponents() != null && issue.getComponents() != null) {
            Iterator<BasicComponent> iComponents = issue.getComponents().iterator();
            String components = "";
            while (iComponents.hasNext()) {
                String iComponent = iComponents.next().getName();
                // Check for redundant components
                if (!componentsList.contains(iComponent)) {
                    components = components + ", " + iComponent;
                }
            }
            components = components.replaceFirst(", ", "");
            row.getCell(report.getIssueColumns().getComponents(), Row.CREATE_NULL_AS_BLANK).setCellValue(components);
        }

        if (report.getIssueColumns().getLabels() != null && issue.getLabels() != null) {
            Iterator<String> iLabels = issue.getLabels().iterator();
            String labels = "";
            while (iLabels.hasNext()) {
                String iLabel = iLabels.next();
                // Check for redundant labels
                if (!labelsList.contains(iLabel)) {
                    labels = labels + ", " + iLabel;
                }
            }
            labels = labels.replaceFirst(", ", "");
            row.getCell(report.getIssueColumns().getLabels(), Row.CREATE_NULL_AS_BLANK).setCellValue(labels);
        }

        if (report.getIssueColumns().getAssignee() != null && issue.getAssignee() != null) {
            row.getCell(report.getIssueColumns().getAssignee(), Row.CREATE_NULL_AS_BLANK).setCellValue(issue.getAssignee().getDisplayName());
        }

        if (report.getIssueColumns().getDueDate() != null && issue.getDueDate() != null) {
            XSSFCell dueDateCell = row.getCell(report.getIssueColumns().getDueDate(), Row.CREATE_NULL_AS_BLANK);
            dueDateCell.setCellValue(issue.getDueDate().toDate());
            XSSFCellStyle cs = dueDateCell.getCellStyle();
            cs.setDataFormat(dueDateFormat);
            dueDateCell.setCellStyle(cs);
        }
    }

    private void adjustCellsWidth(XSSFSheet sheet) {
        IssueColumnsType columns = config.getReport().getIssueColumns();

        if (columns.getSummary() != null) sheet.autoSizeColumn(columns.getSummary(), true);
        if (columns.getKey() != null) sheet.autoSizeColumn(columns.getKey(), true);
        if (columns.getRelation() != null) sheet.autoSizeColumn(columns.getRelation(), true);
        if (columns.getParentKey() != null) sheet.autoSizeColumn(columns.getParentKey(), true);
        if (columns.getEstimation() != null) sheet.autoSizeColumn(columns.getEstimation(), true);
        if (columns.getSpentTime() != null) sheet.autoSizeColumn(columns.getSpentTime(), true);
        if (columns.getRemainingTime() != null) sheet.autoSizeColumn(columns.getRemainingTime(), true);
        if (columns.getStatus() != null) sheet.autoSizeColumn(columns.getStatus(), true);
        if (columns.getAfVersion() != null) sheet.autoSizeColumn(columns.getAfVersion(), true);
        if (columns.getComponents() != null) sheet.autoSizeColumn(columns.getComponents(), true);
        if (columns.getLabels() != null) sheet.autoSizeColumn(columns.getLabels(), true);
        if (columns.getAssignee() != null) sheet.autoSizeColumn(columns.getAssignee(), true);
    }

    private void removeRows(XSSFSheet sheet, int startRow) {
        for (int i = startRow; i <= sheet.getLastRowNum(); ) {
            XSSFRow currentRow = sheet.getRow(i++);
            // Skip missing rows
            if (currentRow != null) {
                sheet.removeRow(currentRow);
            }
        }
    }

    private void publishTimeToCell(XSSFRow row, Integer cellIndex, Double value) {
        if (cellIndex != null) {
            if (row.getCell(cellIndex) != null) {
                row.getCell(cellIndex).setCellValue(value);
            } else {
                XSSFCell cell = row.createCell(cellIndex, Cell.CELL_TYPE_NUMERIC);
                if (config.getReport().getTimeTrackingFormat() != null) {
                    XSSFCellStyle style = workbook.createCellStyle();
                    DataFormat format = workbook.createDataFormat();
                    style.setDataFormat(format.getFormat(config.getReport().getTimeTrackingFormat()));
                    cell.setCellStyle(style);
                }
                cell.setCellValue(value);
            }
        }
    }

    private boolean isIssueInScope(String issueKey) {
        String[] issueKeyParts = issueKey.split(ISSUE_DIVIDER);
        if (issueKeyParts.length != 2) {
            return false;
        }
        if (projects != null) {
            if (!projects.contains(issueKeyParts[0])) {
                return false;
            }
        }
        return true;

    }

    private Issue getJiraIssue(String issueKey) {
        Issue issue = null;

        try {
            issue = jiraClient.getIssueClient().getIssue(issueKey).claim();
        } catch (RestClientException e) {
            if (e.getStatusCode().isPresent()) {
                if (e.getStatusCode().get().equals(404)) {
                    log.error("Issue " + issueKey + " wasn't found. It doesn't exist or you have not enough rights to access it.");
                } else {
                    log.error("Issue " + issueKey + " wasn't found. Error message: \"" + e.getMessage() + "\". Status code: " + e.getStatusCode().get() + ".");
                }
            } else {
                log.error("Issue " + issueKey + " wasn't found. Error message: \"" + e.getMessage() + "\". No status code provided.");
            }
        }

        return issue;
    }

    private String getRootIssueKey(XSSFSheet sheet) {
        if (config.getReport().getRootIssue() == null) {
            return null;
        }
        XSSFRow row = sheet.getRow(config.getReport().getRootIssue().getCell().getRow());
        if (row == null) return null;
        XSSFCell cell = row.getCell(config.getReport().getRootIssue().getCell().getCol());
        if (cell == null) return null;
        if (cell.getStringCellValue().isEmpty()) return null;
        String key = cell.getStringCellValue();
        if (!isIssueInScope(key)) return null;
        return key;
    }

    private String getJQLQuery(XSSFSheet sheet) {
        if (config.getReport().getJqlQuery() == null) {
            return null;
        }
        XSSFRow row = sheet.getRow(config.getReport().getJqlQuery().getCell().getRow());
        if (row == null) return null;
        XSSFCell cell = row.getCell(config.getReport().getJqlQuery().getCell().getCol());
        if (cell == null) return null;
        if (cell.getStringCellValue().isEmpty()) return null;
        return cell.getStringCellValue();
    }

    public void saveReport(String reportFile) throws ConfigurationException {
        String notification = "Rewriting";

        if (config.getReport().getReportName() != null) {
            reportFile = config.getReport().getReportName().getFullName(new DateTime(), config.getLocale()) + ".xlsx";
            notification = "Saving report to";
        }

        log.info(notification + " file " + reportFile + "...");
        try {
            FileOutputStream fos = new FileOutputStream(new File(reportFile));
            workbook.write(fos);
            fos.close();
            saveFlag = true;
        } catch (IOException e) {
            ConfigurationException ex = new ConfigurationException("Something wrong happened during saving report: " + e.getMessage());
            ex.setRootCause(e);
            log.fatal(ex.getMessage());
            throw ex;
        }
    }

    public void disconnect() {
        if (jiraClient != null) {
            try {
                log.info("Shutting down connection to Jira!");
                jiraClient.close();
            } catch (IOException e) {
                log.error("Something wrong happened during JIRA client disconnection: " + e.getMessage());
            }
        }
    }

    public boolean isReportSaved() {
        return saveFlag;
    }

    public ConfigType getConfig() {
        return config;
    }
}