text:
package org.springframework.security.saml2.core;

/**
 * A list of SAML known 2 error codes used during SAML authentication.
 *
 * @since 5.2
 */
public interface Saml2ErrorCodes {

	/**
	 * SAML Data does not represent a SAML 2 Response object. A valid XML object was
	 * received, but that object was not a SAML 2 Response object of type
	 * {@code ResponseType} per specification
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=46
	 */
	String UNKNOWN_RESPONSE_CLASS = "unknown_response_class";

	/**
	 * The response data is malformed or incomplete. An invalid XML object was received,
	 * and XML unmarshalling failed.
	 */
	String MALFORMED_RESPONSE_DATA = "malformed_response_data";

	/**
	 * Response destination does not match the request URL. A SAML 2 response object was
	 * received at a URL that did not match the URL stored in the {code Destination}
	 * attribute in the Response object.
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=38
	 */
	String INVALID_DESTINATION = "invalid_destination";

	/**
	 * The assertion was not valid. The assertion used for authentication failed
	 * validation. Details around the failure will be present in the error description.
	 */
	String INVALID_ASSERTION = "invalid_assertion";

	/**
	 * The signature of response or assertion was invalid. Either the response or the
	 * assertion was missing a signature or the signature could not be verified using the
	 * system's configured credentials. Most commonly the IDP's X509 certificate.
	 */
	String INVALID_SIGNATURE = "invalid_signature";

	/**
	 * The assertion did not contain a subject element. The subject element, type
	 * SubjectType, contains a {@code NameID} or an {@code EncryptedID} that is used to
	 * assign the authenticated principal an identifier, typically a username.
	 *
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=18
	 */
	String SUBJECT_NOT_FOUND = "subject_not_found";

	/**
	 * The subject did not contain a user identifier The assertion contained a subject
	 * element, but the subject element did not have a {@code NameID} or
	 * {@code EncryptedID} element
	 *
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=18
	 */
	String USERNAME_NOT_FOUND = "username_not_found";

	/**
	 * The system failed to decrypt an assertion or a name identifier. This error code
	 * will be thrown if the decryption of either a {@code EncryptedAssertion} or
	 * {@code EncryptedID} fails.
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=17
	 */
	String DECRYPTION_ERROR = "decryption_error";

	/**
	 * An Issuer element contained a value that didn't
	 * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=15
	 */
	String INVALID_ISSUER = "invalid_issuer";

	/**
	 * An error happened during validation. Used when internal, non classified, errors are
	 * caught during the authentication process.
	 */
	String INTERNAL_VALIDATION_ERROR = "internal_validation_error";

	/**
	 * The relying party registration was not found. The registration ID did not
	 * correspond to any relying party registration.
	 */
	String RELYING_PARTY_REGISTRATION_NOT_FOUND = "relying_party_registration_not_found";

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('Custom_Setting_model', 'custom');
	}
	public function index() {
		$data['bootstap_theme'] = $this->custom->get_custom_values('bootstrap_theme');
		$this->load->view('hotel/layout/header');
		$this->load->view('hotel/layout/header_script', $data);
		$this->load->view('hotel/home/index');
		$this->load->view('hotel/layout/footer');
		$this->load->view('hotel/layout/footer_script');
	}
}

redpajama_set_name: RedPajamaGithub


text:
//
//  HHCompositeResultsControllerDelegateTests.m
//  HHCompositeResultsController
//
//  Created by Hyuk Hur on 2014. 10. 1..
//  Copyright (c) 2014년 Hyuk Hur. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <OCMock/OCMock.h>
#import <CoreData/CoreData.h>
#import <HHFixedResultsController/HHFixedResultsController.h>
#import "HHCompositeResultsController.h"

@interface HHSectionInfo : NSObject  <NSFetchedResultsSectionInfo>
@property (nonatomic) NSString *name;
@property (nonatomic) NSString *indexTitle;
@property (nonatomic, readonly) NSUInteger numberOfObjects;
@property (nonatomic) NSMutableArray *objects;
@property (nonatomic) NSMutableArray *nextObjects;
@end

@interface HHCompositeResultsControllerDelegateTests : XCTestCase
@property NSArray *objects;
@property HHCompositeResultsController *hhfrc;
@property NSFetchedResultsController *frc;
@property OCMockObject<NSFetchedResultsControllerDelegate> *delegate;
@property NSFetchRequest *request;
@property HHFixedResultsController *frc1;
@property HHFixedResultsController *frc2;
@property OCMockObject *frc3;
@property OCMockObject *frc4;
@end

@implementation HHCompositeResultsControllerDelegateTests

- (id)checkWithSectionInfo:(NSString *)name indexTitle:(NSString *)indexTitle
{
    return [OCMArg checkWithBlock:^BOOL(HHSectionInfo *obj) {
        return [obj.name isEqualToString:name] && [obj.indexTitle isEqualToString:indexTitle];
    }];
}

- (void)setUp {
    [super setUp];

    self.objects = @[
                     [@{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""} mutableCopy],
                     @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                     @{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                     @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                     @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                     ];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:nil];
    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"detail" ascending:YES]];
    request.predicate = [NSPredicate predicateWithValue:YES];
    [self setRequest:request];

    self.frc1 = [[HHFixedResultsController alloc] initWithFetchRequest:request
                                                               objects:@[
                                                                         @{@"type":@"a_type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                                                         @{@"type":@"b_type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                                                         @{@"type":@"a_types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                                                         @{@"type":@"a_type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                                                         ]
                                                    sectionNameKeyPath:@"type"
                                                             cacheName:nil];
    [self.frc1 performFetch:nil];
    self.frc2 = [[HHFixedResultsController alloc] initWithFetchRequest:[request copy]
                                                               objects:@[
                                                                         @{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                                                         @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                                                         @{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                                                         @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                                                         @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                                                         ]
                                                    sectionNameKeyPath:@"type"
                                                             cacheName:nil];
    [self.frc2 performFetch:nil];

    self.frc3 = [OCMockObject mockForClass:[NSFetchedResultsController class]];
    [[self.frc3 stub] setDelegate:[OCMArg any]];
    self.frc4 = [OCMockObject mockForClass:[NSFetchedResultsController class]];
    [[self.frc4 stub] setDelegate:[OCMArg any]];

    self.hhfrc = [[HHCompositeResultsController alloc] initWithFetchRequest:nil managedObjectContext:nil sectionNameKeyPath:nil cacheName:nil];
    self.frc = self.hhfrc.fetchedResultsController;
    self.delegate = [OCMockObject mockForProtocol:@protocol(NSFetchedResultsControllerDelegate)];
    self.frc.delegate = self.delegate;
    [self.hhfrc addObject:self.frc1.fetchedResultsController];
    [self.hhfrc addObject:(NSFetchedResultsController *)self.frc3];
    [self.hhfrc addObject:self.frc2.fetchedResultsController];
    [self.hhfrc addObject:(NSFetchedResultsController *)self.frc4];
    }

- (void)testPerformFetch {
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[self.frc3 expect] performFetch:[OCMArg anyObjectRef]];
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[self.frc4 expect] performFetch:[OCMArg anyObjectRef]];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    NSError *error = nil;
    XCTAssertTrue([self.frc performFetch:&error]);

    [self.frc3 verify];
    [self.frc4 verify];
}

- (void) testDidChangeObjectWithNSFetchedResultsChangeInsert {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:OCMOCK_ANY];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeSection:[OCMArg isNotNil] atIndex:0 forChangeType:(NSFetchedResultsChangeInsert)];

    [[self.delegate expect] controller:self.frc didChangeObject:OCMOCK_ANY atIndexPath:[OCMArg isNil] forChangeType:(NSFetchedResultsChangeInsert) newIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:0 inSection:7]]];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    [self.frc2 addObject:@{@"type":@"a_type", @"title":@"titl", @"detail":@"test value9 and value", @"type2":@""}];
    [self.frc2 performFetch:nil];

    [self.delegate verify];
}

/*
 On add and remove operations, only the added/removed object is reported.
 It's assumed that all objects that come after the affected object are also moved, but these moves are not reported.
 */
- (void) testDidChangeObjectWithNSFetchedResultsChangeDelete {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];
    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg isEqual:@{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""}] atIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:2 inSection:4]] forChangeType:(NSFetchedResultsChangeDelete) newIndexPath:[OCMArg isNil]];

    NSArray *changedObjects = @[
                                @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                @{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                ];

    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

/*
 A move is reported when the changed attribute on the object is one of the sort descriptors used in the fetch request.
 An update of the object is assumed in this case, but no separate update message is sent to the delegate.
 */
- (void) testDidChangeObjectWithNSFetchedResultsChangeMove {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];

    self.frc.delegate = nil;
    [self.frc2 setObjects:self.objects];
    [self.frc2 performFetch:nil];
    self.frc.delegate = self.delegate;

    [[self.delegate reject] controller:self.frc didChangeObject:OCMOCK_ANY atIndexPath:OCMOCK_ANY forChangeType:NSFetchedResultsChangeInsert newIndexPath:OCMOCK_ANY];
    [[self.delegate reject] controller:self.frc didChangeObject:OCMOCK_ANY atIndexPath:OCMOCK_ANY forChangeType:NSFetchedResultsChangeDelete newIndexPath:OCMOCK_ANY];
    [[self.delegate reject] controller:self.frc didChangeObject:OCMOCK_ANY atIndexPath:OCMOCK_ANY forChangeType:NSFetchedResultsChangeUpdate newIndexPath:OCMOCK_ANY];

    [[[self.frc3 stub] andReturn:@[@""]] sections];

    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg isEqual:@{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""}] atIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:1 inSection:4]] forChangeType:(NSFetchedResultsChangeMove) newIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:2 inSection:4]]];
    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg isEqual:@{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""}] atIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:0 inSection:4]] forChangeType:(NSFetchedResultsChangeMove) newIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:1 inSection:4]]];
    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg isEqual:@{@"type":@"1type", @"title":@"title one", @"detail":@"test value", @"type2":@""}] atIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:2 inSection:4]] forChangeType:(NSFetchedResultsChangeMove) newIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:0 inSection:4]]];

    [self.objects[0] setObject:@"test value" forKey:@"detail"];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

