text:
static void deleteObjectsWithoutRemoteIDs(NSManagedObjectContext *context, Class class, NSArray *remoteIDs)
{
    SLAttributeMapping *attributeMapping = [class attributeMapping];
    NSString *idKey = [attributeMapping convertJSONObjectAttributeToManagedObjectAttribute:[class objectDescription].uniqueIdentifierOfJSONObjects];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass(class)];
    request.predicate = [NSPredicate predicateWithFormat:@"NOT (%K IN %@)", idKey, remoteIDs];

    NSError *error = nil;
    NSArray *objectsToBeDeleted = [context executeFetchRequest:request error:&error];
    NSCAssert(error == nil, @"error while fetching: %@", error);

    for (id object in objectsToBeDeleted) {
        [context deleteObject:object];
    }
}

static void class_swizzleSelector(Class class, SEL originalSelector, SEL newSelector)
{
    Method origMethod = class_getInstanceMethod(class, originalSelector);
    Method newMethod = class_getInstanceMethod(class, newSelector);
    if(class_addMethod(class, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(class, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

@implementation NSManagedObject (SLRESTfulCoreDataQueryInterface)

+ (void)load
{
    class_swizzleSelector(object_getClass(self), @selector(resolveInstanceMethod:), @selector(__SLRESTfulCoreDataResolveInstanceMethod:));
    class_swizzleSelector(object_getClass(self), @selector(resolveInstanceMethod:), @selector(_resolveCRUDBasedRelationshipInstanceMethod:));
}

+ (BOOL)_resolveCRUDBasedRelationshipInstanceMethod:(SEL)sel
{
    if ([self _resolveCRUDBasedRelationshipInstanceMethod:sel]) {
        return YES;
    }

    NSString *selectorName = NSStringFromSelector(sel);

    if (![selectorName hasSuffix:@"withCompletionHandler:"]) {
        return NO;
    }

    NSMutableString *mutableSelectorName = selectorName.mutableCopy;
    NSUInteger colonCount = [mutableSelectorName replaceOccurrencesOfString:@":" withString:@"." options:NSLiteralSearch range:NSMakeRange(0, mutableSelectorName.length)];

    if (colonCount != 2) {
        return NO;
    }

    // CoreData is creating for the entity SLEntity1 an new subclass SLEntity1_SLEntity1 and KVO an additional NSKeyValueObserving_SLEntity1_SLEntity1
    Class class = self;
    while (class != [class class]) {
        class = [class class];
    }

    NSUInteger firstColonPosition = [selectorName rangeOfString:@":"].location;
    NSString *firstSelectorPart = [selectorName substringToIndex:firstColonPosition];

    if (![firstSelectorPart hasSuffix:@"Object"]) {
        return NO;
    }

    __block NSEntityDescription *entityDescription = nil;

    if ([NSThread currentThread].isMainThread) {
        entityDescription = [NSEntityDescription entityForName:NSStringFromClass(class) inManagedObjectContext:[class mainThreadManagedObjectContext]];
    } else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            entityDescription = [NSEntityDescription entityForName:NSStringFromClass(class) inManagedObjectContext:[class mainThreadManagedObjectContext]];
        });
    }

    NSUInteger objectLength = @"Object".length;
    NSString *firstSelectorPartWithoutObject = [firstSelectorPart stringByReplacingCharactersInRange:NSMakeRange(firstSelectorPart.length - objectLength, objectLength) withString:@""];

    if ([firstSelectorPartWithoutObject hasPrefix:@"add"]) {
        // addFloorsObject:withCompletionHandler:
        NSString *relationshipName = [firstSelectorPartWithoutObject substringFromIndex:3];
        relationshipName = [relationshipName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[relationshipName substringToIndex:1].lowercaseString];

        NSRelationshipDescription *relationship = entityDescription.relationshipsByName[relationshipName];
        if (!relationship) {
            NSLog(@"%@: relationship %@ was not found", class, relationshipName);
            return NO;
        }

        NSParameterAssert(relationship.inverseRelationship);
        NSString *inverseRelationshipName = relationship.inverseRelationship.name;

        Class destinationEntityClass = NSClassFromString(relationship.destinationEntity.name);
        NSURL *CRUDBaseURL = [[class objectDescription] CRUDBaseURLForRelationship:relationshipName];

        if (!CRUDBaseURL) {
            NSLog(@"No CRUDBaseURL found for %@, relationship: %@", class, relationshipName);
            return NO;
        }

        NSString *name = [[destinationEntityClass attributeMapping] convertManagedObjectAttributeToJSONObjectAttribute:inverseRelationshipName];
        CRUDBaseURL = [NSURL URLWithString:[CRUDBaseURL.absoluteString stringByReplacingOccurrencesOfString:@":" withString:[NSString stringWithFormat:@":%@.", name]]];

        IMP implementation = imp_implementationWithBlock(^(NSManagedObject *blockSelf, NSManagedObject *object, void(^completionHandler)(id object, NSError *error)) {
            [object setValue:blockSelf forKey:inverseRelationshipName];

            [object postToURL:CRUDBaseURL completionHandler:^(NSManagedObject *updatedObject, NSError *error) {
                if (error) {
                    if (completionHandler) {
                        completionHandler(nil, error);
                    }
                    return;
                }

                NSManagedObjectContext *context = [class backgroundThreadManagedObjectContext];
                [context performBlock:^(NSArray *objects) {
                    NSManagedObject *updatedObject = objects[0];
                    NSManagedObject *blockSelf = objects[1];

                    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:NSStringFromClass(class) inManagedObjectContext:context];
                    NSRelationshipDescription *relationshipDescription = entityDescription.relationshipsByName[relationshipName];
                    NSAssert(relationshipDescription != nil, @"");

                    if (relationshipDescription.isToMany) {
                        NSString *selectorName = [firstSelectorPart stringByAppendingString:@":"];
                        ((void(*)(id, SEL, id))objc_msgSend)(blockSelf, NSSelectorFromString(selectorName), updatedObject);
                    } else {
                        [updatedObject setValue:blockSelf forKey:relationshipDescription.name];
                    }

                    NSError *saveError = nil;
                    [context save:&saveError];
                    NSAssert(saveError == nil, @"error saving NSManagedObjectContext: %@", saveError);

                    [[class mainThreadManagedObjectContext] performBlock:^(NSArray *objects) {
                        if (completionHandler) {
                            completionHandler(objects[0], nil);
                        }
                    } withObject:@[ updatedObject ]];
                } withObject:@[ updatedObject, blockSelf ]];
            }];
        });

        class_addMethod(self, sel, implementation, "v@:@@");

        return YES;
    } else if ([firstSelectorPartWithoutObject hasPrefix:@"delete"]) {
        // deleteFloorsObject:withCompletionHandler:
        NSString *relationshipName = [firstSelectorPartWithoutObject substringFromIndex:6];
        relationshipName = [relationshipName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[relationshipName substringToIndex:1].lowercaseString];

        NSRelationshipDescription *relationship = entityDescription.relationshipsByName[relationshipName];
        if (!relationship) {
            NSLog(@"%@: relationship %@ was not found", class, relationshipName);
            return NO;
        }

        NSParameterAssert(relationship.inverseRelationship);
        NSString *inverseRelationshipName = relationship.inverseRelationship.name;

        Class destinationEntityClass = NSClassFromString(relationship.destinationEntity.name);
        NSURL *CRUDBaseURL = [[class objectDescription] CRUDBaseURLForRelationship:relationshipName];

        if (!CRUDBaseURL) {
            NSLog(@"No CRUDBaseURL found for %@, relationship: %@", class, relationshipName);
            return NO;
        }

        NSString *name = [[destinationEntityClass attributeMapping] convertManagedObjectAttributeToJSONObjectAttribute:inverseRelationshipName];
        CRUDBaseURL = [NSURL URLWithString:[CRUDBaseURL.absoluteString stringByReplacingOccurrencesOfString:@":" withString:[NSString stringWithFormat:@":%@.", name]]];
        CRUDBaseURL = [CRUDBaseURL URLByAppendingPathComponent:[NSString stringWithFormat:@":%@", [destinationEntityClass objectDescription].uniqueIdentifierOfJSONObjects]];

        IMP implementation = imp_implementationWithBlock(^(NSManagedObject *blockSelf, NSManagedObject *object, void(^completionHandler)(NSError *error)) {
            [object setValue:blockSelf forKey:inverseRelationshipName];
            [object deleteToURL:CRUDBaseURL completionHandler:completionHandler];
        });

        class_addMethod(self, sel, implementation, "v@:@@");

        return YES;
    }

    return NO;
}

