text:
#include "bindings/core/v8/V8GCController.h"

#include "bindings/core/v8/ActiveScriptWrappable.h"
#include "bindings/core/v8/RetainedDOMInfo.h"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8MutationObserver.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8ScriptRunner.h"
#include "bindings/core/v8/WrapperTypeInfo.h"
#include "core/dom/Attr.h"
#include "core/dom/Document.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/TemplateContentDocumentFragment.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLTemplateElement.h"
#include "core/html/imports/HTMLImportsController.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/svg/SVGElement.h"
#include "platform/Histogram.h"
#include "platform/TraceEvent.h"
#include "public/platform/BlameContext.h"
#include "public/platform/Platform.h"
#include "wtf/Partitions.h"
#include "wtf/Vector.h"
#include <algorithm>

namespace blink {

// FIXME: This should use opaque GC roots.
static void addReferencesForNodeWithEventListeners(v8::Isolate* isolate, Node* node, const v8::Persistent<v8::Object>& wrapper)
{
    ASSERT(node->hasEventListeners());

    EventListenerIterator iterator(node);
    while (EventListener* listener = iterator.nextListener()) {
        if (listener->type() != EventListener::JSEventListenerType)
            continue;
        V8AbstractEventListener* v8listener = static_cast<V8AbstractEventListener*>(listener);
        if (!v8listener->hasExistingListenerObject())
            continue;

        isolate->SetReference(wrapper, v8::Persistent<v8::Value>::Cast(v8listener->existingListenerObjectPersistentHandle()));
    }
}

Node* V8GCController::opaqueRootForGC(v8::Isolate*, Node* node)
{
    ASSERT(node);
    if (node->inShadowIncludingDocument()) {
        Document& document = node->document();
        if (HTMLImportsController* controller = document.importsController())
            return controller->master();
        return &document;
    }

    if (node->isAttributeNode()) {
        Node* ownerElement = toAttr(node)->ownerElement();
        if (!ownerElement)
            return node;
        node = ownerElement;
    }

    while (Node* parent = node->parentOrShadowHostOrTemplateHostNode())
        node = parent;

    return node;
}

class MinorGCUnmodifiedWrapperVisitor : public v8::PersistentHandleVisitor {
public:
    explicit MinorGCUnmodifiedWrapperVisitor(v8::Isolate* isolate)
        : m_isolate(isolate)
    { }

    void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override
    {

        if (classId != WrapperTypeInfo::NodeClassId && classId != WrapperTypeInfo::ObjectClassId) {
            return;
        }

        // MinorGC does not collect objects because it may be expensive to
        // update references during minorGC
        if (classId == WrapperTypeInfo::ObjectClassId) {
            v8::Persistent<v8::Object>::Cast(*value).MarkActive();
            return;
        }

        v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value));
        ASSERT(V8DOMWrapper::hasInternalFieldsSet(wrapper));
        if (toWrapperTypeInfo(wrapper)->hasPendingActivity(wrapper)) {
            v8::Persistent<v8::Object>::Cast(*value).MarkActive();
            return;
        }

        if (classId == WrapperTypeInfo::NodeClassId) {
            ASSERT(V8Node::hasInstance(wrapper, m_isolate));
            Node* node = V8Node::toImpl(wrapper);
            if (node->hasEventListeners()) {
                v8::Persistent<v8::Object>::Cast(*value).MarkActive();
                return;
            }
            // FIXME: Remove the special handling for SVG elements.
            // We currently can't collect SVG Elements from minor gc, as we have
            // strong references from SVG property tear-offs keeping context SVG element alive.
            if (node->isSVGElement()) {
                v8::Persistent<v8::Object>::Cast(*value).MarkActive();
                return;
            }
        }
    }

private:
    v8::Isolate* m_isolate;
};

class MajorGCWrapperVisitor : public v8::PersistentHandleVisitor {
public:
    explicit MajorGCWrapperVisitor(v8::Isolate* isolate, bool constructRetainedObjectInfos)
        : m_isolate(isolate)
        , m_domObjectsWithPendingActivity(0)
        , m_liveRootGroupIdSet(false)
        , m_constructRetainedObjectInfos(constructRetainedObjectInfos)
    {
    }

    void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override
    {
        if (classId != WrapperTypeInfo::NodeClassId && classId != WrapperTypeInfo::ObjectClassId)
            return;

        v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value));
        ASSERT(V8DOMWrapper::hasInternalFieldsSet(wrapper));

        const WrapperTypeInfo* type = toWrapperTypeInfo(wrapper);
        if (type->hasPendingActivity(wrapper)) {
            // If you hit this assert, you'll need to add a [DependentiLifetime]
            // extended attribute to the DOM interface. A DOM interface that
            // overrides hasPendingActivity must be marked as [DependentiLifetime].
            RELEASE_ASSERT(!value->IsIndependent());
            m_isolate->SetObjectGroupId(*value, liveRootId());
            ++m_domObjectsWithPendingActivity;
        }

        if (value->IsIndependent())
            return;

        if (classId == WrapperTypeInfo::NodeClassId) {
            ASSERT(V8Node::hasInstance(wrapper, m_isolate));
            Node* node = V8Node::toImpl(wrapper);
            if (node->hasEventListeners())
                addReferencesForNodeWithEventListeners(m_isolate, node, v8::Persistent<v8::Object>::Cast(*value));
            Node* root = V8GCController::opaqueRootForGC(m_isolate, node);
            m_isolate->SetObjectGroupId(*value, v8::UniqueId(reinterpret_cast<intptr_t>(root)));
            if (m_constructRetainedObjectInfos)
                m_groupsWhichNeedRetainerInfo.append(root);
        } else if (classId == WrapperTypeInfo::ObjectClassId) {
            type->visitDOMWrapper(m_isolate, toScriptWrappable(wrapper), v8::Persistent<v8::Object>::Cast(*value));
        } else {
            ASSERT_NOT_REACHED();
        }
    }

    void notifyFinished()
    {
        if (!m_constructRetainedObjectInfos)
            return;
        std::sort(m_groupsWhichNeedRetainerInfo.begin(), m_groupsWhichNeedRetainerInfo.end());
        Node* alreadyAdded = 0;
        v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler();
        for (size_t i = 0; i < m_groupsWhichNeedRetainerInfo.size(); ++i) {
            Node* root = m_groupsWhichNeedRetainerInfo[i];
            if (root != alreadyAdded) {
                profiler->SetRetainedObjectInfo(v8::UniqueId(reinterpret_cast<intptr_t>(root)), new RetainedDOMInfo(root));
                alreadyAdded = root;
            }
        }
        if (m_liveRootGroupIdSet)
            profiler->SetRetainedObjectInfo(liveRootId(), new ActiveDOMObjectsInfo(m_domObjectsWithPendingActivity));
    }

private:
    v8::UniqueId liveRootId()
    {
        const v8::Persistent<v8::Value>& liveRoot = V8PerIsolateData::from(m_isolate)->ensureLiveRoot();
        const intptr_t* idPointer = reinterpret_cast<const intptr_t*>(&liveRoot);
        v8::UniqueId id(*idPointer);
        if (!m_liveRootGroupIdSet) {
            m_isolate->SetObjectGroupId(liveRoot, id);
            m_liveRootGroupIdSet = true;
            ++m_domObjectsWithPendingActivity;
        }
        return id;
    }

    v8::Isolate* m_isolate;
    // v8 guarantees that Blink will not regain control while a v8 GC runs
    // (=> no Oilpan GCs will be triggered), hence raw, untraced members
    // can safely be kept here.
    Vector<UntracedMember<Node>> m_groupsWhichNeedRetainerInfo;
    int m_domObjectsWithPendingActivity;
    bool m_liveRootGroupIdSet;
    bool m_constructRetainedObjectInfos;
};

static unsigned long long usedHeapSize(v8::Isolate* isolate)
{
    v8::HeapStatistics heapStatistics;
    isolate->GetHeapStatistics(&heapStatistics);
    return heapStatistics.used_heap_size();
}

namespace {

void visitWeakHandlesForMinorGC(v8::Isolate* isolate)
{
    MinorGCUnmodifiedWrapperVisitor visitor(isolate);
    isolate->VisitWeakHandles(&visitor);
}

void objectGroupingForMajorGC(v8::Isolate* isolate, bool constructRetainedObjectInfos)
{
    MajorGCWrapperVisitor visitor(isolate, constructRetainedObjectInfos);
    isolate->VisitHandlesWithClassIds(&visitor);
    visitor.notifyFinished();
}

void gcPrologueForMajorGC(v8::Isolate* isolate, bool constructRetainedObjectInfos)
{
    objectGroupingForMajorGC(isolate, constructRetainedObjectInfos);
}

} // namespace

void V8GCController::gcPrologue(v8::Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags)
{
    if (isMainThread())
        ScriptForbiddenScope::enter();

    // Attribute garbage collection to the all frames instead of a specific
    // frame.
    if (BlameContext* blameContext = Platform::current()->topLevelBlameContext())
        blameContext->Enter();

    // TODO(haraken): A GC callback is not allowed to re-enter V8. This means
    // that it's unsafe to run Oilpan's GC in the GC callback because it may
    // run finalizers that call into V8. To avoid the risk, we should post
    // a task to schedule the Oilpan's GC.
    // (In practice, there is no finalizer that calls into V8 and thus is safe.)

    v8::HandleScope scope(isolate);
    switch (type) {
    case v8::kGCTypeScavenge:
        if (ThreadState::current())
            ThreadState::current()->willStartV8GC(BlinkGC::V8MinorGC);

        TRACE_EVENT_BEGIN1("devtools.timeline,v8", "MinorGC", "usedHeapSizeBefore", usedHeapSize(isolate));
        visitWeakHandlesForMinorGC(isolate);
        break;
    case v8::kGCTypeMarkSweepCompact:
        if (ThreadState::current())
            ThreadState::current()->willStartV8GC(BlinkGC::V8MajorGC);

        TRACE_EVENT_BEGIN2("devtools.timeline,v8", "MajorGC", "usedHeapSizeBefore", usedHeapSize(isolate), "type", "atomic pause");
        gcPrologueForMajorGC(isolate, flags & v8::kGCCallbackFlagConstructRetainedObjectInfos);
        break;
    case v8::kGCTypeIncrementalMarking:
        if (ThreadState::current())
            ThreadState::current()->willStartV8GC(BlinkGC::V8MajorGC);

        TRACE_EVENT_BEGIN2("devtools.timeline,v8", "MajorGC", "usedHeapSizeBefore", usedHeapSize(isolate), "type", "incremental marking");
        gcPrologueForMajorGC(isolate, flags & v8::kGCCallbackFlagConstructRetainedObjectInfos);
        break;
    case v8::kGCTypeProcessWeakCallbacks:
        TRACE_EVENT_BEGIN2("devtools.timeline,v8", "MajorGC", "usedHeapSizeBefore", usedHeapSize(isolate), "type", "weak processing");
        break;
    default:
        ASSERT_NOT_REACHED();
    }
}

