text:
/*!
/* CSS Buttons */
/* --------------------------------------------------------- */
/* Button psuedo states */
/* ------------------------- */
/* Easily pump out default styles, as well as :hover, :focus, :active, */
/* and disabled options for all buttons */
/* Base styles */
/* -------------------------------------------------- */
/* Core styles */
.btn {
  display: inline-block;
  padding: 14px 28.8px;
  margin-bottom: 0;
  /* For input.btn */

  font-size: 14px;
  font-weight: 500;
  line-height: 14px;
  letter-spacing: 1px;
  text-align: center;
  text-transform: uppercase;
  text-shadow: none;
  vertical-align: middle;
  cursor: pointer;
  border: 1px solid transparent;
  /* ensure that buttons do not have a border */

  border-radius: 100px;
  white-space: nowrap;
  -webkit-transition-duration: 0.1s;
  -moz-transition-duration: 0.1s;
  -o-transition-duration: 0.1s;
  transition-duration: 0.1s;
  -webkit-transition-property: color, background-color;
  -moz-transition-property: color, background-color;
  -o-transition-property: color, background-color;
  transition-property: color, background-color;
  -webkit-transition-timing-function: cubic-bezier(0.694, 0.0482, 0.335, 1);
  -moz-transition-timing-function: cubic-bezier(0.694, 0.0482, 0.335, 1);
  -o-transition-timing-function: cubic-bezier(0.694, 0.0482, 0.335, 1);
  transition-timing-function: cubic-bezier(0.694, 0.0482, 0.335, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.btn:focus {
  outline: thin dotted #333;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}
.btn:hover,
.btn:focus {
  color: #fff;
  text-decoration: none;
}
.btn:active,
.btn.active {
  outline: 0;
  background-image: none;
  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
  cursor: default;
  pointer-events: none;
  /* Future-proof disabling of clicks */

  opacity: 0.65;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
  box-shadow: none;
}
/* Alternate buttons */
/* -------------------------------------------------- */
.btn-default {
  color: #222222;
  background-color: #e5e5e5;
  border-color: #e5e5e5;
}
.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active {
  background-color: #cccccc;
  border-color: #cccccc;
}
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
  background-color: #e5e5e5;
  border-color: #e5e5e5;
}
.btn-primary {
  color: #fcfcfc;
  background-color: #33b5e5;
  border-color: #33b5e5;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active {
  background-color: #1a9bcb;
  border-color: #1a9bcb;
}
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #33b5e5;
  border-color: #33b5e5;
}
/* Warning appears as orange */
.btn-warning {
  color: #fcfcfc;
  background-color: #ffbb33;
  border-color: #ffbb33;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning:active,
.btn-warning.active {
  background-color: #ffaa00;
  border-color: #ffaa00;
}
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
  background-color: #ffbb33;
  border-color: #ffbb33;
}
/* Danger and error appear as red */
.btn-danger {
  color: #fcfcfc;
  background-color: #ff4444;
  border-color: #ff4444;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger:active,
.btn-danger.active {
  background-color: #ff1111;
  border-color: #ff1111;
}
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
  background-color: #ff4444;
  border-color: #ff4444;
}
/* Success appears as green */
.btn-success {
  color: #fcfcfc;
  background-color: #99cc00;
  border-color: #99cc00;
}
.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active {
  background-color: #739900;
  border-color: #739900;
}
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
  background-color: #99cc00;
  border-color: #99cc00;
}
/* Info appears as blue-green */
.btn-info {
  color: #fcfcfc;
  background-color: #aa66cc;
  border-color: #aa66cc;
}
.btn-info:hover,
.btn-info:focus,
.btn-info:active,
.btn-info.active {
  background-color: #9540bf;
  border-color: #9540bf;
}
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
  background-color: #aa66cc;
  border-color: #aa66cc;
}
/* Jade appears as green-blue */
.btn-jade {
  color: #fcfcfc;
  background-color: #62c98f;
  border-color: #62c98f;
}
.btn-jade:hover,
.btn-jade:focus,
.btn-jade:active,
.btn-jade.active {
  background-color: #3fb974;
  border-color: #3fb974;
}
.btn-jade.disabled:hover,
.btn-jade[disabled]:hover,
fieldset[disabled] .btn-jade:hover,
.btn-jade.disabled:focus,
.btn-jade[disabled]:focus,
fieldset[disabled] .btn-jade:focus,
.btn-jade.disabled:active,
.btn-jade[disabled]:active,
fieldset[disabled] .btn-jade:active,
.btn-jade.disabled.active,
.btn-jade[disabled].active,
fieldset[disabled] .btn-jade.active {
  background-color: #62c98f;
  border-color: #62c98f;
}
/* Inverse appears as white */
.btn-inverse {
  color: #262829;
  background-color: #ffffff;
  border-color: #ffffff;
}
.btn-inverse:hover,
.btn-inverse:focus,
.btn-inverse:active,
.btn-inverse.active {
  background-color: #e6e6e6;
  border-color: #e6e6e6;
}
.btn-inverse.disabled:hover,
.btn-inverse[disabled]:hover,
fieldset[disabled] .btn-inverse:hover,
.btn-inverse.disabled:focus,
.btn-inverse[disabled]:focus,
fieldset[disabled] .btn-inverse:focus,
.btn-inverse.disabled:active,
.btn-inverse[disabled]:active,
fieldset[disabled] .btn-inverse:active,
.btn-inverse.disabled.active,
.btn-inverse[disabled].active,
fieldset[disabled] .btn-inverse.active {
  background-color: #ffffff;
  border-color: #ffffff;
}
.btn-inverse:hover,
.btn-inverse:focus,
.btn-inverse:active,
.btn-inverse.active {
  color: #262829;
  background-color: #e6e6e6;
  border-color: #e6e6e6;
}
/* Link buttons */
/* ------------------------- */
/* Make a button look and behave like a link */
.btn-link,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
  background-color: transparent;
  background-image: none;
  -webkit-box-shadow: none;
  box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
  border-color: transparent;
}
.btn-link {
  color: #33b5e5;
  font-weight: normal;
  cursor: pointer;
  border-radius: 0;
}
.btn-link:hover,
.btn-link:focus {
  color: #1a9bcb;
  text-decoration: underline;
  background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
  color: #333333;
  text-decoration: none;
}
/* Button Sizes */
/* -------------------------------------------------- */
.btn-jumbo {
  padding: 26.599999999999998px 54px;
  font-size: 18px;
}
.btn-large {
  padding: 21px 45px;
  font-size: 18px;
}
.btn-small {
  padding: 5px 18px;
  font-size: 12px;
  line-height: 1.5;
  /* ensure proper height of button next to small input */

}
.btn-mini {
  padding: 3px 16px;
  font-size: 11px;
  line-height: 1;
  /* ensure proper height of button next to small input */

}
/* Button Sizes */
/* -------------------------------------------------- */
/* Large button */
.button-large {
  width: 100%;
  font-family: "Open Sans", 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding: 0 30px;
  font-size: 17px;
  line-height: 64px;
  letter-spacing: 1px;
  border-radius: 40px;
}
/* Small button */
.button-small {
  padding: 9px 25px;
  font-size: 12px;
}
/* Mini button */
.button-mini {
  padding: 6px 20px;
  font-size: 10px;
}
/* Block button */
/* -------------------------------------------------- */
.btn-block {
  display: block;
  width: 100%;
  padding-left: 0;
  padding-right: 0;
}
/* Vertically space out multiple block buttons */
.btn-block + .btn-block {
  margin-top: 5px;
}
/* Specificity overrides */
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
  width: 100%;
}
/* Centered button */
.button-centered {
  position: absolute;
  top: 50%;
  left: 50%;
}
/* Alternate styles */
/* -------------------------------------------------- */
.button-jade {
  color: #fcfcfc;
  background: #62c98f;
  -webkit-transition: all 0.1s ease-out;
  -moz-transition: all 0.1s ease-out;
  -o-transition: all 0.1s ease-out;
  transition: all 0.1s ease-out;
}
.button-jade:hover {
  color: #fcfcfc;
  background: #20c97b;
}
/* Cool gray */
.button-coolgray {
  color: #fff;
  background-color: #3f4546;
}
.button-white {
  color: #222;
  background: #fff;
}
.button-white:hover {
  color: #222;
  background: #e5e5e5;
}
.button-dark {
  color: #fff;
  background-color: #222;
}
.button-dark:hover {
  background-color: #444;
}
/* Buttons */
/* -------------------------------- */
.btn-facebook {
  display: block;
  width: 180px;
  padding-left: 24px;
  font-size: 18px;
  font-weight: 300;
  line-height: 56px;
  text-decoration: none;
  background-color: #3a5898;
  background-position: 12px center;
  background-repeat: no-repeat;
  border-radius: 10px;
}
.btn-facebook:hover {
  background-color: #2f4a84;
}
/*!
/* CSS Section
/* ----------------------------------------- */
/* Base Palette */
/* Base Typography */
/* Spacing */
.section {
  font-family: "Open Sans", 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding: 50px 0 40px;
  background-color: #ffffff;
  text-shadow: none;
  /* Add vertical spacing to Bootstrap grid columns */

  /* Headigns */

  /* Paragraph and button styles. */

  /* ------------------------------------------- */

  /* We use .label instead of .btn since less code is required for customizations. */

}
.section .col {
  padding: 0 70px;
}
.section h2,
.section h3 {
  color: #222;
  padding: 15px 0 5px 0;
  margin: 0;
  font-weight: 300;
}
.section h3 {
  font-size: 26px;
  line-height: 32px;
}
.section p,
.section .label {
  color: #222;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  line-height: 24px;
  font-size: 14px;
}
.section .label {
  padding: 0 12px;
  font-size: 11px;
  font-weight: 300;
  text-shadow: none;
  text-transform: uppercase;
  background: #e6e6e6;
}
.section .label:hover {
  color: #fff;
  background: rgba(0, 0, 0, 0.35);
}
.section-aqua {
  background-color: #30beda;
}
.section-aqua h1,
.section-aqua h2,
.section-aqua h3 {
  color: #ffffff;
}
.section-aqua p,
.section-aqua .label,
.section-aqua .label:hover {
  color: #c7eef5;
}
.section-aqua .label {
  background: #219eb6;
}
.section-aqua .label:hover {
  background: rgba(0, 0, 0, 0.35);
}
.section-blue {
  background-color: #008fd5;
}
.section-blue h1,
.section-blue h2,
.section-blue h3 {
  color: #ffffff;
}
.section-blue p,
.section-blue .label,
.section-blue .label:hover {
  color: #88d8ff;
}
.section-blue .label {
  background: #006da2;
}
.section-blue .label:hover {
  background: rgba(0, 0, 0, 0.35);
}
.section-slate {
  background-color: #4b5c66;
}
.section-slate h1,
.section-slate h2,
.section-slate h3 {
  color: #ffffff;
}
.section-slate p,
.section-slate .label,
.section-slate .label:hover {
  color: #a6b5be;
}
.section-slate .label {
  background: #354149;
}
.section-slate .label:hover {
  background: rgba(0, 0, 0, 0.35);
}
.section-violet {
  background-color: #5a62d2;
}
.section-violet h1,
.section-violet h2,
.section-violet h3 {
  color: #ffffff;
}
.section-violet p,
.section-violet .label,
.section-violet .label:hover {
  color: #e6e7f8;
}
.section-violet .label {
  background: #353fc4;
}
.section-violet .label:hover {
  background: rgba(0, 0, 0, 0.35);
}
.section-gray {
  background-color: #89949b;
}
.section-gray h1,
.section-gray h2,
.section-gray h3 {
  color: #ffffff;
}
.section-gray p,
.section-gray .label,
.section-gray .label:hover {
  color: #eaeced;
}
.section-gray .label {
  background: #6f7b82;
}
.section-gray .label:hover {
  background: rgba(0, 0, 0, 0.35);
}