#pragma mark - sections

- (void) testDidChangeSectionWithNSFetchedResultsChangeInsert {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];

    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:0 newIndexPath:[OCMArg any]];
    [[[self.frc3 stub] andReturn:@[@""]] sections];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"1types" indexTitle:@"1types"] atIndex:6 forChangeType:(NSFetchedResultsChangeDelete)];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"3type" indexTitle:@"3type"] atIndex:6 forChangeType:(NSFetchedResultsChangeInsert)];

    [self.frc2 addObject:@{@"type":@"3type", @"title":@"title third", @"detail":@"test value3", @"type2":@""}];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testDidChangeSectionWithNSFetchedResultsChangeDelete {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [[[self.frc3 stub] andReturn:@[@""]] sections];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"1types" indexTitle:@"1"] atIndex:6 forChangeType:(NSFetchedResultsChangeDelete)];
    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg isEqual:@{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""}] atIndexPath:[OCMArg isEqual:[NSIndexPath indexPathForRow:0 inSection:6]] forChangeType:(NSFetchedResultsChangeDelete) newIndexPath:[OCMArg isNil]];

    NSArray *changedObjects = @[
                                @{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                ];

    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

#pragma mark - something chagned

- (void) testWillAndDidChangeContentAndDidChangeContentWhenObjectRemoved {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    NSArray *changedObjects = @[
                                @{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                @{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                ];
    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillAndDidChangeContentAndDidChangeContentWhenObjectAdded {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:0 newIndexPath:[OCMArg any]];
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    [self.frc2 addObject:@{@"type":@"1type", @"title":@"title five", @"detail":@"test value5", @"type2":@""}];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillAndDidChangeContentAndDidChangeContentWhenAnObjectAdded {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:0 newIndexPath:[OCMArg any]];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    [self.frc2 addObject:@{@"type":@"1type", @"title":@"title five", @"detail":@"test value5", @"type2":@""}];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillAndDidChangeContentAndDidChangeContentWhenObjectMoved {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:(NSFetchedResultsChangeMove) newIndexPath:[OCMArg any]];

    NSArray *changedObjects = @[
                                @{@"type":@"1type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                @{@"type":@"1types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                @{@"type":@"2type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                ];

    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillAndDidChangeContentAndDidChangeContentWhenObjectChanged {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:0 newIndexPath:[OCMArg any]];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeSection:[OCMArg isNotNil] atIndex:0 forChangeType:(NSFetchedResultsChangeDelete)];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    NSArray *changedObjects = @[
                                @{@"type":@"1type", @"title":@"title 1", @"detail":@"test value one", @"type2":@""},
                                @{@"type":@"2type", @"title":@"title 2", @"detail":@"test value two", @"type2":@""},
                                @{@"type":@"1types",@"title":@"title 4", @"detail":@"test value four", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title 0", @"detail":@"test value zero", @"type2":@""},
                                @{@"type":@"1type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                ];

    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillAndDidChangeContentAndDidChangeContentWhenSectionChanged {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[[self.delegate stub] ignoringNonObjectArgs] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:0 newIndexPath:[OCMArg any]];

    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[[self.frc3 stub] andReturn:@[@""]] sections];

    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"type" indexTitle:@"type"] atIndex:4 forChangeType:(NSFetchedResultsChangeInsert)];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"types" indexTitle:@"types"] atIndex:5 forChangeType:(NSFetchedResultsChangeInsert)];

    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"1type" indexTitle:@"1"] atIndex:4 forChangeType:(NSFetchedResultsChangeDelete)];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"2type" indexTitle:@"2"] atIndex:5 forChangeType:(NSFetchedResultsChangeDelete)];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"1types" indexTitle:@"1"] atIndex:6 forChangeType:(NSFetchedResultsChangeDelete)];

    NSArray *changedObjects = @[
                                @{@"type":@"type", @"title":@"title one", @"detail":@"test value1", @"type2":@""},
                                @{@"type":@"type", @"title":@"title two", @"detail":@"test value2", @"type2":@""},
                                @{@"type":@"types",@"title":@"title fouth", @"detail":@"test value4", @"type2":@""},
                                @{@"type":@"type", @"title":@"title zero", @"detail":@"test value0", @"type2":@""},
                                @{@"type":@"type", @"title":@"title", @"detail":@"test value0", @"type2":@""},
                                ];

    [self.frc2 setObjects:changedObjects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testWillNotAndDidNotChangeContentAndDidChangeContent {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [self.frc2 performFetch:nil];
    [self.delegate verify];

    [[self.delegate reject] controllerWillChangeContent:self.frc];
    [[self.delegate reject] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testSectionIndexTitleForSectionName {
    self.frc.delegate = nil;
    [self.frc2 setObjects:nil];
    [self.frc2 performFetch:nil];
    self.frc.delegate = self.delegate;

    [[[self.frc3 stub] andReturn:@[@""]] sections];
    [[self.delegate expect] controllerWillChangeContent:self.frc];
    [[self.delegate expect] controllerDidChangeContent:self.frc];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg isEqual:@"1type"]];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg isEqual:@"2type"]];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg isEqual:@"1types"]];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg isEqual:@"1type"]];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg isEqual:@"1type"]];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg any] atIndex:4 forChangeType:(NSFetchedResultsChangeInsert)];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg any] atIndex:5 forChangeType:(NSFetchedResultsChangeInsert)];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg any] atIndex:6 forChangeType:(NSFetchedResultsChangeInsert)];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg isNil] forChangeType:NSFetchedResultsChangeInsert newIndexPath:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg isNil] forChangeType:NSFetchedResultsChangeInsert newIndexPath:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg isNil] forChangeType:NSFetchedResultsChangeInsert newIndexPath:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg isNil] forChangeType:NSFetchedResultsChangeInsert newIndexPath:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg isNil] forChangeType:NSFetchedResultsChangeInsert newIndexPath:[OCMArg any]];

    [self.frc2 setObjects:self.objects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

- (void) testSectionIndexTitleForSectionNameWithoutChanged {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [self.frc2 setObjects:self.objects];
    [self.frc2 performFetch:nil];

    [[self.delegate reject] controllerWillChangeContent:self.frc];
    [[self.delegate reject] controllerDidChangeContent:self.frc];
    [[self.delegate reject] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];

    [self.frc2 setObjects:self.objects];
    [self.frc2 performFetch:nil];
    [self.delegate verify];
}

#pragma mark - KVO

- (void) testWillAndDidChangeContentWithoutPerfomPatch {
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg isNotNil] atIndex:0 forChangeType:(NSFetchedResultsChangeInsert)];

//    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg any] atIndexPath:[OCMArg any] forChangeType:(NSFetchedResultsChangeUpdate) newIndexPath:[OCMArg any]];

    self.objects[0][@"detail"] = @"value1 test";
    [self.frc2 notifiyChangeObject:self.objects[0] key:@"detail" oldValue:@"test value1" newValue:@"value1 test"];
    [self.delegate verify];
}

/*
 An update is reported when an object's state changes, but the changed attributes aren't part of the sort keys.
 */
- (void) testDidChangeObjectWithNSFetchedResultsChangeUpdate {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg isNotNil] atIndex:0 forChangeType:(NSFetchedResultsChangeInsert)];

//    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg checkWithBlock:^BOOL(id obj) {
//        return [self.objects[0][@"detail"] isEqualToString:@"value1 test"];
//    }] atIndexPath:[OCMArg any] forChangeType:(NSFetchedResultsChangeUpdate) newIndexPath:[OCMArg any]];

    self.objects[0][@"detail"] = @"value1 test";
    [self.frc2 notifiyChangeObject:self.objects[0] key:@"detail" oldValue:@"test value1" newValue:@"value1 test"];
    [self.delegate verify];
}

- (void) testDidNotChangeObjectWithNSFetchedResultsChangeUpdate {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate stub] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate stub] controller:self.frc didChangeSection:[OCMArg isNotNil] atIndex:0 forChangeType:(NSFetchedResultsChangeInsert)];

    [[self.delegate stub] controller:self.frc didChangeObject:[OCMArg checkWithBlock:^BOOL(id obj) {
        return [self.objects[0][@"detail"] isEqualToString:@"test value1"];
    }] atIndexPath:[OCMArg any] forChangeType:(NSFetchedResultsChangeUpdate) newIndexPath:[OCMArg any]];

    self.objects[0][@"detail"] = @"value1 test";
    [self.frc2 notifiyChangeObject:self.objects[0] key:@"detail" oldValue:@"test value1" newValue:@"test value1"];
    [self.delegate verify];
}

- (void) _testDidChangeObjectWithChangingSectionKeyValue {
    [[self.delegate stub] controllerWillChangeContent:self.frc];
    [[self.delegate stub] controllerDidChangeContent:self.frc];
    [[self.delegate expect] controller:self.frc sectionIndexTitleForSectionName:[OCMArg any]];
    [[self.delegate expect] controller:self.frc didChangeSection:[self checkWithSectionInfo:@"" indexTitle:@""] atIndex:0 forChangeType:(NSFetchedResultsChangeMove)];

    [[self.delegate expect] controller:self.frc didChangeObject:[OCMArg checkWithBlock:^BOOL(id obj) {
        return [self.objects[0][@"detail"] isEqualToString:@"value1 test"];
    }] atIndexPath:[OCMArg any] forChangeType:(NSFetchedResultsChangeUpdate) newIndexPath:[OCMArg any]];

    self.objects[0][@"detail"] = @"value1 test";
    [self.frc2 notifiyChangeObject:self.objects[0] key:@"type" oldValue:@"1type" newValue:@"3type"];
    [self.delegate verify];
}

@end