+ (BOOL)__SLRESTfulCoreDataResolveInstanceMethod:(SEL)sel
{
    if ([self __SLRESTfulCoreDataResolveInstanceMethod:sel]) {
        return YES;
    }

    NSString *selectorName = NSStringFromSelector(sel);

    if (![selectorName hasSuffix:@"WithCompletionHandler:"]) {
        return NO;
    }

    if ([selectorName rangeOfString:@":"].location != selectorName.length - 1) {
        return NO;
    }

    // CoreData is creating for the entity SLEntity1 an new subclass SLEntity1_SLEntity1 and KVO an additional NSKeyValueObserving_SLEntity1_SLEntity1
    Class class = self;
    while (class != [class class]) {
        class = [class class];
    }

    NSString *className = NSStringFromClass(class);

    NSRange range = [selectorName rangeOfString:@"WithCompletionHandler:"];
    NSString *relationship = [selectorName substringToIndex:range.location];

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:className
                                                         inManagedObjectContext:[class mainThreadManagedObjectContext]];
    NSRelationshipDescription *relationshipDescription = entityDescription.relationshipsByName[relationship];

    if (!relationshipDescription) {
        return NO;
    }

    NSURL *CRUDBaseURL = [[class objectDescription] CRUDBaseURLForRelationship:relationship];

    if (!CRUDBaseURL) {
        NSLog(@"No CRUDBaseURL found for %@, relationship: %@", className, relationship);
        return NO;
    }

    BOOL isToMany = relationshipDescription.isToMany;

    IMP implementation = imp_implementationWithBlock(^(NSManagedObject *blockSelf, void(^completionHandler)(NSArray *objects, NSError *error)) {
        [blockSelf fetchObjectsForRelationship:relationship fromURL:CRUDBaseURL completionHandler:^(NSArray *fetchedObjects, NSError *error) {
            if (!completionHandler) {
                return;
            }

            if (isToMany) {
                completionHandler(fetchedObjects, error);
            } else {
                completionHandler(fetchedObjects.lastObject, error);
            }
        }];
    });

    class_addMethod(self, sel, implementation, "v@:@");

    return YES;
}

+ (void)fetchObjectFromURL:(NSURL *)URL
         completionHandler:(void(^)(id fetchedObject, NSError *error))completionHandler
{
    NSString *jsonPrefix = [self objectDescription].jsonPrefix;
    if (jsonPrefix) {
        [[self backgroundQueue] registerResponseObjectTransformerForNextRequest:^id(NSDictionary *object) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                return object[jsonPrefix];
            }

            return object;
        }];
    }

    [self fetchObjectsFromURL:URL deleteEveryOtherObject:NO completionHandler:^(NSArray *fetchedObjects, NSError *error) {
        if (!completionHandler) {
            return;
        }

        if (error) {
            completionHandler(nil, error);
            return;
        }

        completionHandler(fetchedObjects.lastObject, nil);
    }];
}

+ (void)fetchObjectsFromURL:(NSURL *)URL
          completionHandler:(void(^)(NSArray *fetchedObjects, NSError *error))completionHandler
{
    [self fetchObjectsFromURL:URL
       deleteEveryOtherObject:YES
            completionHandler:completionHandler];
}

+ (void)fetchObjectsFromURL:(NSURL *)URL
     deleteEveryOtherObject:(BOOL)deleteEveryOtherObject
          completionHandler:(void (^)(NSArray *, NSError *))completionHandler
{
    // send request to given URL
    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidStartNotification object:nil];

    NSString *pluralizedJSONPrefix = [self objectDescription].pluralizedJSONPrefix;
    if (pluralizedJSONPrefix) {
        [[self backgroundQueue] registerResponseObjectTransformerForNextRequest:^id(NSDictionary *object) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                return object[pluralizedJSONPrefix];
            }

            return object;
        }];
    }

    [[self backgroundQueue] getRequestToURL:URL
                          completionHandler:^(id JSONObject, NSError *error)
     {
         NSMutableArray *fetchedObjectIDs = [NSMutableArray array];

         if (error != nil) {
             // check for error
             [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

             if (completionHandler) {
                 completionHandler(nil, error);
             }
             return;
         }

         // success for now
         NSManagedObjectContext *backgroundContext = [self backgroundThreadManagedObjectContext];

         [backgroundContext performBlock:^{

             void(^successBlock)(NSArray *objects) = ^(NSArray *objects) {
                 NSManagedObjectContext *mainThreadContext = [self mainThreadManagedObjectContext];
                 [mainThreadContext performBlock:^(NSArray *objects) {
                     [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];
                     if (completionHandler) {
                         completionHandler(objects, nil);
                     }
                 } withObject:objects];
             };

             void(^failureBlock)(NSError *error) = ^(NSError *error) {
                 dispatch_async(dispatch_get_main_queue(), ^(void) {
                     [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];
                     if (completionHandler) {
                         completionHandler(nil, error);
                     }
                 });
             };

             NSMutableArray *updatedObjects = [NSMutableArray array];

             if ([JSONObject isKindOfClass:NSArray.class]) {
                 // convert all JSON objects into NSManagedObjects
                 for (NSDictionary *rawDictionary in JSONObject) {
                     if (![rawDictionary isKindOfClass:NSDictionary.class]) {
                         failureBlock([NSError SLRESTfulCoreDataErrorBecauseBackgroundQueueReturnedUnexpectedJSONObject:JSONObject fromURL:URL]);
                         return;
                     }

                     id object = [self updatedObjectWithRawJSONDictionary:rawDictionary inManagedObjectContext:backgroundContext];
                     if (object) {
                         [updatedObjects addObject:object];
                     } else {
                         failureBlock([NSError SLRESTfulCoreDataErrorBecauseJSONObjectDidNotConvertInManagedObject:JSONObject fromURL:URL]);
                         return;
                     }

                     NSString *idKey = [[self attributeMapping] convertJSONObjectAttributeToManagedObjectAttribute:[self objectDescription].uniqueIdentifierOfJSONObjects];
                     id JSONObjectID = [object valueForKey:idKey];
                     if (JSONObjectID) {
                         [fetchedObjectIDs addObject:JSONObjectID];
                     }
                 }
             } else if ([JSONObject isKindOfClass:NSDictionary.class]) {
                 id object = [self updatedObjectWithRawJSONDictionary:JSONObject inManagedObjectContext:backgroundContext];

                 if (object) {
                     [updatedObjects addObject:object];

                     NSString *idKey = [[self attributeMapping] convertJSONObjectAttributeToManagedObjectAttribute:[self objectDescription].uniqueIdentifierOfJSONObjects];
                     id JSONObjectID = [object valueForKey:idKey];
                     if (JSONObjectID) {
                         [fetchedObjectIDs addObject:JSONObjectID];
                     }
                 } else {
                     failureBlock([NSError SLRESTfulCoreDataErrorBecauseJSONObjectDidNotConvertInManagedObject:JSONObject fromURL:URL]);
                     return;
                 }
             } else {
                 // object is not supported
                 failureBlock([NSError SLRESTfulCoreDataErrorBecauseBackgroundQueueReturnedUnexpectedJSONObject:JSONObject fromURL:URL]);
                 return;
             }

             if (deleteEveryOtherObject) {
                 // now delete every object not returned from the API
                 deleteObjectsWithoutRemoteIDs(backgroundContext, self, fetchedObjectIDs);
             }

             NSError *saveError = nil;
             if (![backgroundContext save:&saveError]) {
                 failureBlock(saveError);
             } else {
                 successBlock(updatedObjects);
             }
         }];
     }];
}

