text:
//
//  YSCMacros.h
//  YSCKit
//
//  Created by Builder on 16/6/29.
//  Copyright © 2016年 Builder. All rights reserved.
//

#import <sys/time.h>

//==============================================================================
//
//  @Description:
//      该文件定义了基础库YSCKit中常用的宏定义
//
//==============================================================================

#ifndef YSCMacros_h
#define YSCMacros_h

/** 处于调试或者开发模式 */
#define IS_DEBUG_OR_DEVELOP_MODE    (YSCConfigManagerInstance.isDebugModel || [YSCGeneral isArchiveByDevelopment])
/** 是否输出log */
#define IS_NSLOG_AVAILABLE          IS_DEBUG_OR_DEVELOP_MODE

#define __NSLog(s, ...) do { \
            if (IS_NSLOG_AVAILABLE) { \
                NSMutableString *logString = [NSMutableString stringWithFormat:@"[%@(%d)] ",[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__]; \
                if (s) { \
                    [logString appendFormat:(s), ##__VA_ARGS__]; \
                } \
                else { \
                    [logString appendString:@"(null)"]; \
                } \
                NSLog(@"%@", logString); \
                [YSCLog saveLog:logString]; \
            } \
        } while (0)
#define NSLog(...) __NSLog(__VA_ARGS__)

/** 去掉字符串的头尾空格 */
#define TRIM_STRING(_string) (\
        ( ! [_string isKindOfClass:[NSString class]]) ? \
        @"" : [_string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] \
        )

/**
 *  对象判空
 *  注意:只对原始数据进行判断,即全空的字符串不为空
 */
#define OBJECT_IS_EMPTY(_object) (_object == nil \
        || [_object isKindOfClass:[NSNull class]] \
        || ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
        || ([_object respondsToSelector:@selector(count)]  && [(NSArray *)_object count] == 0))
#define OBJECT_ISNOT_EMPTY(_object) ( ! OBJECT_IS_EMPTY(_object))
#define RETURN_WHEN_OBJECT_IS_EMPTY(_object)        if (OBJECT_IS_EMPTY(_object)) { return ;    }
#define RETURN_NIL_WHEN_OBJECT_IS_EMPTY(_object)    if (OBJECT_IS_EMPTY(_object)) { return nil; }
#define RETURN_EMPTY_WHEN_OBJECT_IS_EMPTY(_object)  if (OBJECT_IS_EMPTY(_object)) { return @""; }
#define RETURN_YES_WHEN_OBJECT_IS_EMPTY(_object)    if (OBJECT_IS_EMPTY(_object)) { return YES; }
#define RETURN_NO_WHEN_OBJECT_IS_EMPTY(_object)     if (OBJECT_IS_EMPTY(_object)) { return NO;  }
#define RETURN_ZERO_WHEN_OBJECT_IS_EMPTY(_object)   if (OBJECT_IS_EMPTY(_object)) { return 0;   }

/**
 *  创建单例
 */
#ifndef DEFINE_SHARED_INSTANCE_USING_BLOCK
    #define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
        static dispatch_once_t pred = 0; \
        __strong static id _sharedObject = nil; \
        dispatch_once(&pred, ^{ \
            if (block) { \
                _sharedObject = block(); \
            } \
        }); \
        return _sharedObject;
#endif

/**
 * @brief   swizzling instance method
 *
 * @usage:
 *      SWIZZLING_INSTANCE_METHOD(self.class, @selector(viewDidLoad), @selector(ysc_viewDidLoad))
 */
#ifndef SWIZZLING_INSTANCE_METHOD
    #define SWIZZLING_INSTANCE_METHOD(clazz, originalSelector, swizzledSelector) { \
        Method originalMethod = class_getInstanceMethod(clazz, originalSelector); \
        Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSelector); \
        BOOL isAddedMethod = class_addMethod(clazz, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); \
        if (isAddedMethod) { \
            class_replaceMethod(clazz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); \
        } \
        else { \
            method_exchangeImplementations(originalMethod, swizzledMethod); \
        } }
#endif

/**
 * @brief   swizzling class method
 *
 * @usage:
 *      SWIZZLING_INSTANCE_METHOD(object_getClass((id)self), @selector(viewDidLoad), @selector(ysc_viewDidLoad))
 */
#ifndef SWIZZLING_CLASS_METHOD
    #define SWIZZLING_CLASS_METHOD(clazz, originalSelector, swizzledSelector) { \
        Method originalMethod = class_getInstanceMethod(clazz, originalSelector); \
        Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSelector); \
        BOOL isAddedMethod = class_addMethod(clazz, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); \
        if (isAddedMethod) { \
            class_replaceMethod(clazz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); \
        } \
        else { \
            method_exchangeImplementations(originalMethod, swizzledMethod); \
        } }
#endif

/**
 *  代码段简写
 */
#define RGBA(r, g, b, a)                [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:a]
#define RGB(r, g, b)                    RGBA(r,g,b,1.0f)
#define RGB_GRAY(c)                     RGBA(c,c,c,1.0f)
#define RANDOM_INT(from,to)             ((int)((from) + arc4random() % ((to)-(from) + 1)))  //随机数 [from,to] 之间
#define GET_NSERROR_MESSAGE(e)          ((NSError *)e).userInfo[NSLocalizedDescriptionKey]  //=e.localizedDescription
#define KEY_WINDOW                      [UIApplication sharedApplication].keyWindow
#define FUNCTION_NAME                   [NSString stringWithUTF8String:__FUNCTION__]

#define IS_NIB_EXISTS(nib)              [[NSFileManager defaultManager] fileExistsAtPath:[[NSBundle mainBundle] pathForResource:nib ofType:@"nib"]]
#define CREATE_NSERROR_WITH_Code(c,m)   [NSError errorWithDomain:@"YSCKit" code:c userInfo:@{NSLocalizedDescriptionKey : m}]
#define CREATE_NSERROR(m)               CREATE_NSERROR_WITH_Code(0,m)
#define PRINT_DEALLOCING                NSLog(@"[%@] is deallocing...",NSStringFromClass(self.class));
#define DEPRECATED_MARK(_instead_msg)   NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, _instead_msg) // 用于标示变量或方法已经过期了

/**
 * 1. if (NSOrderedAscending != COMPARE_VERSION(v1,v2))  { //v1 >= v2 }
 * 2. if (NSOrderedDescending == COMPARE_VERSION(v1,v2)) { //v1 > v2 }
 * 3. if (NSOrderedAscending == COMPARE_VERSION(v1,v2))  { //v1 < v2 }
 */
#define COMPARE_VERSION(v1,v2)          [v1 compare:v2 options:NSNumericSearch]
#define COMPARE_CURRENT_VERSION(v)      COMPARE_VERSION([[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"], (v))
#define APP_SKIP_VERSION(v)             [NSString stringWithFormat:@"APP_SKIP_VERSION_%@", v]
#define APP_LAUNCH_VERSION(v)           [NSString stringWithFormat:@"APP_LAUNCH_VERSION_%@", v]

/**
 * @brief 关闭performSelector的leak警告提示
 *
 * @usage:
 *   PERFORM_SELECTOR_WITHOUT_LEAKWARNING(
 *      [_target performSelector:_action withObject:self]
 *   );
 *
 *   OR
 *
 *   id result;
 *   PERFORM_SELECTOR_WITHOUT_LEAKWARNING(
 *      result = [_target performSelector:_action withObject:self]
 *   );
 */
#ifndef PERFORM_SELECTOR_WITHOUT_LEAKWARNING
    #define PERFORM_SELECTOR_WITHOUT_LEAKWARNING(block) \
        do { \
            _Pragma("clang diagnostic push") \
            _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
            if (block) { \
                block(); \
            } \
            _Pragma("clang diagnostic pop") \
        } while (0)
#endif

/**
 *  注册通知与发送通知
 */
//注册通知
#define ADD_OBSERVER_WITH_OBJECT(_selector, _name, _object) \
        ([[NSNotificationCenter defaultCenter] addObserver:self selector:_selector name:_name object:_object])
#define ADD_OBSERVER(_selector,_name) \
        ADD_OBSERVER_WITH_OBJECT(_selector, _name, nil)
//发送通知
#define POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, _info) \
        ([[NSNotificationCenter defaultCenter] postNotificationName:_name object:_object userInfo:(_info)])
#define POST_NOTIFICATION(_name) \
        POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, nil)
#define POST_NOTIFICATION_WITH_OBJECT(_name, _object) \
        POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, nil)
#define POST_NOTIFICATION_WITH_INFO(_name, _info) \
        POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, _info)
//移除通知
#define REMOVE_OBSERVER(_name) \
        ([[NSNotificationCenter defaultCenter] removeObserver:self name:_name object:nil])
#define REMOVE_ALL_OBSERVERS(_self) \
        ([[NSNotificationCenter defaultCenter] removeObserver:_self])

/**
 * @usage:
 *   YSCBenchmark(^{
 *   // code
 *   }, ^(double ms) {
 *   NSLog(@"time cost: %.2f ms",ms);
 *   });
 */
static inline void YSCBenchmark(void (^block)(void), void (^complete)(double ms)) {
    // <QuartzCore/QuartzCore.h> version
    /*
     extern double CACurrentMediaTime (void);
     double begin, end, ms;
     begin = CACurrentMediaTime();
     block();
     end = CACurrentMediaTime();
     ms = (end - begin) * 1000.0;
     complete(ms);
     */

    // <sys/time.h> version
    struct timeval t0, t1;
    gettimeofday(&t0, NULL);
    block();
    gettimeofday(&t1, NULL);
    double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_usec - t0.tv_usec) * 1e-3;
    complete(ms);
}

/**
 * @usage:
 *   @interface NSObject (MyAdd)
 *       @property (nonatomic, strong) NSMutableArray *textFields;
 *   @end
 *
 *   #import <objc/runtime.h>
 *   @implementation NSObject (MyAdd)
 *       YSC_DYNAMIC_PROPERTY_LAZYLOAD(textFields, NSMutableArray *, [NSMutableArray new])
 *   @end
 */