text:
package com.sixt.service.framework.health;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sixt.service.framework.ServiceProperties;
import com.sixt.service.framework.metrics.GoGauge;
import com.sixt.service.framework.metrics.MetricBuilderFactory;
import com.sixt.service.framework.registry.consul.RegistrationManager;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.sixt.service.framework.FeatureFlags.DEFAULT_HEALTH_CHECK_POLL_INTERVAL;
import static com.sixt.service.framework.FeatureFlags.HEALTH_CHECK_POLL_INTERVAL;

@Singleton
public class HealthCheckManager implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(HealthCheckManager.class);

    private final int pollTime; //in seconds
    private final MetricBuilderFactory metricBuilderFactory;
    private final RegistrationManager registrationManager;
    private final String serviceId;
    private final ServiceProperties serviceProps;
    private final HttpClient httpClient;
    private final AtomicBoolean isShutdown = new AtomicBoolean(false);
    private ScheduledExecutorService executorService;
    protected Deque<HealthCheckContributor> pollingContributors = new ConcurrentLinkedDeque<>();
    protected Deque<HealthCheckContributor> oneShotContributors = new ConcurrentLinkedDeque<>();
    protected int failingChecksGauge;

    @Inject
    public HealthCheckManager(MetricBuilderFactory metricBuilderFactory,
                              RegistrationManager registrationManager,
                              ServiceProperties serviceProps,
                              HttpClient httpClient) {
        this.metricBuilderFactory = metricBuilderFactory;
        this.registrationManager = registrationManager;
        this.serviceProps = serviceProps;
        this.serviceId = serviceProps.getServiceInstanceId();
        this.httpClient = httpClient;
        pollTime = serviceProps.getIntegerProperty(HEALTH_CHECK_POLL_INTERVAL, DEFAULT_HEALTH_CHECK_POLL_INTERVAL);
    }

    public void registerPollingContributor(HealthCheckContributor contrib) {
        pollingContributors.add(contrib);
    }

    /**
     * A One-shot contributor is one that is removed from the list of contributors
     * as soon as it is healthy again.
     */
    public void registerOneShotContributor(HealthCheckContributor contrib) {
        oneShotContributors.add(contrib);
        reportCurrentStatus();
    }

    public void initialize() {
        GoGauge gauge = metricBuilderFactory.newMetric("health_checks").buildGauge();
        gauge.register("failing", () -> failingChecksGauge);
        executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(this, 0, pollTime, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        reportCurrentStatus();
    }

    private void reportCurrentStatus() {
        try {
            if (registrationManager.isRegistered()) {
                Collection<HealthCheck> healthChecks = getCurrentHealthChecks();
                HealthCheck.Status summary = getSummaryFor(healthChecks);
                updateHealthStatus(summary);
            } else {
                logger.debug("Waiting for {} to be registered before updating health"
                        , serviceProps.getServiceName());
            }
        } catch (Exception ex) {
            if (!isShutdown.get()) {
                logger.warn("Caught exception updating health status", ex);
            }
        }
    }

    //TODO: specific to consul; need to refactor
    public void updateHealthStatus(HealthCheck.Status status) throws Exception {
        logger.trace("Updating health of {}", serviceProps.getServiceName());
        ContentResponse httpResponse = httpClient.newRequest(getHealthCheckUri(status)).method(HttpMethod.PUT).send();
        if (httpResponse.getStatus() != 200) {
            logger.warn("Received {} trying to update health", httpResponse.getStatus());
        }
    }

    private String getHealthCheckUri(HealthCheck.Status status) {
        StringBuilder sb = new StringBuilder("http://").append(serviceProps.getRegistryServer()).
                append("/v1/agent/check/").append(status.getConsulStatus()).append("/service:").
                append(serviceId);
        return sb.toString();
    }

    public Collection<HealthCheck> getCurrentHealthChecks() {
        int failCount = 0;
        List<HealthCheck> retval = new ArrayList<>();
        Iterator<HealthCheckContributor> iter = pollingContributors.iterator();
        while (iter.hasNext()) {
            HealthCheckContributor contributor = iter.next();
            HealthCheck hc = contributor.getHealthCheck();
            if (hc != null) {
                retval.add(hc);
                if (! hc.isStatus(HealthCheck.Status.PASS)) {
                    failCount++;
                }
            }
        }
        iter = oneShotContributors.iterator();
        while (iter.hasNext()) {
            HealthCheckContributor contributor = iter.next();
            HealthCheck hc = contributor.getHealthCheck();
            if (hc != null) {
                retval.add(hc);
                if (HealthCheck.Status.PASS.equals(hc.getStatus())) {
                    iter.remove();
                } else {
                    failCount++;
                }
            }
        }
        failingChecksGauge = failCount;
        return retval;
    }

    /**
     * We return the most severe of the statuses within the collection
     */
    public HealthCheck.Status getSummaryFor(Collection<HealthCheck> checks) {
        HealthCheck.Status retval = HealthCheck.Status.PASS;
        for (HealthCheck check : checks) {
            if (check.getStatus().moreSevereThan(retval)) {
                retval = check.getStatus();
            }
        }
        return retval;
    }

    public void shutdown() {
        isShutdown.set(true);
        executorService.shutdown();
    }
}


text:
package org.jetbrains.plugins.groovy.unwrap;

import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;

import java.util.Set;

public abstract class GroovyElseUnwrapperBase extends GroovyUnwrapper {
  public GroovyElseUnwrapperBase(@NotNull String description) {
    super(description);
  }

  @Override
  public boolean isApplicableTo(@NotNull PsiElement e) {
    return (isElseBlock(e) || isElseKeyword(e)) && isValidConstruct(e);
  }

  private static boolean isElseKeyword(PsiElement e) {
    PsiElement p = e.getParent();
    return p instanceof GrIfStatement && PsiImplUtil.isLeafElementOfType(e, GroovyTokenTypes.kELSE);
  }

  private static boolean isValidConstruct(PsiElement e) {
    return ((GrIfStatement)e.getParent()).getElseBranch() != null;
  }

  @Override
  public void collectElementsToIgnore(@NotNull PsiElement element, @NotNull Set<PsiElement> result) {
    PsiElement parent = element.getParent();

    while (parent instanceof GrIfStatement) {
      result.add(parent);
      parent = parent.getParent();
    }
  }

  @Override
  protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException {
    GrStatement elseBranch;

    if (isElseKeyword(element)) {
      elseBranch = ((GrIfStatement)element.getParent()).getElseBranch();
    }
    else {
      elseBranch = (GrStatement)element;
    }

    unwrapElseBranch(elseBranch, element.getParent(), context);
  }

  protected abstract void unwrapElseBranch(GrStatement branch, PsiElement parent, Context context) throws IncorrectOperationException;
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OopFactory.X12.Parsing.Model;
using OopFactory.X12.Parsing.Model.Typed;

namespace OopFactory.X12.Tests.Unit.Creation
{
    [TestClass]
    public class Invoice810CreationTester
    {
        private string expectedX12 = @"ISA*00*          *00*          *30*943274043      *16*0069088189999  *990104*1532*U*00401*000000035*1*T*>~
  GS*IN*943274043TO*0069088189999*19990104*1532*1*X*004010~
    ST*810*0001~
      BIG*19981014*3662*****N6~
      N1*BT*The Scheduling Coordinator, Inc~
        N3*53241 Hamilton Dr~
        N4*Palo Alto*CA*95622*US~
      N1*RE*Bank of America- (Mkt and GMC)~
        N3*1850 Gateway Boulevard~
        N4*Concord*CA*94520*US~
        REF*11*1233626208~
        REF*01*026009593~
      ITD*03*****19981020~
      IT1*1*1*EA*2896035.3~
        PID*X****RMR Scheduling Coordinator - Estimated RMR~
      TDS*289603530~
      CTT*1~
    SE*16*0001~
  GE*1*1~
IEA*1*000000035~";