- (void)fetchObjectsForRelationship:(NSString *)relationship
                            fromURL:(NSURL *)URL
                  completionHandler:(void (^)(NSArray *fetchedObjects, NSError *error))completionHandler
{
    if (self.entity.relationshipsByName[relationship]) {
        [self fetchObjectsForRelationship:relationship
                                  fromURL:URL
                   deleteEveryOtherObject:YES
                        completionHandler:completionHandler];
    } else if (self.entity.propertiesByName[relationship]) {
        NSFetchedPropertyDescription *fetchedPropertyDescription = self.entity.propertiesByName[relationship];
        NSParameterAssert([fetchedPropertyDescription isKindOfClass:[NSFetchedPropertyDescription class]]);

        Class class = NSClassFromString(fetchedPropertyDescription.fetchRequest.entity.managedObjectClassName);
        [class fetchObjectsFromURL:[URL URLBySubstitutingAttributesWithManagedObject:self] deleteEveryOtherObject:NO completionHandler:completionHandler];
    } else {
        NSAssert(NO, @"cannot fetch objects for relationship %@", relationship);
    }
}

- (void)fetchObjectsForRelationship:(NSString *)relationship
                            fromURL:(NSURL *)URL
             deleteEveryOtherObject:(BOOL)deleteEveryOtherObject
                  completionHandler:(void (^)(NSArray *fetchedObjects, NSError *error))completionHandler
{
    NSParameterAssert(self.entity.relationshipsByName[relationship]);

    if (self.isInserted || self.hasChanges) {
        NSError *saveError = nil;
        [self.managedObjectContext save:&saveError];
        NSAssert(saveError == nil, @"error while saving: %@", saveError);
    }

    NSRelationshipDescription *relationshipDescription = self.entity.relationshipsByName[relationship];
    NSString *pluralizedJSONPrefix = [NSClassFromString(relationshipDescription.destinationEntity.name) objectDescription].pluralizedJSONPrefix;
    NSString *jsonPrefix = [NSClassFromString(relationshipDescription.destinationEntity.name) objectDescription].jsonPrefix;

    if (relationshipDescription.isToMany && pluralizedJSONPrefix) {
        [[self.class backgroundQueue] registerResponseObjectTransformerForNextRequest:^id(NSDictionary *object) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                return object[pluralizedJSONPrefix];
            }

            return object;
        }];
    } else if (!relationshipDescription.isToMany && jsonPrefix) {
        [[self.class backgroundQueue] registerResponseObjectTransformerForNextRequest:^id(NSDictionary *object) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                return object[jsonPrefix];
            }

            return object;
        }];
    }

    // send request to given URL
    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidStartNotification object:nil];

    [[self.class backgroundQueue] getRequestToURL:[URL URLBySubstitutingAttributesWithManagedObject:self]
                                completionHandler:^(id JSONObject, NSError *error)
     {
         if (error) {
             // check for error
             [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

             if (completionHandler) {
                 completionHandler(nil, error);
             }
             return;
         } else {
             // success for now
             NSManagedObjectID *objectID = self.objectID;
             NSManagedObjectContext *backgroundContext = [self.class backgroundThreadManagedObjectContext];

             [backgroundContext performBlock:^{
                 NSManagedObject *backgroundSelf = [backgroundContext objectWithID:objectID];
                 NSError *error = nil;

                 NSArray *updatedObjects = [backgroundSelf updateObjectsForRelationship:relationship
                                                                         withJSONObject:JSONObject
                                                                                fromURL:URL
                                                                 deleteEveryOtherObject:deleteEveryOtherObject
                                                                                error:&error];

                 NSManagedObjectContext *mainThreadContext = [self.class mainThreadManagedObjectContext];
                 [mainThreadContext performBlock:^(NSArray *objects) {
                     [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                     if (completionHandler) {
                         completionHandler(objects, error);
                     }
                 } withObject:updatedObjects];
             }];
         }
     }];
}

- (void)postToURL:(NSURL *)URL completionHandler:(void (^)(id JSONObject, NSError *error))completionHandler
{
    if (self.isInserted || self.hasChanges) {
        NSError *saveError = nil;
        [self.managedObjectContext save:&saveError];
        NSAssert(saveError == nil, @"error while saving: %@", saveError);
    }

    NSDictionary *rawJSONDictionary = self.rawJSONDictionary;

    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidStartNotification object:nil];

    NSString *jsonPrefix = [NSClassFromString(self.entity.name) objectDescription].jsonPrefix;
    if (jsonPrefix) {
        [[self.class backgroundQueue] registerRequestObjectTransformerForNextRequest:^id(id object) {
            return @{ jsonPrefix: object };
        }];
    }

    [[self.class backgroundQueue] postJSONObject:rawJSONDictionary
                                           toURL:[URL URLBySubstitutingAttributesWithManagedObject:self]
                               completionHandler:^(id JSONObject, NSError *error) {
                                   if (error) {
                                       [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                                       if (completionHandler) {
                                           completionHandler(self, error);
                                       }
                                   } else {
                                       NSManagedObjectID *objectID = self.objectID;

                                       NSManagedObjectContext *context = [self.class backgroundThreadManagedObjectContext];
                                       [context performBlock:^{
                                           NSManagedObject *backgroundSelf = [context objectWithID:objectID];
                                           if (backgroundSelf.managedObjectContext && !backgroundSelf.isDeleted) {
                                               [backgroundSelf updateWithRawJSONDictionary:JSONObject];
                                           }

                                           NSError *saveError = nil;
                                           [context save:&saveError];
                                           NSAssert(saveError == nil, @"error saving NSManagedObjectContext: %@", saveError);

                                           dispatch_async(dispatch_get_main_queue(), ^(void) {
                                               [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                                               if (completionHandler) {
                                                   completionHandler(self, nil);
                                               }
                                           });
                                       }];
                                   }
                               }];
}

- (void)putToURL:(NSURL *)URL completionHandler:(void (^)(id JSONObject, NSError *error))completionHandler
{
    if (self.isInserted || self.hasChanges) {
        NSError *saveError = nil;
        [self.managedObjectContext save:&saveError];
        NSAssert(saveError == nil, @"error while saving: %@", saveError);
    }

    NSDictionary *rawJSONDictionary = self.rawJSONDictionary;

    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidStartNotification object:nil];

    NSString *jsonPrefix = [NSClassFromString(self.entity.name) objectDescription].jsonPrefix;
    if (jsonPrefix) {
        [[self.class backgroundQueue] registerRequestObjectTransformerForNextRequest:^id(id object) {
            return @{ jsonPrefix: object };
        }];
    }

    [[self.class backgroundQueue] putJSONObject:rawJSONDictionary
                                          toURL:[URL URLBySubstitutingAttributesWithManagedObject:self]
                              completionHandler:^(id JSONObject, NSError *error) {
                                  if (error) {
                                      [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                                      if (completionHandler) {
                                          completionHandler(self, error);
                                      }
                                  } else {
                                      NSManagedObjectID *objectID = self.objectID;

                                      NSManagedObjectContext *context = [self.class backgroundThreadManagedObjectContext];
                                      [context performBlock:^{
                                          NSManagedObject *backgroundSelf = [context objectWithID:objectID];
                                          if (backgroundSelf.managedObjectContext && !backgroundSelf.isDeleted) {
                                              [backgroundSelf updateWithRawJSONDictionary:JSONObject];
                                          }

                                          NSError *saveError = nil;
                                          [context save:&saveError];

                                          dispatch_async(dispatch_get_main_queue(), ^(void) {
                                              [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                                              if (completionHandler) {
                                                  completionHandler(self, saveError);
                                              }
                                          });
                                      }];
                                  }
                              }];
}

- (void)deleteToURL:(NSURL *)URL completionHandler:(void (^)(NSError *error))completionHandler
{
    URL = [URL URLBySubstitutingAttributesWithManagedObject:self];
    NSDictionary *rawJSONDictionary = self.rawJSONDictionary;
    Class class = self.class;

    NSManagedObjectContext *context = self.managedObjectContext;
    [context deleteObject:self];

    NSError *saveError = nil;
    [context save:&saveError];
    NSAssert(saveError == nil, @"error saving NSManagedObjectContext: %@", saveError);

    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidStartNotification object:nil];

    [[self.class backgroundQueue] deleteRequestToURL:URL completionHandler:^(NSError *error) {
        if (error) {
            NSManagedObjectContext *backgroundContext = [class backgroundThreadManagedObjectContext];
            [backgroundContext performBlock:^{
                [class updatedObjectWithRawJSONDictionary:rawJSONDictionary inManagedObjectContext:backgroundContext];

                NSError *saveError = nil;
                [backgroundContext save:&saveError];
                NSAssert(saveError == nil, @"error saving NSManagedObjectContext: %@", saveError);

                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

                    if (completionHandler) {
                        completionHandler(error);
                    }
                });
            }];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:SLRESTfulCoreDataRemoteOperationDidFinishNotification object:nil];

            if (completionHandler) {
                completionHandler(saveError);
            }
        }
    }];
}