text:
static BOOL databaseDeletionTestWasDatabaseAtPathDeleted = NO;

@interface TD_Database()
- (BOOL) closeInternal; // expose the internal close method.
@end

@interface TD_MockDatabase : TD_Database

@property (assign, nonatomic) BOOL isCloseExecuted;
@property (assign, nonatomic) BOOL forceCloseFailure;

@end

@implementation TD_MockDatabase

#pragma mark - Init object
- (id)initWithPath:(NSString *)path
{
    self = [super initWithPath:path];
    if (self) {
        _isCloseExecuted = NO;
        _forceCloseFailure = NO;
    }

    return self;
}

#pragma mark - TD_Database methods
- (BOOL)closeInternal
{
    self.isCloseExecuted = YES;

    return (self.forceCloseFailure ? NO : [super closeInternal]);
}

+ (BOOL)deleteClosedDatabaseAtPath:(NSString *)path error:(NSError **)outError
{
    databaseDeletionTestWasDatabaseAtPathDeleted = YES;

    return [super deleteClosedDatabaseAtPath:path error:outError];
}

@end

@interface TD_DatabaseDeletionTests : CloudantTests

@property (assign, nonatomic) BOOL willBeDeletedNotificationReceived;

@end

@implementation TD_DatabaseDeletionTests

- (void)setUp
{
    [super setUp];

    databaseDeletionTestWasDatabaseAtPathDeleted = NO;

    self.willBeDeletedNotificationReceived = NO;
}

- (void)tearDown { [super tearDown]; }

- (void)testDeleteDatabasePostNotification
{
    CDTEncryptionKeyNilProvider *provider = [CDTEncryptionKeyNilProvider provider];
    NSString *path = [NSTemporaryDirectory()
        stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_postNotification"];

    TD_MockDatabase *db =
        [TD_MockDatabase createEmptyDBAtPath:path withEncryptionKeyProvider:provider];

    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(didReceivedWillBeDeletedNotification:)
                          name:TD_DatabaseWillBeDeletedNotification
                        object:db];

    [db deleteDatabase:nil];

    [defaultCenter removeObserver:self name:TD_DatabaseWillBeDeletedNotification object:db];

    XCTAssertTrue(self.willBeDeletedNotificationReceived,
                  @"Send the corresponding notification when a db is deleted");
}