#ifndef YSC_DYNAMIC_PROPERTY_LAZYLOAD
    #define YSC_DYNAMIC_PROPERTY_LAZYLOAD(_getter_, _type_, _initObject_) \
        - (_type_)_getter_ { \
            _type_ target = objc_getAssociatedObject(self, _cmd); \
            if ( ! target) { \
                target = _initObject_; \
                objc_setAssociatedObject(self, _cmd, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC); \
            } \
            return target; \
        }
#endif

/**
 * usage:
 *   @interface NSObject (MyAdd)
 *       @property (nonatomic, assign) BOOL isError;
 *   @end
 *
 *   #import <objc/runtime.h>
 *   @implementation NSObject (MyAdd)
 *       YSC_DYNAMIC_PROPERTY_BOOL(isError, setIsError)
 *   @end
 */
#ifndef YSC_DYNAMIC_PROPERTY_BOOL
    #define YSC_DYNAMIC_PROPERTY_BOOL(_getter_, _setter_) \
        - (void)_setter_:(BOOL)value { \
            NSNumber *number = [NSNumber numberWithBool:value]; \
            [self willChangeValueForKey:@#_getter_]; \
            objc_setAssociatedObject(self, _cmd, number, OBJC_ASSOCIATION_RETAIN); \
            [self didChangeValueForKey:@#_getter_]; \
        } \
        - (BOOL)_getter_ { \
            NSNumber *number = objc_getAssociatedObject(self, @selector(_setter_:)); \
            return [number boolValue]; \
        }
#endif

/**
 *   Synthsize a dynamic object property in @implementation scope.
 *   It allows us to add custom properties to existing classes in categories.
 *
 *   @param association  ASSIGN / RETAIN / COPY / RETAIN_NONATOMIC / COPY_NONATOMIC
 *   @warning #import <objc/runtime.h>
 *   *******************************************************************************
 *
 * @usage:
 *   @interface NSObject (MyAdd)
 *       @property (nonatomic, retain) UIColor *myColor;
 *   @end
 *
 *   #import <objc/runtime.h>
 *   @implementation NSObject (MyAdd)
 *       YSC_DYNAMIC_PROPERTY_OBJECT(myColor, setMyColor, RETAIN_NONATOMIC, UIColor *)
 *   @end
 */
#ifndef YSC_DYNAMIC_PROPERTY_OBJECT
    #define YSC_DYNAMIC_PROPERTY_OBJECT(_getter_, _setter_, _association_, _type_) \
        - (void)_setter_:(_type_)object { \
            [self willChangeValueForKey:@#_getter_]; \
            objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_##_association_); \
            [self didChangeValueForKey:@#_getter_]; \
        } \
        - (_type_)_getter_ { \
            return objc_getAssociatedObject(self, @selector(_setter_:)); \
        }
#endif

/**
 * @usage:
 *   @interface NSObject (MyAdd)
 *       @property (nonatomic, retain) CGPoint myPoint;
 *   @end
 *
 *   #import <objc/runtime.h>
 *   @implementation NSObject (MyAdd)
 *       YSC_DYNAMIC_PROPERTY_CTYPE(myPoint, setMyPoint, CGPoint)
 *   @end
 */
#ifndef YSC_DYNAMIC_PROPERTY_CTYPE
    #define YSC_DYNAMIC_PROPERTY_CTYPE(_getter_, _setter_, _type_) \
        - (void)_setter_:(_type_)object { \
            [self willChangeValueForKey:@#_getter_]; \
            NSValue *value = [NSValue value:&object withObjCType:@encode(_type_)]; \
            objc_setAssociatedObject(self, _cmd, value, OBJC_ASSOCIATION_RETAIN); \
            [self didChangeValueForKey:@#_getter_]; \
        } \
        - (_type_)_getter_ { \
            _type_ cValue = { 0 }; \
            NSValue *value = objc_getAssociatedObject(self, @selector(_setter_:)); \
            [value getValue:&cValue]; \
            return cValue; \
        }
#endif

/**
 * @usage:
 *   @weakiy(self)
 *   [self doSomething^{
 *       @strongiy(self)
 *       if (!self) return;
 *       ...
 *   }];
 */
#ifndef weakiy
    #if DEBUG
        #if __has_feature(objc_arc)
            #define weakiy(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
        #else
            #define weakiy(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
        #endif
    #else
        #if __has_feature(objc_arc)
            #define weakiy(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
        #else
            #define weakiy(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
        #endif
    #endif
#endif

#ifndef strongiy
    #if DEBUG
        #if __has_feature(objc_arc)
            #define strongiy(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
        #else
            #define strongiy(object) autoreleasepool{} __typeof__(object) object = block##_##object;
        #endif
    #else
        #if __has_feature(objc_arc)
            #define strongiy(object) try{} @finally{} __typeof__(object) object = weak##_##object;
        #else
            #define strongiy(object) try{} @finally{} __typeof__(object) object = block##_##object;
        #endif
    #endif
#endif

#endif /* YSCMacros_h */


text:
    <navbar></navbar>

What's happening, {{ getActiveUser().firstName }}?

            <input ng-model='kweetText' type="text" class="form-control">

                <div  class="pull-left" ng-hide="getRemainingCharacterCount() < 0">
                    {{ getRemainingCharacterCount() }} characters remaining.

                <div ng-show="getRemainingCharacterCount() < 0">
                    Your kweet is {{ getRemainingCharacterCount() | abs}} characters too long!

= 0 && kweetText.length > 0" class="pull-right">
                    <button ng-click="postKweet()" type="submit" class="btn btn-success">Post</button>

Timeline

                <input ng-model="SearchText" type="text" class="search form-control" placeholder="Search"/>

                        <image ng-src='{{ getUser(kweet.userId).avatar }}'/>
                        {{ kweet.content }}

                        {{ getUser(kweet.userId).username}} @ {{ kweet.timestamp | date:'HH:mm, d MMM y'}}

Kweets ( {{ getActiveUser().kweets.length }} )

                    <image ng-src='{{ getActiveUser().avatar }}'/>
                    {{ getMostRecentKweet(getActiveUser().id).content }}

                    {{ getActiveUser().username }} @ {{ getMostRecentKweet(getActiveUser().id).timestamp | date:'HH:mm, d MMM y'}}

Followers ( {{ getActiveUser().followers.length }} )

Following ( {{ getActiveUser().following.length }} )

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace NetSuite\Classes;

class PayrollItemSearchRow extends SearchRow {
    public $basic;
    public $customSearchJoin;
    static $paramtypesmap = array(
        "basic" => "PayrollItemSearchRowBasic",
        "customSearchJoin" => "CustomSearchRowBasic[]",
    );
}


text:
Troilus
======
**Troilus** is a high level Cassandra Java client on the top of the [DataStax Java Driver for Apache Cassandra](https://github.com/datastax/java-driver).
It supports synchronous programming and asynchronous programming.

The main features of Troilus are
* providing a Java8-based Interface as well as a Java7-based interface (module troilus-core-java7)
* Supporting sync as well as async programming
* [reactive streams](http://www.reactive-streams.org) support
* (Entity) Bean-Mapping support for tables and user defined data types (incl. mapping support of generic artefacts such as Java8/Guava Optional and Guava ImmutableCollections)
* Build-in data swap check
* Build-in prepared statement management
* Implementation support for data-related constraint checks (mandatory fields, more complex data swap validation checks, …)

#Maven
-------
Java8-based
``` java
<dependency>
	<groupId>net.oneandone</groupId>
	<artifactId>troilus-core</artifactId>
	<version>0.3</version>
</dependency>
```

Java7-based
``` java
<dependency>
	<groupId>net.oneandone</groupId>
	<artifactId>troilus-core-java7</artifactId>
	<version>0.3</version>
</dependency>
```

#Examples
-------

##Create a Dao
First a DataStax Java Driver [Session](https://github.com/datastax/java-driver) object has to be created
``` java
Cluster cluster = Cluster.builder()
                         .addContactPoint(node)
                         .build();
Session session = cluster.connect("ks_hotel_reservation_system");
```

This Session object will be used to create a new instance of a `Dao`. In the examples below the [hotels table](troilus-core/src/test/resources/com/unitedinternet/troilus/example/hotels.ddl) is used
``` java
Dao hotelsDao = new DaoImpl(session, "hotels");
```

Pre-configured dao
``` java
Dao hotelsDao = new DaoImpl(session, "hotels")
                          .withConsistency(ConsistencyLevel.LOCAL_QUORUM);
```

##Write
Write a row in a column-oriented way
``` java
hotelsDao.writeWithKey("id", "BUP932432")
         .value("name", "City Budapest")
         .value("room_ids", ImmutableSet.of("1", "2", "3", "122", "123", "124", "322", "333"))
         .value("classification", ClassifierEnum.FOUR)
         .withWritetime(microsSinceEpoch)
         .execute();
```

Write a row in an entity-oriented way.
``` java
hotel = new Hotel("BUP14334",
                  "Richter Panzio",
       	          ImmutableSet.of("1", "2", "3", "4", "5"),
                  Optional.of(ClassifierEnum.TWO),
                  Optional.empty());

hotelsDao.writeEntity(hotel)
         .execute();
```

The columns will be mapped by using `@Field` annotated fields. The JEE [`@Column`](http://docs.oracle.com/javaee/7/api/javax/persistence/Column.html) annotation is also supported for compatibility reasons. However, the name field is supported only
``` java
public class Hotel  {

    @Field(name = "id")
    private String id = null;

    @Field(name = "name")
    private String name = null;

    @Field(name = "room_ids")
    private ImmutableSet<String> roomIds = ImmutableSet.of();

    @Field(name = "classification")
    private Optional<ClassifierEnum> classification = Optional.empty();

    @Field(name = "description")
    private Optional<String> description = Optional.empty();

    @SuppressWarnings("unused")
    private Hotel() { }

    public Hotel(String id,
                 String name,
                 ImmutableSet<String> roomIds,
                 Optional<ClassifierEnum> classification,
                 Optional<String> description) {
        this.id = id;
        this.name = name;
        this.roomIds = roomIds;
        this.classification = classification;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public ImmutableSet<String> getRoomIds() {
        return roomIds;
    }

    public Optional<ClassifierEnum> getClassification() {
        return classification;
    }

    public Optional<String> getDescription() {
        return description;
    }
}
```

### updating values
``` java
hotelsDao.writeWithKey("id","BUP932432")
         .value("description", "The City Budapest is in the business district on the Pest side of the river.")
         .execute();
  ```

### removing values
``` java
hotelsDao.writeWithKey("id","BUP932432")
         .value("description", Optional.empty())
         .execute();
```

or
``` java
hotelsDao.writeWithKey("id","BUP932432")
         .value("description", null)
         .execute();
```

### value update based on where conditions
``` java
hotelsDao.writeWhere(QueryBuilder.in("id", "BUP932432", "BUP233544", "BUP2433"))
         .value("classification", ClassifierEnum.FOUR)
         .execute();
```

##Delete

``` java
hotelsDao.deleteWithKey("id", "BUP932432")
         .execute();
```

### lightweight transactions
transaction-safe, ***unique insert*** with `ifNotExists()`(performs the insertion only if the row does not already exist)
``` java
try {
   hotelsDao.writeWithKey("id", "BUP932432")
            .value("name", "City Budapest")
            .value("room_ids", ImmutableSet.of("1", "2", "3", "122", "123", "124", "322", "333"))
            .value("classification", ClassifierEnum.FOUR)
            .withWritetime(microsSinceEpoch)
            .ifNotExists()
            .withSerialConsistency(ConsistencyLevel.SERIAL)
            .execute();

} catch (IfConditionException ice) {
   // ...
}
```

transaction-safe, ***conditional update*** with `onlyIf(..conditions..)` (uses IF followed by a condition to be met for the update to succeed)
``` java
try {
   hotelsDao.writeWithKey("id", "BUP932432")
            .value("name" "Budapest City")
            .onlyIf(QueryBuilder.eq("name", "City Budapest"))
            .withSerialConsistency(ConsistencyLevel.SERIAL)
            .execute();

} catch (IfConditionException ice) {
   // ...
}
```

transaction-safe, ***conditional delete*** with `onlyIf(..conditions..)` (uses IF followed by a condition to be met for the update to succeed)
``` java
try {
   hotelsDao.deleteWithKey("id","BUP932432")
            .onlyIf(QueryBuilder.eq("name", "Budapest City"))
            .withSerialConsistency(ConsistencyLevel.SERIAL)
            .execute();

} catch (IfConditionException ice) {
   // ...
}
```

transaction-safe ***delete*** with `ifExists`
``` java
try {
   hotelsDao.deleteWithKey("id","BUP932432")
            .ifExists()
            .withSerialConsistency(ConsistencyLevel.SERIAL)
            .execute();

} catch (IfConditionException ice) {
   // ...
}
```

##Batching
Non if-conditional mutating operations (insert, update, delete) can be executed in a batched manner by combining it with another mutating operation. This is provided by the `combinedWith(...)` method.
``` java
Batchable deletion = hotelsDao.deleteWithKey("id", "BUP932432");

hotelsDao.deleteWithKey("id", "BUP14334")
         .combinedWith(deletion)
         .withWriteAheadLog()
         .execute();
```

##Read
###Read a single row

Read a row in an entity-oriented way.
``` java
Optional<Hotel> optionalHotel = hotelsDao.readWithKey("id", "BUP45544")
                                         .asEntity(Hotel.class)
                                         .execute();
optionalHotel.ifPresent(hotel -> System.out.println(hotel.getName()));
```

Read a row in a column-oriented way
``` java
Optional<Record> optionalRecord = hotelsDao.readWithKey("id", "BUP14334")
                                           .column("id")
                                           .column("name")
                                           .withConsistency(ConsistencyLevel.LOCAL_ONE)
                                           .execute();
optionalRecord.ifPresent(record -> record.getString("name").ifPresent(name -> System.out.println(name)));
```

Read a row in a column-oriented way with `Name` definitions.
``` java
import static ....HotelTableColumns.*;

Optional<Record> optionalRecord = hotelsDao.readWithKey(ID, "BUP3443")
                                           .column(NAME)
                                           .column(CLASSIFICATION)
                                           .execute();
optionalRecord.ifPresent(record -> record.getValue(NAME).

Present(name -> System.out.println(name)));
optionalRecord.ifPresent(record -> record.getValue(CLASSIFICATION).ifPresent(classification -> System.out.println(classification)));
```

with definitions
``` java
public final class HotelTableColumns  {
    public static final ColumnName<String> ID = ColumnName.defineString("id");
    public static final ColumnName<String> NAME = ColumnName.defineString("name");
    public static final ColumnName<Set<String>> ROOM_IDS = ColumnName.defineSet("room_ids", String.class);
    public static final ColumnName<Address> ADDRESS = ColumnName.define("address", Address.class);
    public static final ColumnName<String> DESCRIPTION = ColumnName.defineString("description");
    public static final ColumnName<ClassifierEnum> CLASSIFICATION = ColumnName.define("classification", ClassifierEnum.class);
}
```

Read with meta data (ttl, writetime)
``` java
Record record = hotelsDao.readWithKey("id", "BUP14334")
                         .column("id")
         	             .column("name")
            	         .columnWithMetadata("description")
                         .withConsistency(ConsistencyLevel.LOCAL_ONE)
                         .execute()
                         .get();

record.getTtl("description").ifPresent(ttl -> System.out.println("ttl=" + ttl)));
```

###Read a list of rows

Read all of the table
``` java
Iterable<Hotel> hotelIterator = hotelsDao.readAll()
                                         .asEntity(Hotel.class)
                                         .withLimit(5000)
                                         .execute();
hotelIterator.forEach(hotel -> System.out.println(hotel));
```

Read specific ones by using conditions
``` java
Iterable<Hotel> hotelIterator = hotelsDao.readWhere(QueryBuilder.in("ID", "BUP45544", "BUP14334"))
                                         .asEntity(Hotel.class)
                                         .withAllowFiltering()
                                         .execute();
hotelIterator.forEach(hotel -> System.out.println(hotel));
```

#User-defined types support
-------

to use the user-defined types support a Java class which represents the user-definied type has to be implemented. The fields to be mapped have to be annotated with `@Field`

``` java
public class Address {

    @Field(name = "street")
    private String street;

    @Field(name = "city")
    private String city;

    @Field(name = "post_code")
    private String postCode;

    @SuppressWarnings("unused")
    private Address() { }

    public Address(String street, String city, String postCode) {
        this.street = street;
        this.city = city;
        this.postCode = postCode;
    }

    public String getStreet() {
        return street;
    }

    public String getCity() {
        return city;
    }

    public String getPostCode() {
        return postCode;
    }
}
```

##Write

Write a row in a column-oriented way
``` java
hotelsDao.writeWithKey("id", "BUP932432")
         .value("name", "City Budapest")
         .value("room_ids", ImmutableSet.of("1", "2", "3", "122", "123", "124", "322", "333"))
         .value("classification", ClassifierEnum.FOUR)
         .value("address", new Address("Thököly Ut 111", "Budapest", "1145"))
         .withWritetime(microsSinceEpoch)
         .execute();
```

Write a row in a entity-oriented way
``` java
hotel = new Hotel("BUP14334",
                  "Richter Panzio",
                  ImmutableSet.of("1", "2", "3", "4", "5"),
                  Optional.of(ClassifierEnum.TWO),
                  Optional.empty(),
                  new Address("Thököly Ut 111", "Budapest", "1145"));

hotelsDao.writeEntity(hotel)
         .execute();
```

``` java
public class Hotel  {

    @Field(name = "id")
    private String id = null;

    @Field(name = "name")
    private String name = null;

    @Field(name = "room_ids")
    private ImmutableSet<String> roomIds = ImmutableSet.of();

    @Field(name = "classification")
    private Optional<ClassifierEnum> classification = Optional.empty();

    @Field(name = "description")
    private Optional<String> description = Optional.empty();

    @Field(name = "address")
    private Address address = null;

    @SuppressWarnings("unused")
    private Hotel() { }

    public Hotel(String id,
                 String name,
                 ImmutableSet<String> roomIds,
                 Optional<ClassifierEnum> classification,
                 Optional<String> description,
                 Address address) {
        this.id = id;
        this.name = name;
        this.roomIds = roomIds;
        this.classification = classification;
        this.description = description;
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public ImmutableSet<String> getRoomIds() {
        return roomIds;
    }

    public Optional<ClassifierEnum> getClassification() {
        return classification;
    }

    public Optional<String> getDescription() {
        return description;
    }

    public Address getAddress() {
        return address;
    }
}
```

##Read

Read a row in a entity-oriented way
``` java
hotel = hotelsDao.readWithKey("id", "BUP14334")
                 .asEntity(Hotel.class)
                 .execute()
                 .get();

System.out.println(hotel.getAddress());
```

Read a row in a column-oriented way
``` java
record = hotelsDao.readWithKey("id", "BUP14334")
                  .column("id")
                  .column("name")
                  .column("classification")
                  .column("address")
                  .withConsistency(ConsistencyLevel.LOCAL_ONE)
                  .execute()
                  .get();

System.out.println(record.getString("classification"));
System.out.println(record.getObject("address", Address.class));
```

#Asynchronous Examples
-------

##Async Write
By calling `executeAsync()` instead `execute()` the method returns immediately without waiting for the database response. Further more the `executeAsync()` returns a Java8 [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) object which can be used for async processing
``` java
hotel = new Hotel("BUP14334",
                  "Richter Panzio",
                  Optional.of(ClassifierEnum.TWO),
                  Optional.empty());

CompletableFuture<Result> future = hotelsDao.writeEntity(hotel)
                                            .withConsistency(ConsistencyLevel.ANY)
                                            .executeAsync();
```

##Async Read

As already mentioned above the methods returns immediately without waiting for the database response. The consumer code within the `thenAccept(...)` method will be called as soon as the database response is received.

read single row
``` java
hotelsDao.readWithKey("id", "BUP45544")
         .asEntity(Hotel.class)
	     .executeAsync()
         .thenAccept(optionalHotel.ifPresent(hotel -> System.out.println(hotel));
```

read a list of rows. Please consider that the Iterator has a blocking behavior which means the streaming of the result could block
``` java
hotelsDao.readAll()
         .asEntity(Hotel.class)
         .withLimit(5000)
         .executeAsync()
         .thenAccept(hotelIt -> hotelIt.forEach(hotel -> System.out.println(hotel)));
```

For true asynchronous streaming a [Subscriber](http://www.reactive-streams.org) could be registered which will be executed in an asynchronous, reactive way
``` java
Subscriber<Hotel> mySubscriber = new MySubscriber();

hotelsDao.readAll()
         .asEntity(Hotel.class)
         .withLimit(5000)
         .executeAsync()
         .thenAccept(publisher -> publisher.subscribe(mySubscriber));
```

The Subscriber implements call back methods such as `onNext(...)` or `onError(...)` to process the result stream in a reactive way. By calling the hotels.subscribe(subscriber) above the `onSubscribe(...)` method of the subscriber below will be called.
``` java
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

public class MySubscriber<T> implements Subscriber<Hotel> {
    private final AtomicReference<Subscription> subscriptionRef = new AtomicReference<>();
    //...

    @Override
    public void onSubscribe(Subscription subscription) {
        this.subscriptionRef.set(subscription);
        subscription.request(1);  // here, requesting elements starts the streaming implicitly
    }

    @Override
    public void onNext(Hotel hotel) {
        System.out.println(hotel);
        subscription.request(1);
    }

    @Override
    public void onComplete() {
        //..
    }

    @Override
    public void onError(Throwable t) {
        //..
    }
}
```

#Interceptor Examples
The interceptor support can be used to implement (more complex) constraint checks on the client-side  (Cassandra also supports server-side [trigger](http://www.datastax.com/documentation/cql/3.1/cql/cql_reference/trigger_r.html) which can also be used to implement contraints). To register interceptors the `Dao` supports the `withInterceptor(...)` method.

``` java
Dao phoneNumbersDao = new DaoImpl(getSession(), "phone_numbers");

Dao phoneNumbersDaoWithConstraints = phoneNumbersDao.withInterceptor(new PhonenumbersConstraints(deviceDao))
												    .withInterceptor(ConstraintsInterceptor.newConstraints()
                                                                                .withNotNullColumn("device_id")
                                                                                .withImmutableColumn("device_id"));
```

##ConstraintsInterceptor Examples
To implement simple constraints the  `ConstraintsInterceptor` can be used
``` java
Dao phoneNumbersDaoWithConstraints = phoneNumbersDao.withInterceptor(ConstraintsInterceptor.newConstraints()
                                                                                .withNotNullColumn("device_id")
                                                                                .withImmutableColumn("device_id"));
```

##More Complexe Interceptor Examples
The interceptor below implements a back relation check regarding the [phone_numbers](troilus-core/src/test/resources/com/unitedinternet/troilus/example/phone_numbers.ddl) table.
``` java
class PhonenumbersConstraints implements SingleReadQueryRequestInterceptor,
                                         SingleReadQueryResponseInterceptor {

    private final Dao deviceDao;

    public PhonenumbersConstraints(Dao deviceDao) {
        this.deviceDao = deviceDao.withConsistency(ConsistencyLevel.QUORUM);
    }

    @Override
    public CompletableFuture<SingleReadQueryData> onSingleReadRequestAsync( SingleReadQueryData queryData) {
        // force that device_id will be fetched
        if (!queryData.getColumnsToFetch().isEmpty() && !queryData.getColumnsToFetch().containsKey("device_id")) {
            queryData = queryData.columnsToFetch(Immutables.merge(queryData.getColumnsToFetch(), "device_id", false));
        }
        return CompletableFuture.completedFuture(queryData);
    }

    @Override
    public CompletableFuture<Optional<Record>> onSingleReadResponseAsync(SingleReadQueryData queryData, Optional<Record> optionalRecord) {

        if (optionalRecord.isPresent() && optionalRecord.get().getString("device_id").isPresent()) {
            return deviceDao.readWithKey("device_id", optionalRecord.get().getString("device_id").get())
                            .column("phone_numbers")
                            .withConsistency(ConsistencyLevel.ONE)
                            .executeAsync()
                            .thenApply(optionalRec -> {
                                                        optionalRec.ifPresent(rec -> {
                                                            Optional<ImmutableSet<String>> set = rec.getSet("phone_numbers", String.class);
                                                            if (set.isPresent() && !set.get().contains(queryData.getKey().get("number"))) {
                                                                throw new ConstraintException("reverse reference devices table -> phone_numbers table does not exit");
                                                            }
                                                        });

                                                        return optionalRecord;
                                                      });

        } else {
            return CompletableFuture.completedFuture(optionalRecord);
        }
    }
}
```


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/pipeline_job.proto

package com.google.cloud.aiplatform.v1beta1;

public interface PipelineTaskExecutorDetailOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Output only. The detailed info for a container executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.ContainerDetail container_detail = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   *
   * @return Whether the containerDetail field is set.
   */
  boolean hasContainerDetail();
  /**
   *
   *
   *

   * Output only. The detailed info for a container executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.ContainerDetail container_detail = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   *
   * @return The containerDetail.
   */
  com.google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.ContainerDetail
      getContainerDetail();
  /**
   *
   *
   *

   * Output only. The detailed info for a container executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.ContainerDetail container_detail = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  com.google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.ContainerDetailOrBuilder
      getContainerDetailOrBuilder();

  /**
   *
   *
   *

   * Output only. The detailed info for a custom job executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.CustomJobDetail custom_job_detail = 2 [deprecated = true, (.google.api.field_behavior) = OUTPUT_ONLY];
   *
   *
   * @deprecated google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.custom_job_detail is
   *     deprecated. See google/cloud/aiplatform/v1beta1/pipeline_job.proto;l=370
   * @return Whether the customJobDetail field is set.
   */
  @java.lang.Deprecated
  boolean hasCustomJobDetail();
  /**
   *
   *
   *

   * Output only. The detailed info for a custom job executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.CustomJobDetail custom_job_detail = 2 [deprecated = true, (.google.api.field_behavior) = OUTPUT_ONLY];
   *
   *
   * @deprecated google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.custom_job_detail is
   *     deprecated. See google/cloud/aiplatform/v1beta1/pipeline_job.proto;l=370
   * @return The customJobDetail.
   */
  @java.lang.Deprecated
  com.google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.CustomJobDetail
      getCustomJobDetail();
  /**
   *
   *
   *

   * Output only. The detailed info for a custom job executor.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.CustomJobDetail custom_job_detail = 2 [deprecated = true, (.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  @java.lang.Deprecated
  com.google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.CustomJobDetailOrBuilder
      getCustomJobDetailOrBuilder();

  public com.google.cloud.aiplatform.v1beta1.PipelineTaskExecutorDetail.DetailsCase
      getDetailsCase();
}


text:
namespace memory {

namespace {

class MockHardFaultDeltasWindow;

class TestSwapThrashingMonitorDelegateWin
    : public SwapThrashingMonitorDelegateWin {
 public:
  using HardFaultDeltasWindow =
      SwapThrashingMonitorDelegateWin::HardFaultDeltasWindow;

  TestSwapThrashingMonitorDelegateWin()
      : SwapThrashingMonitorDelegateWin::SwapThrashingMonitorDelegateWin(),
        observation_override_(0U) {
    SetMockWindow();
  }
  ~TestSwapThrashingMonitorDelegateWin() override {}

  void SetMockWindow();

  bool RecordHardFaultCountForChromeProcesses() override {
    hard_fault_deltas_window_->OnObservation(observation_override_);
    return true;
  }

  // Override the next observations that the window will receive.
  void OverrideNextObservationDelta(uint64_t observation_delta) {
    observation_override_ += observation_delta;
  }

  MockHardFaultDeltasWindow* sample_window() { return mock_window_; }

 private:
  uint64_t observation_override_;

  MockHardFaultDeltasWindow* mock_window_;
};

// A mock for the HardFaultDeltasWindow class.
//
// Used to access some protected fields of the HardFaultDeltasWindow class.
class MockHardFaultDeltasWindow
    : public TestSwapThrashingMonitorDelegateWin::HardFaultDeltasWindow {
 public:
  MockHardFaultDeltasWindow()
      : TestSwapThrashingMonitorDelegateWin::HardFaultDeltasWindow() {}
  ~MockHardFaultDeltasWindow() override {}

  size_t SampleCount() { return observation_deltas_.size(); }

  size_t WindowLength() { return kHardFaultDeltasWindowSize; }
};

void TestSwapThrashingMonitorDelegateWin::SetMockWindow() {
  std::unique_ptr<MockHardFaultDeltasWindow> mock_window =
      std::make_unique<MockHardFaultDeltasWindow>();
  mock_window_ = mock_window.get();
  hard_fault_deltas_window_.reset(mock_window.release());
}

}  // namespace

TEST(SwapThrashingMonitorDelegateWinTest, StateTransition) {
  TestSwapThrashingMonitorDelegateWin monitor;

  // Arbitrarily chosen high thrashing rate.
  const uint64_t kHighSwappingRate = 5000;

  // This state test the transitions from the SWAP_THRASHING_LEVEL_NONE state
  // to the SWAP_THRASHING_LEVEL_CONFIRMED one and then ensure that the cooldown
  // mechanism works.

  // We expect the system to initially be in the SWAP_THRASHING_LEVEL_NONE
  // state.
  EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_NONE,
            monitor.SampleAndCalculateSwapThrashingLevel());

  // Fill the sample window with 0s.
  while (monitor.sample_window()->SampleCount() <
         monitor.sample_window()->WindowLength()) {
    monitor.OverrideNextObservationDelta(0);
    EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_NONE,
              monitor.SampleAndCalculateSwapThrashingLevel());
  }

  EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_NONE,
            monitor.SampleAndCalculateSwapThrashingLevel());
  EXPECT_EQ(monitor.sample_window()->SampleCount(),
            monitor.sample_window()->WindowLength());

  // Adds high samples until we reach the suspected status.
  size_t high_sample_count = 0;
  while (high_sample_count < monitor.sample_window()->WindowLength()) {
    high_sample_count++;
    monitor.OverrideNextObservationDelta(kHighSwappingRate);
    if (monitor.SampleAndCalculateSwapThrashingLevel() ==
        SwapThrashingLevel::SWAP_THRASHING_LEVEL_SUSPECTED) {
      break;
    }
  }
  size_t suspected_state_sample_count = high_sample_count;
  EXPECT_LT(suspected_state_sample_count,
            monitor.sample_window()->WindowLength());

  // And now add samples until we reach the confirmed value.
  while (high_sample_count < monitor.sample_window()->WindowLength()) {
    high_sample_count++;
    monitor.OverrideNextObservationDelta(kHighSwappingRate);
    if (monitor.SampleAndCalculateSwapThrashingLevel() ==
        SwapThrashingLevel::SWAP_THRASHING_LEVEL_CONFIRMED) {
      break;
    }
  }
  size_t confirmed_state_sample_count = high_sample_count;

  EXPECT_LE(confirmed_state_sample_count,
            monitor.sample_window()->WindowLength());
  EXPECT_GT(confirmed_state_sample_count, suspected_state_sample_count);

  // Finish filling the window with high values.
  while (high_sample_count < monitor.sample_window()->WindowLength()) {
    high_sample_count++;
    monitor.OverrideNextObservationDelta(kHighSwappingRate);
    EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_CONFIRMED,
              monitor.SampleAndCalculateSwapThrashingLevel());
  }

  // Add 0s to the windows, the thrashing level should slowly decrease.
  while (high_sample_count > 0) {
    monitor.OverrideNextObservationDelta(0);
    if (high_sample_count > confirmed_state_sample_count) {
      EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_CONFIRMED,
                monitor.SampleAndCalculateSwapThrashingLevel());
    } else if (high_sample_count > suspected_state_sample_count) {
      EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_SUSPECTED,
                monitor.SampleAndCalculateSwapThrashingLevel());
    } else {
      EXPECT_EQ(SwapThrashingLevel::SWAP_THRASHING_LEVEL_NONE,
                monitor.SampleAndCalculateSwapThrashingLevel());
    }
    high_sample_count--;
  }
}

}  // namespace memory


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>All Classes</title>
<meta name="date" content="2017-05-01">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AbstractAnimationScreen

AiPlayer

AnimationPlayerWin

AnimationTileFlash

Chancellor

College

Drawer

Earthquake

GameEngine

GameEngine.State

GameScreen

GameTimer

HowToPlay

IAnimation

IAnimation.AnimationType

IAnimationFinish

LabelledElement

LeaderboardBackend

LeaderboardFrontend

Main

MainMenu

Malfunction

Market

MiniGameScreen

MiniGameScreen.GameActions

Overlay

Player

PlayerSelectScreen

RandomEvent

Roboticon

SplashScreen

Tile

Trade

TTFont


text:
require 'test_helper'

class BerlinAghScraperDetailTest < ActiveSupport::TestCase
  def setup
    @scraper = BerlinAghScraper
  end

  test 'extract complete paper, written interpellation' do
    html = Nokogiri::HTML(File.read(Rails.root.join('test/fixtures/be/detail.html')))
    body = @scraper.extract_body(html)
    seperator = @scraper.extract_seperators(body).first
    paper = @scraper.extract_paper(seperator)

    assert_equal(
      {
        legislative_term: '17',
        full_reference: '17/14146',
        reference: '14146',
        doctype: Paper::DOCTYPE_WRITTEN_INTERPELLATION,
        title: 'Videoüberwachung in Berliner Kitas?',
        url: 'http://pardok.parlament-berlin.de/starweb/adis/citat/VT/17/SchrAnfr/s17-14146.pdf',
        published_at: Date.parse('14.07.2014'),
        originators: { people: ['Susanne Graf'], parties: ['Piraten'] },
        is_answer: true,
        answerers: { ministries: ['SenBildJugWiss'] },
        source_url: 'http://pardok.parlament-berlin.de/starweb/AHAB/servlet.starweb?path=AHAB/lisshfl.web&id=ahabfastlink&format=WEBVORGLFL&search=WP%3D17+AND+DNR%3D14146'
      }, paper)
  end

  test 'extract complete paper, minor interpellation' do
    html = Nokogiri::HTML(File.read(Rails.root.join('test/fixtures/be/detail_17_13104.html')))
    body = @scraper.extract_body(html)
    seperator = @scraper.extract_seperators(body).first
    paper = @scraper.extract_paper(seperator)

    assert_equal(
      {
        legislative_term: '17',
        full_reference: '17/13104',
        reference: '13104',
        doctype: Paper::DOCTYPE_MINOR_INTERPELLATION,
        title: 'Jugendberufsagentur und Arbeit',
        url: 'http://pardok.parlament-berlin.de/starweb/adis/citat/VT/17/KlAnfr/ka17-13104.pdf',
        published_at: Date.parse('10.03.2014'),
        originators: { people: ['Elke Breitenbach'], parties: ['Die Linke'] },
        is_answer: true,
        answerers: { ministries: ['SenBildJugWiss'] },
        source_url: 'http://pardok.parlament-berlin.de/starweb/AHAB/servlet.starweb?path=AHAB/lisshfl.web&id=ahabfastlink&format=WEBVORGLFL&search=WP%3D17+AND+DNR%3D13104'
      }, paper)
  end
end


text:
const assert = require('assert')
const lib = require('../../../lib')

describe('lib.util', () => {

  describe('#findRouteConflicts', () => {
    const handler = function () { }

    it('should return empty list if there are no route conflicts', () => {
      const routes = [
        {
          method: 'GET',
          path: '/test/foo',
          handler: 'TestController.foo'
        },
        {
          method: [ 'GET', 'POST' ],
          path: '/',
          handler: 'HomeController.index'
        }
      ]

      const conflicts = lib.Util.findRouteConflicts(routes)

      assert.equal(conflicts.length, 0)
    })
    it('should return list of errors if there are route conflicts', () => {
      const routes = [
        {
          method: 'GET',
          path: '/test/foo',
          handler: 'TestController.foo'
        },
        {
          method: [ 'GET', 'POST' ],
          path: '/test/foo',
          handler: 'TestController.bar'
        }
      ]

      const conflicts = lib.Util.findRouteConflicts(routes)

      assert.equal(conflicts.length, 1)
    })
    it('should return no results for a valid route list', () => {
      const routeList = [
        { method: '*', path: '/a', handler: handler },
        { method: '*', path: '/b', handler: handler },
        { method: '*', path: '/c', handler: handler }
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)
      assert.equal(conflicts.length, 0)
    })
    it('should return no errors for identical paths with different methods', () => {
      const routeList = [
        { method: 'GET', path: '/a', handler: handler },
        { method: [ 'POST', 'PUT' ], path: '/a', handler: handler },
        { method: '*', path: '/c', handler: handler }
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)
      assert.equal(conflicts.length, 0)
    })
    it('should return errors for routes with identical paths and overlapping wildcard method', () => {
      const routeList = [
        { method: '*', path: '/a', handler: handler },
        { method: 'GET', path: '/a', handler: handler },
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)
      assert.equal(conflicts.length, 1)
    })
    it('should detect invalid route list (duplicate paths)', () => {
      const routeList = [
        { method: 'GET', path: '/a', handler: handler },
        { method: 'GET', path: '/a', handler: handler }
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)

      assert.equal(conflicts.length, 1)
      assert.equal(conflicts[0].errors[0].message, 'New route /a conflicts with existing /a')
    })
    it('should detect multiple errors in invalid route list (duplicate paths)', () => {
      const routeList = [
        { method: 'GET', path: '/a', handler: handler },
        { method: 'GET', path: '/a', handler: handler },
        { method: 'GET', path: '/a', handler: handler }
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)

      assert.equal(conflicts.length, 2)
      assert.equal(conflicts[0].errors[0].message, 'New route /a conflicts with existing /a')
    })
    it('should validate non-overlapping methods for a single path', () => {
      const routeList = [
        { method: 'POST', path: '/a', handler: handler },
        { method: 'GET', path: '/a', handler: handler }
      ]

      const conflicts = lib.Util.findRouteConflicts(routeList)
      assert.equal(conflicts.length, 0)
    })

  })

})


text:
/*
 * IMPORTANT: This header file describes INTERNAL interfaces to libdispatch
 * which are subject to change in future releases of Mac OS X. Any applications
 * relying on these interfaces WILL break.
 */

#ifndef __DISPATCH_PRIVATE__
#define __DISPATCH_PRIVATE__

#include <mach/boolean.h>
#include <mach/mach.h>
#include <mach/message.h>
#include <unistd.h>
#include <sys/cdefs.h>
#include <sys/event.h>
#include <pthread.h>

#ifndef __DISPATCH_BUILDING_DISPATCH__
#include_next <dispatch/dispatch.h>

// Workaround <rdar://problem/6597365/>
#ifndef __DISPATCH_PUBLIC__
#include "/usr/include/dispatch/dispatch.h"
#endif

#ifndef __DISPATCH_INDIRECT__
#define __DISPATCH_INDIRECT__
#endif

#include <dispatch/benchmark.h>
#include <dispatch/queue_private.h>
#include <dispatch/source_private.h>

#ifndef DISPATCH_NO_LEGACY
#include <dispatch/legacy.h>
#endif

#undef __DISPATCH_INDIRECT__

#endif /* !__DISPATCH_BUILDING_DISPATCH__ */

/* LEGACY: Use DISPATCH_API_VERSION */
#define LIBDISPATCH_VERSION DISPATCH_API_VERSION

__BEGIN_DECLS

DISPATCH_NOTHROW
void
libdispatch_init(void);

#define DISPATCH_COCOA_COMPAT 1
#if DISPATCH_COCOA_COMPAT

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
DISPATCH_NOTHROW
mach_port_t
_dispatch_get_main_queue_port_4CF(void);

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
DISPATCH_NOTHROW
void
_dispatch_main_queue_callback_4CF(mach_msg_header_t *msg);

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
extern void (*dispatch_begin_thread_4GC)(void);

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
extern void (*dispatch_end_thread_4GC)(void);

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
extern void *(*_dispatch_begin_NSAutoReleasePool)(void);

__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
extern void (*_dispatch_end_NSAutoReleasePool)(void *);

#endif

/* pthreads magic */

DISPATCH_NOTHROW void dispatch_atfork_prepare(void);
DISPATCH_NOTHROW void dispatch_atfork_parent(void);
DISPATCH_NOTHROW void dispatch_atfork_child(void);
DISPATCH_NOTHROW void dispatch_init_pthread(pthread_t);

/*
 * Extract the context pointer from a mach message trailer.
 */
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_NA)
void *
dispatch_mach_msg_get_context(mach_msg_header_t *msg);

__END_DECLS

#endif


text:
package annis.libgui;

import java.io.Serializable;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * A corpus set defines a named set of corpus names.
 * @author Thomas Krause <thomas.krause@alumni.hu-berlin.de>
 */
@XmlRootElement
public class CorpusSet implements Serializable
{

  private Set<String> corpora = new TreeSet<String>();
  private String name = "";

  @XmlElement(name="corpus")
  public Set<String> getCorpora()
  {
    return corpora;
  }

  public void setCorpora(Set<String> corpora)
  {
    this.corpora = corpora;
  }

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  @Override
  public int hashCode()
  {
    int hash = 7;
    hash = 37 * hash + (this.name != null ? this.name.hashCode() : 0);
    return hash;
  }

  @Override
  public boolean equals(Object obj)
  {
    if (obj == null)
    {
      return false;
    }
    if (getClass() != obj.getClass())
    {
      return false;
    }
    final CorpusSet other = (CorpusSet) obj;
    if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name))
    {
      return false;
    }
    return true;
  }

}


text:
package radl.test;

import radl.common.xml.DocumentBuilder;

public class StateBuilder {

  private final StatesBuilder parent;

  public StateBuilder(StatesBuilder parent) {
    this.parent = parent;
  }

  DocumentBuilder builder() {
    return parent.builder();
  }

  public StatesBuilder end() {
    while (!"states".equals(builder().getCurrent().getLocalName())) {
      builder().end();
    }
    return parent;
  }

  public StateBuilder transitioningTo(String name, String state) {
    return withTransition(name, state).end();
  }

  public TransitionBuilder withTransition(String name, String state) {
    if (!"transitions".equals(builder().getCurrent().getLocalName())) {
      builder().element("transitions");
    }
    return new TransitionBuilder(this, name, state);
  }

  public StateBuilder containing(String propertyGroup) {
    builder().attribute("property-group", propertyGroup);
    return this;
  }
}


text:
package ro.uaic.info.nlptools.ggs.engine.core;

public class GGSMacroNotFoundException extends GGSException {
    public GGSMacroNotFoundException(String macro) {
        super("Cannot find a macro entry with name \"" + macro + "\"");
    }
}


text:
package org.apache.calcite.schema.impl;

import org.apache.calcite.adapter.enumerable.CallImplementor;
import org.apache.calcite.adapter.enumerable.NullPolicy;
import org.apache.calcite.adapter.enumerable.ReflectiveCallNotNullImplementor;
import org.apache.calcite.adapter.enumerable.RexImpTable;
import org.apache.calcite.linq4j.function.SemiStrict;
import org.apache.calcite.linq4j.function.Strict;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.schema.ImplementableFunction;
import org.apache.calcite.schema.ScalarFunction;
import org.apache.calcite.sql.SqlOperatorBinding;

import com.google.common.collect.ImmutableMultimap;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import static org.apache.calcite.util.Static.RESOURCE;

/**
* Implementation of {@link org.apache.calcite.schema.ScalarFunction}.
*/
public class ScalarFunctionImpl extends ReflectiveFunctionBase
    implements ScalarFunction, ImplementableFunction {
  private final CallImplementor implementor;

  /** Private constructor. */
  private ScalarFunctionImpl(Method method, CallImplementor implementor) {
    super(method);
    this.implementor = implementor;
  }

  /**
   * Creates {@link org.apache.calcite.schema.ScalarFunction} for each method in
   * a given class.
   */
  public static ImmutableMultimap<String, ScalarFunction> createAll(
      Class<?> clazz) {
    final ImmutableMultimap.Builder<String, ScalarFunction> builder =
        ImmutableMultimap.builder();
    for (Method method : clazz.getMethods()) {
      if (method.getDeclaringClass() == Object.class) {
        continue;
      }
      if (!Modifier.isStatic(method.getModifiers())
          && !classHasPublicZeroArgsConstructor(clazz)) {
        continue;
      }
      final ScalarFunction function = create(method);
      builder.put(method.getName(), function);
    }
    return builder.build();
  }

  /**
   * Creates {@link org.apache.calcite.schema.ScalarFunction} from given class.
   *
   * <p>If a method of the given name is not found or it does not suit,
   * returns {@code null}.
   *
   * @param clazz class that is used to implement the function
   * @param methodName Method name (typically "eval")
   * @return created {@link ScalarFunction} or null
   */
  public static ScalarFunction create(Class<?> clazz, String methodName) {
    final Method method = findMethod(clazz, methodName);
    if (method == null) {
      return null;
    }
    return create(method);
  }

  /**
   * Creates {@link org.apache.calcite.schema.ScalarFunction} from given method.
   * When {@code eval} method does not suit, {@code null} is returned.
   *
   * @param method method that is used to implement the function
   * @return created {@link ScalarFunction} or null
   */
  public static ScalarFunction create(Method method) {
    if (!Modifier.isStatic(method.getModifiers())) {
      Class clazz = method.getDeclaringClass();
      if (!classHasPublicZeroArgsConstructor(clazz)) {
        throw RESOURCE.requireDefaultConstructor(clazz.getName()).ex();
      }
    }
    CallImplementor implementor = createImplementor(method);
    return new ScalarFunctionImpl(method, implementor);
  }

  /**
   * Creates unsafe version of {@link ScalarFunction} from any method. The method
   * does not need to be static or belong to a class with default constructor. It is
   * the responsibility of the underlying engine to initialize the UDF object that
   * contain the method.
   *
   * @param method method that is used to implement the function
   */
  public static ScalarFunction createUnsafe(Method method) {
    CallImplementor implementor = createImplementor(method);
    return new ScalarFunctionImpl(method, implementor);
  }

  public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
    return typeFactory.createJavaType(method.getReturnType());
  }

  public CallImplementor getImplementor() {
    return implementor;
  }

  private static CallImplementor createImplementor(final Method method) {
    final NullPolicy nullPolicy = getNullPolicy(method);
    return RexImpTable.createImplementor(
        new ReflectiveCallNotNullImplementor(method), nullPolicy, false);
  }

  private static NullPolicy getNullPolicy(Method m) {
    if (m.getAnnotation(Strict.class) != null) {
      return NullPolicy.STRICT;
    } else if (m.getAnnotation(SemiStrict.class) != null) {
      return NullPolicy.SEMI_STRICT;
    } else if (m.getDeclaringClass().getAnnotation(Strict.class) != null) {
      return NullPolicy.STRICT;
    } else if (m.getDeclaringClass().getAnnotation(SemiStrict.class) != null) {
      return NullPolicy.SEMI_STRICT;
    } else {
      return NullPolicy.NONE;
    }
  }

  public RelDataType getReturnType(RelDataTypeFactory typeFactory,
      SqlOperatorBinding opBinding) {
    // Strict and semi-strict functions can return null even if their Java
    // functions return a primitive type. Because when one of their arguments
    // is null, they won't even be called.
    final RelDataType returnType = getReturnType(typeFactory);
    switch (getNullPolicy(method)) {
    case STRICT:
      for (RelDataType type : opBinding.collectOperandTypes()) {
        if (type.isNullable()) {
          return typeFactory.createTypeWithNullability(returnType, true);
        }
      }
      break;
    case SEMI_STRICT:
      return typeFactory.createTypeWithNullability(returnType, true);
    }
    return returnType;
  }
}

// End ScalarFunctionImpl.java


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Xaml
{
    public class XamlWriterSettings
    {
        public XamlWriterSettings()
        {
        }

        public XamlWriterSettings(XamlWriterSettings settings)
        {
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2013 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resource oid="10000000-0000-0000-0000-000000000304"
		  xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
          xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
          xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
          xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
          xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
          xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<name>Dummy Resource White</name>
	<connectorRef type="c:ConnectorType">
		<filter>
			<q:and>
				<q:equal>
					<q:path>connectorType</q:path>
					<q:value>com.evolveum.icf.dummy.connector.DummyConnector</q:value>
				</q:equal>
				<q:equal>
					<q:path>connectorVersion</q:path>
					<q:value>2.0</q:value>
				</q:equal>
			</q:and>
		</filter>
	</connectorRef>
	<connectorConfiguration xmlns:icfi="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"
	               xmlns:icfc="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3">

		<icfc:configurationProperties>
			<icfi:instanceId>white</icfi:instanceId>
		</icfc:configurationProperties>

	</connectorConfiguration>

</resource>


text:
import { merge } from "lodash"
import { mount } from "enzyme"
import { ModalHeader } from "Components/Modal/ModalHeader"
import { FormSwitcher } from "Components/Authentication/FormSwitcher"
import { AuthStatic } from "../AuthStatic"

describe("AuthStatic", () => {
  const getWrapper = props => {
    return mount(<AuthStatic {...props} />)
  }

  let props
  beforeAll(() => {
    props = {
      type: "login",
      meta: {
        title: "A title",
      },
      handleSubmit: jest.fn(),
      options: {},
    }
  })

  it("Renders the FormSwitcher", () => {
    const component = getWrapper(props)
    expect(component.find(FormSwitcher).exists()).toBe(true)
  })

  it("Renders the DesktopHeader", () => {
    const component = getWrapper(props)
    expect(component.find(ModalHeader).text()).toMatch("A title")
  })

  it("shows description on login", () => {
    const component = getWrapper(
      merge(props, {
        meta: {
          description: "a description",
        },
      })
    )
    expect(component.find(ModalHeader).text()).toMatch("a description")
  })
})


text:
/* eslint-env jasmine, jquery */
/* global loadFixtures */

'use strict';

describe('events', function() {
  var select = false;

  beforeEach(function() {
    jasmine.getFixtures().fixturesPath = 'base/test/fixtures';
    loadFixtures('basic.html');

    select = $('#basic');
    select.selectric();
  });

  it('should trigger change event', function() {
    var changedFn = jasmine.createSpy('changedFn');
    select.on('change', changedFn);
    $('.selectric').click();
    $('.selectric-items').find('li:eq(4)').click();
    expect(changedFn).toHaveBeenCalled();
  });

  it('should not trigger change event', function() {
    var notChangedFn = jasmine.createSpy('notChangedFn');
    select.on('change', notChangedFn);
    $('.selectric').click();
    $('.selectric-items').find('li.selected').click();
    expect(notChangedFn).not.toHaveBeenCalled();
  });

  it('should trigger events', function() {
    var events = jasmine.createSpyObj('events', [
      'beforeInit',
      'init',
      'beforeOpen',
      'open',
      'beforeClose',
      'close',
      'beforeHighlight',
      'highlight',
      'beforeSelect',
      'select',
      'beforeChange',
      'change',
      'refresh'
    ]);

    select.selectric('destroy');
    select.on('selectric-before-init',      events.beforeInit);
    select.on('selectric-init',             events.init);
    select.on('selectric-before-open',      events.beforeOpen);
    select.on('selectric-open',             events.open);
    select.on('selectric-before-close',     events.beforeClose);
    select.on('selectric-close',            events.close);
    select.on('selectric-before-highlight', events.beforeHighlight);
    select.on('selectric-highlight',        events.highlight);
    select.on('selectric-before-select',    events.beforeSelect);
    select.on('selectric-select',           events.select);
    select.on('selectric-before-change',    events.beforeChange);
    select.on('selectric-change',           events.change);
    select.on('selectric-refresh',          events.refresh);
    select.selectric();

    $('.selectric').click();
    $('.selectric-items').find('li:eq(4)').click();
    select.selectric('refresh');

    expect(events.beforeInit).toHaveBeenCalled();
    expect(events.init).toHaveBeenCalled();
    expect(events.beforeOpen).toHaveBeenCalled();
    expect(events.open).toHaveBeenCalled();
    expect(events.beforeClose).toHaveBeenCalled();
    expect(events.close).toHaveBeenCalled();
    expect(events.beforeHighlight).toHaveBeenCalled();
    expect(events.highlight).toHaveBeenCalled();
    expect(events.beforeSelect).toHaveBeenCalled();
    expect(events.select).toHaveBeenCalled();
    expect(events.beforeChange).toHaveBeenCalled();
    expect(events.change).toHaveBeenCalled();
    expect(events.refresh).toHaveBeenCalled();
  });

  it('should trigger callbacks', function() {
    var callbacks = jasmine.createSpyObj('callbacks', [
      'beforeInit',
      'init',
      'beforeOpen',
      'open',
      'beforeClose',
      'close',
      'beforeChange',
      'change',
      'refresh'
    ]);

    select.selectric({
      onBeforeInit:   callbacks.beforeInit,
      onInit:         callbacks.init,
      onBeforeOpen:   callbacks.beforeOpen,
      onOpen:         callbacks.open,
      onBeforeClose:  callbacks.beforeClose,
      onClose:        callbacks.close,
      onBeforeChange: callbacks.beforeChange,
      onChange:       callbacks.change,
      onRefresh:      callbacks.refresh
    });

    $('.selectric').click();
    $('.selectric-items').find('li:eq(4)').click();
    select.selectric('refresh');

    expect(callbacks.beforeInit).toHaveBeenCalled();
    expect(callbacks.init).toHaveBeenCalled();
    expect(callbacks.beforeOpen).toHaveBeenCalled();
    expect(callbacks.open).toHaveBeenCalled();
    expect(callbacks.beforeClose).toHaveBeenCalled();
    expect(callbacks.close).toHaveBeenCalled();
    expect(callbacks.beforeChange).toHaveBeenCalled();
    expect(callbacks.change).toHaveBeenCalled();
    expect(callbacks.refresh).toHaveBeenCalled();
  });

  it('should not bind events when select is disabled after init', function() {
    select.prop('disabled', true).selectric('refresh');
    $('.selectric').trigger('click');
    expect($('.selectric-wrapper').hasClass('selectric-open')).toBe(false);
  });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RecordFactoryInputStream (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.hssf.record

Class RecordFactoryInputStream

java.lang.Object

org.apache.poi.hssf.record.RecordFactoryInputStream

public final class RecordFactoryInputStream
extends java.lang.Object

A stream based way to get at complete records, with
 as low a memory footprint as possible.
 This handles reading from a RecordInputStream, turning
 the data into full records, processing continue records
 etc.
 Most users should use HSSFEventFactory /
 HSSFListener and have new records pushed to
 them, but this does allow for a "pull" style of coding.

Constructor Summary

Constructors

Constructor and Description

RecordFactoryInputStream(java.io.InputStream in,
                        boolean shouldIncludeContinueRecords)

Method Summary

Methods

Modifier and Type
Method and Description

Record
nextRecord()

Returns the next (complete) record from the
 stream, or null if there are no more.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RecordFactoryInputStream

public RecordFactoryInputStream(java.io.InputStream in,
                        boolean shouldIncludeContinueRecords)

Parameters:

shouldIncludeContinueRecords - caller can pass false if loose
 ContinueRecords should be skipped (this is sometimes useful in event based
 processing).

Method Detail

nextRecord

public Record nextRecord()

Returns the next (complete) record from the
 stream, or null if there are no more.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
<!doctype html>

    <meta charset="utf-8">
    <title>ChemBio Crunch</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="../../bootstrap/dist/css/bootstrap.css" />

    <link rel="stylesheet" href="../../codemirror/lib/codemirror.css" />
    <link rel="stylesheet" href="../../chembiohub-theme/css/main.css" />

    <link rel="stylesheet" href="../../chembiohub-theme/css/cbh-template-header.css">
    <link rel="stylesheet" href="../../chembiohub-theme/css/font.css">

                <button class="btn pull-right scrollToTop btn-lg">Back to top  </button>

                            ChemBio Hub Project

                            Old Road Campus Research Building

                            Roosevelt Drive

                            Oxford OX3 7DQ

                            01865 617577

                         Follow @OxChemBioHub

                         Email ChemBio Hub

                        Follow +OxChemBioHub

                        We gratefully acknowledge the support of the following organisations:

                    Thank you to our funding partners

                Copyright University of Oxford 2014


text:
import logging

from dipy.direction import (DeterministicMaximumDirectionGetter,
                            ProbabilisticDirectionGetter,
                            ClosestPeakDirectionGetter)
from dipy.io.image import load_nifti
from dipy.io.peaks import load_peaks
from dipy.io.stateful_tractogram import Space, StatefulTractogram
from dipy.io.streamline import save_tractogram
from dipy.tracking import utils
from dipy.tracking.local_tracking import (LocalTracking,
                                          ParticleFilteringTracking)
from dipy.tracking.stopping_criterion import (BinaryStoppingCriterion,
                                              CmcStoppingCriterion,
                                              ThresholdStoppingCriterion)
from dipy.workflows.workflow import Workflow

class LocalFiberTrackingPAMFlow(Workflow):
    @classmethod
    def get_short_name(cls):
        return 'track_local'

    def _get_direction_getter(self, strategy_name, pam, pmf_threshold,
                              max_angle):
        """Get Tracking Direction Getter object.

        Parameters
        ----------
        strategy_name : str
            String representing direction getter name.
        pam : instance of PeaksAndMetrics
            An object with ``gfa``, ``peak_directions``, ``peak_values``,
            ``peak_indices``, ``odf``, ``shm_coeffs`` as attributes.
        pmf_threshold : float
            Threshold for ODF functions.
        max_angle : float
            Maximum angle between streamline segments.

        Returns
        -------
        direction_getter : instance of DirectionGetter
            Used to get directions for fiber tracking.

        """
        dg, msg = None, ''
        if strategy_name.lower() in ["deterministic", "det"]:
            msg = "Deterministic"
            dg = DeterministicMaximumDirectionGetter.from_shcoeff(
                pam.shm_coeff,
                sphere=pam.sphere,
                max_angle=max_angle,
                pmf_threshold=pmf_threshold)
        elif strategy_name.lower() in ["probabilistic", "prob"]:
            msg = "Probabilistic"
            dg = ProbabilisticDirectionGetter.from_shcoeff(
                pam.shm_coeff,
                sphere=pam.sphere,
                max_angle=max_angle,
                pmf_threshold=pmf_threshold)
        elif strategy_name.lower() in ["closestpeaks", "cp"]:
            msg = "ClosestPeaks"
            dg = ClosestPeakDirectionGetter.from_shcoeff(
                pam.shm_coeff,
                sphere=pam.sphere,
                max_angle=max_angle,
                pmf_threshold=pmf_threshold)
        elif strategy_name.lower() in ["eudx", ]:
            msg = "Eudx"
            dg = pam
        else:
            msg = "No direction getter defined. Eudx"
            dg = pam

        logging.info('{0} direction getter strategy selected'.format(msg))
        return dg

    def _core_run(self, stopping_path, use_binary_mask, stopping_thr,
                  seeding_path, seed_density, step_size, direction_getter,
                  out_tract, save_seeds):

        stop, affine = load_nifti(stopping_path)
        if use_binary_mask:
            stopping_criterion = BinaryStoppingCriterion(stop > stopping_thr)
        else:
            stopping_criterion = ThresholdStoppingCriterion(stop, stopping_thr)
        logging.info('stopping criterion done')
        seed_mask, _ = load_nifti(seeding_path)
        seeds = \
            utils.seeds_from_mask(
                seed_mask, affine,
                density=[seed_density, seed_density, seed_density])
        logging.info('seeds done')

        tracking_result = LocalTracking(direction_getter,
                                        stopping_criterion,
                                        seeds,
                                        affine,
                                        step_size=step_size,
                                        save_seeds=save_seeds)

        logging.info('LocalTracking initiated')

        if save_seeds:
            streamlines, seeds = zip(*tracking_result)
            seeds = {'seeds': seeds}
        else:
            streamlines = list(tracking_result)
            seeds = {}

        sft = StatefulTractogram(streamlines, seeding_path, Space.RASMM,
                                 data_per_streamline=seeds)
        save_tractogram(sft, out_tract, bbox_valid_check=False)
        logging.info('Saved {0}'.format(out_tract))

    def run(self, pam_files, stopping_files, seeding_files,
            use_binary_mask=False,
            stopping_thr=0.2,
            seed_density=1,
            step_size=0.5,
            tracking_method="eudx",
            pmf_threshold=0.1,
            max_angle=30.,
            out_dir='',
            out_tractogram='tractogram.trk',
            save_seeds=False):
        """Workflow for Local Fiber Tracking.

        This workflow use a saved peaks and metrics (PAM) file as input.

        Parameters
        ----------
        pam_files : string
           Path to the peaks and metrics files. This path may contain
            wildcards to use multiple masks at once.
        stopping_files : string
            Path to images (e.g. FA) used for stopping criterion for tracking.
        seeding_files : string
            A binary image showing where we need to seed for tracking.
        use_binary_mask : bool, optional
            If True, uses a binary stopping criterion. If the provided
            `stopping_files` are not binary, `stopping_thr` will be used to
            binarize the images.
        stopping_thr : float, optional
            Threshold applied to stopping volume's data to identify where
            tracking has to stop (default 0.2).
        seed_density : int, optional
            Number of seeds per dimension inside voxel (default 1).
             For example, seed_density of 2 means 8 regularly distributed
             points in the voxel. And seed density of 1 means 1 point at the
             center of the voxel.
        step_size : float, optional
            Step size used for tracking (default 0.5mm).
        tracking_method : string, optional
            Select direction getter strategy :
             - "eudx" (Uses the peaks saved in the pam_files)
             - "deterministic" or "det" for a deterministic tracking
               (Uses the sh saved in the pam_files, default)
             - "probabilistic" or "prob" for a Probabilistic tracking
               (Uses the sh saved in the pam_files)
             - "closestpeaks" or "cp" for a ClosestPeaks tracking
               (Uses the sh saved in the pam_files)
        pmf_threshold : float, optional
            Threshold for ODF functions (default 0.1).
        max_angle : float, optional
            Maximum angle between streamline segments (range [0, 90],
            default 30).
        out_dir : string, optional
           Output directory (default input file directory).
        out_tractogram : string, optional
           Name of the tractogram file to be saved (default 'tractogram.trk').
        save_seeds : bool, optional
            If true, save the seeds associated to their streamline
            in the 'data_per_streamline' Tractogram dictionary using
            'seeds' as the key.

        References
        ----------
        Garyfallidis, University of Cambridge, PhD thesis 2012.
        Amirbekian, University of California San Francisco, PhD thesis 2017.

        """
        io_it = self.get_io_iterator()

        for pams_path, stopping_path, seeding_path, out_tract in io_it:

            logging.info('Local tracking on {0}'
                         .format(pams_path))

            pam = load_peaks(pams_path, verbose=False)
            dg = self._get_direction_getter(tracking_method, pam,
                                            pmf_threshold=pmf_threshold,
                                            max_angle=max_angle)

            self._core_run(stopping_path, use_binary_mask, stopping_thr,
                           seeding_path, seed_density, step_size, dg,
                           out_tract, save_seeds)

class PFTrackingPAMFlow(Workflow):
    @classmethod
    def get_short_name(cls):
        return 'track_pft'

    def run(self, pam_files, wm_files, gm_files, csf_files, seeding_files,
            step_size=0.2,
            seed_density=1,
            pmf_threshold=0.1,
            max_angle=20.,
            pft_back=2,
            pft_front=1,
            pft_count=15,
            out_dir='',
            out_tractogram='tractogram.trk',
            save_seeds=False):
        """Workflow for Particle Filtering Tracking.

        This workflow use a saved peaks and metrics (PAM) file as input.

        Parameters
        ----------
        pam_files : string
           Path to the peaks and metrics files. This path may contain
            wildcards to use multiple masks at once.
        wm_files : string
            Path to white matter partial volume estimate for tracking (CMC).
        gm_files : string
            Path to grey matter partial volume estimate for tracking (CMC).
        csf_files : string
            Path to cerebrospinal fluid partial volume estimate for tracking
            (CMC).
        seeding_files : string
            A binary image showing where we need to seed for tracking.
        step_size : float, optional
            Step size used for tracking (default 0.2mm).
        seed_density : int, optional
            Number of seeds per dimension inside voxel (default 1).
             For example, seed_density of 2 means 8 regularly distributed
             points in the voxel. And seed density of 1 means 1 point at the
             center of the voxel.
        pmf_threshold : float, optional
            Threshold for ODF functions (default 0.1).
        max_angle : float, optional
            Maximum angle between streamline segments (range [0, 90],
            default 20).
        pft_back : float, optional
            Distance in mm to back track before starting the particle filtering
            tractography (default 2mm). The total particle filtering
            tractography distance is equal to back_tracking_dist +
            front_tracking_dist.
        pft_front : float, optional
            Distance in mm to run the particle filtering tractography after the
            the back track distance (default 1mm). The total particle filtering
            tractography distance is equal to back_tracking_dist +
            front_tracking_dist.
        pft_count : int, optional
            Number of particles to use in the particle filter (default 15).
        out_dir : string, optional
           Output directory (default input file directory)
        out_tractogram : string, optional
           Name of the tractogram file to be saved (default 'tractogram.trk')
        save_seeds : bool, optional
            If true, save the seeds associated to their streamline
            in the 'data_per_streamline' Tractogram dictionary using
            'seeds' as the key

        References
        ----------
        Girard, G., Whittingstall, K., Deriche, R., & Descoteaux, M. Towards
        quantitative connectivity analysis: reducing tractography biases.
        NeuroImage, 98, 266-278, 2014.

        """
        io_it = self.get_io_iterator()

        for pams_path, wm_path, gm_path, csf_path, seeding_path, out_tract \
                in io_it:

            logging.info('Particle Filtering tracking on {0}'
                         .format(pams_path))

            pam = load_peaks(pams_path, verbose=False)

            wm, affine, voxel_size = load_nifti(wm_path, return_voxsize=True)
            gm, _ = load_nifti(gm_path)
            csf, _ = load_nifti(csf_path)
            avs = sum(voxel_size) / len(voxel_size)  # average_voxel_size
            stopping_criterion = CmcStoppingCriterion.from_pve(
                wm, gm, csf, step_size=step_size, average_voxel_size=avs)
            logging.info('stopping criterion done')
            seed_mask, _ = load_nifti(seeding_path)
            seeds = utils.seeds_from_mask(seed_mask, affine,
                                          density=[seed_density, seed_density,
                                                   seed_density])
            logging.info('seeds done')
            dg = ProbabilisticDirectionGetter

            direction_getter = dg.from_shcoeff(pam.shm_coeff,
                                               max_angle=max_angle,
                                               sphere=pam.sphere,
                                               pmf_threshold=pmf_threshold)

            tracking_result = ParticleFilteringTracking(
                direction_getter,
                stopping_criterion,
                seeds, affine,
                step_size=step_size,
                pft_back_tracking_dist=pft_back,
                pft_front_tracking_dist=pft_front,
                pft_max_trial=20,
                particle_count=pft_count,
                save_seeds=save_seeds)

            logging.info('ParticleFilteringTracking initiated')

            if save_seeds:
                streamlines, seeds = zip(*tracking_result)
                seeds = {'seeds': seeds}
            else:
                streamlines = list(tracking_result)
                seeds = {}

            sft = StatefulTractogram(streamlines, seeding_path, Space.RASMM,
                                     data_per_streamline=seeds)
            save_tractogram(sft, out_tract, bbox_valid_check=False)
            logging.info('Saved {0}'.format(out_tract))


text:
using System;
using System.Collections.Generic;

using Machine.Container.Model;

namespace Machine.Container.Services.Impl
{
  public class ActivatorStoreActivatorResolver : IActivatorResolver
  {
    public virtual IActivator ResolveActivator(IResolutionServices services, ServiceEntry entry)
    {
      if (!services.ActivatorStore.HasActivator(entry))
      {
        return null;
      }
      IActivator activator = services.ActivatorStore.ResolveActivator(entry);
      if (activator.CanActivate(services))
      {
        return activator;
      }
      if ((services.Flags & LookupFlags.ThrowIfUnable) == LookupFlags.ThrowIfUnable)
      {
        throw new ServiceResolutionException("Unable to activate: " + entry);
      }
      return null;
    }
  }
}