- (void)updateWithCompletionHandler:(void(^)(id managedObject, NSError *error))completionHandler
{
    if (self.isInserted || self.hasChanges) {
        NSError *saveError = nil;
        [self.managedObjectContext save:&saveError];
        NSAssert(saveError == nil, @"error while saving: %@", saveError);
    }

    NSURL *CRUDBaseURL = [self.class objectDescription].CRUDBaseURL;
    NSParameterAssert(CRUDBaseURL);

    CRUDBaseURL = [CRUDBaseURL URLByAppendingPathComponent:[@":" stringByAppendingString:[[self.class objectDescription] uniqueIdentifierOfJSONObjects]]];
    CRUDBaseURL = [CRUDBaseURL URLBySubstitutingAttributesWithManagedObject:self];

    [self.class fetchObjectFromURL:CRUDBaseURL completionHandler:completionHandler];
}

- (void)createWithCompletionHandler:(void(^)(id managedObject, NSError *error))completionHandler
{
    NSURL *CRUDBaseURL = [self.class objectDescription].CRUDBaseURL;
    NSParameterAssert(CRUDBaseURL);

    [self postToURL:CRUDBaseURL completionHandler:completionHandler];
}

- (void)saveWithCompletionHandler:(void(^)(id managedObject, NSError *error))completionHandler
{
    NSURL *CRUDBaseURL = [self.class objectDescription].CRUDBaseURL;
    NSParameterAssert(CRUDBaseURL);

    CRUDBaseURL = [CRUDBaseURL URLByAppendingPathComponent:[@":" stringByAppendingString:[[self.class objectDescription] uniqueIdentifierOfJSONObjects]]];

    [self putToURL:CRUDBaseURL completionHandler:completionHandler];
}

- (void)deleteWithCompletionHandler:(void(^)(NSError *error))completionHandler
{
    NSURL *CRUDBaseURL = [self.class objectDescription].CRUDBaseURL;
    NSParameterAssert(CRUDBaseURL);

    CRUDBaseURL = [CRUDBaseURL URLByAppendingPathComponent:[@":" stringByAppendingString:[[self.class objectDescription] uniqueIdentifierOfJSONObjects]]];

    [self deleteToURL:CRUDBaseURL completionHandler:completionHandler];
}

@end


text:
Using `stream::iterator` to create an `Iterable` results in an `Iterable` which
can only be iterated once, and will throw an `IllegalArgumentException` on
subsequent attempts.

The contract of `Iterable` is poorly defined, but many APIs will assume that
`Iterable`s allow multiple iteration.

To give a concrete example using protocol buffers,

```java
MyProto construct(Stream<Integer> ints) {
  return MyProto.newBuilder()
      .addAllSubMessage(
          ints.map(i -> SubMessage.newBuilder().setVal(i).build())::iterator)
      .build();
}
```

With the current implementation of the protocol buffer generated code, this will
work, but the following minor change will lead to re-iteration and failure,

```java
MyProto construct(Stream<Integer> ints) {
  MyProto.Builder builder = MyProto.newBuilder();
  builder.addSubMessageBuilder().setVal(0);
  return builder
      .addAllSubMessage(
          ints.map(i -> SubMessage.newBuilder().setVal(i).build())::iterator)
      .build(); // build iterates twice, and throws.
}
```

To avoid such pitfalls, the `Stream` can either be terminated with
`forEachOrdered`

```java
MyProto construct(Stream<Integer> ints) {
  MyProto.Builder builder = MyProto.newBuilder();
  ints.map(i -> SubMessage.newBuilder().setVal(i).build())
      .forEachOrdered(builder::addSubMessage);
  return builder.build();
}
```

or collected (with the caveat that the contents of the `Stream` will now be
materialized into memory at once),

```java
MyProto construct(Stream<Integer> ints) {
  return MyProto.newBuilder()
      .addAllSubMessage(
          ints.map(i -> SubMessage.newBuilder().setVal(i).build())
              .collect(toImmutableList()))
      .build();
}
```