- (void)testDeleteDatabaseCloseDBIfItIsOpen
{
    CDTEncryptionKeyNilProvider *provider = [CDTEncryptionKeyNilProvider provider];
    NSString *path = [NSTemporaryDirectory()
        stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_closeIfOpen"];

    TD_MockDatabase *db =
        [TD_MockDatabase createEmptyDBAtPath:path withEncryptionKeyProvider:provider];

    [db deleteDatabase:nil];

    XCTAssertTrue(db.isCloseExecuted, @"Close the database before deleting it");
}

- (void)testDeleteDatabaseDoesNotCloseDBIfItIsNotOpen
{
    NSString *path = [NSTemporaryDirectory()
        stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_notCloseIfNotOpen"];

    TD_MockDatabase *db = [[TD_MockDatabase alloc] initWithPath:path];

    [db deleteDatabase:nil];

    XCTAssertFalse(db.isCloseExecuted,
                   @"If the db was not open, do not close it before deleting it");
}

- (void)testDeleteDatabaseCallsDeleteAtPath
{
    CDTEncryptionKeyNilProvider *provider = [CDTEncryptionKeyNilProvider provider];
    NSString *path = [NSTemporaryDirectory()
        stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_deleteAtPath"];

    TD_MockDatabase *db =
        [TD_MockDatabase createEmptyDBAtPath:path withEncryptionKeyProvider:provider];

    [db deleteDatabase:nil];

    XCTAssertTrue(databaseDeletionTestWasDatabaseAtPathDeleted,
                  @"Call the primery method to delete the database");
}

- (void)testDeleteDatabaseDoesNotCallDeleteAtPathIfCloseFails
{
    CDTEncryptionKeyNilProvider *provider = [CDTEncryptionKeyNilProvider provider];
    NSString *path = [NSTemporaryDirectory()
                      stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_NotDeleteAtPath"];

    TD_MockDatabase *db =
        [TD_MockDatabase createEmptyDBAtPath:path withEncryptionKeyProvider:provider];

    db.forceCloseFailure = YES;
    [db deleteDatabase:nil];

    XCTAssertFalse(databaseDeletionTestWasDatabaseAtPathDeleted,
                   @"Do not delete the db if it can not be closed");
}

- (void)testDeleteDatabaseRemoveFiles
{
    CDTEncryptionKeyNilProvider *provider = [CDTEncryptionKeyNilProvider provider];
    NSString *path = [NSTemporaryDirectory()
                      stringByAppendingPathComponent:@"TD_DatabaseDeletionTests_removeFiles"];

    TD_MockDatabase *db =
        [TD_MockDatabase createEmptyDBAtPath:path withEncryptionKeyProvider:provider];

    [db deleteDatabase:nil];

    XCTAssertFalse(db.exists, @"When a db is delete, all files are removed from disk");
}

- (void)didReceivedWillBeDeletedNotification:(NSNotification *)notification
{
    self.willBeDeletedNotificationReceived = YES;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<rec-mapping prefix="edm" schemaVersion="5.2.3" locked="false">
  <facts>
    <entry>
      <string>baseUrl</string>
      <string>http://acc.brabantcloud.delving.org/</string>
    </entry>
    <entry>
      <string>orgId</string>
      <string>brabantcloud</string>
    </entry>
    <entry>
      <string>spec</string>
      <string>ton-smits-huis</string>
    </entry>
    <entry>
      <string>dataProvider</string>
      <string>Ton Smits Huis</string>
    </entry>
    <entry>
      <string>schemaVersions</string>
      <string>tib_1.0.3, edm_5.2.3</string>
    </entry>
    <entry>
      <string>dataProviderUri</string>
      <string>http://id.musip.nl/crm_e39/2872</string>
    </entry>
    <entry>
      <string>name</string>
      <string>Ton Smits Huis</string>
    </entry>
    <entry>
      <string>rights</string>
      <string>http://www.europeana.eu/rights/rr-r/</string>
    </entry>
    <entry>
      <string>provider</string>
      <string>Erfgoed Brabant</string>
    </entry>
    <entry>
      <string>language</string>
      <string>nl</string>
    </entry>
    <entry>
      <string>type</string>
      <string>IMAGE</string>
    </entry>
    <entry>
      <string>country</string>
      <string>Netherlands</string>
    </entry>
  </facts>
  <functions>
    <mapping-function name="deepZoomUrltwee">
      <groovy-code>
        <string>image = it.toString().replaceAll('^.*[\\/|\\\\]','').replaceAll('(?i)\\.jpg|\\.jpeg|\\.tif|\\.tiff|\\.png|\\.gif','.tif.dzi')</string>
        <string>"http://media.delving.org/iip/deepzoom/mnt/tib/tiles/brabantcloud/${spec}/${image}"</string>
      </groovy-code>
    </mapping-function>
  </functions>
  <dyn-opts/>
  <node-mappings>
    <node-mapping inputPath="/constant" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:citName">
      <groovy-code>
        <string>'ccBrabant_TSH'</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/object_number" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:citOldId">
      <groovy-code>
        <string>"ccBrabant_TSH_${_objectnumber}"</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:thumbLarge"/>
    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:thumbSmall"/>
    <node-mapping inputPath="/facts/name" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:collection"/>
    <node-mapping inputPath="/input/whateverroot/creator.role" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:creatorRole"/>
    <node-mapping inputPath="/input/whateverroot/production.date.start" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:productionPeriod"/>
    <node-mapping inputPath="/input/whateverroot/production.date.start" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:productionStart"/>
    <node-mapping inputPath="/input/whateverroot/production.date.end" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:productionEnd"/>
    <node-mapping inputPath="/input/whateverroot/dimension.part" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:dimension">
      <siblings>
        <path>/input/whateverroot/dimension.type</path>
        <path>/input/whateverroot/dimension.unit</path>
        <path>/input/whateverroot/dimension.value</path>
      </siblings>
      <groovy-code>
        <string>"${_M3['dimensiontype'].text[0]} ${_M3['dimensionpart']}: ${_M3['dimensionvalue']} ${_M3['dimensionunit']} "</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/object_number" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:objectNumber"/>
    <node-mapping inputPath="/input/whateverroot/object_name/@value" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:objectSoort"/>
    <node-mapping inputPath="/input/whateverroot/material/@value" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:material"/>
    <node-mapping inputPath="/input/whateverroot/production.place" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:place"/>
    <node-mapping inputPath="/input/whateverroot/technique/@value" outputPath="/edm:RDF/nave:BrabantCloudResource/nave:technique"/>
    <node-mapping inputPath="/input/whateverroot/title" outputPath="/edm:RDF/edm:ProvidedCHO/dc:title">
      <groovy-code>
        <string>if (_absent_) {</string>
        <string>"geen titel"</string>
        <string>}</string>
        <string>else {</string>
        <string>"${_title}"</string>
        <string>}</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/creator" outputPath="/edm:RDF/edm:ProvidedCHO/dc:creator"/>
    <node-mapping inputPath="/input/whateverroot/content.subject" outputPath="/edm:RDF/edm:ProvidedCHO/dc:subject" operator="ALL"/>
    <node-mapping inputPath="/input/whateverroot/description" outputPath="/edm:RDF/edm:ProvidedCHO/dc:description"/>
    <node-mapping inputPath="/input/whateverroot/object_number" outputPath="/edm:RDF/edm:ProvidedCHO/dc:identifier"/>
    <node-mapping inputPath="/constant" outputPath="/edm:RDF/edm:ProvidedCHO/dc:rights">
      <groovy-code>
        <string>'© L. Smits-Zoetmulder. De werken van Ton Smits zijn auteursrechtelijk beschermd. Indien u zijn werken openbaar wil maken dient u vooraf toestemming te verkrijgen. Neemt u hiervoor contact op met mevr. L. Smits–Zoetmulder, Jacob Reviuslaan 25, 5644 TP Eindhoven.'</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/constant" outputPath="/edm:RDF/edm:ProvidedCHO/dcterms:rightsHolder">
      <groovy-code>
        <string>'L. Smits-Zoetmulder. De werken van Ton Smits zijn auteursrechtelijk beschermd. Indien u zijn werken openbaar wil maken dient u vooraf toestemming te verkrijgen. Neemt u hiervoor contact op met mevr. L. Smits–Zoetmulder, Jacob Reviuslaan 25, 5644 TP Eindhoven.'</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/ore:Aggregation/edm:isShownBy/@rdf:resource"/>

    <node-mapping inputPath="/facts/rights" outputPath="/edm:RDF/ore:Aggregation/edm:rights"/>

    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/ore:Aggregation/edm:isShownAt/@rdf:resource">
      <groovy-code>
          <!--todo: note that this loop should be generated in the snippet-->
          <string>_input.whateverroot * { _whateverroot -></string>
          <string>_whateverroot.reproductionreference * { _reproductionreference -></string>
          <string>"${largeThumbnail(_reproductionreference).sanitizeURI()}"</string>
          <string>}</string>
          <string>}</string>
      </groovy-code>
    </node-mapping>
    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/ore:Aggregation/edm:object/@rdf:resource"/>
    <node-mapping inputPath="/facts/provider" outputPath="/edm:RDF/ore:Aggregation/edm:provider"/>
    <node-mapping inputPath="/facts/dataProvider" outputPath="/edm:RDF/ore:Aggregation/edm:dataProvider"/>
    <node-mapping inputPath="/facts/type" outputPath="/edm:RDF/edm:ProvidedCHO/edm:type"/>
    <node-mapping inputPath="/input/whateverroot/priref" outputPath="/edm:RDF/ore:Aggregation/edm:uri"/>
    <node-mapping inputPath="/facts/language" outputPath="/edm:RDF/ore:Aggregation/edm:language"/>
    <node-mapping inputPath="/facts/country" outputPath="/edm:RDF/ore:Aggregation/edm:country"/>
    <node-mapping inputPath="/facts/spec" outputPath="/edm:RDF/ore:Aggregation/edm:collectionName"/>
    <node-mapping inputPath="/facts/name" outputPath="/edm:RDF/ore:Aggregation/edm:collectionTitle"/>
    <node-mapping inputPath="/input/whateverroot/reproduction.reference" outputPath="/edm:RDF/nave:DelvingResource/nave:deepZoomUrl">
      <groovy-code>
        <string>"${deepZoomUrltwee(_reproductionreference).sanitizeURI()}"</string>
      </groovy-code>
    </node-mapping>
  </node-mappings>
</rec-mapping>


text:
title: Serialization In NServiceBus
summary: How instances of .net classes are serialized onto the transport.
---

NServiceBus takes instances of .net objects (messages, events and commands) and then sens/receives them over a specified [Transport](/nservicebus/transports/). As part of this the object need to be serialized and deserialized. To achieve this NServiceBus uses "Serializers".

## Supported Serializers

- [XmlSerializer](xml.md)
- [JsonSerializer](json.md)
- [BinarySerializer](binary.md)

### Community run Serializers

There are several community run Serializers that can be seen on the full list of [Extensions](/platform/extensions.md#serializers).

## Using an existing Serializer

The default Serializer used in NServiceBus projects is the custom [XmlSerializer](xml.md).

The pages dedicated to particular Serializers show how to configure the endpoint to use each of them. Unless explicitly configured otherwise, NServiceBus will use XmlSerializer for serializing and deserializing all messages.

Note that the same Serializer must be used by the sending endpoint to serialize messages and by receiving endpoint to deserialize them.


text:
require_relative 'boot'

require 'rails/all'
require 'csv'
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module AcidTest
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1
    config.encoding = 'utf-8'
    config.time_zone = 'Santiago'
    config.active_record.default_timezone = :local
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
    config.i18n.default_locale = :es
    config.i18n.available_locales = [:es, :en]

    config.autoload_paths << "#{Rails.root}/lib"
    config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
    config.assets.paths << Rails.root.join('vendor','assets')
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
  end
end


text:
'use strict';
(function (angular) {
	angular.module('pluggable', ['pluggable.testmodule']);
	angular.module('pluggable.testmodule', []);
})(window.angular);


text:
package org.scalatest.words

import org.scalatest._
import Matchers._
import matchers.{BePropertyMatcher, BePropertyMatchResult}
import java.io.File

class ResultOfAWordToBePropertyMatcherApplicationSpec extends Spec {

  object `ResultOfAWordToBePropertyMatcherApplication ` {

    case class MyFile(
      val name: String,
      val file: Boolean,
      val isDirectory: Boolean
    )

    class FileBePropertyMatcher extends BePropertyMatcher[MyFile] {
      def apply(file: MyFile) = {
        new BePropertyMatchResult(file.file, "file")
      }
      override def toString: String = "file"
    }

    def `should have pretty toString` {
      val result = new ResultOfAWordToBePropertyMatcherApplication(new FileBePropertyMatcher)
      result.toString should be ("a file")
    }
  }

}


text:
using GutenTag;

namespace GutenTag.Hspi
{
    public class Audio : Tag
    {
        public Audio() : base("audio")
        {
        }
    }
}


text:
package de.adesso.wickedcharts.chartjs.chartoptions;

import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * Efficient way to customize or change the default behavior of a chart.
 *
 * @see http://www.chartjs.org/docs/latest/developers/plugins.html?h=plugin
 *
 * @author SvenWirz
 */
@Accessors(chain = true)
@lombok.Data
public class Plugins implements Serializable{
	private static final long serialVersionUID = 1L;
	private Filler filler;
	private SamplesFillerAnalyzer samples_filler_analyzer;
}


text:
package org.apache.druid.segment.column;

import org.apache.druid.common.config.NullHandling;

import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.Comparator;

/**
 * Wrapper of {@link TypeStrategy} for nullable types, which stores {@link NullHandling#IS_NULL_BYTE} or
 * {@link NullHandling#IS_NOT_NULL_BYTE} in the leading byte of any value, as appropriate. If the value is null, only
 * {@link NullHandling#IS_NULL_BYTE} will be set, otherwise, the value bytes will be written after the null byte.
 *
 * layout: | null (byte) | value (byte[]) |
 *
 * This is not the most efficient way to track nulls, it is recommended to only use this wrapper if you MUST store null
 * values.
 *
 * @see TypeStrategy
 */
public final class NullableTypeStrategy<T> implements Comparator<T>
{
  private final TypeStrategy<T> delegate;
  private final Comparator<T> delegateComparator;

  public NullableTypeStrategy(TypeStrategy<T> delegate)
  {
    this.delegate = delegate;
    this.delegateComparator = Comparator.nullsFirst(delegate::compare);
  }

  public int estimateSizeBytes(@Nullable T value)
  {
    if (value == null) {
      return Byte.BYTES;
    }
    return Byte.BYTES + delegate.estimateSizeBytes(value);
  }

  @Nullable
  public T read(ByteBuffer buffer)
  {
    if ((buffer.get() & NullHandling.IS_NULL_BYTE) == NullHandling.IS_NULL_BYTE) {
      return null;
    }
    return delegate.read(buffer);
  }

  public int write(ByteBuffer buffer, @Nullable T value, int maxSizeBytes)
  {
    final int max = Math.min(buffer.limit() - buffer.position(), maxSizeBytes);
    final int remaining = max - Byte.BYTES;
    if (remaining >= 0) {
      // if we have room left, write the null byte and the value
      if (value == null) {
        buffer.put(NullHandling.IS_NULL_BYTE);
        return Byte.BYTES;
      }
      buffer.put(NullHandling.IS_NOT_NULL_BYTE);
      int written = delegate.write(buffer, value, maxSizeBytes - Byte.BYTES);
      return written < 0 ? written : Byte.BYTES + written;
    } else {
      if (value == null) {
        return remaining;
      }
      // call delegate.write anyway to get the total amount of extra space needed to serialize the value
      return remaining + delegate.write(buffer, value, 0);
    }
  }

  @Nullable
  public T read(ByteBuffer buffer, int offset)
  {
    final int oldPosition = buffer.position();
    try {
      buffer.position(offset);
      T value = read(buffer);
      return value;
    }
    finally {
      buffer.position(oldPosition);
    }
  }

  /**
   * Whether the {@link #read} methods return an object that may retain a reference to the provided {@link ByteBuffer}.
   * If a reference is sometimes retained, this method returns true. It returns false if, and only if, a reference
   * is *never* retained.
   */
  public boolean readRetainsBufferReference()
  {
    return delegate.readRetainsBufferReference();
  }

  public int write(ByteBuffer buffer, int offset, @Nullable T value, int maxSizeBytes)
  {
    final int oldPosition = buffer.position();
    try {
      buffer.position(offset);
      return write(buffer, value, maxSizeBytes);
    }
    finally {
      buffer.position(oldPosition);
    }
  }

  @Override
  public int compare(T o1, T o2)
  {
    return delegateComparator.compare(o1, o2);
  }
}


text:
import { Autor } from './../model/autor';
import { Injectable } from '@angular/core';

@Injectable()
export class AutorService{

    autores: Autor[] = [];

    consultarAutor(){}

    consultarAutorPorId(){}

}


text:
"""
The tests provided in this module have been tested for compliance with
the Threema Gateway server. Obviously, the simulated server does not
completely mimic the behaviour of the Gateway server.
"""
import asyncio

import pytest

from threema.gateway import (
    ReceptionCapability,
    e2e,
    simple,
)
from threema.gateway.exception import (
    BlobServerError,
    CreditsServerError,
    IDServerError,
    KeyServerError,
    MessageServerError,
    ReceptionCapabilitiesServerError,
)

@asyncio.coroutine
def get_latest_blob_ids(server, connection):
    blobs = [(yield from (yield from connection.download(blob_id)).read())
             for blob_id in server.latest_blob_ids]
    return blobs

class TestLookupPublicKey:
    @pytest.mark.asyncio
    def test_invalid_identitiy(self, invalid_connection):
        with pytest.raises(KeyServerError) as exc_info:
            yield from invalid_connection.get_public_key('ECHOECHO')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_invalid_length(self, connection):
        with pytest.raises(KeyServerError) as exc_info:
            yield from connection.get_public_key('TEST')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_unknown_id(self, connection):
        with pytest.raises(KeyServerError) as exc_info:
            yield from connection.get_public_key('00000000')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_id(self, connection, server):
        key = yield from connection.get_public_key('ECHOECHO')
        assert key.hex_pk() == server.echoecho_key

    @pytest.mark.asyncio
    def test_cache_expiration(self, connection, server):
        connection.get_public_key.cache_clear()
        connection.get_public_key.cache.expiration = 0.05
        for _ in range(10):
            yield from self.test_valid_id(connection, server)
        cache_info = connection.get_public_key.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 9
        yield from asyncio.sleep(0.2)
        yield from self.test_valid_id(connection, server)
        cache_info = connection.get_public_key.cache_info()
        # For some reason, the cache is not always being cleared and I don't want
        # Travis to fail all the time
        assert cache_info.misses == 1 or cache_info.misses == 2

    @pytest.mark.asyncio
    def test_cache_hits(self, connection, server):
        connection.get_public_key.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_id(connection, server)
        cache_info = connection.get_public_key.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestLookupIDByPhone:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from invalid_connection.get_id(phone='44123456789')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_unknown_phone(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone='44987654321')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_invalid_phone(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone='-12537825318')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_phone(self, connection):
        id_ = yield from connection.get_id(phone='44123456789')
        assert id_ == 'ECHOECHO'

    @pytest.mark.asyncio
    def test_cache_hits(self, connection):
        connection.get_id.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_phone(connection)
        cache_info = connection.get_id.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestLookupIDByPhoneHash:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from invalid_connection.get_id(phone_hash='invalid_hash')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_invalid_length(self, connection):
        phone_hash = '98b05f6eda7a878f6f016bdcdc9db6eb61a6b190e814ff787142115af14421'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone_hash=phone_hash)
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_odd_length(self, connection):
        phone_hash = '98b05f6eda7a878f6f016bdcdc9db6eb61a6b190e814ff787142115af144214'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone_hash=phone_hash)
        # Note: This status code might not be intended and may change in the future
        assert exc_info.value.status == 500

    @pytest.mark.asyncio
    def test_invalid_phone_hash(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone_hash='1234')
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_unknown_phone_hash(self, connection):
        phone_hash = '98b05f6eda7a878f6f016bdcdc9db6eb61a6b190e814ff787142115af144214a'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(phone_hash=phone_hash)
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_phone_hash(self, connection):
        phone_hash = '98b05f6eda7a878f6f016bdcdc9db6eb61a6b190e814ff787142115af144214c'
        id_ = yield from connection.get_id(phone_hash=phone_hash)
        assert id_ == 'ECHOECHO'

    @pytest.mark.asyncio
    def test_cache_hits(self, connection):
        connection.get_id.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_phone_hash(connection)
        cache_info = connection.get_id.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestLookupIDByEmail:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from invalid_connection.get_id(email='echoecho@example.com')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_unknown_email(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email='somemail@example.com')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_invalid_email(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email='invalid')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_email(self, connection):
        id_ = yield from connection.get_id(email='echoecho@example.com')
        assert id_ == 'ECHOECHO'

    @pytest.mark.asyncio
    def test_cache_hits(self, connection):
        connection.get_id.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_email(connection)
        cache_info = connection.get_id.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestLookupIDByEmailHash:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from invalid_connection.get_id(email_hash='invalid_hash')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_invalid_length(self, connection):
        email_hash = '45a13d422b40f81936a9987245d3f6d9064c90607273af4f578246b4484669'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email_hash=email_hash)
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_odd_length(self, connection):
        email_hash = '45a13d422b40f81936a9987245d3f6d9064c90607273af4f578246b4484669e'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email_hash=email_hash)
        # Note: This status code might not be intended and may change in the future
        assert exc_info.value.status == 500

    @pytest.mark.asyncio
    def test_invalid_email_hash(self, connection):
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email_hash='1234')
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_unknown_email_hash(self, connection):
        email_hash = '45a13d422b40f81936a9987245d3f6d9064c90607273af4f578246b4484669e1'
        with pytest.raises(IDServerError) as exc_info:
            yield from connection.get_id(email_hash=email_hash)
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_email_hash(self, connection):
        email_hash = '45a13d422b40f81936a9987245d3f6d9064c90607273af4f578246b4484669e2'
        id_ = yield from connection.get_id(email_hash=email_hash)
        assert id_ == 'ECHOECHO'

    @pytest.mark.asyncio
    def test_cache_hits(self, connection):
        connection.get_id.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_email_hash(connection)
        cache_info = connection.get_id.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestReceptionCapabilities:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(ReceptionCapabilitiesServerError) as exc_info:
            yield from invalid_connection.get_reception_capabilities('ECHOECHO')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_invalid_length(self, connection):
        with pytest.raises(ReceptionCapabilitiesServerError) as exc_info:
            yield from connection.get_reception_capabilities('TEST')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_unknown_id(self, connection):
        with pytest.raises(ReceptionCapabilitiesServerError) as exc_info:
            yield from connection.get_reception_capabilities('00000000')
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_valid_id(self, connection):
        key = yield from connection.get_reception_capabilities('ECHOECHO')
        assert key == {
            ReceptionCapability.text,
            ReceptionCapability.image,
            ReceptionCapability.video,
            ReceptionCapability.file
        }

    @pytest.mark.asyncio
    def test_cache_hits(self, connection):
        connection.get_reception_capabilities.cache_clear()
        for _ in range(1000):
            yield from self.test_valid_id(connection)
        cache_info = connection.get_reception_capabilities.cache_info()
        assert cache_info.misses == 1
        assert cache_info.hits == 999

class TestCredits:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(CreditsServerError) as exc_info:
            yield from invalid_connection.get_credits()
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_valid(self, connection):
        assert (yield from connection.get_credits()) == 100

class TestUploadBlob:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(BlobServerError) as exc_info:
            yield from invalid_connection.upload(b'\x01')
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_insufficient_credits(self, nocredit_connection):
        with pytest.raises(BlobServerError) as exc_info:
            yield from nocredit_connection.upload(b'\x01')
        assert exc_info.value.status == 402

    @pytest.mark.asyncio
    def test_just_ok(self, connection, server):
        blob_id = yield from connection.upload(bytes(20 * (2**20)))
        assert len(blob_id) == 32
        # Note: Remove big blob because further tests may hang
        del server.blobs[blob_id]

    @pytest.mark.asyncio
    def test_too_big(self, connection, server):
        with pytest.raises(BlobServerError) as exc_info:
            blob_id = yield from connection.upload(bytes((20 * (2**20)) + 1))
            # Note: Remove big blob because further tests may hang
            del server.blobs[blob_id]
        assert exc_info.value.status == 413

    @pytest.mark.asyncio
    def test_zero(self, connection):
        with pytest.raises(BlobServerError) as exc_info:
            yield from connection.upload(b'')
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_file(self, connection):
        assert len((yield from connection.upload(b'\x01'))) == 32

class TestDownloadBlob:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection, blob_id):
        with pytest.raises(BlobServerError) as exc_info:
            yield from (yield from invalid_connection.download(blob_id)).read()
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_invalid_id(self, connection):
        with pytest.raises(BlobServerError) as exc_info:
            yield from (yield from connection.download('f' * 15)).read()
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_unknown_id(self, connection):
        with pytest.raises(BlobServerError) as exc_info:
            yield from (yield from connection.download('f' * 16)).read()
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_file(self, connection, blob_id, blob):
        response = yield from connection.download(blob_id)
        assert (yield from response.read()) == blob

    @pytest.mark.asyncio
    def test_no_credits(self, nocredit_connection, blob_id, blob):
        response = yield from nocredit_connection.download(blob_id)
        assert (yield from response.read()) == blob