void V8GCController::gcEpilogue(v8::Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags)
{
    switch (type) {
    case v8::kGCTypeScavenge:
        TRACE_EVENT_END1("devtools.timeline,v8", "MinorGC", "usedHeapSizeAfter", usedHeapSize(isolate));
        // TODO(haraken): Remove this. See the comment in gcPrologue.
        if (ThreadState::current())
            ThreadState::current()->scheduleV8FollowupGCIfNeeded(BlinkGC::V8MinorGC);
        break;
    case v8::kGCTypeMarkSweepCompact:
        TRACE_EVENT_END1("devtools.timeline,v8", "MajorGC", "usedHeapSizeAfter", usedHeapSize(isolate));
        if (ThreadState::current())
            ThreadState::current()->scheduleV8FollowupGCIfNeeded(BlinkGC::V8MajorGC);
        break;
    case v8::kGCTypeIncrementalMarking:
        TRACE_EVENT_END1("devtools.timeline,v8", "MajorGC", "usedHeapSizeAfter", usedHeapSize(isolate));
        break;
    case v8::kGCTypeProcessWeakCallbacks:
        TRACE_EVENT_END1("devtools.timeline,v8", "MajorGC", "usedHeapSizeAfter", usedHeapSize(isolate));
        break;
    default:
        ASSERT_NOT_REACHED();
    }

    if (isMainThread())
        ScriptForbiddenScope::exit();

    if (BlameContext* blameContext = Platform::current()->topLevelBlameContext())
        blameContext->Leave();

    // v8::kGCCallbackFlagForced forces a Blink heap garbage collection
    // when a garbage collection was forced from V8. This is either used
    // for tests that force GCs from JavaScript to verify that objects die
    // when expected.
    if (flags & v8::kGCCallbackFlagForced) {
        // This single GC is not enough for two reasons:
        //   (1) The GC is not precise because the GC scans on-stack pointers conservatively.
        //   (2) One GC is not enough to break a chain of persistent handles. It's possible that
        //       some heap allocated objects own objects that contain persistent handles
        //       pointing to other heap allocated objects. To break the chain, we need multiple GCs.
        //
        // Regarding (1), we force a precise GC at the end of the current event loop. So if you want
        // to collect all garbage, you need to wait until the next event loop.
        // Regarding (2), it would be OK in practice to trigger only one GC per gcEpilogue, because
        // GCController.collectAll() forces multiple V8's GC.
        Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC);

        // Forces a precise GC at the end of the current event loop.
        if (ThreadState::current()) {
            RELEASE_ASSERT(!ThreadState::current()->isInGC());
            ThreadState::current()->setGCState(ThreadState::FullGCScheduled);
        }
    }

    // v8::kGCCallbackFlagCollectAllAvailableGarbage is used when V8 handles
    // low memory notifications.
    if (flags & v8::kGCCallbackFlagCollectAllAvailableGarbage) {
        // This single GC is not enough. See the above comment.
        Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC);

        // Do not force a precise GC at the end of the current event loop.
        // According to UMA stats, the collection rate of the precise GC
        // scheduled at the end of the low memory handling is extremely low,
        // because the above conservative GC is sufficient for collecting
        // most objects. So we intentionally don't schedule a precise GC here.
    }

    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());
}

void V8GCController::collectGarbage(v8::Isolate* isolate)
{
    v8::HandleScope handleScope(isolate);
    RefPtr<ScriptState> scriptState = ScriptState::create(v8::Context::New(isolate), DOMWrapperWorld::create(isolate));
    ScriptState::Scope scope(scriptState.get());
    V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, "if (gc) gc();"), isolate);
    scriptState->disposePerContextData();
}

void V8GCController::collectAllGarbageForTesting(v8::Isolate* isolate)
{
    for (unsigned i = 0; i < 5; i++)
        isolate->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection);
}

class DOMWrapperTracer : public v8::PersistentHandleVisitor {
public:
    explicit DOMWrapperTracer(Visitor* visitor)
        : m_visitor(visitor)
    {
    }

    void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override
    {
        if (classId != WrapperTypeInfo::NodeClassId && classId != WrapperTypeInfo::ObjectClassId)
            return;

        const v8::Persistent<v8::Object>& wrapper = v8::Persistent<v8::Object>::Cast(*value);

        if (m_visitor)
            toWrapperTypeInfo(wrapper)->trace(m_visitor, toScriptWrappable(wrapper));
    }

private:
    Visitor* m_visitor;
};

void V8GCController::traceDOMWrappers(v8::Isolate* isolate, Visitor* visitor)
{
    DOMWrapperTracer tracer(visitor);
    isolate->VisitHandlesWithClassIds(&tracer);
}

class PendingActivityVisitor : public v8::PersistentHandleVisitor {
public:
    PendingActivityVisitor(v8::Isolate* isolate, ExecutionContext* executionContext)
        : m_isolate(isolate)
        , m_executionContext(executionContext)
        , m_pendingActivityFound(false)
    {
    }

    void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override
    {
        // If we have already found any wrapper that has a pending activity,
        // we don't need to check other wrappers.
        if (m_pendingActivityFound)
            return;

        if (classId != WrapperTypeInfo::NodeClassId && classId != WrapperTypeInfo::ObjectClassId)
            return;

        v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value));
        ASSERT(V8DOMWrapper::hasInternalFieldsSet(wrapper));
        // The ExecutionContext check is heavy, so it should be done at the last.
        if (toWrapperTypeInfo(wrapper)->hasPendingActivity(wrapper)
            // TODO(haraken): Currently we don't have a way to get a creation
            // context from a wrapper. We should implement the way and enable
            // the following condition.
            //
            // This condition affects only compositor workers, where one isolate
            // is shared by multiple workers. If we don't have the condition,
            // a worker object for a compositor worker doesn't get collected
            // until all compositor workers in the same isolate lose pending
            // activities. In other words, not having the condition delays
            // destruction of a worker object of a compositor worker.
            //
            /* && toExecutionContext(wrapper->creationContext()) == m_executionContext */
            )
            m_pendingActivityFound = true;
    }

    bool pendingActivityFound() const { return m_pendingActivityFound; }

private:
    v8::Isolate* m_isolate;
    Persistent<ExecutionContext> m_executionContext;
    bool m_pendingActivityFound;
};

bool V8GCController::hasPendingActivity(v8::Isolate* isolate, ExecutionContext* executionContext)
{
    // V8GCController::hasPendingActivity is used only when a worker checks if
    // the worker contains any wrapper that has pending activities.
    ASSERT(!isMainThread());

    DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scanPendingActivityHistogram, new CustomCountHistogram("Blink.ScanPendingActivityDuration", 1, 1000, 50));
    double startTime = WTF::currentTimeMS();
    v8::HandleScope scope(isolate);
    PendingActivityVisitor visitor(isolate, executionContext);
    toIsolate(executionContext)->VisitHandlesWithClassIds(&visitor);
    scanPendingActivityHistogram.count(static_cast<int>(WTF::currentTimeMS() - startTime));
    return visitor.pendingActivityFound();
}

} // namespace blink


text:
An OAuth2 library for Mac OS X & iOS (Cocoa & Cocoa touch).

## Description