or suppressed using `@SuppressWarnings("StreamToIterable")`. Only suppress if
you're sure the API you're using will only iterate the resulting one-shot
`Iterable` once, and can't accept a `Stream` or an `Iterator`.

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';
import ReactModal from 'react-modal';
import ScrollWatch from '../denali/ScrollWatch';
import Icon from '../denali/icons/Icon';
import { css, cx } from '@emotion/css';
import { rgba } from 'polished';
import {
    colors,
    cssDropShadow,
    cssFontStyles,
    cssScrollDropShadowTop,
} from '../denali/styles';

// http://reactcommunity.org/react-modal/examples/set_app_element.html
ReactModal.setAppElement('body');

const modalOverlayClass = css`
    background-color: rgba(0, 0, 0, 0.6);
    bottom: 0;
    left: 0;
    opacity: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 5;
    &.animated {
        transition: all 0.2s ease-out;
    }

    &.ReactModal__Overlay--after-open {
        opacity: 1;
    }

    /* Animate fade out on close. This is currently not used as tests fail */
    &.ReactModal__Overlay--before-close {
        opacity: 0;
    }
`;

const modalContentClass = css`
    ${cssDropShadow};
    background: ${colors.white};
    border: 1px solid ${colors.border};
    border-radius: 4px;
    box-sizing: border-box;
    display: flex;
    flex-flow: column nowrap;
    justify-content: stretch;
    max-height: calc(100vh - 120px);
    max-width: calc(100vw - 120px);
    min-width: 150px;
    left: 50%;
    margin: 0 auto;
    outline: none;
    position: absolute;
    top: 70px;
    transform: translate(-50%, 0);
    label: modal;

    & > .header {
        align-items: center;
        border-bottom: 1px solid ${colors.border};
        box-shadow: none;
        display: flex;
        flex: 0 0 50px;
        flex-flow: row nowrap;
        justify-content: space-between;
        padding: 0 20px;
        position: relative;

        & > .title {
            ${cssFontStyles.title};
        }

        & > .close-button {
            margin-left: 15px;
            margin-right: -5px;
        }

        ::after {
            ${cssScrollDropShadowTop};
            background: transparent;
            bottom: -20px;
            content: '';
            height: 20px;
            left: 0;
            opacity: 0;
            position: absolute;
            right: 0;
            transition: opacity 0.2s ease;
        }

        &.scrolled::after {
            opacity: 1;
        }
    }

    & > .content {
        flex: 1 1 auto;
        font-size: 0.8571rem;
        overflow: auto;
        padding: 20px;
    }
`;

/**
 * Modal uses [`react-modal`](http://reactcommunity.org/react-modal/) under the
 * hood. To prevent the page from scrolling when the modal is showing, add the
 * following to the app's global CSS:
 *
 * ```css
 * .ReactModal__Body--open {
 *   overflow: hidden;
 * }
 */
export const Modal = (props) => (
    <ReactModal
        aria={{
            labelledby: 'modal-title',
            describedby: 'modal-content',
        }}
        className={cx(modalContentClass, 'denali-modal', props.className)}
        closeTimeoutMS={200}
        contentLabel='Modal'
        contentRef={props.contentRef}
        isOpen={props.isOpen}
        overlayClassName={cx(
            modalOverlayClass,
            {
                animated: !props.noanim,
            },
            'react-modal-overlay'
        )}
        overlayRef={props.overlayRef}
        onRequestClose={props.onClose}
        shouldCloseOnOverlayClick={props.shouldCloseOnOverlayClick}
    >
        <ScrollWatch>
            {({ scrollRef, scrolled, handleScroll }) => {
                const headerClass = `header${scrolled ? ' scrolled' : ''}`;
                return (
                    <React.Fragment>
                        <header
                            className={headerClass}
                            data-testid='modal-header'
                        >
                            <div
                                className={
                                    typeof props.title === 'string'
                                        ? 'title'
                                        : undefined
                                }
                                id='modal-title'
                                data-testid='modal-title'
                            >
                                {props.title}
                            </div>
                            <div
                                className='close-button'
                                onClick={props.onClose}
                            >
                                <Icon
                                    color={colors.grey800}
                                    isLink
                                    size='28px'
                                />
                            </div>
                        </header>
                        <div
                            className='content'
                            id='modal-content'
                            ref={scrollRef}
                            onScroll={handleScroll}
                            data-testid='modal-content'
                        >
                            {props.children}
                        </div>
                    </React.Fragment>
                );
            }}
        </ScrollWatch>
    </ReactModal>
);

Modal.propTypes = {
    /**
     * Content to render inside modal
     * @ignore
     */
    children: PropTypes.any,
    /** Additonal class to apply to the outer div of the modal content */
    className: PropTypes.string,
    /** Content ref callback */
    contentRef: PropTypes.func,
    /** Modal open/closed state */
    isOpen: PropTypes.bool.isRequired,
    /** Disable animations / transitions */
    noanim: PropTypes.bool,
    /** Overlay ref callback */
    overlayRef: PropTypes.func,
    /** Close modal when clicking outside of it */
    shouldCloseOnOverlayClick: PropTypes.bool,
    /** Modal title */
    title: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    /**
     * Handler for closing the modal. Usually, the parent component will set
     * `isOpen` to false
     */
    onClose: PropTypes.func.isRequired,
};

Modal.defaultProps = {
    noanim: false,
    shouldCloseOnOverlayClick: false,
    title: '',
};

export default Modal;


text:
@interface PodsDummy_Pods_examples_tests_ios : NSObject
@end
@implementation PodsDummy_Pods_examples_tests_ios
@end


text:
date: 2017-01-21
title: Instalando o complemento
video_id: -7dyMliIxM0
description: Como instalar o complemento Contadoria Cálculos.
categories:
  - calculos-previdenciarios
resources:
  - name: "Link para complemento "
    link: https://workspace.google.com/marketplace/app/c%C3%A1lculos_previdenci%C3%A1rios/636397858322?hl=pt_BR
type: Video
set: primeiros-passos
set_order: 3
---

O complemento **Cálculos Previdenciários** disponibiliza nas planilhas *Google Sheets* ferramentas que facilitam a elaboração de cálculos previdenciários.

Neste tutorial mostraremos como instalá-lo. As instruções sobre como utilizá-lo você encontrará distribuídas em outros tutoriais.

Siga estes passos:

1. Acesse o link logo abaixo do vídeo para visualizar a página do complemento na *Chrome Webstore*.
1. Você deve estar logado no *Google Drive*. Se ainda não estiver, clique em **fazer login** e digite seu nome de usuário e senha.
1. Na porção superior direita da tela você verá um botão azul de instalação:
{% include image.html url="/images/Botao_instalar.png" description="Botão Instalar" %}
1. Clique em `+`. Uma planilha será aberta para confirmação do procedimento.
1. Clique no botão `Continuar`.
1. Selecione sua conta do *Google Drive* e clique em `Permitir`.

Com isso, o complemento será adicionado ao menu de `Complementos` de todas as suas planilhas.


text:
#pragma once

#include <atomic>
#include <functional>
#include <thread>
#include <unordered_set>
#include <vector>
#include <boost/noncopyable.hpp>
#include <semaphore.h>
#include <errno.h>
#include <assert.h>

#include <folly/ScopeGuard.h>
#include <folly/detail/CacheLocality.h>
#include <folly/detail/Futex.h>