class TestSendSimple:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=invalid_connection,
                to_id='ECHOECHO',
                text='Hello'
            ).send()
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_insufficient_credits(self, nocredit_connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=nocredit_connection,
                to_id='ECHOECHO',
                text='Hello'
            ).send()
        assert exc_info.value.status == 402

    @pytest.mark.asyncio
    def test_message_too_long(self, connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=connection,
                to_id='ECHOECHO',
                text='0' * 3501
            ).send()
        assert exc_info.value.status == 413

    @pytest.mark.asyncio
    def test_unknown_id(self, connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=connection,
                to_id='00000000',
                text='Hello'
            ).send()
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_unknown_email(self, connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=connection,
                email='somemail@example.com',
                text='Hello'
            ).send()
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_unknown_phone(self, connection):
        with pytest.raises(MessageServerError) as exc_info:
            yield from simple.TextMessage(
                connection=connection,
                phone='44987654321',
                text='Hello'
            ).send()
        assert exc_info.value.status == 404

    @pytest.mark.asyncio
    def test_via_id(self, connection):
        id_ = yield from simple.TextMessage(
            connection=connection,
            to_id='ECHOECHO',
            text='0' * 3500
        ).send()
        assert id_ == '0' * 16

    @pytest.mark.asyncio
    def test_via_email(self, connection):
        id_ = yield from simple.TextMessage(
            connection=connection,
            email='echoecho@example.com',
            text='Hello'
        ).send()
        assert id_ == '0' * 16

    @pytest.mark.asyncio
    def test_via_phone(self, connection):
        id_ = yield from simple.TextMessage(
            connection=connection,
            phone='44123456789',
            text='Hello'
        ).send()
        assert id_ == '0' * 16