        [TestMethod]
        public void Create810_4010Version()
        {
            var message = new Interchange(Convert.ToDateTime("1/4/99 15:32"), 35, false, '~','*','>')
            {
                SecurityInfoQualifier = "00",
                InterchangeSenderIdQualifier = "30",
                InterchangeSenderId = "943274043",
                InterchangeReceiverIdQualifier = "16",
                InterchangeReceiverId = "0069088189999"
            };

            var fg = message.AddFunctionGroup("IN", Convert.ToDateTime("1/4/1999 15:32"), 1);
            fg.ApplicationSendersCode = "943274043TO";
            fg.ApplicationReceiversCode = "0069088189999";
            fg.ResponsibleAgencyCode = "X";
            fg.VersionIdentifierCode = "004010";

            var trans = fg.AddTransaction("810", "0001");

            var big = trans.AddSegment(new TypedSegmentBIG());
            big.BIG01_InvoiceDate = Convert.ToDateTime("10/14/1998");
            big.BIG02_InvoiceNumber = "3662";
            big.BIG07_TransactionTypeCode = "N6";

            var billTo = trans.AddLoop(new TypedLoopN1());
            billTo.N101_EntityIdentifierCodeEnum = EntityIdentifierCode.BillToParty;
            billTo.N102_Name = "The Scheduling Coordinator, Inc";

            var billToAddress = billTo.AddSegment(new TypedSegmentN3());
            billToAddress.N301_AddressInformation = "53241 Hamilton Dr";

            var billToLocale = billTo.AddSegment(new TypedSegmentN4());
            billToLocale.N401_CityName = "Palo Alto";
            billToLocale.N402_StateOrProvinceCode = "CA";
            billToLocale.N403_PostalCode = "95622";
            billToLocale.N404_CountryCode = "US";

            var remitTo = trans.AddLoop(new TypedLoopN1());
            remitTo.N101_EntityIdentifierCodeEnum = EntityIdentifierCode.PartyToReceiveCommercialInvoiceRemittance;
            remitTo.N102_Name = "Bank of America- (Mkt and GMC)";

            var remitToAddress = remitTo.AddSegment(new TypedSegmentN3());
            remitToAddress.N301_AddressInformation = "1850 Gateway Boulevard";

            var remitToLocale = remitTo.AddSegment(new TypedSegmentN4());
            remitToLocale.N401_CityName = "Concord";
            remitToLocale.N402_StateOrProvinceCode = "CA";
            remitToLocale.N403_PostalCode = "94520";
            remitToLocale.N404_CountryCode = "US";

            var remitToRef1 = remitTo.AddSegment(new TypedSegmentREF());
            remitToRef1.REF01_ReferenceIdQualifier = "11";
            remitToRef1.REF02_ReferenceId = "1233626208";

            var remitToRef2 = remitTo.AddSegment(new TypedSegmentREF());
            remitToRef2.REF01_ReferenceIdQualifier = "01";
            remitToRef2.REF02_ReferenceId = "026009593";

            var itd = trans.AddSegment(new TypedSegmentITD());
            itd.ITD01_TermsTypeCode = "03";
            itd.ITD06_TermsNetDueDate = Convert.ToDateTime("10/20/1998");

            var it1 = trans.AddLoop(new TypedLoopIT1());
            it1.IT101_AssignedIdentification = "1";
            it1.IT102_QuantityInvoiced = 1;
            it1.IT103_UnitOrBasisForMeasurementCode = UnitOrBasisOfMeasurementCode.Each;
            it1.IT104_UnitPrice = 2896035.3m;

            var pid = it1.AddLoop(new TypedLoopPID());
            pid.PID01_ItemDescriptionType = "X";
            pid.PID05_Description = "RMR Scheduling Coordinator - Estimated RMR";

            var tds = trans.AddSegment(new TypedSegmentTDS());
            tds.TDS01_AmountN2 = 289603530;

            var ctt = trans.AddSegment(new TypedSegmentCTT());
            ctt.CTT01_NumberOfLineItems = 1;

            var x12 = message.SerializeToX12(true);

            Trace.Write(x12);

            Assert.AreEqual(expectedX12, x12);
        }
    }
}


text:
<?php

namespace OAuth2\Test;

class AccessTokenTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvalidRefreshToken()
    {
        new \OAuth2\AccessToken(['invalid_access_token' => 'none']);
    }

    public function testExpiresInCorrection()
    {
        $options = array('access_token' => 'access_token', 'expires_in' => 100);
        $token = new \OAuth2\AccessToken($options);
        $this->assertNotNull($token->expires);
    }
}


text:
package com.gmail.cs475x.anybar4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;

import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;

public class AnyBar4j {

	/**
	 * The default host that AnyBar4j connects to.
	 */
	public static final String DEFAULT_HOST = "localhost";

	/**
	 * The default port that AnyBar is bound to.
	 */
	public static final int DEFAULT_PORT = 1738;

	/**
	 * The hostname or IP address of the target machine.
	 */
	public final InetAddress host;

	/**
	 * The port to connect to on the target machine.
	 */
	public final int port;

	/**
	 * The client socket.
	 */
	private DatagramSocket socket;

	public static void main(String[] args)
	throws IOException {
		OptionParser parser = new OptionParser();

		OptionSpec<Void> optionHelp = parser.acceptsAll(Arrays.asList("?", "help"), "Show the available command line flags with descriptions.");
		OptionSpec<String> optionImage = parser.acceptsAll(Arrays.asList("c", "color", "i", "image"), "The name of the image to display in the AnyBar instance.").withRequiredArg().ofType(String.class).defaultsTo(AnyBarImage.WHITE.toString());
		OptionSpec<String> optionHost = parser.acceptsAll(Arrays.asList("h", "host", "ip"), "The hostname or IP address of the machine running the AnyBar instance.").withRequiredArg().ofType(String.class).defaultsTo(DEFAULT_HOST);
		OptionSpec<Integer> optionPort = parser.acceptsAll(Arrays.asList("p", "port"), "The port number that the AnyBar instance is running on.").withRequiredArg().ofType(Integer.class).defaultsTo(DEFAULT_PORT);

		OptionSet options = parser.parse(args);

		if (options.has(optionHelp)) {
			System.out.println("AnyBar4j v1.0.0");
			System.out.println("Copyright (c) 2015 cs475x (Cody)\n");
			parser.printHelpOn(System.out);

			return;
		}

		AnyBar4j anybar = null;
		String image = options.valueOf(optionImage);
		String host = options.valueOf(optionHost);
		Integer port = options.valueOf(optionPort);

		try {
			anybar = new AnyBar4j(host, port);

			anybar.setImage(image);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (anybar != null) {
				anybar.close();
			}
		}
	}

	/**
	 * Constructs an AnyBar4j instance that will connect to the default host and port.
	 *
	 * @throws SocketException if a new socket could not be created.
	 * @throws UnknownHostException if the supplied hostname is invalid.
	 */
	public AnyBar4j()
	throws SocketException, UnknownHostException {
		this(DEFAULT_HOST, DEFAULT_PORT);
	}

	/**
	 * Constructs an AnyBar4j instance that will connect to the specified host and port.
	 *
	 * @param host The hostname or IP that AnyBar is running on.
	 * @param port The port that AnyBar is running on.
	 * @throws SocketException if a new socket could not be created.
	 * @throws UnknownHostException if the supplied hostname is invalid.
	 */
	public AnyBar4j(String host, int port)
	throws SocketException, UnknownHostException {
		this.host = InetAddress.getByName(host);
		this.port = port > 0 ? port : 1738;
		this.socket = new DatagramSocket();
	}

	/**
	 * Sets the displayed image on the AnyBar instance to one of the defaults.
	 *
	 * @param image The image to display.
	 * @throws IOException
	 */
	public void setImage(AnyBarImage image)
	throws IOException {
		this.setImage(image.toString());
	}

	/**
	 * Sets the displayed image on the AnyBar instance.
	 *
	 * @param imageName The name of the image to display.
	 * @throws IOException if the packet could not be sent.
	 */
	public void setImage(String imageName)
	throws IOException {
		if (this.socket != null) {
			byte[] data = imageName.getBytes();
			DatagramPacket packet = new DatagramPacket(data, data.length, this.host, this.port);

			this.socket.send(packet);
		}
	}

	/**
	 * Closes the client socket.
	 */
	public void close() {
		if (this.socket != null) {
			this.socket.close();
		}
	}

	/**
	 * The default images/colors in AnyBar.
	 */
	public enum AnyBarImage {
		WHITE,
		RED,
		ORANGE,
		YELLOW,
		GREEN,
		CYAN,
		BLUE,
		PURPLE,
		BLACK,
		QUESTION,
		EXCLAMATION;

		@Override
		public String toString() {
			return this.name().toLowerCase();
		}
	}

}


text:
import { lowQualitySuggestionConfidenceThreshold } from 'wherehows-web/constants/metadata-acquisition';
import { formatAsCapitalizedStringWithSpaces } from 'wherehows-web/utils/helpers/string';
import { module, test } from 'qunit';

module('Unit | Utility | datasets/metadata acquisition', function() {
  test('lowQualitySuggestionConfidenceThreshold is a number', function(assert) {
    assert.ok(typeof lowQualitySuggestionConfidenceThreshold === 'number');
  });

  test('formatAsCapitalizedStringWithSpaces generates the correct display string', function(assert) {
    [
      ['CONFIDENTIAL', 'Confidential'],
      ['LIMITED_DISTRIBUTION', 'Limited distribution'],
      ['HIGHLY_CONFIDENTIAL', 'Highly confidential']
    ].forEach(([source, target]) => {
      assert.equal(formatAsCapitalizedStringWithSpaces(source), target, `correctly converts ${source}`);
    });
  });
});


text:
API Platform is a next-generation web framework designed to easily create API-first projects without compromising extensibility
and flexibility:

* Design your own data model as plain old PHP classes or [**import an existing one**](https://api-platform.com/docs/schema-generator)
  from the [Schema.org](https://schema.org/) vocabulary.
* **Expose in minutes a hypermedia REST or a GraphQL API** with pagination, data validation, access control, relation embedding,
  filters and error handling...
* Benefit from Content Negotiation: [GraphQL](https://graphql.org), [JSON-LD](https://json-ld.org), [Hydra](https://hydra-cg.com),
  [HAL](https://github.com/mikekelly/hal_specification/blob/master/hal_specification.md), [JSONAPI](https://jsonapi.org/), [YAML](https://yaml.org/), [JSON](https://www.json.org/), [XML](https://www.w3.org/XML/) and [CSV](https://www.ietf.org/rfc/rfc4180.txt) are supported out of the box.
* Enjoy the **beautiful automatically generated API documentation** ([Swagger](https://swagger.io/)/[OpenAPI](https://www.openapis.org/)).
* Add [**a convenient Material Design administration interface**](https://api-platform.com/docs/admin) built with [React](https://reactjs.org/)
  without writing a line of code.
* **Scaffold fully functional Progressive-Web-Apps and mobile apps** built with [React](https://api-platform.com/docs/client-generator/react),
[Vue.js](https://api-platform.com/docs/client-generator/vuejs) or [React Native](https://api-platform.com/docs/client-generator/react-native)
thanks to [the client generator](https://api-platform.com/docs/client-generator) (a Vue.js generator is also available).
* Install a development environment and deploy your project in production using **[Docker](https://api-platform.com/docs/distribution)**
and [Kubernetes](https://api-platform.com/docs/deployment/kubernetes).
* Easily add **[JSON Web Token](https://api-platform.com/docs/core/jwt) or [OAuth](https://oauth.net/) authentication**.
* Create specs and tests with a **developer friendly API testing tool** on top of [Behat](https://behat.org/).

[![GitHub Actions](https://github.com/api-platform/core/workflows/CI/badge.svg)](https://github.com/api-platform/core/actions?workflow=CI)
[![Travis CI](https://travis-ci.org/api-platform/core.svg?branch=master)](https://travis-ci.org/api-platform/core)
[![CircleCI](https://circleci.com/gh/api-platform/core/tree/master.svg?style=shield)](https://circleci.com/gh/api-platform/core/tree/master)
[![AppVeyor](https://ci.appveyor.com/api/projects/status/grwuyprts3wdqx5l/branch/master?svg=true)](https://ci.appveyor.com/project/dunglas/dunglasapibundle/branch/master)
[![Codecov](https://codecov.io/gh/api-platform/core/branch/master/graph/badge.svg)](https://codecov.io/gh/api-platform/core/branch/master)
[![SymfonyInsight](https://insight.symfony.com/projects/92d78899-946c-4282-89a3-ac92344f9a93/mini.svg)](https://insight.symfony.com/projects/92d78899-946c-4282-89a3-ac92344f9a93)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/api-platform/core/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/api-platform/core/?branch=master)

The official project documentation is available **[on the API Platform website](https://api-platform.com)**.

API Platform embraces open web standards (OpenAPI, JSON-LD, GraphQL, Hydra, HAL, JSONAPI, JWT, OAuth, HTTP...) and the
[Linked Data](https://www.w3.org/standards/semanticweb/data) movement. Your API will automatically expose structured data
in Schema.org / JSON-LD. It means that your API Platform application is usable **out of the box** with technologies of
the semantic web.

It also means that **your SEO will be improved** because **[Google leverages these formats](https://developers.google.com/search/docs/guides/intro-structured-data)**.

Last but not least, the server component of API Platform is built on top of the [Symfony](https://symfony.com) framework,
while client components leverage [React](https://reactjs.org/) (a [Vue.js](https://vuejs.org/) flavor is also available).
It means that you can:

* Use **thousands of Symfony bundles and React components** with API Platform.
* Integrate API Platform in **any existing Symfony or React application**.
* Reuse **all your Symfony and React skills**, benefit of the incredible amount of documentation available.
* Enjoy the popular [Doctrine ORM](https://www.doctrine-project.org/projects/orm.html) (used by default, but fully optional:
  you can use the data provider you want, including but not limited to MongoDB and Elasticsearch)

## Install

[Read the official "Getting Started" guide](https://api-platform.com/docs/distribution).

## Credits

Created by [Kévin Dunglas](https://dunglas.fr). Commercial support available at [Les-Tilleuls.coop](https://les-tilleuls.coop).


text:
Tecnologia

Els materials

1. Què són els materials?
2. Els materials es poden classificar segons l'origen i el caràcter metàlic i no metàlic. Comenta-ho.
3. Descriu els metalls fèrric.
4. Descriu els metalls no fèrrics.


text:
This chapter focus on guidelines that are specific to writing typings.

## Design Principles

- Enable typing author to stay true to the shape of the library as much as possible.
- Use latest TypeScript best practices in authoring typings

## Topics

- [Functions](./functions.md)
- [Overloading](./overloading.md)
- [Namespaces and Modules](./namespaces-and-modules.md)
- [Shape of typings](./shape-of-typings.md)
- [tslint configuration](./tslint.md)

Also check out [Typings Writing Guidelines](https://github.com/types/_guidelines)


text:
package org.apache.james.mime4j.message.storage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @version $Id: TempStorage.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
 */
public abstract class TempStorage {
    private static Log log = LogFactory.getLog(TempStorage.class);
    private static TempStorage inst = null;

    static {

        String clazz = System.getProperty("org.apache.james.mime4j.tempStorage");
        try {

            if (clazz != null) {
                inst = (TempStorage) Class.forName(clazz).newInstance();
            }

        } catch (Throwable t) {
            log.warn("Unable to create or instantiate TempStorage class '"
                      + clazz + "' using SimpleTempStorage instead", t);
        }

        if (inst == null) {
            inst = new SimpleTempStorage();
        }
    }

    /**
     * Gets the root temporary path which should be used to
     * create new temporary paths or files.
     *
     * @return the root temporary path.
     */
    public abstract TempPath getRootTempPath();

    public static TempStorage getInstance() {
        return inst;
    }

    public static void setInstance(TempStorage inst) {
        if (inst == null) {
            throw new NullPointerException("inst");
        }
        TempStorage.inst = inst;
    }
}


text:
class UsersController {
  /** @ngInject */
  constructor($http) {
    $http
      .get('app/users/users.json')
      .then(response => {
        this.users = response.data;
      });
  }
}

export const users = {
  template: require('./users.html'),
  controller: UsersController
};


text:
<?php
/**
 * @author Michał Pawłowski <michal@pawlowski.be>
 */

namespace Vero\ACL;

/**
 * Access Control List.
 */
class ACL
{
    protected $data = [];
    protected $backend;
    protected $sessionRole;

    protected $last = [];

    /**
     * Construct ACL with specified backend
     */
    public function __construct(Backend $backend)
    {
        $this -> backend = $backend;
    }

    /**
     * Set role for current session.
     *
     * @return self
     */
    public function setSessionRole(Role $role)
    {
        $this -> sessionRole = $role;
        return $this;
    }

    /**
     * Returns true if role have access to key.
     *
     * @param string|array
     * @param null|string|Role
     * @return boolean
     */
    public function check($key, $role = null)
    {
        $role = $this -> getRole($role === null ? $this -> sessionRole : $role);

        if (is_array($key)) {
            $keyS = implode('/', $key);
        } else {
            $keyS = $key;
            $key = explode('/', $key);
        }

        if (!isset($this -> last[$role][$keyS])) {
            $this -> last[$role][$keyS] = $this -> doCheck($key, $role);
        }

        return $this -> last[$role][$keyS];
    }

    /**
     * Real check algorithm implementation.
     *
     * @param array $key
     * @param string $role
     * @return boolean
     */
    protected function doCheck(array $key, $role)
    {
        $next = $this -> getData($role);

        foreach ($key as $part) {
            if (isset($next[$part])) {
                if (!$next[$part]['access']) {
                    return false;
                }

                $next = isset($next[$part]['items']) ? $next[$part]['items'] : [];

            } else {
                return isset($next['*']) ? $next['*']['access'] : false;
            }
        }

        return true;
    }

    /**
     * Set access for specified role and key.
     *
     * @param string|Role
     * @param string|array
     * @param boolean
     */
    public function set($role, $key, $value)
    {
        $role = $this -> getRole($role);
        $value = (boolean) $value;

        if ($this -> check($key, $role) == $value) {
            return;
        }

        if (!is_array($key)) {
            $key = explode('/', $key);
        }

        // search key
        $last = null;
        $next = & $this -> getData($role);

        foreach ($key as $part) {
            if (!isset($next[$part]) || !$next[$part]['access']) {
                $next[$part] = [
                    'access' => true
                ];
            }

            $last = & $next[$part];

            if (!isset($last['items'])) {
                $last['items'] = [];
            }

            $next = & $last['items'];
        }

        $last['access'] = $value;
    }

    /**
     * Save settings for speciefied role.
     *
     * @param string|Role
     */
    public function save($role)
    {
        if (!$this -> backend instanceof WritableBackend) {
            throw new \InvalidArgumentException(
                'Provided backend must be instance of Vero\ALC\WritableBackend for permanent change of settings.'
            );
        }

        $role = $this -> getRole($role);
        $this -> backend -> save($role, $this -> getData($role));
    }

    /**
     * Check, if role argument is valid and returm role ID.
     *
     * @param scalar|Role
     * @return string
     * @throws \InvalidArgumentException
     */
    protected function getRole($role)
    {
        if (!$role instanceof Role && !is_scalar($role)) {
            throw new \InvalidArgumentException('Role must be instance of Vero\ALC\Role or scalar.');
        }

        if ($role instanceof Role) {
            return $role -> getRole();
        }

        return $role;
    }

    /**
     * Load and return data for specified role.
     *
     * @param string
     * @return array
     */
    protected function & getData($role)
    {
        if (!isset($this -> data[$role])) {
            $this -> data[$role] = (array) $this -> backend -> get($role);
        }

        return $this -> data[$role];
    }
}


text:
require('../../modules/es6.reflect.get');
module.exports = require('../../modules/_core').Reflect.get;


text:
<?php

// To run this example from the command line:
// $ cd examples
// $ php de_DE_example.php "Ein Beispieltext aus dem du die Schlüsselwörter extrahieren möchtest."

require '../vendor/autoload.php';

use DonatelloZa\RakePlus\RakePlus;

if ($argc < 2) {
    echo "Please specify the text you would like to be parsed, e.g.:\n";
    echo "php de_DE_example.php \"Ein Beispieltext aus dem du die Schlüsselwörter extrahieren möchtest.\"\n";
    exit(1);
}

$keywords = RakePlus::create($argv[1], 'de_DE')->keywords();
print "The keywords for \"{$argv[1]}\" is:\n";
print_r($keywords);

$phrases = RakePlus::create($argv[1], 'de_DE')->get();
print "The phrases for \"{$argv[1]}\" is:\n";
print_r($phrases);


text:
package com.ilivoo.hibernate.learning.map.bidirection_join.manytomany.xml2;

import java.io.Serializable;

public class Score implements Serializable{

	private static final long serialVersionUID = 6761138423196283112L;

	private Integer id;

	private Course course;

	private Student student;

	private float score;

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public float getScore() {
		return score;
	}

	public void setScore(float score) {
		this.score = score;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
}


text:
package sparklyr

import org.apache.spark._
import org.apache.spark.rdd.RDD
import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.catalyst.encoders.RowEncoder

object ApplyUtils {
  def groupBy(rdd: RDD[Row], colPosition: Array[Int]): RDD[Row] = {
    rdd.groupBy(
      r => colPosition.map(p => r.get(p)).mkString("|")
    ).map(
      r => Row(r._2.toSeq)
    )
  }

  def groupBy(
    data: org.apache.spark.sql.Dataset[Row],
    colPosition: Array[Int]): org.apache.spark.sql.Dataset[Row] = {

      val schema: StructType = StructType(
        List(
          StructField("array", ArrayType(data.schema))
        )
      )

      val encoder = RowEncoder(schema)

      data.groupByKey(
        r => colPosition.map(p => r.get(p)).mkString("|")
      )(org.apache.spark.sql.Encoders.STRING).mapGroups(
        (k, r) => Row(r.toList)
      )(encoder)

    }

  def groupByArrow(
    data: org.apache.spark.sql.Dataset[Row],
    colPosition: Array[Int],
    timeZoneId: String,
    recordsPerBatch: Int): org.apache.spark.sql.Dataset[Row] = {

      val schema: StructType = StructType(
        List(
          StructField("array", ArrayType(BinaryType))
        )
      )

      val encoder = RowEncoder(schema)
      val sourceSchema = data.schema

      data.groupByKey(
        r => colPosition.map(p => r.get(p)).mkString("|")
      )(org.apache.spark.sql.Encoders.STRING).mapGroups(
        (k, r) => Row((new ArrowConvertersImpl()).toBatchArray(r, sourceSchema, timeZoneId, recordsPerBatch))
      )(encoder)

    }
}


text:
import { AxisScale } from '@visx/axis';

export default function getScaleBandwidth<Scale extends AxisScale>(scale?: Scale) {
  // Broaden type before using 'xxx' in s as typeguard.
  const s = scale as AxisScale;
  return s && 'bandwidth' in s ? s?.bandwidth() ?? 0 : 0;
}


text:
require 'test_helper'

describe Cask::CLI do
  it "lists the taps for casks that show up in two taps" do
    Cask::CLI.nice_listing(%w[
      phinze-cask/adium
      phinze-cask/google-chrome
      passcod-cask/adium
    ]).must_equal(%w[
      google-chrome
      passcod-cask/adium
      phinze-cask/adium
    ])
  end

  describe "process" do
    it "creates the appdir if it does not exist" do
      Cask.appdir.rmdir
      shutup {
        Cask::CLI.process('list')
      }
      Cask.appdir.directory?.must_equal true
    end

    it "respects the env variable when choosing what appdir to create, not touching the default appdir" do
      default_applications_dir = Cask.appdir
      default_applications_dir.rmdir
      custom_applications_dir = Pathname(Dir.mktmpdir('custom_app_dir'))
      custom_applications_dir.rmdir

      default_applications_dir.directory?.must_equal false
      custom_applications_dir.directory?.must_equal false

      begin
        ENV['HOMEBREW_CASK_OPTS'] = "--appdir=#{custom_applications_dir}"
        shutup {
          Cask::CLI.process('list')
        }
      ensure
        ENV.delete 'HOMEBREW_CASK_OPTS'
      end

      default_applications_dir.directory?.must_equal false
      custom_applications_dir.directory?.must_equal true
    end

    it "creates the qlplugindir if it does not exist" do
      Cask.qlplugindir.rmdir
      shutup {
        Cask::CLI.process('list')
      }
      Cask.qlplugindir.directory?.must_equal true
    end

    it "respects the env variable when choosing what qlplugindir to create, not touching the default qlplugindir" do
      default_qlplugin_dir = Cask.qlplugindir
      default_qlplugin_dir.rmdir
      custom_qlplugin_dir = Pathname(Dir.mktmpdir('custom_qlplugin_dir'))
      custom_qlplugin_dir.rmdir

      default_qlplugin_dir.directory?.must_equal false
      custom_qlplugin_dir.directory?.must_equal false

      begin
        ENV['HOMEBREW_CASK_OPTS'] = "--qlplugindir=#{custom_qlplugin_dir}"
        shutup {
          Cask::CLI.process('list')
        }
      ensure
        ENV.delete 'HOMEBREW_CASK_OPTS'
      end

      default_qlplugin_dir.directory?.must_equal false
      custom_qlplugin_dir.directory?.must_equal true
    end

    it "respects the ENV variable when choosing a non-default Caskroom location" do
      default_caskroom_dir = Cask.caskroom
      default_caskroom_dir.rmdir
      custom_caskroom_dir = Pathname(Dir.mktmpdir('custom_caskroom_dir'))
      custom_caskroom_dir.rmdir

      default_caskroom_dir.directory?.must_equal false
      custom_caskroom_dir.directory?.must_equal false

      begin
        ENV['HOMEBREW_CASK_OPTS'] = "--caskroom=#{custom_caskroom_dir}"
        shutup {
          Cask::CLI.process('list')
        }
      ensure
        ENV.delete 'HOMEBREW_CASK_OPTS'
      end

      default_caskroom_dir.directory?.must_equal false
      custom_caskroom_dir.directory?.must_equal true
    end

    it "exits with a status of 1 when something goes wrong" do
      Cask::CLI.expects(:exit).with(1)
      Cask::CLI.expects(:lookup_command).raises(CaskError)
      shutup {
        Cask::CLI.process('list')
      }
    end
  end
end


text:
class UsersController < ApplicationController
  before_action :require_login
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to root_path, notice: 'User was successfully created.' }
        format.json { render action: 'show', status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        # If we're changing the user's password, Devise will invalidate all
        # sessions as this user, so let's check to see if that's happened and
        # reauthenticate them if so.
        if user_params.key?(:password) and current_user.id == @user.id
          sign_in(@user, bypass: true)
        end

        format.html { redirect_to edit_profile_path, notice: 'Your profile has been updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to root_path }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      if params[:id]
        @user = User.find(params[:id])
      else
        @user = current_user
      end

      authorize @user
    end

    # Never trust parameters from the scary internet, only allow the
    # whitelist through.
    def user_params
      params.require(:user).permit(:email, :password, :application_goal,
                                   :followup_offset, :name)
                           .delete_if {|key, value| value.empty?}
    end
end


text:
pytest-difido
=============

PyTest plugin for creating flexible and informative test reports

----

This `pytest`_ plugin was generated with `Cookiecutter`_ along with `@hackebrot`_'s `cookiecutter-pytest-plugin`_ template.

Features
--------

* Flexible locally generated HTML report on the running machine
* Reports are generated at runtime. No need to wait for test execution to end
* Easily attach files and images to the report
* Works also in remote mode. You can add `Difido server <https://github.com/Top-Q/difido-reports/releases/>`_ that allows publishing reports to central server
* Console reports - Reports to the console in addition to the HTML output mainly for development phase and CI/CD systems
* Extensible - Allows to implement and add additional reporters

Requirements
------------

* PyTest >= 4.0.0
* Python >= 3

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

You can install "pytest-difido" via `pip`_ from `PyPI`_::

    $ pip install pytest-difido

Usage
-----

To use the report, add the report fixture to your test cases. You can report simple message, links, HTML elements and more

..  code-block:: python

    def test_messaging(report):
        # Simple message will be added to the report
        report.that("Simple report message")
        # link to Google
        report.link(title='Google', link=r'http:\\www.google.com')

        # Message will be hidden inside toggle element
        report.start_level("start toggle")
        report.that("In toggle")
        report.stop_level()

        # Message will appear in bold font
        report.step("bold message")

        # HTML element will be added to the report
        report.html("Table", """

            Company
            Contact

            ACME Corporation
            Road Bumper

            DOLO Inc
            Wired Coyote

            """)

Files and images can be attached to the HTML report. The files are copied to the local and remote reports.

..  code-block:: python

    def test_files(report):
        # File will be copied and attached to the report
        report.file(file_path=os.path.join("resources", "some_file.txt"), description="My text file")
        # Image will added with thumbnail
        report.img(img_path=os.path.join("resources", "cat.jpg"), description="Cats are awesome")

Properties can be added to the suite or to each test. The properties are disaplyed in the report and, if ElasticSearch integration is enabled, can be searched.

..  code-block:: python

    def test_add_properties(report):
        # Property will be added to the execution
        report.add_execution_properties("int_Execution", "66")

        # Property will be added to the current running test
        report.add_test_property("double_testProp", "1.56")

If you prefer to use to report without fixtures, or if you want to use it from places other then your test cases, you can intantiate the `Report` class.
The 'Report' class is implemented as singleton so you will always get the same instance

..  code-block:: python

    def test_report_without_fixture():
        """
        If you don't want to get the reporter as fixture or if you want to use it not from test method
        you can just instantiate the Report class. The Report class is implemented as Singleton
        """
        from difido.report_manager import Report
        report = Report()
        report.that("very important message")

Server Installation
--------------------

This step is **not** mandatory. Local reports will be generated also without the Difido server. Follow this step only if you wish to
have central server for publishing test results. If all you need is local reports that will be generated on the running machine, skip this step

* Download the latest Difido server ZIP file from the `Difido releases`_ page
* Extract the content of the file
* Run the '[root]/bin/start.bat' or '[root]/bin/start.sh' file according to your OS.
* Set the host and port in the client configuration as shown in the next section
* Add the 'difido.reporters.RemoteReporter' to the 'df_reporters' list in the configuration. More information about reporters can be found in the 'Reporters' section

You can access the server from your browser (E.G http://localhost:8080/). For more information please refer to the `Difido server Wiki page`_

Configuration
-------------

You can configure the reporter from the `pytest.ini` file or from the command line.
In the case where a parameter is defined using both methods, the value defined from the command line takes precedence

pytest.ini examples

..  code-block:: ini

    [pytest]
    ; Host or ip of Difido server. Default localhost
    df_host = 192.168.0.13
    ; Port of Difido server. Default 8080
    df_port = 8090
    ; Result folder for HTML and console reports. Default is current directory
    df_output_folder = /etc/log/
    ; Reporters are defined in the following comma-separated list
    df_reporters = difido.reporters.LocalReporter,difido.reporters.RemoteReporter,difido.reporters.ConsoleReporter

Command line example

..  code-block:: ini

    $ pytest .\tests\test_report_examples.py --df_host=192.168.10.1 --df_port=8090

**Configuration Properties**

* **df_output_folder** - Result folder for HTML and console reports (default .)
* **df_host**          - Host or ip of Difido server (default localhost)
* **df_port**          - Difido server port (default 8080)
* **df_reporters**     - Comma-separated list of reporter classes. The all reporters recieves the event from the report manager
* **df_description**   - Description of test execution as shown in the Difido server

Reporters
---------

Reporters are Python classes that translates the events recieved from the tests and generates a single report format.
The plugin currently includes three types of reporters:

* **difido.reporters.LocalReporter** - Generates local HTML reports to the repors output folder
* **difido.reporters.RemoteReporter** - Pulishes results to the Difido server
* **difido.reporters.ConsoleReporter** - Writes to the conole. At the end of the run the output is also copied to a file in the reports output folder.

You can decide which reporters you want to enabled by adding or removing the classes from the 'df_reporters' list.
By default, only the 'LocalReporter' and 'ConsoleReporter' are included in the list. To use the remote reporter, for example, you will need to add it by configuring the 'df_reporters' as following:

..  code-block:: ini

  df_reporters = difido.reporters.LocalReporter,difido.reporters.RemoteReporter,difido.reporters.ConsoleReporter

You can also implement your own reporter and add it to the list.

Contributing
------------
Contributions are very welcome. Tests can be run with `tox`_, please ensure
the coverage at least stays the same before you submit a pull request.

License
-------

Distributed under the terms of the `Apache Software License 2.0`_ license, "pytest-difido" is free and open source software

Issues
------

If you encounter any problems, please `file an issue`_ along with a detailed description.

.. _`Cookiecutter`: https://github.com/audreyr/cookiecutter
.. _`@hackebrot`: https://github.com/hackebrot
.. _`MIT`: http://opensource.org/licenses/MIT
.. _`BSD-3`: http://opensource.org/licenses/BSD-3-Clause
.. _`GNU GPL v3.0`: http://www.gnu.org/licenses/gpl-3.0.txt
.. _`Apache Software License 2.0`: http://www.apache.org/licenses/LICENSE-2.0
.. _`cookiecutter-pytest-plugin`: https://github.com/pytest-dev/cookiecutter-pytest-plugin
.. _`file an issue`: https://github.com/Top-Q/difido-reports/issues
.. _`pytest`: https://github.com/pytest-dev/pytest
.. _`tox`: https://tox.readthedocs.io/en/latest/
.. _`pip`: https://pypi.org/project/pip/
.. _`PyPI`: https://pypi.org/project
.. _`Difido releases`: https://github.com/Top-Q/difido-reports/releases/
.. _`Difido server Wiki page`: https://github.com/Top-Q/difido-reports/wiki/The-Difido-Server


text:
import time
import bluetooth
import os
from abstract_driver import AbstractDriver
from pprint import pprint

#ERRORS
DEVICES_NOT_FOUND    = "Could not find bluetooth devices nearby."
DEVICE_NOT_CONNECTED = "Could not find target bluetooth device nearby."

class BluetoothDriver(AbstractDriver):

    DEVICE_NAME    = None
    DEVICE_ADDRESS = None
    DEVICE_PORT    = 1
    DEV            = None

    # ----------------------------------------------------------------------
    # Basic Functions
    # ----------------------------------------------------------------------

    def __init__(self, name="Pinguino", dev=None):
        self.DEVICE_NAME = name

        list_devs = BluetoothDriver.nearbyDevs(self.DEVICE_NAME)
        if dev is None:
            if list_devs:
                self.DEVICE_ADDRESS = list_devs[0]
            else:
                raise Exception(DEVICES_NOT_FOUND)
        else:
            if not dev in list_devs:
                raise Exception(DEVICE_NOT_CONNECTED)
            else:
                self.DEVICE_ADDRESS = dev

        self.__connect__()

    # ----------------------------------------------------------------------
    def __connect__(self):
        pprint(self.DEVICE_ADDRESS)
        while(True):
            try:
                self.DEV = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
                self.DEV.connect((self.DEVICE_ADDRESS, self.DEVICE_PORT))
                break;
            except bluetooth.btcommon.BluetoothError as error:
                self.DEV.close()
                print "Could not connect: ", error, "; Retrying in 10s..."
                time.sleep(10)

    # ----------------------------------------------------------------------
    def __disconnect__(self):
        self.DEV.close()

    # ----------------------------------------------------------------------
    def disconnect(self):
        self.__disconnect__()

    # ----------------------------------------------------------------------
    # I/O Functions
    # ----------------------------------------------------------------------

    def write(self, msg):
        self.DEV.send(msg)
        '''try:

        except usb.USBError, V:
            raise Exception(V[1])'''

    #----------------------------------------------------------------------
    def read(self, length=1024):
        return self.DEV.recv(length)
        '''try:
            return "".join(map(chr, self.dh.bulkRead(self.ENDPOINT_IN, length, self.TIMEOUT)))
        except usb.core.USBError, V:
            raise Exception(V[1])'''

    def readProcess(self, cmd):
        self.write(cmd)
        return self.read()

    # ----------------------------------------------------------------------
    # Static Methods
    # ----------------------------------------------------------------------
    @staticmethod
    def nearbyDevs(target_name = "Pinguino"):
        devs = []
        pprint(devs)
        nearby_devices = bluetooth.discover_devices()
        pprint(nearby_devices)
        for dev in nearby_devices:
            if target_name == bluetooth.lookup_name( dev ):
                devs.append(dev)
        return devs


text: @extends('frontEnd.master')


text:
define_upgrade do
  if Partybus.config.bootstrap_server
    must_be_data_master
    # Make sure API is down
    stop_services(["nginx", "opscode-erchef"])

    start_services(["oc_bifrost", "postgresql"])
    force_restart_service("opscode-chef-mover")
    log "Granting READ permission for users within the same org using internal group membership"

    run_command("/opt/opscode/embedded/bin/escript " +
                "/opt/opscode/embedded/service/opscode-chef-mover/scripts/migrate " +
                "mover_global_admins_user_addition_callback " +
                "normal " +
                "mover_transient_queue_batch_migrator")

    stop_services(["opscode-chef-mover"])
  end
end


text:
namespace mcr {

class CMiniFrameWnd : public CWnd
{
public:
	CMiniFrameWnd();

	//BOOL Create(DWORD style, const RECT& rect, CWnd* parent_wnd, UINT id);
	//BOOL CreateEx(DWORD ex_style, DWORD style, const RECT& rect, CWnd* parent_wnd, UINT id);

//	CWnd* CreateView(CCreateContext* context, UINT id= AFX_IDW_PANE_FIRST);

//	CView* GetActiveView() const;
//	void SetActiveView(CView* view, bool notify= true);

};

} // namespace


text:
package org.apache.river.test.spec.locatordiscovery;

import java.util.logging.Level;

import org.apache.river.qa.harness.TestException;
import org.apache.river.test.share.LocatorsUtil;

import net.jini.core.discovery.LookupLocator;

/**
 * This class verifies that the LookupLocatorDiscovery utility
 * operates in a manner consistent with the specification. In particular, this
 * class verifies that "the method getLocators returns a new
 * array upon each invocation."
 *
 * The environment in which this class expects to operate is as follows:
 *

 *
 zero lookup services
 *
 an instance of the lookup locator discovery utility that is
 *         constructed using an array of locators consistent with the
 *         the test's configuration
 *

 *
 * If the lookup locator discovery utility functions as specified, then on
 * each separate invocation of the getLocators method, a new
 * array containing the LookupLocator instances with which the
 * lookup locator discovery utility is configured to discover will be returned.
 *
 */
public class GetLocatorsNew extends GetLocators {

    /** Executes the current test by doing the following:
     *

     *
 twice invokes getLocators to retrieve the locators the lookup
     *         locator discovery utility is currently configured to discover
     *
 verifies that each invocation returns different arrays having
     *         the same contents
     *

     */
    public void run() throws Exception {
        super.run();

        logger.log(Level.FINE, "1st call to getLocators ...");
        LookupLocator[] lldLocs0 = lld.getDiscoveredLocators();

        logger.log(Level.FINE, "2nd call to getLocators ...");
        LookupLocator[] lldLocs1 = lld.getDiscoveredLocators();

        logger.log(Level.FINE, "verifying arrays from calls "
                          +"to getLocators() are different arrays "
                          +"with equal content ...");
        if(lldLocs0 == lldLocs1) {
            throw new TestException("same array returned on different calls");
        }//endif
	if (!LocatorsUtil.compareLocatorSets(lldLocs0, lldLocs1,Level.FINE)) {
	    throw new TestException("Locator set are not equivalent");
	}
    }//end run

}//end class GetLocatorsNew


text:
from coapthon import defines
from coapthon.messages.option import Option

__author__ = 'Giacomo Tanganelli'
__version__ = "2.0"

class Message(object):
    """
    Manage messages.
    """
    def __init__(self):

        """
        Initialize a CoAP Message.

        """
        # The type. One of {CON, NON, ACK or RST}.
        self._type = None
        # The 16-bit Message Identification.
        self._mid = None
        # The token, a 0-8 byte array.
        self.token = None
        # The set of options of this message.
        self._options = []
        # The payload of this message.
        self.payload = None
        # The destination address of this message.
        self.destination = None
        # The source address of this message.
        self.source = None
        # Indicates if the message has been acknowledged.
        self._acknowledged = False
        # Indicates if the message has been rejected.
        self._rejected = False
        # Indicates if the message has timeouted.
        self._timeouted = False
        # Indicates if the message has been canceled.
        self._canceled = False
        # Indicates if the message is a duplicate.
        self._duplicate = False
        # The timestamp
        self._timestamp = None
        # The code
        self.code = None

    @property
    def options(self):
        """
        Property for retrieving the options of the message.

        :return: the options
        """
        return self._options

    def add_option(self, option):
        """
        Add an option to the message.

        :type option: coapthon2.messages.option.Option
        :param option: the option
        :raise TypeError: if the option is not repeatable and such option is already present in the message
        """
        assert isinstance(option, Option)
        name, type_value, repeatable, defaults = defines.options[option.number]
        if not repeatable:
            try:
                self._options.index(option)
                raise TypeError("Option : %s is not repeatable", name)
            except ValueError:
                self._options.append(option)
        else:
            self._options.append(option)

    def del_option(self, option):
        """
        Delete an option from the message

        :type option: coapthon2.messages.option.Option
        :param option: the option
        """
        assert isinstance(option, Option)
        try:
            while True:
                self._options.remove(option)
        except ValueError:
            pass

    def del_option_name(self, name):
        """
        Delete an option from the message by name

        :param name: option name
        """
        for o in self._options:
            assert isinstance(o, Option)
            if o.number == defines.inv_options[name]:
                self._options.remove(o)

    @property
    def mid(self):
        """
        Return the mid of the message.

        :return: the MID
        """
        return self._mid

    @mid.setter
    def mid(self, m):
        """
        Sets the MID of the message.

        :param m: the MID
        :raise AttributeError: if m is not int or cannot be represented on 16 bits.
        """
        if not isinstance(m, int) or m > 65536:
            raise AttributeError
        self._mid = m

    @property
    def type(self):
        """
        Return the type of the message.

        :return: the type
        """
        return self._type

    @type.setter
    def type(self, t):
        """
        Sets the type of the message.

        :param t: the type
        :raise AttributeError: if t is not a valid type
        """
        if not isinstance(t, int) or t not in defines.types:
            raise AttributeError
        self._type = t

    @property
    def duplicated(self):
        """
        Checks if this message is a duplicate.

        :return: True, if is a duplicate
        """
        return self._duplicate

    @duplicated.setter
    def duplicated(self, d):
        """
        Marks this message as a duplicate.

        :param d: if a duplicate
        """
        assert isinstance(d, bool)
        self._duplicate = d

    @property
    def acknowledged(self):
        """
        Checks if is this message has been acknowledged.

        :return: True, if is acknowledged
        """
        return self._acknowledged

    @acknowledged.setter
    def acknowledged(self, a):
        """
        Marks this message as acknowledged.

        :param a: if acknowledged
        """
        assert isinstance(a, bool)
        self._acknowledged = a

    @property
    def rejected(self):
        """
        Checks if this message has been rejected.

        :return: True, if is rejected
        """
        return self._rejected

    @rejected.setter
    def rejected(self, r):
        """
        Marks this message as rejected.

        :param r: if rejected
        """
        assert isinstance(r, bool)
        self._rejected = r

    @property
    def timeouted(self):
        """
        Checks if this message has timeouted. Confirmable messages in particular
        might timeout.

        :return: True, if has timeouted
        """
        return self._timeouted

    @timeouted.setter
    def timeouted(self, t):
        """
        Marks this message as timeouted. Confirmable messages in particular might
        timeout.

        :param t: if timeouted
        """
        assert isinstance(t, bool)
        self._timeouted = t

    @property
    def cancelled(self):
        """
        Checks if this message has been canceled.

        :return: True, if is canceled
        """
        return self._canceled

    @cancelled.setter
    def cancelled(self, c):
        """
        Marks this message as canceled.

        :param c: if canceled
        """
        assert isinstance(c, bool)
        self._canceled = c

    @staticmethod
    def new_ack(message):
        """
        Create a new acknowledgment for the specified message.

        :param message: the message to acknowledge
        :return: the acknowledgment
        """
        ack = Message()
        types = {v: k for k, v in defines.types.iteritems()}
        ack.type = types['ACK']
        ack._mid = message.mid
        ack.code = 0
        ack.token = None
        ack.destination = message.source
        return ack

    @staticmethod
    def new_rst(message):
        """
        Create a new reset message for the specified message.

        :param message: the message to reject
        :return: the rst message
        """
        rst = Message()
        types = {v: k for k, v in defines.types.iteritems()}
        rst.type = types['RST']
        rst._mid = message.mid
        rst.token = None
        rst.code = 0
        rst.destination = message.source
        return rst

    def __str__(self):
        """
        Return the message as a formatted string.

        :return: the string representing the message
        """
        msg = "Source: " + str(self.source) + "\n"
        msg += "Destination: " + str(self.destination) + "\n"
        msg += "Type: " + str(defines.types[self.type]) + "\n"
        msg += "MID: " + str(self._mid) + "\n"
        if self.code is None:
            self.code = 0
        try:
            msg += "Code: " + str(defines.inv_responses[self.code]) + "\n"
        except KeyError:
            msg += "Code: " + str(defines.codes[self.code]) + "\n"
        msg += "Token: " + str(self.token) + "\n"
        for opt in self._options:
            msg += str(opt)
        msg += "Payload: " + "\n"
        msg += str(self.payload) + "\n"
        return msg

    @property
    def etag(self):
        """
        Get the ETag option of the message.

        :return: the ETag values or [] if not specified by the request
        """
        value = []
        for option in self.options:
            if option.number == defines.inv_options['ETag']:
                value.append(option.value)
        return value

    @etag.setter
    def etag(self, etag):
        """
        Add an ETag option to the message.

        :param etag: the etag
        """
        option = Option()
        option.number = defines.inv_options['ETag']
        option.value = etag
        self.add_option(option)

    @etag.deleter
    def etag(self):
        """
        Delete an ETag from a message.

        """
        self.del_option_name("ETag")

    @property
    def content_type(self):
        """
        Get the Content-Type option of a response.

        :return: the Content-Type value or 0 if not specified by the response
        """
        value = 0
        for option in self.options:
            if option.number == defines.inv_options['Content-Type']:
                value = int(option.value)
        return value

    @content_type.setter
    def content_type(self, content_type):
        """
        Set the Content-Type option of a response.

        :type content_type: int
        :param content_type: the Content-Type
        """
        option = Option()
        option.number = defines.inv_options['Content-Type']
        option.value = int(content_type)
        self.add_option(option)


text:
#ifndef UBLOX_AT_CELLULAR_NETWORK_H_
#define UBLOX_AT_CELLULAR_NETWORK_H_

#include "AT_CellularNetwork.h"
#include "APN_db.h"

namespace mbed
{

class UBLOX_AT_CellularNetwork : public AT_CellularNetwork
{
public:
    UBLOX_AT_CellularNetwork(ATHandler &atHandler);
    virtual ~UBLOX_AT_CellularNetwork();

    virtual nsapi_error_t connect();

    virtual const char *get_gateway();

protected:
    virtual NetworkStack *get_stack();

    virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology opRat);

    virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack);

    virtual RegistrationMode has_registration(RegistrationType rat);

private:

    /** Length of IMSI buffer.
     */
    static const int MAX_IMSI_LENGTH = 15;

    /** The type of authentication to use.
     */
    nsapi_security_t _auth;

    /** Connect the on board IP stack of the modem.
     *
     * @return      True if successful, otherwise false.
     */
    nsapi_error_t open_data_channel();

    /** Activate one of the on-board modem's connection profiles.
     *
     * @param apn      The APN to use.
     * @param username The user name to use.
     * @param password The password to use.
     * @param auth     The authentication method to use
     *                 (NSAPI_SECURITY_NONE, NSAPI_SECURITY_PAP,
     *                 NSAPI_SECURITY_CHAP or NSAPI_SECURITY_UNKNOWN).
     * @return         True if successful, otherwise false.
     */
    bool activate_profile(const char* apn, const char* username, const char* password);

    /** Convert nsapi_security_t to the modem security numbers.
     *
     * @param nsapi_security      Security protocol.
     * @return                    Modem security numbers.
     */
    int nsapi_security_to_modem_security(nsapi_security_t nsapi_security);

    /** Disconnect the on board IP stack of the modem.
     *
     * @return      True if successful, otherwise false.
     */
    bool disconnect_modem_stack();

    /** Read IMSI of modem.
     */
    nsapi_error_t get_imsi(char* imsi);

    /** Get the next set of credentials from the database.
     */
    void get_next_credentials(char ** config);
};

} // namespace mbed

#endif // UBLOX_AT_CELLULAR_NETWORK_H_


text:
#pragma once
#include <aws/chime-sdk-voice/ChimeSDKVoice_EXPORTS.h>
#include <aws/chime-sdk-voice/ChimeSDKVoiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace ChimeSDKVoice
{
namespace Model
{

  /**
   */
  class AWS_CHIMESDKVOICE_API GetPhoneNumberOrderRequest : public ChimeSDKVoiceRequest
  {
  public:
    GetPhoneNumberOrderRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetPhoneNumberOrder"; }

    Aws::String SerializePayload() const override;

    inline const Aws::String& GetPhoneNumberOrderId() const{ return m_phoneNumberOrderId; }

    inline bool PhoneNumberOrderIdHasBeenSet() const { return m_phoneNumberOrderIdHasBeenSet; }

    inline void SetPhoneNumberOrderId(const Aws::String& value) { m_phoneNumberOrderIdHasBeenSet = true; m_phoneNumberOrderId = value; }

    inline void SetPhoneNumberOrderId(Aws::String&& value) { m_phoneNumberOrderIdHasBeenSet = true; m_phoneNumberOrderId = std::move(value); }

    inline void SetPhoneNumberOrderId(const char* value) { m_phoneNumberOrderIdHasBeenSet = true; m_phoneNumberOrderId.assign(value); }

    inline GetPhoneNumberOrderRequest& WithPhoneNumberOrderId(const Aws::String& value) { SetPhoneNumberOrderId(value); return *this;}

    inline GetPhoneNumberOrderRequest& WithPhoneNumberOrderId(Aws::String&& value) { SetPhoneNumberOrderId(std::move(value)); return *this;}

    inline GetPhoneNumberOrderRequest& WithPhoneNumberOrderId(const char* value) { SetPhoneNumberOrderId(value); return *this;}

  private:

    Aws::String m_phoneNumberOrderId;
    bool m_phoneNumberOrderIdHasBeenSet = false;
  };

} // namespace Model
} // namespace ChimeSDKVoice
} // namespace Aws