namespace folly { namespace test {

/**
 * DeterministicSchedule coordinates the inter-thread communication of a
 * set of threads under test, so that despite concurrency the execution is
 * the same every time.  It works by stashing a reference to the schedule
 * in a thread-local variable, then blocking all but one thread at a time.
 *
 * In order for DeterministicSchedule to work, it needs to intercept
 * all inter-thread communication.  To do this you should use
 * DeterministicAtomic<T> instead of std::atomic<T>, create threads
 * using DeterministicSchedule::thread() instead of the std::thread
 * constructor, DeterministicSchedule::join(thr) instead of thr.join(),
 * and access semaphores via the helper functions in DeterministicSchedule.
 * Locks are not yet supported, although they would be easy to add with
 * the same strategy as the mapping of sem_wait.
 *
 * The actual schedule is defined by a function from n -> [0,n). At
 * each step, the function will be given the number of active threads
 * (n), and it returns the index of the thread that should be run next.
 * Invocations of the scheduler function will be serialized, but will
 * occur from multiple threads.  A good starting schedule is uniform(0).
 */
class DeterministicSchedule : boost::noncopyable {
 public:
  /**
   * Arranges for the current thread (and all threads created by
   * DeterministicSchedule::thread on a thread participating in this
   * schedule) to participate in a deterministic schedule.
   */
  explicit DeterministicSchedule(const std::function<int(int)>& scheduler);

  /** Completes the schedule. */
  ~DeterministicSchedule();

  /**
   * Returns a scheduling function that randomly chooses one of the
   * runnable threads at each step, with no history.  This implements
   * a schedule that is equivalent to one in which the steps between
   * inter-thread communication are random variables following a poisson
   * distribution.
   */
  static std::function<int(int)> uniform(long seed);

  /**
   * Returns a scheduling function that chooses a subset of the active
   * threads and randomly chooses a member of the subset as the next
   * runnable thread.  The subset is chosen with size n, and the choice
   * is made every m steps.
   */
  static std::function<int(int)> uniformSubset(long seed, int n = 2,
                                               int m = 64);

  /** Obtains permission for the current thread to perform inter-thread
   *  communication. */
  static void beforeSharedAccess();

  /** Releases permission for the current thread to perform inter-thread
   *  communication. */
  static void afterSharedAccess();

  /** Launches a thread that will participate in the same deterministic
   *  schedule as the current thread. */
  template <typename Func, typename... Args>
  static inline std::thread thread(Func&& func, Args&&... args) {
    // TODO: maybe future versions of gcc will allow forwarding to thread
    auto sched = tls_sched;
    auto sem = sched ? sched->beforeThreadCreate() : nullptr;
    auto child = std::thread([=](Args... a) {
      if (sched) sched->afterThreadCreate(sem);
      SCOPE_EXIT { if (sched) sched->beforeThreadExit(); };
      func(a...);
    }, args...);
    if (sched) {
      beforeSharedAccess();
      sched->active_.insert(child.get_id());
      afterSharedAccess();
    }
    return child;
  }

  /** Calls child.join() as part of a deterministic schedule. */
  static void join(std::thread& child);

  /** Calls sem_post(sem) as part of a deterministic schedule. */
  static void post(sem_t* sem);

  /** Calls sem_trywait(sem) as part of a deterministic schedule, returning
   *  true on success and false on transient failure. */
  static bool tryWait(sem_t* sem);

  /** Calls sem_wait(sem) as part of a deterministic schedule. */
  static void wait(sem_t* sem);

  /** Used scheduler_ to get a random number b/w [0, n). If tls_sched is
   *  not set-up it falls back to std::rand() */
  static int getRandNumber(int n);

 private:
  static FOLLY_TLS sem_t* tls_sem;
  static FOLLY_TLS DeterministicSchedule* tls_sched;

  std::function<int(int)> scheduler_;
  std::vector<sem_t*> sems_;
  std::unordered_set<std::thread::id> active_;

  sem_t* beforeThreadCreate();
  void afterThreadCreate(sem_t*);
  void beforeThreadExit();
};

/**
 * DeterministicAtomic<T> is a drop-in replacement std::atomic<T> that
 * cooperates with DeterministicSchedule.
 */
template <typename T>
struct DeterministicAtomic {
  std::atomic<T> data;

  DeterministicAtomic() = default;
  ~DeterministicAtomic() = default;
  DeterministicAtomic(DeterministicAtomic<T> const &) = delete;
  DeterministicAtomic<T>& operator= (DeterministicAtomic<T> const &) = delete;

  constexpr /* implicit */ DeterministicAtomic(T v) noexcept : data(v) {}

  bool is_lock_free() const noexcept {
    return data.is_lock_free();
  }