class TestSendE2E:
    @pytest.mark.asyncio
    def test_invalid_identity(self, invalid_connection, server):
        with pytest.raises(MessageServerError) as exc_info:
            yield from e2e.TextMessage(
                connection=invalid_connection,
                to_id='ECHOECHO',
                key=server.echoecho_encoded_key,
                text='Hello'
            ).send()
        assert exc_info.value.status == 401

    @pytest.mark.asyncio
    def test_insufficient_credits(self, nocredit_connection, server):
        with pytest.raises(MessageServerError) as exc_info:
            yield from e2e.TextMessage(
                connection=nocredit_connection,
                to_id='ECHOECHO',
                key=server.echoecho_encoded_key,
                text='Hello'
            ).send()
        assert exc_info.value.status == 402

    @pytest.mark.asyncio
    def test_message_too_long(self, connection, raw_message):
        with pytest.raises(MessageServerError) as exc_info:
            yield from raw_message(
                connection=connection,
                to_id='ECHOECHO',
                nonce=b'0' * 24,
                message=b'1' * 4001
            ).send()
        assert exc_info.value.status == 413

    @pytest.mark.asyncio
    def test_unknown_id(self, connection, server):
        with pytest.raises(MessageServerError) as exc_info:
            yield from e2e.TextMessage(
                connection=connection,
                to_id='00000000',
                key=server.echoecho_encoded_key,
                text='Hello'
            ).send()
        assert exc_info.value.status == 400

    @pytest.mark.asyncio
    def test_raw(self, connection, raw_message):
        id_ = yield from raw_message(
            connection=connection,
            to_id='ECHOECHO',
            nonce=b'0' * 24,
            message=b'1' * 4000
        ).send()
        assert id_ == '1' * 16

    @pytest.mark.asyncio
    def test_via_id(self, connection):
        id_ = yield from e2e.TextMessage(
            connection=connection,
            to_id='ECHOECHO',
            text='Hello'
        ).send()
        assert id_ == '1' * 16

    @pytest.mark.asyncio
    def test_via_id_and_key(self, connection, server):
        id_ = yield from e2e.TextMessage(
            connection=connection,
            to_id='ECHOECHO',
            key=server.echoecho_encoded_key,
            text='Hello'
        ).send()
        assert id_ == '1' * 16

    @pytest.mark.asyncio
    def test_image(self, connection, server):
        server.latest_blob_ids = []
        id_ = yield from e2e.ImageMessage(
            connection=connection,
            to_id='ECHOECHO',
            key=server.echoecho_encoded_key,
            image_path=server.threema_jpg
        ).send()
        assert id_ == '1' * 16
        assert len(server.latest_blob_ids) == 1
        assert all((yield from get_latest_blob_ids(server, connection)))

    @pytest.mark.asyncio
    def test_file(self, connection, server):
        server.latest_blob_ids = []
        id_ = yield from e2e.FileMessage(
            connection=connection,
            to_id='ECHOECHO',
            key=server.echoecho_encoded_key,
            file_path=server.threema_jpg
        ).send()
        assert id_ == '1' * 16
        assert len(server.latest_blob_ids) == 1
        assert all((yield from get_latest_blob_ids(server, connection)))

    @pytest.mark.asyncio
    def test_file_with_thumbnail(self, connection, server):
        server.latest_blob_ids = []
        id_ = yield from e2e.FileMessage(
            connection=connection,
            to_id='ECHOECHO',
            key=server.echoecho_encoded_key,
            file_path=server.threema_jpg,
            thumbnail_path=server.threema_jpg
        ).send()
        assert id_ == '1' * 16
        assert len(server.latest_blob_ids) == 2
        assert all((yield from get_latest_blob_ids(server, connection)))


text:
# Immutable.js

React Redux Form, as of the latest version, has support for Immutable.JS. To use it, just import the parts you need from `react-redux-form/immutable`:

```jsx
import Immutable from 'immutable';
import {
  Form,
  Control,
  actions,
  // ... etc.
} from 'react-redux-form/immutable';
// ... other imports

class MyForm extends Component {
  onFormSubmit(formObj) {
    // ... access form fields e.g. formObj.get('name');
  }
  render() {
    return (
      <Form model="user" onSubmit={this.onFormSubmit}>
        <Control model=".name" />

        {/* ... other controls */}
      </Form>
    );
  }
}

export default MyForm;
```

and it will _just work_ with Immutable.js. When creating your store, make sure to import `createForms`, `combineForms`, `modelReducer`, and/or `formReducer`, etc. from `react-redux-form/immutable`.


text:
import { compose, lensProp, over } from 'ramda'

export default compose(over, lensProp)


text:
ROOT = ../../../../..
DIR = Pegasus/Common/tests/Dir
include $(ROOT)/mak/config.mak
include ../libraries.mak

LOCAL_DEFINES = -DPEGASUS_INTERNALONLY

PROGRAM = TestDir
SOURCES = Dir.cpp

include $(ROOT)/mak/program.mak

tests:
	$(PROGRAM)

poststarttests:


text:
(function() {
  'use strict';

  /**
   * @ngdoc overview
   * @ngname horizon.dashboard.project.containers
   *
   * @description
   * Provides the services and widgets required
   * to support and display the project containers panel.
   */
  angular
    .module('horizon.dashboard.project.containers', [
      'ngRoute',
      'horizon.framework',
      'horizon.app.core.openstack-service-api'
    ])
    .constant('horizon.dashboard.project.containers.account.resourceType', 'OS::Swift::Account')
    .constant('horizon.dashboard.project.containers.container.resourceType', 'OS::Swift::Container')
    .constant('horizon.dashboard.project.containers.object.resourceType', 'OS::Swift::Object')
    .config(config)
    .run(run);

  config.$inject = [
    '$provide',
    '$routeProvider',
    '$windowProvider'
  ];

  /**
   * @name horizon.dashboard.project.containers.basePath
   * @description Base path for the project dashboard
   */
  function config($provide, $routeProvider, $windowProvider) {
    var path = $windowProvider.$get().STATIC_URL + 'dashboard/project/containers/';
    $provide.constant('horizon.dashboard.project.containers.basePath', path);

    var baseRoute = 'project/containers/';
    $provide.constant('horizon.dashboard.project.containers.baseRoute', baseRoute);

    // we include an additional level of URL here to allow for swift service
    // user interaction outside of the scope of containers
    var containerRoute = baseRoute + 'container/';
    $provide.constant('horizon.dashboard.project.containers.containerRoute', containerRoute);

    $routeProvider
      .when('/' + baseRoute, {
        templateUrl: path + 'select-container.html'
      })
      .when('/' + containerRoute, {
        templateUrl: path + 'select-container.html'
      })
      .when('/' + containerRoute + ':container', {
        templateUrl: path + 'objects.html'
      })
      .when('/' + containerRoute + ':container/:folder*', {
        templateUrl: path + 'objects.html'
      });
  }

  run.$inject = [
    'horizon.dashboard.project.containers.account.resourceType',
    'horizon.dashboard.project.containers.container.resourceType',
    'horizon.dashboard.project.containers.object.resourceType',
    'horizon.framework.conf.resource-type-registry.service'
  ];

  function run(accountResCode, containerResCode, objectResCode, registryService) {
    registryService.getResourceType(accountResCode)
      .setNames(gettext('Swift Account'), gettext('Swift Accounts'));
    registryService.getResourceType(containerResCode)
      .setNames(gettext('Swift Container'), gettext('Swift Containers'));

    var objectResourceType = registryService.getResourceType(objectResCode);
    objectResourceType.setNames(gettext('Object'), gettext('Objects'))
      .setProperty('name', {label: gettext('Name')})
      .setProperty('size', { label: gettext('Size')});

    objectResourceType.tableColumns.append({
      id: 'name', priority: 1, sortDefault: true,
      template: '' +
        '{$ item.name $}{$ item.name $}'
    })
    .append({
      id: 'bytes', priority: 1, title: gettext('Size'),
      template: '{$item.bytes | bytes$}' +
        'Folder'
    });

    objectResourceType.filterFacets.append({
      label: gettext('Name'),
      name: 'name',
      singleton: true
    });
  }
})();