This library is based on [draft 10 of the OAuth2 spec](http://tools.ietf.org/html/draft-ietf-oauth-v2-10).
It implements the [native application profile](http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-1.4.3)
and supports the end-user authorization endpoint via an internal or an external user-agent. Furthermore it
also supports the user credentials flow by prompting the end-user for their username and password and use them
directly to obtain an access token. See the description of the delegate for more information how to choose the
authentication flow.

## Getting started

### Get the sources

Getting the sources is as easy as doing a:
`git clone git://github.com/nxtbgthng/OAuth2Client.git`

### Manually including the library in your Xcode project

#### iOS projects

* Place the _OAuth2Client_ folder within your source root
* Drag the _OAuth2Client.xcodeproj_ into your project
* Under your build target, select the _Build Phases_ tab.
    * Under _Target Dependencies_ add _OAuth2Client_
    * Under _Link Binary With Libraries_, add _libOAuth2Client.a_
* Under _Build Settings_,
    * Add `$(SRCROOT)/path/to/OAuth2Client` _Header Search Paths_, set as _recursive_
    * Add `-ObjC` to _Other Linker Flags_
* `#import "NXOAuth2.h"`
* add the Security.framework as a build dependency

#### Desktop Mac projects

- drag the OAuth2Client.xcodeproj into your project
- add OAuth2Client.framework as a build dependency
- add the Security.framework as a build dependency
- add `$(CONFIGURATION_BUILD_DIR)/$(CONTENTS_FOLDER_PATH)/Frameworks` to your targets Framework Search Path
- link your target against OAuth2Client (drag the OAuth2Client.framework product from OAuth2Client.xcodeproj
to your targets *Link Binary With Libraries*)
- `#import <OAuth2Client/NXOAuth2.h>`

*Using the library as a framework in desktop applications is fairly untested. Please
[report any issues](http://github.com/nxtbgthng/OAuth2Client/issues) and help in making the library better.*

### Adding the libary to your project using CocoaPods
[CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. It manages the above
installation steps automatically.

In order to install the library this way add the following line to your `Podfile`:

```pod 'NXOAuth2Client', '~> 1.2.2'```

and run the following command `pod install`.

## Using the OAuth2Client

### Configure your Client

The best place to configure your client is `+[UIApplicationDelegate initialize]` on iOS or `+[NSApplicationDelegate initialize]` on Mac OS X. There you can call `-[NXOAuth2AccountStore setClientID:secret:authorizationURL:tokenURL:redirectURL:forAccountType:]` on the shared account store for each service you want to have access to from your application. The account type is a string which is used as an identifier for a certain service.

+ (void)initialize;
{
	[[NXOAuth2AccountStore sharedStore] setClientID:@"xXxXxXxXxXxX"
                                             secret:@"xXxXxXxXxXxX"
                                   authorizationURL:[NSURL URLWithString:@"https://...your auth URL..."]
                                           tokenURL:[NSURL URLWithString:@"https://...your token URL..."]
                                        redirectURL:[NSURL URLWithString:@"https://...your redirect URL..."]
                                     forAccountType:@"myFancyService"];
}

### Requesting Access to a Service

Once you have configured your client you are ready to request access to one of those services. The NXOAuth2AccountStore provides three different methods for this:

- Username and Password

 [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:@"myFancyService"
 	                                                       username:aUserName
 	                                                       password:aPassword];

- External Browser

 [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:@"myFancyService"];

 If you are using an external browser, your application needs to handle the URL you have registered as an redirect URL for the account type. The service will redirect to that URL after the authentication process.

- Provide an Authorization URL Handler

 [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:@"myFancyService"
 	                            withPreparedAuthorizationURLHandler:^(NSURL *preparedURL){
 	                                // Open a web view or similar
 	                            }];

 Using an authorization URL handler gives you the ability to open the URL in an own web view or do some fancy stuff for authentication. Therefor you pass a block to the NXOAuth2AccountStore while requesting access.

#### On Success

After a successful authentication, a new `NXOAuth2Account` object is in the list of accounts of `NXOAuth2AccountStore`. You will receive a notification of type `NXOAuth2AccountStoreAccountsDidChangeNotification`, e.g., for updating your UI.

[[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreAccountsDidChangeNotification
                                                  object:[NXOAuth2AccountStore sharedStore]
                                                   queue:nil
                                              usingBlock:^(NSNotification *aNotification){
                                                    // Update your UI
                                              }];

If an account was added the `userInfo` dictionary of the notification will contain the new account at the `NXOAuth2AccountStoreNewAccountUserInfoKey`. Note though that this notification can be triggered on other events (e.g. account removal). In that case this key will not be set.

#### On Failure

If the authentication did not succeed, a notification of type `NXOAuth2AccountStoreDidFailToRequestAccessNotification` containing an `NSError` will be send.

[[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreDidFailToRequestAccessNotification
                                                  object:[NXOAuth2AccountStore sharedStore]
                                                   queue:nil
                                              usingBlock:^(NSNotification *aNotification){
                                                    NSError *error = [aNotification.userInfo objectForKey:NXOAuth2AccountStoreErrorKey];
                                                    // Do something with the error
                                              }];

### Getting a List of all Accounts

The authenticated accounts can be accessed via the `NXOAuth2AccountStore`. Either the complete list, only a list of accounts for a specific service or an account with an identifier (maybe cached in the user settings).

for (NXOAuth2Account *account in [[NXOAuth2AccountStore sharedStore] accounts]) {
    // Do something with the account
};

for (NXOAuth2Account *account in [[NXOAuth2AccountStore sharedStore] accountsWithAccountType:@"myFancyService"]) {
    // Do something with the account
};

NXOAuth2Account *account = [[NXOAuth2AccountStore sharedStore] accountWithIdentifier:@"...cached account id..."];

Each `NXOAuth2Account` has a property `userData` which can be used to store some related information for that account.

NXOAuth2Account *account = // ... get an account
NSDictionary *userData = // ...

account.userData = userData;

This payload will be stored together with the accounts in the Keychain. Thus it shouldn't be to big.

### Invoking a Request

An request using the authentication for a service can be invoked via `NXOAuth2Request`. The most convenient method (see below) is a class method which you pass the method, a resource and some parameters (or nil) for the request and to handlers (both optional). One for a progress and the other for the response. The account is used for authentication and can be nil. Then a normal request without authentication will be invoked.

[NXOAuth2Request performMethod:@"GET"
                    onResource:[NSURL URLWithString:@"https://...your service URL..."]
               usingParameters:nil
                   withAccount:anAccount
           sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) { // e.g., update a progress indicator }
               responseHandler:^(NSURLResponse *response, NSData *responseData, NSError *error){
                   // Process the response
               }];

#### Getting a signed NSURLRequest

In some circumstances you have to go the *god old way* and use an `NSURLConnection`. Maybe if you to download a large file. Therefor `NXOAuth2Request` gives you the possibility to get an `NSURLRequest` containing the additional information to authenticate that request.

NXOAuth2Request *theRequest = [[NXOAuth2Request alloc] initWithResource:[NSURL URLWithString:@"https://...your service URL..."]
									                             method:@"GET"
								                             parameters:nil];
theRequest.account = // ... an account

NSURLRequest *sigendRequest = [theRequest signedURLRequest];

[theRequest release];

// Invoke the request with you preferd method

## BSD License

Copyright © 2012, nxtbgthng GmbH

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of nxtbgthng nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<html>
	<head>
		<style>
.markdown-body {
    font-size: 14px;
    line-height: 1.6;
}
.markdown-body>*:first-child { margin-top: 0!important }
.markdown-body>*:last-child { margin-bottom: 0!important }
.markdown-body a.absent { color: #c00 }
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
    margin: 20px 0 10px;
    padding: 0;
    font-weight: bold;
    -webkit-font-smoothing: antialiased;
}
.markdown-body h1 tt,
.markdown-body h1 code,
.markdown-body h2 tt,
.markdown-body h2 code,
.markdown-body h3 tt,
.markdown-body h3 code,
.markdown-body h4 tt,
.markdown-body h4 code,
.markdown-body h5 tt,
.markdown-body h5 code,
.markdown-body h6 tt,
.markdown-body h6 code { font-size: inherit }
.markdown-body h1 {
    font-size: 28px;
    color: #000;
}
.markdown-body h2 {
    font-size: 24px;
    border-bottom: 1px solid #ccc;
    color: #000;
}
.markdown-body h3 { font-size: 18px }
.markdown-body h4 { font-size: 16px }
.markdown-body h5 { font-size: 14px }
.markdown-body h6 {
    color: #777;
    font-size: 14px;
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body li,
.markdown-body table,
.markdown-body pre { margin: 15px 0 }
.markdown-body hr {
    background: transparent url('../../images/modules/pulls/dirty-shade.png') repeat-x 0 0;
    border: 0 none;
    color: #ccc;
    height: 4px;
    padding: 0;
}
.markdown-body>h2:first-child,
.markdown-body>h1:first-child,
.markdown-body>h1:first-child+h2 {
    border: 0;
    margin-top: 0;
    padding-top: 0;
}
.markdown-body>h3:first-child,
.markdown-body>h4:first-child,
.markdown-body>h5:first-child,
.markdown-body>h6:first-child {
    margin-top: 0;
    padding-top: 0;
}
.markdown-body h1+p,
.markdown-body h2+p,
.markdown-body h3+p,
.markdown-body h4+p,
.markdown-body h5+p,
.markdown-body h6+p { margin-top: 0 }
.markdown-body li p.first { display: inline-block }
.markdown-body ul,
.markdown-body ol { padding-left: 30px }
.markdown-body ul li>:first-child,
.markdown-body ol li>:first-child { margin-top: 0 }
.markdown-body ul li>:last-child,
.markdown-body ol li>:last-child { margin-bottom: 0 }
.markdown-body dl { padding: 0 }
.markdown-body dl dt {
    font-size: 14px;
    font-weight: bold;
    font-style: italic;
    padding: 0;
    margin: 15px 0 5px;
}
.markdown-body dl dt:first-child { padding: 0 }
.markdown-body dl dt>:first-child { margin-top: 0 }
.markdown-body dl dt>:last-child { margin-bottom: 0 }
.markdown-body dl dd {
    margin: 0 0 15px;
    padding: 0 15px;
}
.markdown-body dl dd>:first-child { margin-top: 0 }
.markdown-body dl dd>:last-child { margin-bottom: 0 }
.markdown-body blockquote {
    border-left: 4px solid #DDD;
    padding: 0 15px;
    color: #777;
}
.markdown-body blockquote>:first-child { margin-top: 0 }
.markdown-body blockquote>:last-child { margin-bottom: 0 }
.markdown-body table { padding: 0 }
.markdown-body table tr {
    border-top: 1px solid #ccc;
    background-color: #fff;
    margin: 0;
    padding: 0;
}
.markdown-body table tr:nth-child(2n) { background-color: #f8f8f8 }
.markdown-body table tr th,
.markdown-body table tr td {
    border: 1px solid #ccc;
    text-align: left;
    margin: 0;
    padding: 6px 13px;
}
.markdown-body table tr th>:first-child,
.markdown-body table tr td>:first-child { margin-top: 0 }
.markdown-body table tr th>:last-child,
.markdown-body table tr td>:last-child { margin-bottom: 0 }
.markdown-body img { max-width: 100% }
.markdown-body span.frame {
    display: block;
    overflow: hidden;
}
.markdown-body span.frame>span {
    border: 1px solid #ddd;
    display: block;
    float: left;
    overflow: hidden;
    margin: 13px 0 0;
    padding: 7px;
    width: auto;
}
.markdown-body span.frame span img {
    display: block;
    float: left;
}
.markdown-body span.frame span span {
    clear: both;
    color: #333;
    display: block;
    padding: 5px 0 0;
}
.markdown-body span.align-center {
    display: block;
    overflow: hidden;
    clear: both;
}
.markdown-body span.align-center>span {
    display: block;
    overflow: hidden;
    margin: 13px auto 0;
    text-align: center;
}
.markdown-body span.align-center span img {
    margin: 0 auto;
    text-align: center;
}
.markdown-body span.align-right {
    display: block;
    overflow: hidden;
    clear: both;
}
.markdown-body span.align-right>span {
    display: block;
    overflow: hidden;
    margin: 13px 0 0;
    text-align: right;
}
.markdown-body span.align-right span img {
    margin: 0;
    text-align: right;
}
.markdown-body span.float-left {
    display: block;
    margin-right: 13px;
    overflow: hidden;
    float: left;
}
.markdown-body span.float-left span { margin: 13px 0 0 }
.markdown-body span.float-right {
    display: block;
    margin-left: 13px;
    overflow: hidden;
    float: right;
}
.markdown-body span.float-right>span {
    display: block;
    overflow: hidden;
    margin: 13px auto 0;
    text-align: right;
}
.markdown-body code,
.markdown-body tt {
    margin: 0 2px;
    padding: 0 5px;
    white-space: nowrap;
    border: 1px solid #eaeaea;
    background-color: #f8f8f8;
    border-radius: 3px;
}
.markdown-body pre>code {
    margin: 0;
    padding: 0;
    white-space: pre;
    border: none;
    background: transparent;
}
.markdown-body .highlight pre,
.markdown-body pre {
    background-color: #f8f8f8;
    border: 1px solid #ccc;
    font-size: 13px;
    line-height: 19px;
    overflow: auto;
    padding: 6px 10px;
    border-radius: 3px;
}
.markdown-body pre code,
.markdown-body pre tt {
    background-color: transparent;
    border: none;
}
.highlight { background: #fff }
.highlight .c {
    color: #998;
    font-style: italic;
}
.highlight .err {
    color: #a61717;
    background-color: #e3d2d2;
}
.highlight .k { font-weight: bold }
.highlight .o { font-weight: bold }
.highlight .cm {
    color: #998;
    font-style: italic;
}
.highlight .cp {
    color: #999;
    font-weight: bold;
}
.highlight .c1 {
    color: #998;
    font-style: italic;
}
.highlight .cs {
    color: #999;
    font-weight: bold;
    font-style: italic;
}
.highlight .gd {
    color: #000;
    background-color: #fdd;
}
.highlight .gd .x {
    color: #000;
    background-color: #faa;
}
.highlight .ge { font-style: italic }
.highlight .gr { color: #a00 }
.highlight .gh { color: #999 }
.highlight .gi {
    color: #000;
    background-color: #dfd;
}
.highlight .gi .x {
    color: #000;
    background-color: #afa;
}
.highlight .go { color: #888 }
.highlight .gp { color: #555 }
.highlight .gs { font-weight: bold }
.highlight .gu {
    color: #800080;
    font-weight: bold;
}
.highlight .gt { color: #a00 }
.highlight .kc { font-weight: bold }
.highlight .kd { font-weight: bold }
.highlight .kn { font-weight: bold }
.highlight .kp { font-weight: bold }
.highlight .kr { font-weight: bold }
.highlight .kt {
    color: #458;
    font-weight: bold;
}
.highlight .m { color: #099 }
.highlight .s { color: #d14 }
.highlight .na { color: #008080 }
.highlight .nb { color: #0086B3 }
.highlight .nc {
    color: #458;
    font-weight: bold;
}
.highlight .no { color: #008080 }
.highlight .ni { color: #800080 }
.highlight .ne {
    color: #900;
    font-weight: bold;
}
.highlight .nf {
    color: #900;
    font-weight: bold;
}
.highlight .nn { color: #555 }
.highlight .nt { color: #000080 }
.highlight .nv { color: #008080 }
.highlight .ow { font-weight: bold }
.highlight .w { color: #bbb }
.highlight .mf { color: #099 }
.highlight .mh { color: #099 }
.highlight .mi { color: #099 }
.highlight .mo { color: #099 }
.highlight .sb { color: #d14 }
.highlight .sc { color: #d14 }
.highlight .sd { color: #d14 }
.highlight .s2 { color: #d14 }
.highlight .se { color: #d14 }
.highlight .sh { color: #d14 }
.highlight .si { color: #d14 }
.highlight .sx { color: #d14 }
.highlight .sr { color: #009926 }
.highlight .s1 { color: #d14 }
.highlight .ss { color: #990073 }
.highlight .bp { color: #999 }
.highlight .vc { color: #008080 }
.highlight .vg { color: #008080 }
.highlight .vi { color: #008080 }
.highlight .il { color: #099 }
.highlight .gc {
    color: #999;
    background-color: #EAF2F5;
}
.type-csharp .highlight .k { color: #00F }
.type-csharp .highlight .kt { color: #00F }
.type-csharp .highlight .nf {
    color: #000;
    font-weight: normal;
}
.type-csharp .highlight .nc { color: #2B91AF }
.type-csharp .highlight .nn { color: #000 }
.type-csharp .highlight .s { color: #A31515 }
.type-csharp .highlight .sc { color: #A31515 }

		</style>
	</head>
	<body>
		<article class="markdown-body">


text:
using System;

namespace Simplic
{
    public class TypeHelper
    {
        public static object GetDefaultValue(Type type)
        {
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }

        public static Type GetType(string typeName)
        {
            var type = Type.GetType(typeName);
            if (type != null) return type;
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                type = a.GetType(typeName);
                if (type != null)
                    return type;
            }
            return null;
        }
    }
}


text:
#include "ProtoServer.h"

namespace paddle {

void ProtoServer::handleRequest(std::unique_ptr<MsgReader> msgReader,
                                ResponseCallback callback) {
  /// 0 for funcName
  /// 1 for proto
  CHECK_GE(msgReader->getNumBlocks(), (size_t)2);

  std::string funcName(msgReader->getNextBlockLength(), 0);
  /// read function name string
  msgReader->readNextBlock(&funcName[0]);
  /// looking up rpc wrapped callback function
  auto it = nameToFuncMap_.find(funcName);
  if (it != nameToFuncMap_.end()) {
#ifndef PADDLE_DISABLE_TIMER
    gettimeofday(&(*(handleRequestBegin_)), nullptr);
#endif
    it->second(std::move(msgReader), callback);
  } else {
    LOG(ERROR) << "Unknown funcName: " << funcName;
    std::vector<iovec> iovs;
    callback(iovs);
  }
}

void ProtoServer::registerServiceFunctionImp(const std::string& funcName,
                                             ServiceFunction func) {
  CHECK(!nameToFuncMap_.count(funcName)) << "Duplicated registration: "
                                         << funcName;
  nameToFuncMap_[funcName] = func;
}

void ProtoClient::send(const char* funcName,
                       const google::protobuf::MessageLite& proto,
                       const std::vector<iovec>& userIovs) {
  std::string protoStr;
  CHECK(proto.SerializeToString(&protoStr));
  std::vector<iovec> iovs;
  iovs.reserve(iovs.size() + 2);
  /// sending function name string, protobuf data and user additional data
  iovs.push_back({(void*)funcName, strlen(funcName)});
  iovs.push_back({&protoStr[0], protoStr.size()});
  iovs.insert(iovs.end(), userIovs.begin(), userIovs.end());
  channel_->writeMessage(iovs);
}

std::unique_ptr<MsgReader> ProtoClient::recv(
    google::protobuf::MessageLite* proto) {
  std::vector<iovec> iovs;
  std::unique_ptr<MsgReader> msgReader = channel_->readMessage();
  CHECK_GE(msgReader->getNumBlocks(), (size_t)1);
  std::string str(msgReader->getNextBlockLength(), 0);
  msgReader->readNextBlock(&str[0]);
  CHECK(proto->ParseFromString(str));
  return msgReader;
}

}  // namespace paddle


text:
{{{
  "title": "SafeHaven-4-Expand Protection Group Size",
  "date": "1-11-2017",
  "author": "Anshul Arora",
  "attachments": [],
  "contentIsHTML": false
}}}
### Article Overview
This article explains how to expand the size of a Protection Group. This can be useful when a user wants to expand disk size or add a new disk to an already protected VM, or add a new VM to an existing Protection Group. In either case, the first step is to expand the size of the Protection Group.

### Add storage to the Production and Recovery SRN

### Edit Storage
Go to the Centurylink Portal, select the Production SRN and click on "Edit Storage"

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg1.png)

### Add Raw Disk
* On Production SRN
Add 10% of the additional disk for local Cache and 100% for local Replica.

* On Recovery SRN
Add 100% of the additional disk.

Click on Add storage and select Raw Disk from the drop down menu. DO NOT expand existing storage or add a partition.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg2.png)

Enter a value for the new raw disk and click on apply. This has to be repeated for the Recovery SRN. Once the approprite amount of storage has been added to both the production and the recovery SRNs, it needs to be claimed in the storage pool associated with the Protection Group.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg2_1.png)

### Claim Storage Pool
Next step is to claim the newly added storage to the storage pool associated with the Protection group. In order to find out the storage pool associated with the protection group, click on the protection group and see "Data Volume Storage Pool" under "Data Center" for both active(Production) and Peer(recovery) datacenters.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg2_2.png)

To claim the storage to storage pool, select the appropriate SRN and then click on "Claim Storage Pool".

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg3.png)

Select the Newly Added storage and add it to an existining storage pool. Select the right storage pool from the drop down menu and click on Claim.
Note: This has to be done for both Production and Recovery SRN.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg4.png)

### Expand Protection Group
Once the storage has been claimed on both the Production and Recovery SRN, next step is to expand the Protection Group. In order to do so, click on the appropriate Protection Group and then click on "Expand".

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg5.png)

Enter the new value for the size of the Protection Group and then click on Ok.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg6.png)

Once the Resize job finishes, the Protection Group Size can be verified by clicking on the Protection Group and checking the protection group size.

![ConfigureEmail](../images/SH4.0/ExpandPG/expandpg7.png)


text:
package dopengl.shapes;

import android.opengl.GLES20;
import dopengl.GLFloatBuffer;
import dopengl.OpenGLUtil;
import dopengl.programs.ShapeProgram;
import thed.GLBuffer;
import thed.GLColor;

/**
 * Simple OpenGL triangle shape.
 *
 * @author Derek Mulvihill
 */
public class GLTriangle {
    private ShapeProgram program;

    private GLBuffer buffer = new GLBuffer(1);

    private GLFloatBuffer vertexBuffer;
    private GLFloatBuffer colorBuffer;

    public GLTriangle() {
        program = new ShapeProgram();

        vertexBuffer = OpenGLUtil.createBuffer(buffer.getVertices());
        colorBuffer = OpenGLUtil.createBuffer(buffer.getColors());
        colorBuffer.setStepSize(4);
    }

    public void draw(float[] vpMatrix) {
        program.start(vpMatrix);

        program.bufferVertexPosition(vertexBuffer);
        program.bufferVertexColor(colorBuffer);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, buffer.getVertexCount());

        program.end();
    }

    public void drawLineLoop(float[] vpMatrix) {
        program.start(vpMatrix);

        program.bufferVertexPosition(vertexBuffer);
        program.bufferVertexColor(colorBuffer);
        GLES20.glLineWidth(1f);
        GLES20.glDrawArrays(GLES20.GL_LINE_LOOP, 0, buffer.getVertexCount());

        program.end();
    }

    /**
     * Must be at least a length 9 array.
     */
    public void setVertices(float[] vertices) {
        if (vertices.length < 9) {
            return;
        }
        float[] vertexValues = vertexBuffer.getData();
        System.arraycopy(vertices, 0, vertexValues, 0, 9);
    }

    public void setColor(GLColor color) {
        float[] colorValues = colorBuffer.getData();
        System.arraycopy(color.get(), 0, colorValues, 0, 12);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Gmelin, Syst. Nat. , Edn 13 2(2): 1472 (1792)

#### Original name
Aecidium cancellatum Pers., 1792

### Remarks
null


text:
Imports Class1
Partial Class Sales
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '' ListBox1.Items.Clear()
        'Dim OBJ1 As New Class1

        'Dim obj As Data.SqlClient.SqlDataReader
        'obj = OBJ1.getdata("SELECT DISTINCT COMPANY FROM add_phone where company like '%" & TextBox1.Text & "%' ")

        'While (obj.Read)
        '    ListBox1.Items.Add(obj.Item(0))
        'End While

    End Sub

    Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        ListBox1.Items.Clear()
        Dim OBJ1 As New Class1

        Dim obj As Data.SqlClient.SqlDataReader
        obj = OBJ1.getdata("SELECT DISTINCT category FROM categories where category like '%" & TextBox1.Text & "%' ")

        While (obj.Read)
            ListBox1.Items.Add(obj.Item(0))
        End While

        OBJ1.close_conn()
        ScriptManager1.SetFocus(TextBox1)

    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        TextBox1.Focus()
        'TextBox1.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')")
        'TextBox1.Attributes.Add("onfocus", "javascript:SetCursorToTextEnd()")

        'TextBox1.Text = "Dada"

    End Sub
End Class


text: yum install -y atlas gsl


text:
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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.

package google.registry.model;

import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.collect.Streams;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Helper class for {@link Jsonifiable} classes to generate JSON maps for RPC responses.
 *
 * <p>The returned map is mutable. Map entries can be {@code null} but list entries can not. If a
 * list is passed as {@code null}, it'll be substituted with empty list. Lists are not mutable.
 */
public final class JsonMapBuilder {
  private final Map<String, Object> map = new LinkedHashMap<>();

  public JsonMapBuilder put(String name, @Nullable Boolean value) {
    map.put(name, value);
    return this;
  }

  public JsonMapBuilder put(String name, @Nullable Number value) {
    map.put(name, value);
    return this;
  }

  public JsonMapBuilder put(String name, @Nullable String value) {
    map.put(name, value);
    return this;
  }

  public JsonMapBuilder put(String name, @Nullable Jsonifiable value) {
    map.put(name, value == null ? null : value.toJsonMap());
    return this;
  }

  public JsonMapBuilder put(String name, @Nullable Enum<?> value) {
    map.put(name, value == null ? null : value.name());
    return this;
  }

  public <T> JsonMapBuilder putString(String name, @Nullable T value) {
    map.put(name, value == null ? null : value.toString());
    return this;
  }

  public <T> JsonMapBuilder putListOfStrings(String name, @Nullable Iterable<T> value) {
    map.put(
        name,
        value == null
            ? Collections.EMPTY_LIST
            : Streams.stream(value).map(Object::toString).collect(toImmutableList()));
    return this;
  }

  public JsonMapBuilder putListOfJsonObjects(
      String name, @Nullable Iterable<? extends Jsonifiable> value) {
    map.put(
        name,
        value == null
            ? Collections.EMPTY_LIST
            : Streams.stream(value).map(Jsonifiable::toJsonMap).collect(toImmutableList()));
    return this;
  }

  /** Returns mutable JSON object. Please dispose of the builder object after calling me. */
  public Map<String, Object> build() {
    return map;
  }
}


text:
package org.apache.hadoop.hbase.chaos.actions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.hadoop.hbase.ClusterStatus;
import org.apache.hadoop.hbase.ServerName;

/**
* Action that tries to unbalance the regions of a cluster.
*/
public class UnbalanceRegionsAction extends Action {
  private double fractionOfRegions;
  private double fractionOfServers;

  /**
   * Unbalances the regions on the cluster by choosing "target" servers, and moving
   * some regions from each of the non-target servers to random target servers.
   * @param fractionOfRegions Fraction of regions to move from each server.
   * @param fractionOfServers Fraction of servers to be chosen as targets.
   */
  public UnbalanceRegionsAction(double fractionOfRegions, double fractionOfServers) {
    this.fractionOfRegions = fractionOfRegions;
    this.fractionOfServers = fractionOfServers;
  }

  @Override
  public void perform() throws Exception {
    LOG.info("Unbalancing regions");
    ClusterStatus status = this.cluster.getClusterStatus();
    List<ServerName> victimServers = new LinkedList<>(status.getServers());
    int targetServerCount = (int)Math.ceil(fractionOfServers * victimServers.size());
    List<ServerName> targetServers = new ArrayList<>(targetServerCount);
    for (int i = 0; i < targetServerCount; ++i) {
      int victimIx = RandomUtils.nextInt(victimServers.size());
      targetServers.add(victimServers.remove(victimIx));
    }
    unbalanceRegions(status, victimServers, targetServers, fractionOfRegions);
  }
}


text:
/*
	Module: rt2x00
	Abstract: rt2x00 global information.
 */

#ifndef RT2X00_H
#define RT2X00_H

#include <linux/bitops.h>
#include <linux/interrupt.h>
#include <linux/skbuff.h>
#include <linux/workqueue.h>
#include <linux/firmware.h>
#include <linux/leds.h>
#include <linux/mutex.h>
#include <linux/etherdevice.h>
#include <linux/input-polldev.h>
#include <linux/kfifo.h>
#include <linux/hrtimer.h>

#include <net/mac80211.h>

#include "rt2x00debug.h"
#include "rt2x00dump.h"
#include "rt2x00leds.h"
#include "rt2x00reg.h"
#include "rt2x00queue.h"

/*
 * Module information.
 */
#define DRV_VERSION	"2.3.0"
#define DRV_PROJECT	"http://rt2x00.serialmonkey.com"

/* Debug definitions.
 * Debug output has to be enabled during compile time.
 */
#ifdef CONFIG_RT2X00_DEBUG
#define DEBUG
#endif /* CONFIG_RT2X00_DEBUG */

/* Utility printing macros
 * rt2x00_probe_err is for messages when rt2x00_dev is uninitialized
 */
#define rt2x00_probe_err(fmt, ...)					\
	printk(KERN_ERR KBUILD_MODNAME ": %s: Error - " fmt,		\
	       __func__, ##__VA_ARGS__)
#define rt2x00_err(dev, fmt, ...)					\
	wiphy_err((dev)->hw->wiphy, "%s: Error - " fmt,			\
		  __func__, ##__VA_ARGS__)
#define rt2x00_warn(dev, fmt, ...)					\
	wiphy_warn((dev)->hw->wiphy, "%s: Warning - " fmt,		\
		   __func__, ##__VA_ARGS__)
#define rt2x00_info(dev, fmt, ...)					\
	wiphy_info((dev)->hw->wiphy, "%s: Info - " fmt,			\
		   __func__, ##__VA_ARGS__)

/* Various debug levels */
#define rt2x00_dbg(dev, fmt, ...)					\
	wiphy_dbg((dev)->hw->wiphy, "%s: Debug - " fmt,			\
		  __func__, ##__VA_ARGS__)
#define rt2x00_eeprom_dbg(dev, fmt, ...)				\
	wiphy_dbg((dev)->hw->wiphy, "%s: EEPROM recovery - " fmt,	\
		  __func__, ##__VA_ARGS__)

/*
 * Duration calculations
 * The rate variable passed is: 100kbs.
 * To convert from bytes to bits we multiply size with 8,
 * then the size is multiplied with 10 to make the
 * real rate -> rate argument correction.
 */
#define GET_DURATION(__size, __rate)	(((__size) * 8 * 10) / (__rate))
#define GET_DURATION_RES(__size, __rate)(((__size) * 8 * 10) % (__rate))

/*
 * Determine the number of L2 padding bytes required between the header and
 * the payload.
 */
#define L2PAD_SIZE(__hdrlen)	(-(__hdrlen) & 3)

/*
 * Determine the alignment requirement,
 * to make sure the 802.11 payload is padded to a 4-byte boundrary
 * we must determine the address of the payload and calculate the
 * amount of bytes needed to move the data.
 */
#define ALIGN_SIZE(__skb, __header) \
	(  ((unsigned long)((__skb)->data + (__header))) & 3 )

/*
 * Constants for extra TX headroom for alignment purposes.
 */
#define RT2X00_ALIGN_SIZE	4 /* Only whole frame needs alignment */
#define RT2X00_L2PAD_SIZE	8 /* Both header & payload need alignment */

/*
 * Standard timing and size defines.
 * These values should follow the ieee80211 specifications.
 */
#define ACK_SIZE		14
#define IEEE80211_HEADER	24
#define PLCP			48
#define BEACON			100
#define PREAMBLE		144
#define SHORT_PREAMBLE		72
#define SLOT_TIME		20
#define SHORT_SLOT_TIME		9
#define SIFS			10
#define PIFS			( SIFS + SLOT_TIME )
#define SHORT_PIFS		( SIFS + SHORT_SLOT_TIME )
#define DIFS			( PIFS + SLOT_TIME )
#define SHORT_DIFS		( SHORT_PIFS + SHORT_SLOT_TIME )
#define EIFS			( SIFS + DIFS + \
				  GET_DURATION(IEEE80211_HEADER + ACK_SIZE, 10) )
#define SHORT_EIFS		( SIFS + SHORT_DIFS + \
				  GET_DURATION(IEEE80211_HEADER + ACK_SIZE, 10) )

/*
 * Structure for average calculation
 * The avg field contains the actual average value,
 * but avg_weight is internally used during calculations
 * to prevent rounding errors.
 */
struct avg_val {
	int avg;
	int avg_weight;
};

enum rt2x00_chip_intf {
	RT2X00_CHIP_INTF_PCI,
	RT2X00_CHIP_INTF_PCIE,
	RT2X00_CHIP_INTF_USB,
	RT2X00_CHIP_INTF_SOC,
};

/*
 * Chipset identification
 * The chipset on the device is composed of a RT and RF chip.
 * The chipset combination is important for determining device capabilities.
 */
struct rt2x00_chip {
	u16 rt;
#define RT2460		0x2460
#define RT2560		0x2560
#define RT2570		0x2570
#define RT2661		0x2661
#define RT2573		0x2573
#define RT2860		0x2860	/* 2.4GHz */
#define RT2872		0x2872	/* WSOC */
#define RT2883		0x2883	/* WSOC */
#define RT3070		0x3070
#define RT3071		0x3071
#define RT3090		0x3090	/* 2.4GHz PCIe */
#define RT3290		0x3290
#define RT3352		0x3352  /* WSOC */
#define RT3390		0x3390
#define RT3572		0x3572
#define RT3593		0x3593
#define RT3883		0x3883	/* WSOC */
#define RT5390		0x5390  /* 2.4GHz */
#define RT5392		0x5392  /* 2.4GHz */
#define RT5592		0x5592

	u16 rf;
	u16 rev;

	enum rt2x00_chip_intf intf;
};

/*
 * RF register values that belong to a particular channel.
 */
struct rf_channel {
	int channel;
	u32 rf1;
	u32 rf2;
	u32 rf3;
	u32 rf4;
};

/*
 * Channel information structure
 */
struct channel_info {
	unsigned int flags;
#define GEOGRAPHY_ALLOWED	0x00000001

	short max_power;
	short default_power1;
	short default_power2;
};

/*
 * Antenna setup values.
 */
struct antenna_setup {
	enum antenna rx;
	enum antenna tx;
	u8 rx_chain_num;
	u8 tx_chain_num;
};

/*
 * Quality statistics about the currently active link.
 */
struct link_qual {
	/*
	 * Statistics required for Link tuning by driver
	 * The rssi value is provided by rt2x00lib during the
	 * link_tuner() callback function.
	 * The false_cca field is filled during the link_stats()
	 * callback function and could be used during the
	 * link_tuner() callback function.
	 */
	int rssi;
	int false_cca;

	/*
	 * VGC levels
	 * Hardware driver will tune the VGC level during each call
	 * to the link_tuner() callback function. This vgc_level is
	 * is determined based on the link quality statistics like
	 * average RSSI and the false CCA count.
	 *
	 * In some cases the drivers need to differentiate between
	 * the currently "desired" VGC level and the level configured
	 * in the hardware. The latter is important to reduce the
	 * number of BBP register reads to reduce register access
	 * overhead. For this reason we store both values here.
	 */
	u8 vgc_level;
	u8 vgc_level_reg;

	/*
	 * Statistics required for Signal quality calculation.
	 * These fields might be changed during the link_stats()
	 * callback function.
	 */
	int rx_success;
	int rx_failed;
	int tx_success;
	int tx_failed;
};

/*
 * Antenna settings about the currently active link.
 */
struct link_ant {
	/*
	 * Antenna flags
	 */
	unsigned int flags;
#define ANTENNA_RX_DIVERSITY	0x00000001
#define ANTENNA_TX_DIVERSITY	0x00000002
#define ANTENNA_MODE_SAMPLE	0x00000004

	/*
	 * Currently active TX/RX antenna setup.
	 * When software diversity is used, this will indicate
	 * which antenna is actually used at this time.
	 */
	struct antenna_setup active;

	/*
	 * RSSI history information for the antenna.
	 * Used to determine when to switch antenna
	 * when using software diversity.
	 */
	int rssi_history;

	/*
	 * Current RSSI average of the currently active antenna.
	 * Similar to the avg_rssi in the link_qual structure
	 * this value is updated by using the walking average.
	 */
	struct avg_val rssi_ant;
};

/*
 * To optimize the quality of the link we need to store
 * the quality of received frames and periodically
 * optimize the link.
 */
struct link {
	/*
	 * Link tuner counter
	 * The number of times the link has been tuned
	 * since the radio has been switched on.
	 */
	u32 count;

	/*
	 * Quality measurement values.
	 */
	struct link_qual qual;

	/*
	 * TX/RX antenna setup.
	 */
	struct link_ant ant;

	/*
	 * Currently active average RSSI value
	 */
	struct avg_val avg_rssi;

	/*
	 * Work structure for scheduling periodic link tuning.
	 */
	struct delayed_work work;

	/*
	 * Work structure for scheduling periodic watchdog monitoring.
	 * This work must be scheduled on the kernel workqueue, while
	 * all other work structures must be queued on the mac80211
	 * workqueue. This guarantees that the watchdog can schedule
	 * other work structures and wait for their completion in order
	 * to bring the device/driver back into the desired state.
	 */
	struct delayed_work watchdog_work;

	/*
	 * Work structure for scheduling periodic AGC adjustments.
	 */
	struct delayed_work agc_work;

	/*
	 * Work structure for scheduling periodic VCO calibration.
	 */
	struct delayed_work vco_work;
};

enum rt2x00_delayed_flags {
	DELAYED_UPDATE_BEACON,
};

/*
 * Interface structure
 * Per interface configuration details, this structure
 * is allocated as the private data for ieee80211_vif.
 */
struct rt2x00_intf {
	/*
	 * beacon->skb must be protected with the mutex.
	 */
	struct mutex beacon_skb_mutex;

	/*
	 * Entry in the beacon queue which belongs to
	 * this interface. Each interface has its own
	 * dedicated beacon entry.
	 */
	struct queue_entry *beacon;
	bool enable_beacon;

	/*
	 * Actions that needed rescheduling.
	 */
	unsigned long delayed_flags;

	/*
	 * Software sequence counter, this is only required
	 * for hardware which doesn't support hardware
	 * sequence counting.
	 */
	atomic_t seqno;
};

static inline struct rt2x00_intf* vif_to_intf(struct ieee80211_vif *vif)
{
	return (struct rt2x00_intf *)vif->drv_priv;
}

/**
 * struct hw_mode_spec: Hardware specifications structure
 *
 * Details about the supported modes, rates and channels
 * of a particular chipset. This is used by rt2x00lib
 * to build the ieee80211_hw_mode array for mac80211.
 *
 * @supported_bands: Bitmask contained the supported bands (2.4GHz, 5.2GHz).
 * @supported_rates: Rate types which are supported (CCK, OFDM).
 * @num_channels: Number of supported channels. This is used as array size
 *	for @tx_power_a, @tx_power_bg and @channels.
 * @channels: Device/chipset specific channel values (See &struct rf_channel).
 * @channels_info: Additional information for channels (See &struct channel_info).
 * @ht: Driver HT Capabilities (See &ieee80211_sta_ht_cap).
 */
struct hw_mode_spec {
	unsigned int supported_bands;
#define SUPPORT_BAND_2GHZ	0x00000001
#define SUPPORT_BAND_5GHZ	0x00000002

	unsigned int supported_rates;
#define SUPPORT_RATE_CCK	0x00000001
#define SUPPORT_RATE_OFDM	0x00000002

	unsigned int num_channels;
	const struct rf_channel *channels;
	const struct channel_info *channels_info;

	struct ieee80211_sta_ht_cap ht;
};

/*
 * Configuration structure wrapper around the
 * mac80211 configuration structure.
 * When mac80211 configures the driver, rt2x00lib
 * can precalculate values which are equal for all
 * rt2x00 drivers. Those values can be stored in here.
 */
struct rt2x00lib_conf {
	struct ieee80211_conf *conf;

	struct rf_channel rf;
	struct channel_info channel;
};

/*
 * Configuration structure for erp settings.
 */
struct rt2x00lib_erp {
	int short_preamble;
	int cts_protection;

	u32 basic_rates;

	int slot_time;

	short sifs;
	short pifs;
	short difs;
	short eifs;

	u16 beacon_int;
	u16 ht_opmode;
};

/*
 * Configuration structure for hardware encryption.
 */
struct rt2x00lib_crypto {
	enum cipher cipher;

	enum set_key_cmd cmd;
	const u8 *address;

	u32 bssidx;

	u8 key[16];
	u8 tx_mic[8];
	u8 rx_mic[8];

	int wcid;
};

/*
 * Configuration structure wrapper around the
 * rt2x00 interface configuration handler.
 */
struct rt2x00intf_conf {
	/*
	 * Interface type
	 */
	enum nl80211_iftype type;

	/*
	 * TSF sync value, this is dependent on the operation type.
	 */
	enum tsf_sync sync;

	/*
	 * The MAC and BSSID addresses are simple array of bytes,
	 * these arrays are little endian, so when sending the addresses
	 * to the drivers, copy the it into a endian-signed variable.
	 *
	 * Note that all devices (except rt2500usb) have 32 bits
	 * register word sizes. This means that whatever variable we
	 * pass _must_ be a multiple of 32 bits. Otherwise the device
	 * might not accept what we are sending to it.
	 * This will also make it easier for the driver to write
	 * the data to the device.
	 */
	__le32 mac[2];
	__le32 bssid[2];
};

/*
 * Private structure for storing STA details
 * wcid: Wireless Client ID
 */
struct rt2x00_sta {
	int wcid;
};

static inline struct rt2x00_sta* sta_to_rt2x00_sta(struct ieee80211_sta *sta)
{
	return (struct rt2x00_sta *)sta->drv_priv;
}

/*
 * rt2x00lib callback functions.
 */
struct rt2x00lib_ops {
	/*
	 * Interrupt handlers.
	 */
	irq_handler_t irq_handler;

	/*
	 * TX status tasklet handler.
	 */
	void (*txstatus_tasklet) (unsigned long data);
	void (*pretbtt_tasklet) (unsigned long data);
	void (*tbtt_tasklet) (unsigned long data);
	void (*rxdone_tasklet) (unsigned long data);
	void (*autowake_tasklet) (unsigned long data);

	/*
	 * Device init handlers.
	 */
	int (*probe_hw) (struct rt2x00_dev *rt2x00dev);
	char *(*get_firmware_name) (struct rt2x00_dev *rt2x00dev);
	int (*check_firmware) (struct rt2x00_dev *rt2x00dev,
			       const u8 *data, const size_t len);
	int (*load_firmware) (struct rt2x00_dev *rt2x00dev,
			      const u8 *data, const size_t len);

	/*
	 * Device initialization/deinitialization handlers.
	 */
	int (*initialize) (struct rt2x00_dev *rt2x00dev);
	void (*uninitialize) (struct rt2x00_dev *rt2x00dev);

	/*
	 * queue initialization handlers
	 */
	bool (*get_entry_state) (struct queue_entry *entry);
	void (*clear_entry) (struct queue_entry *entry);

	/*
	 * Radio control handlers.
	 */
	int (*set_device_state) (struct rt2x00_dev *rt2x00dev,
				 enum dev_state state);
	int (*rfkill_poll) (struct rt2x00_dev *rt2x00dev);
	void (*link_stats) (struct rt2x00_dev *rt2x00dev,
			    struct link_qual *qual);
	void (*reset_tuner) (struct rt2x00_dev *rt2x00dev,
			     struct link_qual *qual);
	void (*link_tuner) (struct rt2x00_dev *rt2x00dev,
			    struct link_qual *qual, const u32 count);
	void (*gain_calibration) (struct rt2x00_dev *rt2x00dev);
	void (*vco_calibration) (struct rt2x00_dev *rt2x00dev);

	/*
	 * Data queue handlers.
	 */
	void (*watchdog) (struct rt2x00_dev *rt2x00dev);
	void (*start_queue) (struct data_queue *queue);
	void (*kick_queue) (struct data_queue *queue);
	void (*stop_queue) (struct data_queue *queue);
	void (*flush_queue) (struct data_queue *queue, bool drop);
	void (*tx_dma_done) (struct queue_entry *entry);

	/*
	 * TX control handlers
	 */
	void (*write_tx_desc) (struct queue_entry *entry,
			       struct txentry_desc *txdesc);
	void (*write_tx_data) (struct queue_entry *entry,
			       struct txentry_desc *txdesc);
	void (*write_beacon) (struct queue_entry *entry,
			      struct txentry_desc *txdesc);
	void (*clear_beacon) (struct queue_entry *entry);
	int (*get_tx_data_len) (struct queue_entry *entry);

	/*
	 * RX control handlers
	 */
	void (*fill_rxdone) (struct queue_entry *entry,
			     struct rxdone_entry_desc *rxdesc);

	/*
	 * Configuration handlers.
	 */
	int (*config_shared_key) (struct rt2x00_dev *rt2x00dev,
				  struct rt2x00lib_crypto *crypto,
				  struct ieee80211_key_conf *key);
	int (*config_pairwise_key) (struct rt2x00_dev *rt2x00dev,
				    struct rt2x00lib_crypto *crypto,
				    struct ieee80211_key_conf *key);
	void (*config_filter) (struct rt2x00_dev *rt2x00dev,
			       const unsigned int filter_flags);
	void (*config_intf) (struct rt2x00_dev *rt2x00dev,
			     struct rt2x00_intf *intf,
			     struct rt2x00intf_conf *conf,
			     const unsigned int flags);
#define CONFIG_UPDATE_TYPE		( 1 << 1 )
#define CONFIG_UPDATE_MAC		( 1 << 2 )
#define CONFIG_UPDATE_BSSID		( 1 << 3 )

	void (*config_erp) (struct rt2x00_dev *rt2x00dev,
			    struct rt2x00lib_erp *erp,
			    u32 changed);
	void (*config_ant) (struct rt2x00_dev *rt2x00dev,
			    struct antenna_setup *ant);
	void (*config) (struct rt2x00_dev *rt2x00dev,
			struct rt2x00lib_conf *libconf,
			const unsigned int changed_flags);
	int (*sta_add) (struct rt2x00_dev *rt2x00dev,
			struct ieee80211_vif *vif,
			struct ieee80211_sta *sta);
	int (*sta_remove) (struct rt2x00_dev *rt2x00dev,
			   int wcid);
};

/*
 * rt2x00 driver callback operation structure.
 */
struct rt2x00_ops {
	const char *name;
	const unsigned int drv_data_size;
	const unsigned int max_ap_intf;
	const unsigned int eeprom_size;
	const unsigned int rf_size;
	const unsigned int tx_queues;
	const unsigned int extra_tx_headroom;
	const struct data_queue_desc *rx;
	const struct data_queue_desc *tx;
	const struct data_queue_desc *bcn;
	const struct data_queue_desc *atim;
	const struct rt2x00lib_ops *lib;
	const void *drv;
	const struct ieee80211_ops *hw;
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
	const struct rt2x00debug *debugfs;
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */
};

/*
 * rt2x00 state flags
 */
enum rt2x00_state_flags {
	/*
	 * Device flags
	 */
	DEVICE_STATE_PRESENT,
	DEVICE_STATE_REGISTERED_HW,
	DEVICE_STATE_INITIALIZED,
	DEVICE_STATE_STARTED,
	DEVICE_STATE_ENABLED_RADIO,
	DEVICE_STATE_SCANNING,

	/*
	 * Driver configuration
	 */
	CONFIG_CHANNEL_HT40,
	CONFIG_POWERSAVING,
	CONFIG_HT_DISABLED,
	CONFIG_QOS_DISABLED,

	/*
	 * Mark we currently are sequentially reading TX_STA_FIFO register
	 * FIXME: this is for only rt2800usb, should go to private data
	 */
	TX_STATUS_READING,
};

/*
 * rt2x00 capability flags
 */
enum rt2x00_capability_flags {
	/*
	 * Requirements
	 */
	REQUIRE_FIRMWARE,
	REQUIRE_BEACON_GUARD,
	REQUIRE_ATIM_QUEUE,
	REQUIRE_DMA,
	REQUIRE_COPY_IV,
	REQUIRE_L2PAD,
	REQUIRE_TXSTATUS_FIFO,
	REQUIRE_TASKLET_CONTEXT,
	REQUIRE_SW_SEQNO,
	REQUIRE_HT_TX_DESC,
	REQUIRE_PS_AUTOWAKE,

	/*
	 * Capabilities
	 */
	CAPABILITY_HW_BUTTON,
	CAPABILITY_HW_CRYPTO,
	CAPABILITY_POWER_LIMIT,
	CAPABILITY_CONTROL_FILTERS,
	CAPABILITY_CONTROL_FILTER_PSPOLL,
	CAPABILITY_PRE_TBTT_INTERRUPT,
	CAPABILITY_LINK_TUNING,
	CAPABILITY_FRAME_TYPE,
	CAPABILITY_RF_SEQUENCE,
	CAPABILITY_EXTERNAL_LNA_A,
	CAPABILITY_EXTERNAL_LNA_BG,
	CAPABILITY_DOUBLE_ANTENNA,
	CAPABILITY_BT_COEXIST,
	CAPABILITY_VCO_RECALIBRATION,
};

/*
 * Interface combinations
 */
enum {
	IF_COMB_AP = 0,
	NUM_IF_COMB,
};

/*
 * rt2x00 device structure.
 */
struct rt2x00_dev {
	/*
	 * Device structure.
	 * The structure stored in here depends on the
	 * system bus (PCI or USB).
	 * When accessing this variable, the rt2x00dev_{pci,usb}
	 * macros should be used for correct typecasting.
	 */
	struct device *dev;

	/*
	 * Callback functions.
	 */
	const struct rt2x00_ops *ops;

	/*
	 * Driver data.
	 */
	void *drv_data;

	/*
	 * IEEE80211 control structure.
	 */
	struct ieee80211_hw *hw;
	struct ieee80211_supported_band bands[IEEE80211_NUM_BANDS];
	enum ieee80211_band curr_band;
	int curr_freq;

	/*
	 * If enabled, the debugfs interface structures
	 * required for deregistration of debugfs.
	 */
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
	struct rt2x00debug_intf *debugfs_intf;
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */

	/*
	 * LED structure for changing the LED status
	 * by mac8011 or the kernel.
	 */
#ifdef CONFIG_RT2X00_LIB_LEDS
	struct rt2x00_led led_radio;
	struct rt2x00_led led_assoc;
	struct rt2x00_led led_qual;
	u16 led_mcu_reg;
#endif /* CONFIG_RT2X00_LIB_LEDS */

	/*
	 * Device state flags.
	 * In these flags the current status is stored.
	 * Access to these flags should occur atomically.
	 */
	unsigned long flags;

	/*
	 * Device capabiltiy flags.
	 * In these flags the device/driver capabilities are stored.
	 * Access to these flags should occur non-atomically.
	 */
	unsigned long cap_flags;

	/*
	 * Device information, Bus IRQ and name (PCI, SoC)
	 */
	int irq;
	const char *name;

	/*
	 * Chipset identification.
	 */
	struct rt2x00_chip chip;

	/*
	 * hw capability specifications.
	 */
	struct hw_mode_spec spec;

	/*
	 * This is the default TX/RX antenna setup as indicated
	 * by the device's EEPROM.
	 */
	struct antenna_setup default_ant;

	/*
	 * Register pointers
	 * csr.base: CSR base register address. (PCI)
	 * csr.cache: CSR cache for usb_control_msg. (USB)
	 */
	union csr {
		void __iomem *base;
		void *cache;
	} csr;

	/*
	 * Mutex to protect register accesses.
	 * For PCI and USB devices it protects against concurrent indirect
	 * register access (BBP, RF, MCU) since accessing those
	 * registers require multiple calls to the CSR registers.
	 * For USB devices it also protects the csr_cache since that
	 * field is used for normal CSR access and it cannot support
	 * multiple callers simultaneously.
	 */
	struct mutex csr_mutex;

	/*
	 * Current packet filter configuration for the device.
	 * This contains all currently active FIF_* flags send
	 * to us by mac80211 during configure_filter().
	 */
	unsigned int packet_filter;

	/*
	 * Interface details:
	 *  - Open ap interface count.
	 *  - Open sta interface count.
	 *  - Association count.
	 *  - Beaconing enabled count.
	 */
	unsigned int intf_ap_count;
	unsigned int intf_sta_count;
	unsigned int intf_associated;
	unsigned int intf_beaconing;

	/*
	 * Interface combinations
	 */
	struct ieee80211_iface_limit if_limits_ap;
	struct ieee80211_iface_combination if_combinations[NUM_IF_COMB];

	/*
	 * Link quality
	 */
	struct link link;

	/*
	 * EEPROM data.
	 */
	__le16 *eeprom;

	/*
	 * Active RF register values.
	 * These are stored here so we don't need
	 * to read the rf registers and can directly
	 * use this value instead.
	 * This field should be accessed by using
	 * rt2x00_rf_read() and rt2x00_rf_write().
	 */
	u32 *rf;

	/*
	 * LNA gain
	 */
	short lna_gain;

	/*
	 * Current TX power value.
	 */
	u16 tx_power;

	/*
	 * Current retry values.
	 */
	u8 short_retry;
	u8 long_retry;

	/*
	 * Rssi <-> Dbm offset
	 */
	u8 rssi_offset;

	/*
	 * Frequency offset.
	 */
	u8 freq_offset;

	/*
	 * Association id.
	 */
	u16 aid;

	/*
	 * Beacon interval.
	 */
	u16 beacon_int;

	/**
	 * Timestamp of last received beacon
	 */
	unsigned long last_beacon;

	/*
	 * Low level statistics which will have
	 * to be kept up to date while device is running.
	 */
	struct ieee80211_low_level_stats low_level_stats;

	/**
	 * Work queue for all work which should not be placed
	 * on the mac80211 workqueue (because of dependencies
	 * between various work structures).
	 */
	struct workqueue_struct *workqueue;

	/*
	 * Scheduled work.
	 * NOTE: intf_work will use ieee80211_iterate_active_interfaces()
	 * which means it cannot be placed on the hw->workqueue
	 * due to RTNL locking requirements.
	 */
	struct work_struct intf_work;

	/**
	 * Scheduled work for TX/RX done handling (USB devices)
	 */
	struct work_struct rxdone_work;
	struct work_struct txdone_work;

	/*
	 * Powersaving work
	 */
	struct delayed_work autowakeup_work;
	struct work_struct sleep_work;

	/*
	 * Data queue arrays for RX, TX, Beacon and ATIM.
	 */
	unsigned int data_queues;
	struct data_queue *rx;
	struct data_queue *tx;
	struct data_queue *bcn;
	struct data_queue *atim;

	/*
	 * Firmware image.
	 */
	const struct firmware *fw;

	/*
	 * FIFO for storing tx status reports between isr and tasklet.
	 */
	DECLARE_KFIFO_PTR(txstatus_fifo, u32);

	/*
	 * Timer to ensure tx status reports are read (rt2800usb).
	 */
	struct hrtimer txstatus_timer;

	/*
	 * Tasklet for processing tx status reports (rt2800pci).
	 */
	struct tasklet_struct txstatus_tasklet;
	struct tasklet_struct pretbtt_tasklet;
	struct tasklet_struct tbtt_tasklet;
	struct tasklet_struct rxdone_tasklet;
	struct tasklet_struct autowake_tasklet;

	/*
	 * Used for VCO periodic calibration.
	 */
	int rf_channel;

	/*
	 * Protect the interrupt mask register.
	 */
	spinlock_t irqmask_lock;

	/*
	 * List of BlockAckReq TX entries that need driver BlockAck processing.
	 */
	struct list_head bar_list;
	spinlock_t bar_list_lock;
};

struct rt2x00_bar_list_entry {
	struct list_head list;
	struct rcu_head head;

	struct queue_entry *entry;
	int block_acked;

	/* Relevant parts of the IEEE80211 BAR header */
	__u8 ra[6];
	__u8 ta[6];
	__le16 control;
	__le16 start_seq_num;
};

/*
 * Register defines.
 * Some registers require multiple attempts before success,
 * in those cases REGISTER_BUSY_COUNT attempts should be
 * taken with a REGISTER_BUSY_DELAY interval.
 */
#define REGISTER_BUSY_COUNT	100
#define REGISTER_BUSY_DELAY	100

/*
 * Generic RF access.
 * The RF is being accessed by word index.
 */
static inline void rt2x00_rf_read(struct rt2x00_dev *rt2x00dev,
				  const unsigned int word, u32 *data)
{
	BUG_ON(word < 1 || word > rt2x00dev->ops->rf_size / sizeof(u32));
	*data = rt2x00dev->rf[word - 1];
}

static inline void rt2x00_rf_write(struct rt2x00_dev *rt2x00dev,
				   const unsigned int word, u32 data)
{
	BUG_ON(word < 1 || word > rt2x00dev->ops->rf_size / sizeof(u32));
	rt2x00dev->rf[word - 1] = data;
}

/*
 * Generic EEPROM access. The EEPROM is being accessed by word or byte index.
 */
static inline void *rt2x00_eeprom_addr(struct rt2x00_dev *rt2x00dev,
				       const unsigned int word)
{
	return (void *)&rt2x00dev->eeprom[word];
}

static inline void rt2x00_eeprom_read(struct rt2x00_dev *rt2x00dev,
				      const unsigned int word, u16 *data)
{
	*data = le16_to_cpu(rt2x00dev->eeprom[word]);
}

static inline void rt2x00_eeprom_write(struct rt2x00_dev *rt2x00dev,
				       const unsigned int word, u16 data)
{
	rt2x00dev->eeprom[word] = cpu_to_le16(data);
}

static inline u8 rt2x00_eeprom_byte(struct rt2x00_dev *rt2x00dev,
				    const unsigned int byte)
{
	return *(((u8 *)rt2x00dev->eeprom) + byte);
}

/*
 * Chipset handlers
 */
static inline void rt2x00_set_chip(struct rt2x00_dev *rt2x00dev,
				   const u16 rt, const u16 rf, const u16 rev)
{
	rt2x00dev->chip.rt = rt;
	rt2x00dev->chip.rf = rf;
	rt2x00dev->chip.rev = rev;

	rt2x00_info(rt2x00dev, "Chipset detected - rt: %04x, rf: %04x, rev: %04x\n",
		    rt2x00dev->chip.rt, rt2x00dev->chip.rf,
		    rt2x00dev->chip.rev);
}

static inline void rt2x00_set_rt(struct rt2x00_dev *rt2x00dev,
				 const u16 rt, const u16 rev)
{
	rt2x00dev->chip.rt = rt;
	rt2x00dev->chip.rev = rev;

	rt2x00_info(rt2x00dev, "RT chipset %04x, rev %04x detected\n",
		    rt2x00dev->chip.rt, rt2x00dev->chip.rev);
}

static inline void rt2x00_set_rf(struct rt2x00_dev *rt2x00dev, const u16 rf)
{
	rt2x00dev->chip.rf = rf;

	rt2x00_info(rt2x00dev, "RF chipset %04x detected\n",
		    rt2x00dev->chip.rf);
}

static inline bool rt2x00_rt(struct rt2x00_dev *rt2x00dev, const u16 rt)
{
	return (rt2x00dev->chip.rt == rt);
}

static inline bool rt2x00_rf(struct rt2x00_dev *rt2x00dev, const u16 rf)
{
	return (rt2x00dev->chip.rf == rf);
}

static inline u16 rt2x00_rev(struct rt2x00_dev *rt2x00dev)
{
	return rt2x00dev->chip.rev;
}

static inline bool rt2x00_rt_rev(struct rt2x00_dev *rt2x00dev,
				 const u16 rt, const u16 rev)
{
	return (rt2x00_rt(rt2x00dev, rt) && rt2x00_rev(rt2x00dev) == rev);
}

static inline bool rt2x00_rt_rev_lt(struct rt2x00_dev *rt2x00dev,
				    const u16 rt, const u16 rev)
{
	return (rt2x00_rt(rt2x00dev, rt) && rt2x00_rev(rt2x00dev) < rev);
}

static inline bool rt2x00_rt_rev_gte(struct rt2x00_dev *rt2x00dev,
				     const u16 rt, const u16 rev)
{
	return (rt2x00_rt(rt2x00dev, rt) && rt2x00_rev(rt2x00dev) >= rev);
}

static inline void rt2x00_set_chip_intf(struct rt2x00_dev *rt2x00dev,
					enum rt2x00_chip_intf intf)
{
	rt2x00dev->chip.intf = intf;
}

static inline bool rt2x00_intf(struct rt2x00_dev *rt2x00dev,
			       enum rt2x00_chip_intf intf)
{
	return (rt2x00dev->chip.intf == intf);
}

static inline bool rt2x00_is_pci(struct rt2x00_dev *rt2x00dev)
{
	return rt2x00_intf(rt2x00dev, RT2X00_CHIP_INTF_PCI) ||
	       rt2x00_intf(rt2x00dev, RT2X00_CHIP_INTF_PCIE);
}

static inline bool rt2x00_is_pcie(struct rt2x00_dev *rt2x00dev)
{
	return rt2x00_intf(rt2x00dev, RT2X00_CHIP_INTF_PCIE);
}

static inline bool rt2x00_is_usb(struct rt2x00_dev *rt2x00dev)
{
	return rt2x00_intf(rt2x00dev, RT2X00_CHIP_INTF_USB);
}

static inline bool rt2x00_is_soc(struct rt2x00_dev *rt2x00dev)
{
	return rt2x00_intf(rt2x00dev, RT2X00_CHIP_INTF_SOC);
}

/**
 * rt2x00queue_map_txskb - Map a skb into DMA for TX purposes.
 * @entry: Pointer to &struct queue_entry
 *
 * Returns -ENOMEM if mapping fail, 0 otherwise.
 */
int rt2x00queue_map_txskb(struct queue_entry *entry);

/**
 * rt2x00queue_unmap_skb - Unmap a skb from DMA.
 * @entry: Pointer to &struct queue_entry
 */
void rt2x00queue_unmap_skb(struct queue_entry *entry);

/**
 * rt2x00queue_get_tx_queue - Convert tx queue index to queue pointer
 * @rt2x00dev: Pointer to &struct rt2x00_dev.
 * @queue: rt2x00 queue index (see &enum data_queue_qid).
 *
 * Returns NULL for non tx queues.
 */
static inline struct data_queue *
rt2x00queue_get_tx_queue(struct rt2x00_dev *rt2x00dev,
			 const enum data_queue_qid queue)
{
	if (queue < rt2x00dev->ops->tx_queues && rt2x00dev->tx)
		return &rt2x00dev->tx[queue];

	if (queue == QID_ATIM)
		return rt2x00dev->atim;

	return NULL;
}

/**
 * rt2x00queue_get_entry - Get queue entry where the given index points to.
 * @queue: Pointer to &struct data_queue from where we obtain the entry.
 * @index: Index identifier for obtaining the correct index.
 */
struct queue_entry *rt2x00queue_get_entry(struct data_queue *queue,
					  enum queue_index index);

/**
 * rt2x00queue_pause_queue - Pause a data queue
 * @queue: Pointer to &struct data_queue.
 *
 * This function will pause the data queue locally, preventing
 * new frames to be added to the queue (while the hardware is
 * still allowed to run).
 */
void rt2x00queue_pause_queue(struct data_queue *queue);

/**
 * rt2x00queue_unpause_queue - unpause a data queue
 * @queue: Pointer to &struct data_queue.
 *
 * This function will unpause the data queue locally, allowing
 * new frames to be added to the queue again.
 */
void rt2x00queue_unpause_queue(struct data_queue *queue);

/**
 * rt2x00queue_start_queue - Start a data queue
 * @queue: Pointer to &struct data_queue.
 *
 * This function will start handling all pending frames in the queue.
 */
void rt2x00queue_start_queue(struct data_queue *queue);

/**
 * rt2x00queue_stop_queue - Halt a data queue
 * @queue: Pointer to &struct data_queue.
 *
 * This function will stop all pending frames in the queue.
 */
void rt2x00queue_stop_queue(struct data_queue *queue);

/**
 * rt2x00queue_flush_queue - Flush a data queue
 * @queue: Pointer to &struct data_queue.
 * @drop: True to drop all pending frames.
 *
 * This function will flush the queue. After this call
 * the queue is guaranteed to be empty.
 */
void rt2x00queue_flush_queue(struct data_queue *queue, bool drop);

/**
 * rt2x00queue_start_queues - Start all data queues
 * @rt2x00dev: Pointer to &struct rt2x00_dev.
 *
 * This function will loop through all available queues to start them
 */
void rt2x00queue_start_queues(struct rt2x00_dev *rt2x00dev);

/**
 * rt2x00queue_stop_queues - Halt all data queues
 * @rt2x00dev: Pointer to &struct rt2x00_dev.
 *
 * This function will loop through all available queues to stop
 * any pending frames.
 */
void rt2x00queue_stop_queues(struct rt2x00_dev *rt2x00dev);

/**
 * rt2x00queue_flush_queues - Flush all data queues
 * @rt2x00dev: Pointer to &struct rt2x00_dev.
 * @drop: True to drop all pending frames.
 *
 * This function will loop through all available queues to flush
 * any pending frames.
 */
void rt2x00queue_flush_queues(struct rt2x00_dev *rt2x00dev, bool drop);

/*
 * Debugfs handlers.
 */
/**
 * rt2x00debug_dump_frame - Dump a frame to userspace through debugfs.
 * @rt2x00dev: Pointer to &struct rt2x00_dev.
 * @type: The type of frame that is being dumped.
 * @skb: The skb containing the frame to be dumped.
 */
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
void rt2x00debug_dump_frame(struct rt2x00_dev *rt2x00dev,
			    enum rt2x00_dump_type type, struct sk_buff *skb);
#else
static inline void rt2x00debug_dump_frame(struct rt2x00_dev *rt2x00dev,
					  enum rt2x00_dump_type type,
					  struct sk_buff *skb)
{
}
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */

/*
 * Utility functions.
 */
u32 rt2x00lib_get_bssidx(struct rt2x00_dev *rt2x00dev,
			 struct ieee80211_vif *vif);

/*
 * Interrupt context handlers.
 */
void rt2x00lib_beacondone(struct rt2x00_dev *rt2x00dev);
void rt2x00lib_pretbtt(struct rt2x00_dev *rt2x00dev);
void rt2x00lib_dmastart(struct queue_entry *entry);
void rt2x00lib_dmadone(struct queue_entry *entry);
void rt2x00lib_txdone(struct queue_entry *entry,
		      struct txdone_entry_desc *txdesc);
void rt2x00lib_txdone_noinfo(struct queue_entry *entry, u32 status);
void rt2x00lib_rxdone(struct queue_entry *entry, gfp_t gfp);

/*
 * mac80211 handlers.
 */
void rt2x00mac_tx(struct ieee80211_hw *hw,
		  struct ieee80211_tx_control *control,
		  struct sk_buff *skb);
int rt2x00mac_start(struct ieee80211_hw *hw);
void rt2x00mac_stop(struct ieee80211_hw *hw);
int rt2x00mac_add_interface(struct ieee80211_hw *hw,
			    struct ieee80211_vif *vif);
void rt2x00mac_remove_interface(struct ieee80211_hw *hw,
				struct ieee80211_vif *vif);
int rt2x00mac_config(struct ieee80211_hw *hw, u32 changed);
void rt2x00mac_configure_filter(struct ieee80211_hw *hw,
				unsigned int changed_flags,
				unsigned int *total_flags,
				u64 multicast);
int rt2x00mac_set_tim(struct ieee80211_hw *hw, struct ieee80211_sta *sta,
		      bool set);
#ifdef CONFIG_RT2X00_LIB_CRYPTO
int rt2x00mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
		      struct ieee80211_vif *vif, struct ieee80211_sta *sta,
		      struct ieee80211_key_conf *key);
#else
#define rt2x00mac_set_key	NULL
#endif /* CONFIG_RT2X00_LIB_CRYPTO */
int rt2x00mac_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
		      struct ieee80211_sta *sta);
int rt2x00mac_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
			 struct ieee80211_sta *sta);
void rt2x00mac_sw_scan_start(struct ieee80211_hw *hw);
void rt2x00mac_sw_scan_complete(struct ieee80211_hw *hw);
int rt2x00mac_get_stats(struct ieee80211_hw *hw,
			struct ieee80211_low_level_stats *stats);
void rt2x00mac_bss_info_changed(struct ieee80211_hw *hw,
				struct ieee80211_vif *vif,
				struct ieee80211_bss_conf *bss_conf,
				u32 changes);
int rt2x00mac_conf_tx(struct ieee80211_hw *hw,
		      struct ieee80211_vif *vif, u16 queue,
		      const struct ieee80211_tx_queue_params *params);
void rt2x00mac_rfkill_poll(struct ieee80211_hw *hw);
void rt2x00mac_flush(struct ieee80211_hw *hw, u32 queues, bool drop);
int rt2x00mac_set_antenna(struct ieee80211_hw *hw, u32 tx_ant, u32 rx_ant);
int rt2x00mac_get_antenna(struct ieee80211_hw *hw, u32 *tx_ant, u32 *rx_ant);
void rt2x00mac_get_ringparam(struct ieee80211_hw *hw,
			     u32 *tx, u32 *tx_max, u32 *rx, u32 *rx_max);
bool rt2x00mac_tx_frames_pending(struct ieee80211_hw *hw);

/*
 * Driver allocation handlers.
 */
int rt2x00lib_probe_dev(struct rt2x00_dev *rt2x00dev);
void rt2x00lib_remove_dev(struct rt2x00_dev *rt2x00dev);
#ifdef CONFIG_PM
int rt2x00lib_suspend(struct rt2x00_dev *rt2x00dev, pm_message_t state);
int rt2x00lib_resume(struct rt2x00_dev *rt2x00dev);
#endif /* CONFIG_PM */

#endif /* RT2X00_H */


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/timestamp_synopsis.hpp"

namespace vast {

timestamp_synopsis::timestamp_synopsis(vast::type x)
  : min_max_synopsis<timestamp>{std::move(x), timestamp::max(),
                                timestamp::min()} {
  // nop
}

bool timestamp_synopsis::equals(const synopsis& other) const noexcept {
  if (typeid(other) != typeid(timestamp_synopsis))
    return false;
  auto& dref = static_cast<const timestamp_synopsis&>(other);
  return type() == dref.type() && min() == dref.min() && max() == dref.max();
}

} // namespace vast


text:
class BannersController < ApplicationController
  before_action :set_banner, only: [:show, :edit, :update, :destroy]

  # GET /banners
  # GET /banners.json
  def index
    @banners = Banner.all
  end

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

  def click
    @banner = Banner.find(params[:id])
    @banner.hits = @banner.hits + 1
    @banner.save
  end

  # GET /banners/new
  def new
    @banner = Banner.new
  end

  # GET /banners/1/edit
  def edit
  end

  # POST /banners
  # POST /banners.json
  def create
    @banner = Banner.new(banner_params)

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

  # PATCH/PUT /banners/1
  # PATCH/PUT /banners/1.json
  def update
    respond_to do |format|
      if @banner.update(banner_params)
        format.html { redirect_to @banner, notice: 'Banner was successfully updated.' }
        format.json { render :show, status: :ok, location: @banner }
      else
        format.html { render :edit }
        format.json { render json: @banner.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /banners/1
  # DELETE /banners/1.json
  def destroy
    @banner.destroy
    respond_to do |format|
      format.html { redirect_to banners_url, notice: 'Banner was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_banner
      @banner = Banner.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def banner_params
      params.require(:banner).permit(:alt, :link, :impressions, :hits, :image)
    end
end


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Application\Model;

/**
 *
 * @author Alexander
 */
interface AuthorSummaryInterface
{
    /**
     * @return int
     */
    function getSiteId();

    /**
     * @return int
     */
    function getUserId();

    /**
     * @return Application\Model\UserInterface
     */
    function getUser();

    /**
     * @return int
     */
    function getPageCount();

    /**
     * @return int
     */
    function getOriginalCount();

    /**
     * @return int
     */
    function getTranslationCount();

    /**
     * @return int
     */
    function getSCPCount();

    /**
     * @return int
     */
    function getTaleCount();

    /**
     * @return int
     */
    function getJokeCount();

    /**
     * @return int
     */
    function getGOICount();

    /**
     * @return int
     */
    function getTotalRating();

    /**
     * @return int
     */
    function getAverageRating();

    /**
     * @return int
     */
    function getHighestRating();
}


text:
 -- Lua client for https://github.com/ideawu/ssdb
 -- Copyright (c) 2015 Eleme, Inc. Chao Wang <hit9@icloud.com>

local spp = require 'resty.ssdb.spp_lua.spp_lua'

-- Lua 5.1 unpack
-- Lua 5.2+ table.unpack
local unpack = unpack or table.unpack
local tlen = rawlen or table.getn

-- conversions from buffer to lua type
local conversions = {
    number = function(t)
        return tonumber(t[1])
    end,

    string = function(t)
        return t[1]
    end,

    boolean = function(t)
        return tonumber(t[1]) ~= 0
    end,

    table = function(t)
        return t
    end
}

local commands = {
    set             = 'number',
    setx            = 'number',
    expire          = 'number',
    ttl             = 'number',
    setnx           = 'number',
    get             = 'string',
    getset          = 'string',
    del             = 'number',
    incr            = 'number',
    exists          = 'boolean',
    getbit          = 'number',
    setbit          = 'number',
    countbit        = 'number',
    substr          = 'string',
    strlen          = 'number',
    keys            = 'table',
    scan            = 'table',
    rscan           = 'table',
    multi_set       = 'number',
    multi_get       = 'table',
    multi_del       = 'number',
    hset            = 'number',
    hget            = 'string',
    hdel            = 'number',
    hincr           = 'number',
    hexists         = 'boolean',
    hsize           = 'number',
    hlist           = 'table',
    hrlist          = 'table',
    hkeys           = 'table',
    hgetall         = 'table',
    hscan           = 'table',
    hrscan          = 'table',
    hclear          = 'number',
    multi_hset      = 'number',
    multi_hget      = 'table',
    multi_hdel      = 'number',
    zset            = 'number',
    zget            = 'number',
    zdel            = 'number',
    zincr           = 'number',
    zexists         = 'boolean',
    zsize           = 'number',
    zlist           = 'table',
    zrlist          = 'table',
    zkeys           = 'table',
    zscan           = 'table',
    zrscan          = 'table',
    zrank           = 'number',
    zrrank          = 'number',
    zrange          = 'table',
    zrrange         = 'table',
    zclear          = 'number',
    zcount          = 'number',
    zsum            = 'number',
    zavg            = 'number',
    zremrangebyrank = 'number',
    zremrangebyscore= 'number',
    multi_zset      = 'number',
    multi_zget      = 'table',
    multi_zdel      = 'number',
    qsize           = 'number',
    qclear          = 'number',
    qfront          = 'string',
    qback           = 'string',
    qget            = 'string',
    qslice          = 'table',
    qpush           = 'number',
    qpush_front     = 'number',
    qpush_back      = 'number',
    qpop            = 'string',
    qpop_front      = 'string',
    qpop_back       = 'string',
    qlist           = 'table',
    qrlist          = 'table',
    dbsize          = 'number',
    info            = 'table',
    auth            = 'boolean'
}

-- Conn
local Conn = {}
Conn.__index = Conn

function Conn.new(options)
    local self = setmetatable({}, Conn)
    local options = options or {}

    self.port = options.port or 8888
    self.host = options.host or '127.0.0.1'
    self.auth = options.auth
    self.timeout = options.timeout or 1000

    self.sock = nil
    self.cmds = {}
    self.parser = spp.new()
    return self
end

function Conn.setkeepalive(self, ...)
    if not self.sock then
        return nil, 'socket not initialized'
    end
    return self.sock:setkeepalive(...)
end

function Conn.connect(self)
    local err

    self.sock, err = ngx.socket.tcp()

    if err and not sock then
        return sock, err
    end
    self.sock:settimeout(self.timeout)
    return self.sock:connect(self.host, self.port)
end

function Conn.close(self)
    local sock = self.sock
    self.parser:clear()
    self.sock = nil
    return sock:close()
end

function Conn.encode(self, args)
    local args = args or {}
    local reqs = {}

    for _, arg in pairs(args) do
        local len = string.len(tostring(arg))
        local req = string.format('%s\n%s\n', len, arg)
        table.insert(reqs, req)
    end
    table.insert(reqs, '\n')
    return table.concat(reqs)
end

function Conn.send(self, cmds)
    local reqs = {}
    for _, cmd in pairs(cmds) do
        table.insert(reqs, self:encode(cmd))
    end
    return self.sock:send(table.concat(reqs))
end

function Conn.recv(self, len)
    local ress = {}
    while tlen(ress) < len do
        while true do
            local line, err = self.sock:receive()
            if not line then
                if err == 'timeout' then
                    self:close()
                end
                return line, err
            end
            self.parser:feed(line .. '\n')
            if line == '' then
                break
            end
        end
        local res = self.parser:get()
        if res then
            table.insert(ress, res)
        end
    end
    return ress, err
end

function Conn.auth_(self, auth)
    local cmds = {{'auth', auth}}
    local bytes, err = self:send(cmds)
    if not bytes then
        return bytes, err
    end

    local ress, err = self:recv(tlen(cmds))
    if not ress then
        return ress, err
    end

    local list = self:cast(cmds, ress)
    assert(tlen(list) == 1)
    return unpack(list[1])
end

function Conn.cast(self, cmds, ress)
    local list = {}
    for idx, res in pairs(ress) do
        local cmd = cmds[idx]
        local status = table.remove(res, 1)
        local val, err
        if status == 'ok' then
            local type = commands[cmd[1]]
            val = conversions[type](res)
        else
            err = status
        end
        table.insert(list, {val, err})
    end
    return list
end

function Conn.cmd_push(self, name, args)
    local cmd = {name}
    for _, v in pairs(args) do
        table.insert(cmd, v)
    end
    return table.insert(self.cmds, cmd)
end

function Conn.cmd_clear(self)
    while tlen(self.cmds) > 0 do
        table.remove(self.cmds, 1)
    end
end

function Conn.request(self)
    -- lazy connect
    if not self.sock then
        local ok, err = self:connect()
        if not ok then
            return ok, err
        end

        -- make auth
        if self.auth then
            local ok, err = self:auth_(self.auth)
            if not ok then
                return ok, err
            end
        end
    end

    -- send request
    local bytes, err = self:send(self.cmds)
    if not bytes then
        return bytes, err
    end

    -- recv responses
    local ress, err = self:recv(tlen(self.cmds))
    if not ress then
        return ress, err
    end

    -- build values
    local list = self:cast(self.cmds, ress)
    self:cmd_clear()
    return list
end

-- Client
local Client = {}
Client.__index = Client

function Client.new(options)
    local self = setmetatable({}, Client)
    self.conn = Conn.new(options)
    self._pipeline_mode = false

    -- make methods
    for name, _ in pairs(commands) do
        Client[name] = function(self, ...)
            self.conn:cmd_push(name, {...})
            if not self._pipeline_mode then
                local list, err = self.conn:request()
                if not list then
                    return list, err
                end
                return unpack(list[1])
            end
        end
    end
    return self
end

function Client.setkeepalive(self, ...)
    return self.conn:setkeepalive(...)
end

function Client.connect(self, ...)
    return self.conn:connect(...)
end

function Client.close(self)
    return self.conn:close()
end

function Client.start_pipeline(self)
    self._pipeline_mode = true
end

function Client.commit_pipeline(self)
    self._pipeline_mode = false
    return self.conn:request()
end

function Client.cancel_pipeline(self)
    for idx, _ in pairs(self.conn.cmds) do
        self.conn.cmds[idx] = nil
    end
    self._pipeline_mode = false
end

-- exports
return {
    __version__ = '0.0.4',
    newclient = function(options)
        return Client.new(options)
    end
}


text:
// ReSharper disable All

namespace OpenTl.Schema
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0x561bc879)]
	public sealed class TContactBlocked : IContactBlocked
	{
       [SerializationOrder(0)]
       public int UserId {get; set;}

       [SerializationOrder(1)]
       public int Date {get; set;}

	}
}