  bool compare_exchange_strong(
          T& v0, T v1,
          std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    bool rv = data.compare_exchange_strong(v0, v1, mo);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  bool compare_exchange_weak(
          T& v0, T v1,
          std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    bool rv = data.compare_exchange_weak(v0, v1, mo);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T exchange(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data.exchange(v, mo);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  /* implicit */ operator T () const noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T load(std::memory_order mo = std::memory_order_seq_cst) const noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data.load(mo);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data = v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  void store(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    data.store(v, mo);
    DeterministicSchedule::afterSharedAccess();
  }

  T operator++ () noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = ++data;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator++ (int postDummy) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data++;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator-- () noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = --data;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator-- (int postDummy) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data--;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator+= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data += v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T fetch_add(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data += v;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator-= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data -= v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T fetch_sub(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data -= v;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator&= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data &= v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T fetch_and(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data &= v;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator|= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data |= v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T fetch_or(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data |= v;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T operator^= (T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data ^= v);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  T fetch_xor(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data ^= v;
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }
};

}} // namespace folly::test

/* Specialization declarations */

namespace folly { namespace detail {

template<>
int Futex<test::DeterministicAtomic>::futexWake(int count, uint32_t wakeMask);

template<>
FutexResult Futex<test::DeterministicAtomic>::futexWaitImpl(
      uint32_t expected,
      std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
      std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
      uint32_t waitMask);

template<>
Getcpu::Func
AccessSpreader<test::DeterministicAtomic>::pickGetcpuFunc(size_t numStripes);

}} // namespace folly::detail


text:
package gnu.expr;
import javax.script.*;
import java.util.*;
import gnu.mapping.*;
import gnu.kawa.util.WeakIdentityHashMap;

/** Abstract implementation of ScriptEngineFactory for any Kawa Language. */

public abstract class AbstractScriptEngineFactory implements ScriptEngineFactory
{
  Language language;
  protected List<String> names;
  private static List<String> noMimeTypes;

    InheritingEnvironment  savedEnvironment;
    Bindings saveEngineBindings;
    Bindings saveGlobalBindings;

    Environment getEnvironment(ScriptContext ctx) {
        Bindings ebindings = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
        Bindings gbindings = ctx.getBindings(ScriptContext.GLOBAL_SCOPE);
        if (ebindings == saveEngineBindings && gbindings == saveGlobalBindings)
            return savedEnvironment;
        InheritingEnvironment env
            = new BindingsEnvironment("environment-"+(++Language.envCounter),
                                      ebindings, gbindings,
                                      language.getLangEnvironment());
        savedEnvironment = env;
        saveEngineBindings = ebindings;
        saveGlobalBindings = gbindings;
        return env;
    }

  protected AbstractScriptEngineFactory(Language language)
  {
    this.language = language;
  }

  public String getEngineName ()
  {
    return "Kawa-"+language.getName();
  }

  public String getEngineVersion ()
  {
    return kawa.Version.getVersion();
  }

  public String getLanguageVersion ()
  {
    return kawa.Version.getVersion();
  }

  public String getLanguageName ()
  {
    return language.getName();
  }

    public List<String> getExtensions() {
        return language.getExtensions();
    }

  public List<String> getMimeTypes ()
  {
    if (noMimeTypes == null)
      noMimeTypes = Collections.unmodifiableList(new ArrayList<String>(0));
    return noMimeTypes;
  }

  public List<String> getNames()
  {
    if (names == null)
      {
        ArrayList<String> n = new ArrayList<String>(3);
        getNames(n);
        names = Collections.unmodifiableList(n);
      }
    return names;
  }

  protected void getNames (List<String> names)
  {
    names.add(language.getName());
  }

  public String getMethodCallSyntax(String obj, String m, String... args)
  {
    throw new UnsupportedOperationException(getClass().getName()+".getMethodCalSyntax not supported");
  }

  public String getOutputStatement(String toDisplay)
  {
    throw new UnsupportedOperationException(getClass().getName()+".getOutputStatement not supported");
  }

  public String getProgram(String... statements)
  {
    throw new UnsupportedOperationException(getClass().getName()+".getProgram not supported");
  }

  public javax.script.ScriptEngine getScriptEngine()
  {
    return new KawaScriptEngine(this);
  }

  public String getParameter(String key)
  {
    if (key.equals(ScriptEngine.ENGINE))
      return getEngineName();
    if (key.equals(ScriptEngine.ENGINE_VERSION))
      return getEngineVersion();
    if (key.equals(ScriptEngine.NAME))
      return getEngineName();
    if (key.equals(ScriptEngine.LANGUAGE))
      return getLanguageName();
    if (key.equals(ScriptEngine.LANGUAGE_VERSION))
      return getLanguageVersion();
    if (key.equals("THREADING"))
      return "MULTITHREADED";
    return null;
  }

    /** A Location object that proxies lookup in global and engine Bindings.
     */
    public static class BindingsLocation extends NamedLocation<Object> {
        final BindingsEnvironment env;
        final String sname;
        public BindingsLocation(SimpleSymbol name, BindingsEnvironment env) {
            super(name, null);
            this.env = env;
            this.sname = name.getName();
            this.setAlias(null);
        }
        public Object get(Object defaultValue) {
            Object r = env.ebindings.get(sname);
            if (r != null || env.ebindings.containsKey(sname))
                return r;
            r = env.gbindings.get(sname);
            if (r != null || env.gbindings.containsKey(sname))
                return r;
            return defaultValue;
        }
        public Object get() {
            Object unbound = Location.UNBOUND;
            Object v = get(unbound);
            if (v == unbound)
                throw new UnboundLocationException(sname);
            return v;
        }

        public boolean isBound() {
            Object unbound = get(Location.UNBOUND);
            return get(unbound) == unbound;
        }

        public void set(Object newValue) {
            env.ebindings.put(sname, newValue);
        }

        public Environment getEnvironment () {
            return env;
        }
    }

    /** A Environment that proxies lookup in global and engine Bindings.
     */
    public static class BindingsEnvironment extends InheritingEnvironment {
        Bindings ebindings; // Engine Bindings
        Bindings gbindings; // Global Bindings
        public BindingsEnvironment(String name, Bindings ebindings, Bindings gbindings, Environment builtin) {
            super(name, builtin);
            this.ebindings = ebindings;
            this.gbindings = gbindings;
        }

        protected NamedLocation newLocation(Symbol name, Object property) {
            if (property == null && name instanceof SimpleSymbol)
                return new BindingsLocation((SimpleSymbol) name, this);
            else
                return super.newLocation(name, property);
        }

        public NamedLocation lookupDirect (Symbol name, Object property, int hash) {
            NamedLocation loc = super.lookupDirect(name, property, hash);
            if (loc != null && loc.isBound())
                return loc;
            if (ebindings instanceof KawaScriptBindings) {
                loc = ((KawaScriptBindings) ebindings).environment.lookup(name, property, hash);
                if (loc != null && loc.isBound())
                    return loc;
            } else if (property == null && name instanceof SimpleSymbol) {
                String sname = name.getName();
                if (ebindings.containsKey(sname))
                    return addUnboundLocation(name, property, hash);
            }
            if (gbindings instanceof KawaScriptBindings) {
                loc = ((KawaScriptBindings) gbindings).environment.lookup(name, property, hash);
                if (loc != null && loc.isBound())
                    return loc;
            } else if (property == null && name instanceof SimpleSymbol) {
                String sname = name.getName();
                if (gbindings.containsKey(sname))
                    return addUnboundLocation(name, property, hash);
            }
            return loc;
        }

        public void define (Symbol key, Object property, Object newValue) {
            put(key, property, newValue);
        }
        public void fixEntries() {
            for (String key : ebindings.keySet()) {
                lookup(Symbol.valueOf(key));
            }
            for (String key : gbindings.keySet()) {
                lookup(Symbol.valueOf(key));
            }
        }
        public LocationEnumeration enumerateLocations() {
            fixEntries();
            return super.enumerateLocations();
        }
        public LocationEnumeration enumerateAllLocations() {
            fixEntries();
            return super.enumerateAllLocations();
        }
    }

}


text:
<!DOCTYPE html>
<meta charset="utf-8" />

  <title>Reflections - Reflections</title>

  <meta name="description" content="Default Page Description" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://blog.shiv.me/css/latex.css" />
<link rel="stylesheet" href="http://blog.shiv.me/css/main.css" />

<meta name="generator" content="Hugo 0.75.1" />

Reflections

Shiva Velmurugan

Abstract

                  I'm a product manager by day, and programmer by night. I am intrigued by abstraction, programming languages and organizing data.

A month flies by

  Jan 31, 2016

      goals

It has not been a great start. It, however, has been a busy one.
Don't smoke (Stay quit!!) : Going strong! The urge to smoke still surfaces on occasion. I have, however, been able to avoid every time. I must admit that it gets easier, but it always take a bit of an effort.m
Say yes more often: Doing ok. I have caught myself a couple of times. Still needs work

        Read More

Goals for 2016

  Jan 5, 2016

      goals

Thoughts on ello

  Sep 30, 2014

In the tradition of joining new social tools on the interwebs, here some thoughts on my experience.
The usual steps are:
  The first few hours – mostly spent exploring the interface, the features, mired in the comparisons between the “old” and the “new”
  At some point, the lack of interaction and content of previous networks – the constant buzz of twitter, the inane conversations of facebook etc.

        Read More

My Eiffel Tower

  Jul 15, 2014

Getting rid of passwords

  Jul 14, 2014

I hate passwords. Seems like several smart people are on the case of getting rid of the “password”
 Lucas Gonze, argues the loss of meaning around design of user authentication mechanisms. A world without passwords! How will we identify each other? Exchange tokens. Make “forgot password” the default. Passwords are the new pay-wall. A non-violent protest against the cruel overlord — the “password”. Justin Balthrop, calls for a boycott .

        Read More

          ← Newer

          Older →

        Powered By Hugo / Theme HugoTeX

        Shiva Velmurugan
        ©
        2016


text:
void png_setjmp(png_structrp ptr) { setjmp(png_jmpbuf(ptr)); }

void* png_fdopen(int fd, const char* mode) {
  FILE* f = fdopen(fd, mode);
  return static_cast<void*>(f);
}

void png_rewind(void* f) { rewind(static_cast<FILE*>(f)); }

void png_fread(void* buffer, size_t size, size_t count, void* stream) {
  fread(buffer, size, count, static_cast<FILE*>(stream));
}

void png_fclose(void* f) { fclose(static_cast<FILE*>(f)); }

void png_init_io_wrapper(png_structrp png_ptr, void* f) {
  png_init_io(png_ptr, static_cast<FILE*>(f));
}

png_structp png_create_read_struct_wrapper(png_const_charp user_png_ver,
                                           png_voidp error_ptr) {
  return png_create_read_struct(user_png_ver, error_ptr, NULL, NULL);
}

png_structp png_create_write_struct_wrapper(png_const_charp user_png_ver,
                                            png_voidp error_ptr) {
  return png_create_write_struct(user_png_ver, error_ptr, NULL, NULL);
}

void png_read_image_wrapper(png_structrp png_ptr, png_bytep image,
                            size_t height, size_t rowbytes) {
  png_bytep* ptrs = (png_bytep*)malloc(height * sizeof(png_bytep));
  for (size_t i = 0; i != height; ++i) {
    ptrs[i] = image + (i * rowbytes);
  }
  png_read_image(png_ptr, ptrs);
  free(ptrs);
}

void png_write_image_wrapper(png_structrp png_ptr, png_bytep image,
                             size_t height, size_t rowbytes) {
  png_bytep* ptrs = (png_bytep*)malloc(height * sizeof(png_bytep));
  for (size_t i = 0; i != height; ++i) {
    ptrs[i] = image + (i * rowbytes);
  }
  png_write_image(png_ptr, ptrs);
  free(ptrs);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/dashboard.css" rel="stylesheet">
    <title>Welcome to StarterKit</title>

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                </button>
                WINGS PLATFORM

Logout

                <form class="navbar-form navbar-right">

                </form>

Overview (current)

Hi

You are a  user.

Product Details

You do not have permission to view product details

                                ID
                                Name
                                Category
                                Price

                                {{product.ID}}
                                {{product.Name}}
                                {{product.Category}}
                                {{product.Price}}


text:
package org.elasticsearch.http.action.deletebyquery;

import java.io.IOException;
import java.util.Map;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequest;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.action.support.HttpAction;
import org.elasticsearch.action.support.HttpRequest;
import org.elasticsearch.action.support.HttpResponse;
import org.elasticsearch.common.xcontent.XContentHelper;

public class HttpDeleteByQueryAction extends HttpAction<DeleteByQueryRequest, DeleteByQueryResponse> {

    public final static String NAME = "deletebyquery";
    private final static String ENDPOINT = "_query";

    @Override
    protected HttpRequest toRequest(DeleteByQueryRequest request) {
        HttpRequest httpRequest = new HttpRequest(DELETE, ENDPOINT)
                .param("routing", request.routing())
                .param("consistencylevel", request.consistencyLevel().name().toLowerCase())
                .param("replication", request.replicationType().name().toLowerCase())
                .body(request.querySource());
        return httpRequest;
    }

    @Override
    protected DeleteByQueryResponse toResponse(HttpResponse response) throws IOException {
         Map<String, Object> map = XContentHelper.convertToMap(response.getBody(), false).v2();
        logger.info("delete-by-query response = {}", map);
        return null;
    }

}


text:
namespace IBSAT.Models
{
    public class CompartilhamentoModels: CoreModels<CompartilhamentoModels>
    {
        public long ID { get; set; }

        public string URL { get; set; }

        public long ID_EMAIL { get; set; }

        public EmailModels EMAIL { get; set; }

    }
}


text:
package Cache::Memcached::Sweet;

use 5.006;
use strict;
use warnings FATAL => 'all';

use Exporter 'import';

use Cache::Memcached;

our @EXPORT = qw(memcached);

our $VERSION = '0.04';

my $memcached = new Cache::Memcached( servers => [ $ENV{MEMCACHED_HOST} || 'localhost:11211' ] );

sub memcached {
	my ($k, $v, $ttl) = @_;
	if( @_ >= 2) {
		if (ref($v) eq 'CODE') {
			my $code = $v;
			$v = $memcached->get($k);
			unless (defined $v) {
				$v = $code->();
				$memcached->set($k, $v, $ttl);
			}
			return $v;
		} else {
			$memcached->set($k, $v, $ttl) || warn "Setting $k failed";
			return $v;
		}
	} elsif (@_ == 1) {
		$v = $memcached->get($k);
		return $v;
	} else {
		return $memcached;
	}
}

=head1 NAME

Cache::Memcached::Sweet - sugary memcached with callbacks

=head1 SYNOPSIS

  # Reads MEMCACHED_HOST from env, and defaults to localhost:11211 if not set

  use Cache::Memcached::Sweet; # exports the subroutine "memcached"

  my $value = memcached($key, sub {
 	return some_expensive_operation($foo, $bar, $baz);
  });

  my $value = memcached($key); # retrieve value

  memcached($other_key, { a => 1, b => 2 }, 600); # set value with TTL

=head1 FUNCTIONS

L<Cache::Memcached::Sweet> implements and exports the following function

=head2 memcached

  # Set's a value with no TTL
  memcached('foo', $cache_this);

  # Sets a value, with optional ttl
  memcached('bar', { a => 1, b => 2 }, 600);

  # Retrieves a value from the cache
  my $value = memcached('baz');

  # Gets a value if it exists or sets it with the return value from executing the coderef
  # Note: The coderef is called in scalar context
  my $result = memcached('blurgh', sub {
     buzz($blirp, $blurp)
  });

  my $mc = memcached; # Exposes package global instance of Cache::Memcached
  $mc->set_servers()  # ... etc, but not recommended

=head1 CAUTION

This module is meant to provide convenience, and is hardcoded to get the memcached server address from MEMCACHED_HOST or will default to localhost:11211. If you're running some fancy memcached cluster, then this module is probably not for you.

=head1 AUTHOR

Stig Palmquist, C<< <stig at stig.io> >>

=head1 BUGS

https://github.com/pqx/cache-memcached-sweet

=head1 LICENSE AND COPYRIGHT

Copyright 2013 pqx Limited.

This program is distributed under the MIT (X11) License:
L<http://www.opensource.org/licenses/mit-license.php>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

=cut

42;


text:
import {EventAggregator} from 'aurelia-event-aggregator'
import {autoinject, bindable} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import './room-content.css'

export const Events = {
  RoomContentFetched: 'RoomContentFetched'
}

@autoinject()
export class RoomContent {
	description;
	imageUrl;
	@bindable roomTypeId;

	constructor(private messageBus: EventAggregator, private apiClient: HttpClient) {
		this.messageBus.subscribe(Events.RoomContentFetched, data => {
			let content = this.getRoomContent(data);
			this.description = content.Description;
			this.imageUrl = content.ImageUrl;

		});
	}

	getRoomContent(data) {
		return data.filter(match => {
			return this.roomTypeId === match.RoomTypeId;
		})[0];
	}
}