text:
Example plugins built to demonstrate how the BladeRunnerJS (BRJS) toolkit can be extended to provide additional functionality, or alternative developer workflows.

## Plugins

* [echo-command-plugin](echo-command-plugin) - A sample CommandPlugin created as part of the [Echo CommandPlugin Tutorial](http://bladerunnerjs.org/docs/extend/command_plugin_tutorial/)


text:
cask "cakebrewjs" do
  version "1.2.1"
  sha256 "cca2e657dcdea0b1cf146187563e5ab12533b62618ff6227bd2e2b5d5299c4c0"

  url "https://downloads.sourceforge.net/cakebrewjs/v#{version}/cakebrewjs-#{version}-mac.zip"
  name "cakebrewjs"
  desc "Homebrew GUI app written in electron"
  homepage "https://sourceforge.net/projects/cakebrewjs"

  livecheck do
    url "https://sourceforge.net/projects/cakebrewjs/rss?"
    strategy :page_match
    regex(/cakebrewjs-(\d+(?:\.\d+)+)-mac\.zip/i)
  end

  app "cakebrewjs.app"

  zap trash: [
    "~/Library/Application Support/cakebrewjs",
    "~/Library/Caches/cakebrewjs",
    "~/Library/Preferences/com.electron.cakebrewjs.helper.plist",
    "~/Library/Preferences/com.electron.cakebrewjs.plist",
  ]
end


text:
/*
 * Parent-child cooperations sample.
 *
 * The sample shows:
 * - how to create a child-cooperation (cooperation, which has some parent
 *   cooperation).
 * - auto-deregistration of the child-cooperation if the parent cooperation is
 *   deregistering.
 *
 * Parent agent creates a child agent, which do some task.
 * If parent cooperation is deregistering, the child cooperation will be
 * deregistered automatically.
 */

#include <iostream>
#include <sstream>

// Main SObjectizer header file.
#include <so_5/all.hpp>

// Result of task which will be send to a parent agent.
class task_result_t : public so_5::rt::message_t
{
	public:
		task_result_t( unsigned int id ) : m_id( id ) {}

		unsigned int
		id() const
		{
			return m_id;
		}

	private:
		unsigned int m_id;
};

// Child finished to do his task.
class task_completed_t : public so_5::rt::signal_t {};

// Child agent.
/*
	This agent will be created in his own cooperation.
	Agent does some task, sends a result to the parent agent and closes down.
*/
class a_child_t : public so_5::rt::agent_t
{
	public:
		a_child_t( so_5::rt::environment_t & env,
			const so_5::rt::mbox_t & result_mbox,
			unsigned int task_id )
		:	so_5::rt::agent_t( env )
		,	m_result_mbox( result_mbox )
		,	m_task_id( task_id )
		{}

		virtual ~a_child_t()
		{
			std::cout << "Child: agent of the task " << m_task_id
					<< " has destroyed." << std::endl;
		}

		// Definition of the agent for SObjectizer.
		virtual void
		so_define_agent() override
		{
			so_subscribe_self()
				.event( &a_child_t::evt_task_completed );
		}

		// A reaction to start of work in SObjectizer.
		virtual void
		so_evt_start() override
		{
			std::cout << "Child: has started to do task " << m_task_id
					<< std::endl;

			so_5::send_delayed_to_agent< task_completed_t >(
					*this,
					// One second delay.
					std::chrono::seconds( 1 ) );
		}

		virtual void
		so_evt_finish() override
		{
			std::cout << "Child: has finished, task " << m_task_id << std::endl;
		}

		//! Child has completed the task.
		void
		evt_task_completed(
			const so_5::rt::event_data_t< task_completed_t > & )
		{
			std::cout << "Child: has completed his task " << m_task_id
					<< std::endl;

			// Send information about result to the parent agent.
			so_5::send< task_result_t >( m_result_mbox, m_task_id );

			// Deregister child cooperation and close
			// down activity of this child instance.
			so_deregister_agent_coop_normally();
		}

	private:
		// Result mbox.
		const so_5::rt::mbox_t m_result_mbox;

		// Task ID.
		const unsigned int m_task_id;
};

// Parent agent in his parent cooperation.
class a_parent_t : public so_5::rt::agent_t
{
	public:
		a_parent_t( so_5::rt::environment_t & env )
		:	so_5::rt::agent_t( env )
		{}

		virtual ~a_parent_t()
		{
			std::cout << "Parent: agent has destroyed." << std::endl;
		}

		// Definition of the agent for SObjectizer.
		virtual void
		so_define_agent() override
		{
			so_subscribe_self()
				.event( &a_parent_t::evt_task_result );
		}

		// A reaction to start of work in SObjectizer.
		virtual void
		so_evt_start() override
		{
			std::cout << "Parent: agent has started." << std::endl;

			// Our cooperation has created. We may start a child agent work.
			start_child( 0 );
		}

		virtual void
		so_evt_finish() override
		{
			std::cout << "Parent: agent has finished." << std::endl;
		}

		// Task result received from child-agent.
		void
		evt_task_result(
			const task_result_t & task_result )
		{
			std::cout << "Parent: task result " << task_result.id()
				<< " is received." << std::endl;

			// We will start to do a next task.
			start_child( task_result.id() + 1 );
		}

	private:

		//! Starts child to solve a task number ID.
		void
		start_child( unsigned int id )
		{
			std::cout << "Parent: starting a child to do task " << id << std::endl;

			// Creating a child cooperation.
			auto child_coop = so_5::rt::create_child_coop(
					*this, so_5::autoname );

			// Adding agents to the cooperation.
			child_coop->add_agent(
					new a_child_t( so_environment(), so_direct_mbox(), id ) );

			// Initiate child's work.
			so_environment().register_coop( std::move( child_coop ) );
		}

		// Agent mbox.
		so_5::rt::mbox_t m_self_mbox;
};

int
main()
{
	try
	{
		so_5::launch( []( so_5::rt::environment_t & env )
			{
				// Registering the parent cooperation.
				env.register_agent_as_coop( "coop", new a_parent_t( env ) );

				// Give some time to the agents.
				std::this_thread::sleep_for( std::chrono::seconds( 3 ) );
				env.stop();
			} );
	}
	catch( const std::exception & ex )
	{
		std::cerr << "Error: " << ex.what() << std::endl;
		return 1;
	}

	return 0;
}


text:
package net.fortuna.ical4j.model.property;

import java.text.ParseException;

import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.PropertyFactoryImpl;

/**
 * $Id$
 *
 * Created: [Apr 6, 2004]
 *
 * Defines a COMPLETED iCalendar component property.
 *
 * <pre>
 *     4.8.2.1 Date/Time Completed
 *
 *        Property Name: COMPLETED
 *
 *        Purpose: This property defines the date and time that a to-do was
 *        actually completed.
 *
 *        Value Type: DATE-TIME
 *
 *        Property Parameters: Non-standard property parameters can be
 *        specified on this property.
 *
 *        Conformance: The property can be specified in a "VTODO" calendar
 *        component.
 *
 *        Description: The date and time MUST be in a UTC format.
 *
 *        Format Definition: The property is defined by the following notation:
 *
 *          completed  = "COMPLETED" compparam ":" date-time CRLF
 *
 *          compparam  = *(";" xparam)
 * </pre>
 *
 * @author Ben Fortuna
 */
public class Completed extends UtcProperty {

    private static final long serialVersionUID = 6824213281785639181L;

    /**
     * Default constructor.
     */
    public Completed() {
        super(COMPLETED, PropertyFactoryImpl.getInstance());
    }

    /**
     * @param aValue a value string for this component
     * @throws ParseException when the specified string is not a valid date-time represenation
     */
    public Completed(final String aValue) throws ParseException {
        super(COMPLETED, PropertyFactoryImpl.getInstance());
        setValue(aValue);
    }

    /**
     * @param aList a list of parameters for this component
     * @param aValue a value string for this component
     * @throws ParseException when the specified string is not a valid date-time represenation
     */
    public Completed(final ParameterList aList, final String aValue)
            throws ParseException {
        super(COMPLETED, aList, PropertyFactoryImpl.getInstance());
        setValue(aValue);
    }

    /**
     * @param aDate a date
     */
    public Completed(final DateTime aDate) {
        super(COMPLETED, PropertyFactoryImpl.getInstance());
        // time must be in UTC..
        aDate.setUtc(true);
        setDate(aDate);
    }

    /**
     * @param aList a list of parameters for this component
     * @param aDate a date
     */
    public Completed(final ParameterList aList, final DateTime aDate) {
        super(COMPLETED, aList, PropertyFactoryImpl.getInstance());
        // time must be in UTC..
        aDate.setUtc(true);
        setDate(aDate);
    }
}


text:
import abc
import collections
import importlib
import io
import json
import logging
import os.path
from contextlib import contextmanager
from typing import List, Optional, Union, Dict, Iterable

from ..error import CommandError
from ..recordv3 import RecordV3

PathDelimiter = '\\'
TWO_FACTOR_CODE = 'TFC:Keeper'
FIELD_TYPE_ONE_TIME_CODE = 'oneTimeCode'

def replace_email_domain(email, old_domain, new_domain):
    # type: (str, Optional[str], Optional[str]) -> str
    if old_domain and new_domain and email.endswith(f'@{old_domain}'):
        email_user, domain = email.split('@')
        return f'{email_user}@{new_domain}'
    else:
        return email

def importer_for_format(input_format):
    full_name = 'keepercommander.importer.' + input_format
    module = importlib.import_module(full_name)
    if hasattr(module, 'Importer'):
        return module.Importer
    raise Exception('Cannot resolve importer for format {}'.format(input_format))

def exporter_for_format(output_format):
    full_name = 'keepercommander.importer.' + output_format
    module = importlib.import_module(full_name)
    if hasattr(module, 'Exporter'):
        return module.Exporter
    raise Exception('Cannot resolve exporter for format {}'.format(output_format))

def strip_path_delimiter(name, delimiter=PathDelimiter):
    folder = name.strip()
    if folder == delimiter:
        return ''
    if len(folder) > 1:
        if folder[:1] == delimiter and folder[:2] != delimiter*2:
            folder = folder[1:].strip()
    if len(folder) > 1:
        if folder[-1:] == delimiter and folder[-2:] != delimiter*2:
            folder = folder[:-1].strip()
    return folder

def path_components(path, delimiter=PathDelimiter):    # type: (str, str) -> Iterable[str]
    p = path.strip()
    pos = 0
    while pos < len(p):
        idx = p.find(delimiter, pos)
        if idx >= 0:
            if idx+1 < len(p):
                if p[idx+1] == delimiter:
                    pos = idx + 2
                    continue
            comp = p[:idx].strip()
            p = p[idx+1:].strip()
            pos = 0
            if len(comp) > 0:
                yield comp.replace(2*delimiter, delimiter)
        else:
            p = strip_path_delimiter(p, delimiter=delimiter)
            if len(p) > 0:
                yield p.replace(2*delimiter, delimiter)
                p = ''

def check_if_bool(value):
    return value is None or type(value) == bool

class Permission:
    def __init__(self):
        self.uid = None
        self.name = None
        self.manage_users = None
        self.manage_records = None

class SharedFolder:
    def __init__(self):
        self.uid = None
        self.path = None
        self.manage_users = None
        self.manage_records = None
        self.can_edit = None
        self.can_share = None
        self.permissions = None  # type: Optional[List[Permission]]

    def validate(self):
        if not self.path:
            raise CommandError('import', 'shared folder. path cannot be empty')
        for attr in ['manage_users', 'manage_records', 'can_edit', 'can_share']:
            if hasattr(self, attr):
                if not check_if_bool(getattr(self, attr)):
                    raise CommandError('import', 'shared folder. property \'{0}\' should be a boolean'.format(attr))
        if self.permissions:
            for p in self.permissions:
                if not p.name and not p.uid:
                    raise CommandError('import', 'shared folder permission. property \'name\' cannot be empty'.format(attr))
                for attr in ['manage_users', 'manage_records']:
                    if hasattr(p, attr):
                        if not check_if_bool(getattr(p, attr)):
                            raise CommandError('import', 'shared folder permission. property \'{0}\' should be a boolean'.format(attr))

class Attachment(abc.ABC):
    def __init__(self):
        self.name = None
        self.size = None
        self.mime = None

    @abc.abstractmethod
    def open(self):  # type: () -> io.BufferedIOBase
        pass

    def prepare(self):   # type: () -> None
        pass

class Folder:
    def __init__(self):
        self.uid = None        # type: Optional[str]
        self.domain = None     # type: Optional[str]
        self.path = None       # type: Optional[str]
        self.can_edit = None   # type: Optional[str]
        self.can_share = None  # type: Optional[str]

    def get_folder_path(self):
        path = self.domain or ''
        if self.path:
            if path:
                path = path + PathDelimiter
            path = path + self.path
        return path

class RecordField:
    def __init__(self, type=None, label=None, value=None):
        self.type = type    # type: Optional[str]
        self.label = label   # type: Optional[str]
        self.value = value   # type: any

    def name_key(self):
        if self.type and self.label:
            return f'${self.type.lower()}.{self.label.lower()}'
        elif self.type:
            return f'${self.type.lower()}'
        else:
            return (self.label or '').lower()

    @staticmethod
    def hash_value(value):  # type: (any) -> str
        if not value:
            return ''
        if isinstance(value, str):
            value = value.strip()
        elif isinstance(value, list):
            value = [RecordField.hash_value(x) for x in value]
            value = '|'.join((x for x in value if x))
        elif isinstance(value, dict):
            keys = [x for x in value]
            if 'privateKey' in keys:
                if value['privateKey']:
                    try:
                        keys.remove('publicKey')
                    except:
                        pass
            keys.sort()
            kvp = [(x, RecordField.hash_value(value[x])) for x in keys]
            kvp = [x for x in kvp if x[1]]
            value = ';'.join((f'{x[0]}:{x[1]}' for x in kvp))
        else:
            value = str(value)
        return value

    def hash_key(self):  # type: () -> Optional[str]
        value = RecordField.hash_value(self.value)
        if value:
            name = self.name_key()
            return f'{name}:{value}'

class RecordReferences:
    def __init__(self, type='', label=None):
        self.type = type
        self.label = label
        self.uids = []   # type: List[any]

class Record:
    def __init__(self):
        self.uid = None
        self.type = None         # type: Optional[str]
        self.title = None
        self.login = None
        self.password = None
        self.login_url = None
        self.notes = None
        self.fields = []         # type: List[RecordField]
        self.folders = None      # type: Optional[List[Folder]]
        self.attachments = None  # type: Optional[List[Attachment]]
        self.references = None   # type: Optional[List[RecordReferences]]
        self.schema = None       # type: Optional[List[RecordSchemaField]]

    def validate(self):
        if not self.title:
            raise CommandError('import', 'Record: title cannot be empty')
        if self.folders:
            for f in self.folders:
                for attr in ['can_edit', 'can_share']:
                    if hasattr(f, attr):
                        if not check_if_bool(getattr(f, attr)):
                            raise CommandError('import', f'Record \'{self.title}\': folder property \'{attr}\' should be boolean')

class RecordSchemaField:
    def __init__(self):
        self.ref = ''
        self.label = ''

class File:
    def __init__(self):
        self.file_id = None
        self.title = None
        self.name = None
        self.size = None
        self.key = None
        self.mime = None

    def open(self):
        raise NotImplementedError()

    def validate(self):
        pass

class BaseImporter(abc.ABC):
    def execute(self, name, **kwargs):
        # type: (BaseImporter, str, dict) -> Iterable[Union[Record, SharedFolder, File]]
        yield from self.do_import(name, **kwargs)

    @abc.abstractmethod
    def do_import(self, filename, **kwargs):
        # type: (BaseImporter, str, dict) -> Iterable[Union[Record, SharedFolder, File]]
        pass

    def extension(self):
        return ''

    @staticmethod
    def import_host_field(value):    # type: (str) -> Optional[dict]
        if isinstance(value, str):
            host, _, port = value.partition(':')
            return {
                'hostName': host.strip(),
                'port': port.strip()
            }

    @staticmethod
    def import_phone_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            region = ''
            number = ''
            ext = ''
            phone_type, _, rest = value.partition(':')
            if not rest:
                rest = phone_type
                phone_type = ''
            comps = rest.strip().split(' ')
            for comp in comps:
                comp = comp.strip()
                if comp.isalpha():
                    if len(comp) == 2:
                        if not region:
                            region = comp
                    elif not phone_type:
                        phone_type = comp
                elif len(comp) >= 6:
                    if not number:
                        number = comp
                elif not ext:
                    ext = comp
            result = {
                'type': '',
                'region': '',
                'number': number.strip(),
                'ext': ext.strip()
            }
            phone_type = phone_type.strip()
            region = region.strip()
            if phone_type:
                result['type'] = phone_type
            if region:
                result['region'] = region
            return result

    @staticmethod
    def import_name_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            first = ''
            middle = ''
            last = ''
            comma_pos = value.find(',')
            if comma_pos >= 0:
                last = value[:comma_pos]
                rest = value[comma_pos+1:]
            else:
                space_pos = value.rfind(' ')
                if space_pos >= 0:
                    last = value[space_pos+1:]
                    rest = value[:space_pos]
                else:
                    last = value
                    rest = ''
            rest = rest.strip()
            if rest:
                space_pos = rest.rfind(' ')
                if space_pos >= 0:
                    middle = rest[space_pos+1:]
                    first = rest[:space_pos]
                else:
                    middle = ''
                    first = rest

            return {
                'first': first.strip(),
                'middle': middle.strip(),
                'last': last.strip(),
            }

    @staticmethod
    def import_address_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            comps = value.split(',')
            street1 = comps[0].strip() if len(comps) > 0 else ''
            city = comps[1].strip() if len(comps) > 1 else ''
            state, _, zip_code = comps[2].strip().partition(' ') if len(comps) > 2 else ('', '', '')
            country = comps[3].strip() if len(comps) > 3 else ''

            return {
                'street1': street1,
                'street2': '',
                'city': city,
                'state': state,
                'zip': zip_code,
                'country': country
            }

    @staticmethod
    def import_q_and_a_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            q, sign, a = value.partition('?')
            return {
                'question': q.strip() + '?',
                'answer': a.strip(),
            }

    @staticmethod
    def import_card_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            comps = value.split(' ')
            number = ''
            expiration = ''
            cvv = ''
            for comp in comps:
                comp = comp.strip()
                if comp:
                    if len(comp) > 10:
                        number = comp
                    elif comp.find('/') >= 0:
                        expiration = comp
                    elif len(comp) <= 6:
                        cvv = comp
            if number or expiration or cvv:
                return {
                    'cardNumber': number,
                    'cardExpirationDate': expiration,
                    'cardSecurityCode':  cvv,
                }

    @staticmethod
    def import_account_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            account_type = ''
            routing = ''
            account_number = ''
            comps = value.split()
            for comp in comps:
                comp = comp.strip()
                if comp.isnumeric():
                    if not routing:
                        routing = comp
                    elif not account_number:
                        account_number = comp
                else:
                    if not account_type:
                        account_type = comp
            if routing or account_number:
                return {
                    'accountType': account_type,
                    'routingNumber': routing,
                    'accountNumber': account_number
                }

    @staticmethod
    def import_ssh_key_field(value):   # type: (str) -> Optional[dict]
        if isinstance(value, str):
            return {
                'privateKey': value,
                'publicKey': ''
            }

    @staticmethod
    def import_field(field_type, field_value):  # type: (str, str) -> any
        if not field_value:
            return None
        if not field_type:
            return field_value
        if field_type in {'text', 'multiline', 'secret', 'note'}:
            return field_value
        if field_type == 'date':
            try:
                return int(field_value)
            except:
                return None
        if field_type == 'keyPair':
            return BaseImporter.import_ssh_key_field(field_value)

        str_values = field_value.split('\n')
        values = []
        for str_value in str_values:
            if field_type == 'host':
                v = BaseImporter.import_host_field(str_value)
            elif field_type == 'phone':
                v = BaseImporter.import_phone_field(str_value)
            elif field_type == 'name':
                v = BaseImporter.import_name_field(str_value)
            elif field_type == 'address':
                v = BaseImporter.import_address_field(str_value)
            elif field_type == 'securityQuestion':
                v = BaseImporter.import_q_and_a_field(str_value)
            elif field_type == 'paymentCard':
                v = BaseImporter.import_card_field(str_value)
            elif field_type == 'bankAccount':
                v = BaseImporter.import_account_field(str_value)
            else:
                v = str_value
                if field_type in RecordV3.field_values:
                    fv = RecordV3.field_values[field_type]
                    if isinstance(fv.get('value'), dict):
                        try:
                            v = json.loads(str_value)
                        except:
                            pass
                    elif isinstance(fv.get('value'), int):
                        try:
                            v = int(str_value)
                        except:
                            pass
            if v:
                values.append(v)
        if values:
            if len(values) == 1:
                return values[0]
            return values

    @staticmethod
    def adjust_field_label(record, field_type, field_label, fields):
        # type: (Record, str, str, List[Dict]) -> str
        if not isinstance(fields, list):
            return field_label
        if field_type == 'text':
            return field_label
        field = next((x for x in fields if x['$ref'] == field_type), None)
        if not field:
            return field_label
        fl = field.get('label', '')
        if fl == field_label:
            return field_label
        for f in record.fields:
            if f.type == field_type and f.label == fl:
                return field_label
        return fl

class BaseFileImporter(BaseImporter, abc.ABC):
    def __init__(self):
        super(BaseFileImporter, self).__init__()

    def execute(self, name, **kwargs):
        # type: (str, ...) -> collections.Iterable[Union[Record, SharedFolder, File]]

        path = os.path.expanduser(name)
        if not os.path.isfile(path):
            ext = self.extension()
            if ext:
                path = path + '.' + ext

        if not os.path.isfile(path):
            raise CommandError('import', 'File \'{0}\' does not exist'.format(name))

        yield from self.do_import(path, **kwargs)

class BaseExporter(abc.ABC):
    def __init__(self):
        self.max_size = 10 * 1024 * 1024

    def execute(self, filename, items, file_password=None):
        # type: (str, List[Union[Record, SharedFolder, File]], Optional[str]) -> None
        if filename:
            filename = os.path.expanduser(filename)
            if filename.find('.') < 0:
                ext = self.extension()
                if ext:
                    filename = filename + '.' + ext
        elif not self.supports_stdout():
            raise CommandError('export', 'File name parameter is required.')

        self.do_export(filename, items, file_password)
        if filename and os.path.isfile(filename):
            logging.info('Vault has been exported to: %s', os.path.abspath(filename))

    @abc.abstractmethod
    def do_export(self, filename, records, file_password=None):
        # type: (str, List[Record, File], Optional[str]) -> None
        pass

    def has_shared_folders(self):
        return False

    def has_attachments(self):
        return False

    def extension(self):
        return ''

    def supports_stdout(self):
        return False

    def supports_v3_record(self):
        return True

    @staticmethod
    def export_host_field(value):    # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            host = value.get('hostName') or ''
            port = value.get('port') or ''
            if host or port:
                if port:
                    host += ':' + port
            return host

    @staticmethod
    def export_phone_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            phone = value.get('type') or ''
            if phone:
                phone += ':'
            region = value.get('region') or ''
            if region:
                if len(region) == 2 and region.isalpha():
                    pass
                elif region.isnumeric():
                    region = '+' + region
                else:
                    region = ''
                if region:
                    phone += '  ' + region
            number = (value.get('number') or '').replace(' ', '-')
            if number:
                phone += ' ' + number
            ext = (value.get('ext') or '').replace(' ', '-')
            if ext:
                phone += ' ' + ext
            return phone

    @staticmethod
    def export_name_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            first_name = value.get('first') or ''
            middle_name = value.get('middle') or ''
            name = value.get('last') or ''
            if first_name or middle_name or name:
                name = f'{name}, {first_name}'
                if middle_name:
                    name += ' ' + middle_name
            return name

    @staticmethod
    def export_address_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            address = value.get('street1', '').replace(',', '.')
            street2 = value.get('street2', '').replace(',', '.')
            if street2:
                address += ' ' + street2
            city = value.get('city', '').replace(',', '.')
            if city:
                address += ', ' + city
                state = value.get('state', '').replace(',', '.')
                zip_code = value.get('zip', '').replace(',', '.')
                if state or zip_code:
                    address += ', ' + state + ' ' + zip_code
                    country = value.get('country', '').replace(',', '.')
                    if country:
                        address += ', ' + country
            return address

    @staticmethod
    def export_q_and_a_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            q = value.get('question', '').replace('?', '')
            a = value.get('answer', '')
            if q or a:
                return f'{q}? {a}'
            return q

    @staticmethod
    def export_card_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            comps = []
            number = value.get('cardNumber')
            if number:
                comps.append(number)
            expiration = value.get('cardExpirationDate')
            if expiration:
                comps.append(expiration)
            cvv = value.get('cardSecurityCode')
            if cvv:
                comps.append(cvv)
            if comps:
                return ' '.join(comps)

    @staticmethod
    def export_account_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            account_type = value.get('accountType', '').replace(' ', '')
            routing = value.get('routingNumber', '').replace(' ', '')
            account_number = value.get('accountNumber', '').replace(' ', '')
            if routing or account_number:
                comps = []
                if account_type:
                    comps.append(account_type)
                if routing:
                    comps.append(routing)
                if account_number:
                    comps.append(account_number)
                if comps:
                    return ' '.join(comps)

    @staticmethod
    def export_ssh_key_field(value):   # type: (dict) -> Optional[str]
        if isinstance(value, dict):
            return value.get('privateKey', '')

    @staticmethod
    def export_field(field_type, field_value):  # type: (str, any) -> str
        if not field_value:
            return ''

        if isinstance(field_value, str):
            return field_value
        if isinstance(field_value, list):
            values = []
            for value in field_value:
                v = BaseExporter.export_field(field_type, value)
                if v:
                    values.append(v)
            return '\n'.join((x.replace('\n', ' ') for x in values))
        if isinstance(field_value, dict):
            if field_type == 'host':
                return BaseExporter.export_host_field(field_value)
            if field_type == 'phone':
                return BaseExporter.export_phone_field(field_value)
            if field_type == 'name':
                return BaseExporter.export_name_field(field_value)
            if field_type == 'address':
                return BaseExporter.export_address_field(field_value)
            if field_type == 'securityQuestion':
                return BaseExporter.export_q_and_a_field(field_value)
            if field_type == 'paymentCard':
                return BaseExporter.export_card_field(field_value)
            if field_type == 'bankAccount':
                return BaseExporter.export_account_field(field_value)
            if field_type == 'keyPair':
                return BaseExporter.export_ssh_key_field(field_value)
            return json.dumps(field_value)

        return str(field_value)

class BytesAttachment(Attachment):
    def __init__(self, name, buffer):  # type: (str, bytes) -> None
        Attachment.__init__(self)
        self.name = name
        self.data = buffer
        self.size = len(buffer)

    @contextmanager
    def open(self):
        yield io.BytesIO(self.data)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Parsley.js</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="Keywords" content="javascript form validation, javascript, form, validation, jquery, plungin, html, UX">
    <meta name="description" content="Parsley is a dead simple javascript form validation, powerful and UX aware">
    <meta name="author" content="Guillaume Potier">

    <link href="bower_components/bootstrap/docs/assets/css/bootstrap.css" rel="stylesheet" />

    <link href="bower_components/bootstrap/docs/assets/css/bootstrap-responsive.css" rel="stylesheet" />

Home

Documentation

API

            Parsley.js

Javascript forms validation.
Powerful, UX aware & Dead simple.

Never write a single javascript line anymore to validate your forms FrontEnd. Parsley will do that for you – and do it right –, thanks to its powerful DOM-API !

            See documentation & examples

 Download

Version 1.2.2

 Super #UX focused

User Experience matters. A lot. Parsley is totally aware of that, and is designed to help your users and not bother or frustrate them.

See demonstration.

 Super light

Less than 800 lines. Less than 12k minified.
Works with jQuery and Zepto (with data and fx_methods added).

Get Latest version.

 Super free

Parsley is open source, MIT licensed, and developed to help everyone. It will stay that way.

See License.

 Super configurable

Like no other javascript library, Parsley has a full support for #UX concerns and detailed options. Override almost every Parsley default behaviors to fit your exact needs.

See documentation.

 Super simple

Want to validate a form? Just write it in English with the awesome Parsley DOM-API using jQuery data API.

See documentation.

 Super reliable

Form validation is important, #UX is critical. Parsley is shipped almost bug free to help you with that.

 See Parsley Test Suite.

© @guillaumepotier @Wisembly 2012 - Ever heard of #Garlic.js, Parsleys little sister?