text:
static NSString *const kExpandableCloseButtonImageName = @"MPCloseButtonX_SKZ";
static NSString *const kMraidURLScheme = @"mraid";
static NSString *const kMoPubURLScheme = @"mopub";
static NSString *const kMoPubPrecacheCompleteHost = @"precacheComplete";

@interface MRAdViewSKZ ()

@property (nonatomic, strong) NSMutableData *data;
@property (nonatomic, strong) MPAdDestinationDisplayAgentSKZ *destinationDisplayAgent;
@property (nonatomic, strong) MRCalendarManagerSKZ *calendarManager;
@property (nonatomic, strong) MRPictureManagerSKZ *pictureManager;
@property (nonatomic, strong) MRVideoPlayerManagerSKZ *videoPlayerManager;
@property (nonatomic, strong) MRJavaScriptEventEmitterSKZ *jsEventEmitter;
@property (nonatomic, strong) id<MPAdAlertManagerProtocolSKZ> adAlertManager;

- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;

- (NSMutableString *)HTMLWithJavaScriptBridge:(NSString *)HTML;
- (BOOL)HTMLStringIsMRAIDFragment:(NSString *)string;
- (NSMutableString *)fullHTMLFromMRAIDFragment:(NSString *)fragment;
- (NSString *)MRAIDScriptPath;

- (void)layoutCloseButton;
- (void)initializeJavascriptState;

// Delegate callback methods wrapped with -respondsToSelector: checks.
- (void)adDidLoad;
- (void)adDidFailToLoad;
- (void)adWillClose;
- (void)adDidClose;
- (void)adDidRequestCustomCloseEnabled:(BOOL)enabled;
- (void)adWillExpandToFrame:(CGRect)frame;
- (void)adDidExpandToFrame:(CGRect)frame;
- (void)adWillPresentModalView;
- (void)adDidDismissModalView;
- (void)appShouldSuspend;
- (void)appShouldResume;
- (void)adViewableDidChange:(BOOL)viewable;

@end

@implementation MRAdViewSKZ

@synthesize delegate = _delegate;
@synthesize usesCustomCloseButton = _usesCustomCloseButton;
@synthesize expanded = _expanded;
@synthesize data = _data;
@synthesize displayController = _displayController;
@synthesize destinationDisplayAgent = _destinationDisplayAgent;
@synthesize calendarManager = _calendarManager;
@synthesize pictureManager = _pictureManager;
@synthesize videoPlayerManager = _videoPlayerManager;
@synthesize jsEventEmitter = _jsEventEmitter;
@synthesize adAlertManager = _adAlertManager;
@synthesize adType = _adType;

- (id)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame
               allowsExpansion:YES
              closeButtonStyle:MRAdViewCloseButtonStyleAdControlled
                 placementType:MRAdViewPlacementTypeInline];
}

- (id)initWithFrame:(CGRect)frame allowsExpansion:(BOOL)expansion
   closeButtonStyle:(MRAdViewCloseButtonStyle)style placementType:(MRAdViewPlacementType)type
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.opaque = NO;

        _webView = [[MPInstanceProviderSKZ sharedProvider] buildUIWebViewWithFrame:frame];
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
                UIViewAutoresizingFlexibleHeight;
        _webView.backgroundColor = [UIColor clearColor];
        _webView.clipsToBounds = YES;
        _webView.delegate = self;
        _webView.opaque = NO;
        [_webView mp_setScrollableSKZ:NO];

        if ([_webView respondsToSelector:@selector(setAllowsInlineMediaPlayback:)]) {
            [_webView setAllowsInlineMediaPlayback:YES];
        }

        if ([_webView respondsToSelector:@selector(setMediaPlaybackRequiresUserAction:)]) {
            [_webView setMediaPlaybackRequiresUserAction:NO];
        }

        [self addSubview:_webView];

        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeButton.frame = CGRectMake(0, 0, 50, 50);
        UIImage *image = [UIImage imageFromResource:kExpandableCloseButtonImageName];
        [_closeButton setImage:image forState:UIControlStateNormal];

        _allowsExpansion = expansion;
        _closeButtonStyle = style;
        _placementType = type;

        _displayController = [[MRAdViewDisplayControllerSKZ alloc] initWithAdView:self
                                                               allowsExpansion:expansion
                                                              closeButtonStyle:style
                                                               jsEventEmitter:[[MPInstanceProviderSKZ sharedProvider] buildMRJavaScriptEventEmitterWithWebView:_webView]];

        [_closeButton addTarget:_displayController
                         action:@selector(closeButtonPressed)
               forControlEvents:UIControlEventTouchUpInside];

        _destinationDisplayAgent = [[MPInstanceProviderSKZ sharedProvider]
                                    buildMPAdDestinationDisplayAgentWithDelegate:self];
        _calendarManager = [[MPInstanceProviderSKZ sharedProvider]
                             buildMRCalendarManagerWithDelegate:self];
        _pictureManager = [[MPInstanceProviderSKZ sharedProvider]
                             buildMRPictureManagerWithDelegate:self];
        _videoPlayerManager = [[MPInstanceProviderSKZ sharedProvider]
                                buildMRVideoPlayerManagerWithDelegate:self];
        _jsEventEmitter = [[MPInstanceProviderSKZ sharedProvider]
                             buildMRJavaScriptEventEmitterWithWebView:_webView];

        self.adAlertManager = [[MPInstanceProviderSKZ sharedProvider] buildMPAdAlertManagerWithDelegate:self];

        self.adType = MRAdViewAdTypeDefault;
    }
    return self;
}

- (void)dealloc
{
    _webView.delegate = nil;
    [_destinationDisplayAgent setDelegate:nil];
    [_calendarManager setDelegate:nil];
    [_pictureManager setDelegate:nil];
    [_videoPlayerManager setDelegate:nil];
    self.adAlertManager.targetAdView = nil;
    self.adAlertManager.delegate = nil;
}

#pragma mark - <MPAdAlertManagerDelegate>

- (UIViewController *)viewControllerForPresentingMailVC
{
    return [self.delegate viewControllerForPresentingModalView];
}

- (void)adAlertManagerDidTriggerAlert:(MPAdAlertManagerSKZ *)manager
{
    [self.adAlertManager processAdAlertOnce];
}

#pragma mark - Public

- (void)setDelegate:(id<MRAdViewDelegateSKZ>)delegate
{
    [_closeButton removeTarget:delegate
                        action:NULL
              forControlEvents:UIControlEventTouchUpInside];

    _delegate = delegate;

    [_closeButton addTarget:_delegate
                     action:@selector(closeButtonPressed)
           forControlEvents:UIControlEventTouchUpInside];
}

- (void)setExpanded:(BOOL)expanded
{
    _expanded = expanded;
    [self layoutCloseButton];
}

- (void)setUsesCustomCloseButton:(BOOL)shouldUseCustomCloseButton
{
    _usesCustomCloseButton = shouldUseCustomCloseButton;
    [self layoutCloseButton];
}

- (BOOL)isViewable
{
    return MPViewIsVisible(self);
}

- (void)loadCreativeFromURL:(NSURL *)url
{
    [_displayController revertViewToDefaultState];
    _isLoading = YES;
    [self loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)loadCreativeWithHTMLString:(NSString *)html baseURL:(NSURL *)url
{
    [_displayController revertViewToDefaultState];
    _isLoading = YES;
    [self loadHTMLString:html baseURL:url];
}

- (void)rotateToOrientation:(UIInterfaceOrientation)newOrientation
{
    [_displayController rotateToOrientation:newOrientation];
}

- (NSString *)placementType
{
    switch (_placementType) {
        case MRAdViewPlacementTypeInline:
            return @"inline";
        case MRAdViewPlacementTypeInterstitial:
            return @"interstitial";
        default:
            return @"unknown";
    }
}

- (void)handleMRAIDOpenCallForURL:(NSURL *)URL
{
    [self.destinationDisplayAgent displayDestinationForURL:URL];
}

#pragma mark - Private

- (void)initAdAlertManager
{
    self.adAlertManager.adConfiguration = [self.delegate adConfiguration];
    self.adAlertManager.adUnitId = [self.delegate adUnitId];
    self.adAlertManager.targetAdView = self;
    self.adAlertManager.location = [self.delegate location];
    [self.adAlertManager beginMonitoringAlerts];
}

- (void)loadRequest:(NSURLRequest *)request
{
    [self initAdAlertManager];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    if (connection) {
        self.data = [NSMutableData data];
    }
}

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
{
    [self initAdAlertManager];

    // Bail out if we can't locate mraid.js.
    if (![self MRAIDScriptPath]) {
        [self adDidFailToLoad];
        return;
    }

    NSString *HTML = [self HTMLWithJavaScriptBridge:string];
    if (HTML) {
        [_webView disableJavaScriptDialogsSKZ];
        [_webView loadHTMLString:HTML baseURL:baseURL];
    }
}

- (NSMutableString *)HTMLWithJavaScriptBridge:(NSString *)HTML
{
    NSMutableString *resultHTML = [HTML mutableCopy];

    if ([self HTMLStringIsMRAIDFragment:HTML]) {
        MPLogDebug(@"Fragment detected: converting to full payload.");
        resultHTML = [self fullHTMLFromMRAIDFragment:resultHTML];
    }

    NSURL *MRAIDScriptURL = [NSURL fileURLWithPath:[self MRAIDScriptPath]];

    NSRange headTagRange = [resultHTML rangeOfString:@""];
    NSString *MRAIDScriptTag = [NSString stringWithFormat:@"",
                                [MRAIDScriptURL absoluteString]];
    [resultHTML insertString:MRAIDScriptTag atIndex:headTagRange.location + headTagRange.length];

    return resultHTML;
}

- (BOOL)HTMLStringIsMRAIDFragment:(NSString *)string
{
    return ([string rangeOfString:@""].location == NSNotFound ||
            [string rangeOfString:@""].location == NSNotFound);
}

- (NSMutableString *)fullHTMLFromMRAIDFragment:(NSString *)fragment
{
    NSMutableString *result = [fragment mutableCopy];

    NSString *prepend = @""
        @"<meta name='viewport' content='user-scalable=no; initial-scale=1.0'/>"
        @""
        @"";
    [result insertString:prepend atIndex:0];
    [result appendString:@""];

    return result;
}

- (NSString *)MRAIDScriptPath
{
    MRBundleManagerSKZ *bundleManager = [[MPInstanceProviderSKZ sharedProvider] buildMRBundleManager];
    return [bundleManager mraidPath];
}

- (void)layoutCloseButton
{
    if (!_usesCustomCloseButton) {
        CGRect frame = _closeButton.frame;
        frame.origin.x = CGRectGetWidth(CGRectApplyAffineTransform(self.frame, self.transform)) -
                _closeButton.frame.size.width;
        _closeButton.frame = frame;
        _closeButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [self addSubview:_closeButton];
        [self bringSubviewToFront:_closeButton];
    } else {
        [_closeButton removeFromSuperview];
    }
}

- (void)initializeJavascriptState
{
    MPLogDebug(@"Injecting initial JavaScript state.");
    [_displayController initializeJavascriptStateWithViewProperties:@[
            [MRPlacementTypePropertySKZ propertyWithType:_placementType],
            [MRSupportsPropertySKZ defaultProperty]]];
}

- (void)handleCommandWithURL:(NSURL *)URL
{
    NSString *command = URL.host;
    NSDictionary *parameters = MPDictionaryFromQueryString(URL.query);
    BOOL success = YES;

    if ([command isEqualToString:@"createCalendarEvent"]) {
        [self.calendarManager createCalendarEventWithParameters:parameters];
    } else if ([command isEqualToString:@"playVideo"]) {
        [self.videoPlayerManager playVideo:parameters];
    } else if ([command isEqualToString:@"storePicture"]) {
        [self.pictureManager storePicture:parameters];
    } else {
        // TODO: Refactor legacy MRAID command handling.
        MRCommandSKZ *cmd = [MRCommandSKZ commandForString:command];
        cmd.parameters = parameters;
        cmd.view = self;
        success = [cmd execute];
    }

    [self.jsEventEmitter fireNativeCommandCompleteEvent:command];

    if (!success) {
        MPLogDebug(@"Unknown command: %@", command);
        [self.jsEventEmitter fireErrorEventForAction:command withMessage:@"Specified command is not implemented."];
    }
}

- (void)performActionForMoPubSpecificURL:(NSURL *)url
{
    MPLogDebug(@"MRAdView - loading MoPub URL: %@", url);
    NSString *host = [url host];
    if ([host isEqualToString:kMoPubPrecacheCompleteHost] && self.adType == MRAdViewAdTypePreCached) {
        [self adDidLoad];
    } else {
        MPLogWarn(@"MRAdView - unsupported MoPub URL: %@", [url absoluteString]);
    }
}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.data setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self adDidFailToLoad];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
    [self loadHTMLString:str baseURL:nil];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    NSMutableString *urlString = [NSMutableString stringWithString:[url absoluteString]];
    NSString *scheme = url.scheme;

    if ([scheme isEqualToString:kMraidURLScheme]) {
        MPLogDebug(@"Trying to process command: %@", urlString);
        [self handleCommandWithURL:url];
        return NO;
    } else if ([scheme isEqualToString:kMoPubURLScheme]) {
        [self performActionForMoPubSpecificURL:url];
        return NO;
    } else if ([scheme isEqualToString:@"ios-log"]) {
        [urlString replaceOccurrencesOfString:@"%20"
                                   withString:@" "
                                      options:NSLiteralSearch
                                        range:NSMakeRange(0, [urlString length])];
        MPLogDebug(@"Web console: %@", urlString);
        return NO;
    }

    if (!_isLoading && (navigationType == UIWebViewNavigationTypeOther ||
            navigationType == UIWebViewNavigationTypeLinkClicked)) {
        BOOL iframe = ![request.URL isEqual:request.mainDocumentURL];
        if (iframe) return YES;

        [self.destinationDisplayAgent displayDestinationForURL:url];
        return NO;
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [_webView disableJavaScriptDialogsSKZ];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (_isLoading) {
        _isLoading = NO;
        [self initializeJavascriptState];

        switch (self.adType) {
            case MRAdViewAdTypeDefault:
                [self adDidLoad];
                break;
            case MRAdViewAdTypePreCached:
                // wait for the ad to tell us it's done precaching before we notify the publisher
                break;
            default:
                break;
        }
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (error.code == NSURLErrorCancelled) return;
    _isLoading = NO;
    [self adDidFailToLoad];
}

#pragma mark - <MPAdDestinationDisplayAgentDelegate>

- (UIViewController *)viewControllerForPresentingModalView
{
    return [self.delegate viewControllerForPresentingModalView];
}

- (void)displayAgentWillPresentModal
{
    [self adWillPresentModalView];
}

- (void)displayAgentDidDismissModal
{
    [self adDidDismissModalView];
}

- (void)displayAgentWillLeaveApplication
{
    // Do nothing.
}

#pragma mark - <MRCalendarManagerDelegate>

- (void)calendarManager:(MRCalendarManagerSKZ *)manager
        didFailToCreateCalendarEventWithErrorMessage:(NSString *)message
{
    [self.jsEventEmitter fireErrorEventForAction:@"createCalendarEvent"
                                      withMessage:message];
}

- (void)calendarManagerWillPresentCalendarEditor:(MRCalendarManagerSKZ *)manager
{
    [self adWillPresentModalView];
}

- (void)calendarManagerDidDismissCalendarEditor:(MRCalendarManagerSKZ *)manager
{
    [self adDidDismissModalView];
}

- (UIViewController *)viewControllerForPresentingCalendarEditor
{
    return [self viewControllerForPresentingModalView];
}

#pragma mark - <MRPictureManagerDelegate>

- (void)pictureManager:(MRPictureManagerSKZ *)manager didFailToStorePictureWithErrorMessage:(NSString *)message
{
    [self.jsEventEmitter fireErrorEventForAction:@"storePicture"
                                     withMessage:message];
}

#pragma mark - <MRVideoPlayerManagerDelegate>

- (void)videoPlayerManager:(MRVideoPlayerManagerSKZ *)manager didFailToPlayVideoWithErrorMessage:(NSString *)message
{
    [self.jsEventEmitter fireErrorEventForAction:@"playVideo"
                                     withMessage:message];
}

- (void)videoPlayerManagerWillPresentVideo:(MRVideoPlayerManagerSKZ *)manager
{
    [self adWillPresentModalView];
}

- (void)videoPlayerManagerDidDismissVideo:(MRVideoPlayerManagerSKZ *)manager
{
    [self adDidDismissModalView];
}

- (UIViewController *)viewControllerForPresentingVideoPlayer
{
    return [self viewControllerForPresentingModalView];
}

#pragma mark - Delegation Wrappers

- (void)adDidLoad
{
    if ([self.delegate respondsToSelector:@selector(adDidLoad:)]) {
        [self.delegate adDidLoad:self];
    }
}

- (void)adDidFailToLoad
{
    if ([self.delegate respondsToSelector:@selector(adDidFailToLoad:)]) {
        [self.delegate adDidFailToLoad:self];
    }
}

- (void)adWillClose
{
    if ([self.delegate respondsToSelector:@selector(adWillClose:)]) {
        [self.delegate adWillClose:self];
    }
}

- (void)adDidClose
{
    if ([self.delegate respondsToSelector:@selector(adDidClose:)]) {
        [self.delegate adDidClose:self];
    }
}

- (void)adWillExpandToFrame:(CGRect)frame
{
    if ([self.delegate respondsToSelector:@selector(willExpandAd:toFrame:)]) {
        [self.delegate willExpandAd:self toFrame:frame];
    }
}

- (void)adDidExpandToFrame:(CGRect)frame
{
    if ([self.delegate respondsToSelector:@selector(didExpandAd:toFrame:)]) {
        [self.delegate didExpandAd:self toFrame:frame];
    }
}

- (void)adDidRequestCustomCloseEnabled:(BOOL)enabled
{
    if ([self.delegate respondsToSelector:@selector(ad:didRequestCustomCloseEnabled:)]) {
        [self.delegate ad:self didRequestCustomCloseEnabled:enabled];
    }
}

- (void)adWillPresentModalView
{
    [_displayController additionalModalViewWillPresent];

    _modalViewCount++;
    if (_modalViewCount == 1) [self appShouldSuspend];
}

- (void)adDidDismissModalView
{
    [_displayController additionalModalViewDidDismiss];

    _modalViewCount--;
    if (_modalViewCount == 0) [self appShouldResume];
}

- (void)appShouldSuspend
{
    if ([self.delegate respondsToSelector:@selector(appShouldSuspendForAd:)]) {
        [self.delegate appShouldSuspendForAd:self];
    }
}

- (void)appShouldResume
{
    if ([self.delegate respondsToSelector:@selector(appShouldResumeFromAd:)]) {
        [self.delegate appShouldResumeFromAd:self];
    }
}

- (void)adViewableDidChange:(BOOL)viewable
{
    [self.jsEventEmitter fireChangeEventForProperty:[MRViewablePropertySKZ propertyWithViewable:viewable]];
}

@end


text:
.. _ref-event-sourced-actors:

Event-sourced actors
--------------------

An introduction to event-sourced actors is already given in sections :ref:`overview`, :ref:`architecture` and the :ref:`user-guide`. Applications use event-sourced actors for writing events to an event log and for maintaining in-memory write models on the command side (C) of a CQRS_ application. Event-sourced actors distinguish command processing from event processing. They must extend the EventsourcedActor_ trait and implement a :ref:`command-handler` and an :ref:`event-handler`.

.. _command-handler:

Command handler
~~~~~~~~~~~~~~~

A command handler is partial function of type ``PartialFunction[Any, Unit]`` for which a type alias ``Receive`` exists. It can be defined by implementing ``onCommand``:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: command-handler

Messages sent by an application to an event-sourced actor are received by its command handler. Usually, a command handler first validates a command, then derives one or more events from it, persists these events with ``persist`` and replies with the persistence result. The ``persist`` method has the following signature\ [#]_:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: persist-signature

The ``persist`` method can be called one ore more times per received command. Calling ``persist`` does not immediately write events to the event log. Instead, events from ``persist`` calls are collected in memory and written to the event log when ``onCommand`` returns.

Events are written asynchronously to the event-sourced actor's ``eventLog``. After writing, the ``eventLog`` actor internally replies to the event-sourced actor with a success or failure message which is passed as argument to the persist ``handler``. Before calling the persist ``handler``, the event-sourced actor internally calls the ``onEvent`` handler with the written event if writing was successful and ``onEvent`` is defined at that event.

Both, event handler and persist handler are called on a dispatcher thread of the actor. They can therefore safely access internal actor state. The ``sender()`` reference of the original command sender is also preserved, so that a persist handler can reply to the initial command sender.

.. hint::
   The ``EventsourcedActor`` trait also defines a ``persistN`` method. Refer to the EventsourcedActor_ API documentation for details.

.. note::
   A command handler should not modify persistent actor state i.e. state that is derived from events.

.. _state-sync:

State synchronization
~~~~~~~~~~~~~~~~~~~~~

As explained in section :ref:`command-handler`, events are persisted asynchronously. What happens if another command is sent to an event-sourced actor while persistence is in progress? This depends on the value of ``stateSync``, a member of ``EventsourcedActor`` that can be overridden.

.. includecode:: ../../../eventuate-core/src/main/scala/com/rbmhtechnology/eventuate/EventsourcedActor.scala
   :snippet: state-sync

If ``stateSync`` is ``true`` (default), new commands are stashed_ while persistence is in progress. Consequently, new commands see actor state that is *in sync* with the events in the event log. A consequence is limited write throughput, because :ref:`batching` of write requests is not possible in this case\ [#]_. This setting is recommended for event-sourced actors that must validate commands against current state.

If ``stateSync`` is ``false``, new commands are dispatched to ``onCommand`` immediately. Consequently, new commands may see stale actor state. The advantage is significantly higher write throughput as :ref:`batching` of write requests is possible. This setting is recommended for event-sourced actors that don't need to validate commands against current state.

If a sender sends several (update) commands followed by a query to an event-sourced actor that has ``stateSync`` set to ``false``, the query will probably not see the state change from the preceding commands. To achieve read-your-write consistency, the command sender should wait for a reply from the last command before sending the query. The reply must of course be sent from within a ``persist`` handler.

.. note::
   State synchronization settings only apply to a single actor instance. Events that are emitted concurrently by other actors and handled by that instance can arrive at any time and modify actor state. Anyway, concurrent events are not relevant for achieving read-your-write consistency and should be handled as described in the :ref:`user-guide`.

.. _event-handler:

Event handler
~~~~~~~~~~~~~

An event handler is partial function of type ``PartialFunction[Any, Unit]`` for which a type alias ``Receive`` exists. It can be defined by implementing ``onEvent``. An event handler handles persisted events by updating actor state from event details.

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: event-handler

Event metadata of the last handled event can be obtained with the ``last*`` methods defined by ``EventsourcedActor``. For example, ``lastSequenceNr`` returns the event's local sequence number, ``lastVectorTimestamp`` returns the event's vector timestamp. A complete reference is given by the EventsourcedActor_ API documentation.

.. note::
   An event handler should only update internal actor state without having further side-effects. An exception is :ref:`reliable-delivery` of messages and :ref:`guide-event-driven-communication` with PersistOnEvent_.

.. _ref-event-sourced-views:

Event-sourced views
-------------------

An introduction to event-sourced views is already given in sections :ref:`overview`, :ref:`architecture` and the :ref:`user-guide`. Applications use event-sourced views for for maintaining in-memory read models on the query side (Q) of a CQRS_ application.

Like event-sourced actors, event-sourced views distinguish command processing from event processing. They must implement the EventsourcedView_ trait. ``EventsourcedView`` is a functional subset of ``EventsourcedActor`` that cannot ``persist`` events.

.. _ref-event-sourced-writers:

Event-sourced writers
---------------------

An introduction to event-sourced writers is already given in sections :ref:`overview` and :ref:`architecture`. Applications use event-sourced writers for maintaining persistent read models on the query side (Q) of a CQRS_ application.

Like event-sourced views, event-sourced writers can only consume events from an event log but can make incremental batch updates to external, application-defined query databases. A query database can be a relational database, a graph database or whatever is needed by an application. Concrete writers must implement the EventsourcedWriter_ trait.

This section outlines how to update a persistent read model in Cassandra_ from events consumed by an event-sourced writer. The relevant events are:

.. includecode:: ../../../eventuate-examples/src/main/scala/com/rbmhtechnology/example/querydb/Emitter.scala
   :snippet: events

The persistent read model is a ``CUSTOMER`` table with the following structure::

     id | first  | last    | address
    ----+--------+---------+-------------
      1 | Martin | Krasser | Somewhere 1
      2 | Volker | Stampa  | Somewhere 3
      3 | ...    | ...     | ...

The read model update progress is written to a separate ``PROGRESS`` table with a single ``sequence_nr`` column::

     id | sequence_nr
    ----+-------------
      0 |           3

The stored sequence number is that of the last successfully processed event. An event is considered as successfully processed if its data have been written to the ``CUSTOMER`` table. Only a single row is needed in the ``PROGRESS`` table to track the update progress for the whole ``CUSTOMER`` table.

The event-sourced ``Writer`` in the following example implements ``EventsourcedWriter[Long, Unit]`` (where ``Long`` is the type of the initial read result and ``Unit`` the type of write results). It is initialized with an ``eventLog`` from which it consumes events and a Cassandra ``Session`` for writing event processing results.

.. includecode:: ../../../eventuate-examples/src/main/scala/com/rbmhtechnology/example/querydb/Writer.scala
   :snippet: writer

.. hint::
   The full example source code is available `here <https://github.com/RBMHTechnology/eventuate/tree/master/eventuate-examples/src/main/scala/com/rbmhtechnology/example/querydb>`_.

On a high level, the example ``Writer`` implements the following behavior:

- During initialization (after start or restart) it asynchronously ``read``\ s the stored update progress from the ``PROGRESS`` table. The read result is passed as argument to ``readSuccess`` and incremented by ``1`` before returning it to the caller. This causes the ``Writer`` to resume event processing from that position in the event log.
- Event are processed in ``onEvent`` by translating them to Cassandra update statements which are added to an in-memory ``batch`` of type ``Vector[BoundStatement]``. The batch is written to Cassandra when Eventuate calls the ``write`` method.
- The ``write`` method asynchronously updates the ``CUSTOMER`` table with the statements contained in ``batch`` and then updates the ``PROGRESS`` table with the sequence number of the last processed event. After having submitted the statements to Cassandra, the batch is cleared for further event processing. Event processing can run concurrently to write operations.
- A ``batch`` that has been updated while a write operation is in progress is written directly after the current write operation successfully completes. If no write operation is in progress, a change to ``batch`` is written immediately. This keeps read model update delays at a minimum and increases batch sizes under increasing load. Batch sizes can be limited with ``replayBatchSize``.

If a ``write`` (or ``read``) operation fails, the writer is restarted, by default, and resumes event processing from the last stored sequence number + ``1``. This behavior can be changed by overriding ``writeFailure`` (or ``readFailure``) from ``EventsourcedWriter``.

.. note::
   The example does not use Cassandra ``BatchStatement``\ s for reasons explained in `this article <https://medium.com/@foundev/cassandra-batch-loading-without-the-batch-keyword-40f00e35e23e>`_. Atomic writes are not needed because database updates in this example are idempotent and can be re-tried in failure cases. Failure cases where idempotency is relevant are partial updates to the ``CUSTOMER`` table or a failed write to the ``PROGRESS`` table. ``BatchStatement``\ s should only be used when database updates are not idempotent and atomicity is required on database level.

.. _stateful-writers:

Stateful writers
~~~~~~~~~~~~~~~~

The above ``Writer`` implements a stateless writer. Although it accumulates batches while a write operation is in progress, it cannot recover permanent in-memory state from the event log, because event processing only starts from the last stored sequence number. If a writer needs to be stateful, it must return ``None`` from ``readSuccess``. In this case, event replay either starts from scratch or from a previously stored snapshot. A stateful writer should still write the update progress to the ``PROGRESS`` table but exclude events with a sequence number less than or equal to the stored sequence number from contributing to the update ``batch``.

.. _ref-event-sourced-processors:

Event-sourced processors
------------------------

An introduction to event-sourced processors is already given in sections :ref:`overview` and :ref:`architecture`. Applications use event-sourced processors to consume events form a source event log, process these events and write the processed events to a target event log. With processors, event logs can be connected to event stream processing pipelines and graphs.

Event-sourced processors are a specialization of :ref:`event-sourced-writers` where the *external database* is a target event log. Concrete stateless processors must implement the EventsourcedProcessor_ trait, stateful processors the StatefulProcessor_ trait (see also :ref:`stateful-writers`).

The following example ``Processor`` is an implementation of ``EventsourcedProcessor``. In addition to providing a source ``eventLog``, a concrete processor must also provide a ``targetEventLog``:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: processor

The event handler implemented by a processor is ``processEvent``. The type of the handler is defined as:

.. includecode:: ../../../eventuate-core/src/main/scala/com/rbmhtechnology/eventuate/EventsourcedProcessor.scala
   :snippet: process

Processed events, to be written to the target event log, are returned by the handler as ``Seq[Any]``. With this handler signature, events from the source log can be

- excluded from being written to the target log by returning an empty ``Seq``
- transformed one-to-one by returning a ``Seq`` of size 1 or even
- transformed and split by returning a ``Seq`` of size greater than ``1``

.. note::
   ``EventsourcedProcessor`` and ``StatefulProcessor`` internally ensure that writing to the target event log is idempotent. Applications don't need to take extra care about idempotency.

.. _state-recovery:

State recovery
--------------

When an event-sourced actor or view is started or re-started, events are replayed to its ``onEvent`` handler so that internal state can be recovered\ [#]_. This is also the case for stateful event-sourced writers and processors. During event replay the ``recovering`` method returns ``true``. Applications can also define a recovery completion handler by overriding ``onRecovery``:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: recovery-handler

If replay fails the completion handler is called with a ``Failure`` and the actor will be stopped, regardless of the action taken by the handler. The default recovery completion handler does nothing.

At the beginning of event replay, the initiating actor is registered at its event log so that newly written events can be routed to that actor. During replay, the actor internally stashes these newly written events and dispatches them to ``onEvent`` after successful replay. In a similar way, the actor also stashes new commands and dispatches them to ``onCommand`` afterwards. This ensures that new commands never see partially recovered state. When the actor is stopped it is automatically de-registered from its event log.

Backpressure
~~~~~~~~~~~~

Events are replayed in batches. A given batch must have been handled by an event handler before the next batch is replayed. This allows slow event handlers to put backpressure on event replay. The default replay batch size can be configured with:

.. includecode:: ../conf/common.conf
   :snippet: replay-batch-size

Event-sourced components can override the configured default value by overriding ``replayBatchSize``:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: replay-batch-size

.. _snapshots:

Recovery using an application-defined log sequence number
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to keep recovery times small it is almost always sensible to recover using snapshots. However, in some very rare cases an event-sourced actor or view can recover quickly using an application-defined log sequence number. If defined, only events with a sequence number equal to or larger than the given sequence number are replayed.

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: replay-from-sequence-nr

Snapshots
---------

Recovery times increase with the number of events that are replayed to event-sourced components. They can be decreased by starting event replay from a previously saved snapshot of internal state rather than replaying events from scratch. Event-sourced components can save snapshots by calling ``save`` within their command handler:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: snapshot-save

Snapshots are saved asynchronously. On completion, a user-defined handler of type ``Try[SnapshotMetadata] => Unit`` is called. Like a ``persist`` handler, a ``save`` handler may also close over actor state and can reply to the command sender using the ``sender()`` reference.

An event-sourced actor that is :ref:`tracking-conflicting-versions` of application state can also save ``ConcurrentVersions[A, B]`` instances directly. One can even configure custom serializers for type parameter ``A`` as explained in section :ref:`snapshot-serialization`.

During recovery, the latest snapshot saved by an event-sourced component is loaded and can be handled with the ``onSnapshot`` handler. This handler should initialize internal actor state from the loaded snapshot:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: snapshot-load

If ``onSnapshot`` is not defined at the loaded snapshot or not overridden at all, event replay starts from scratch. If ``onSnapshot`` is defined at the loaded snapshot, only events that are not covered by that snapshot will be replayed.

Event-sourced actors that implement ``ConfirmedDelivery`` for :ref:`reliable-delivery` automatically include unconfirmed messages into state snapshots. These are restored on recovery and re-delivered on recovery completion.

.. note::
   State objects passed as argument to ``save`` should be *immutable objects*. If this is not the case, the caller is responsible for creating a defensive copy before passing it as argument to ``save``.

Storage locations
~~~~~~~~~~~~~~~~~

Snapshots are currently stored in a directory that can be configured with

.. includecode:: ../conf/snapshot.conf
   :snippet: snapshot-dir

in ``application.conf``. The maximum number of stored snapshots per event-sourced component can be configured with

.. includecode:: ../conf/snapshot.conf
   :snippet: snapshot-num

If this number is exceeded, older snapshots are automatically deleted.

.. _event-routing:

Event routing
-------------

An event that is emitted by an event-sourced actor or processor can be routed to other event-sourced components if they share an :ref:`event-log`\ [#]_ . The default event routing rules are:

- If an event-sourced component has an undefined ``aggregateId``, all events are routed to it. It may choose to handle only a subset of them though.
- If an event-sourced component has a defined ``aggregateId``, only events emitted by event-sourced actors or processors with the same ``aggregateId`` are routed to it.

Routing destinations are defined during emission of an event and are persisted together with the event\ [#]_. This makes routing decisions repeatable during event replay and allows for routing rule changes without affecting past routing decisions. Applications can define additional routing destinations with the ``customDestinationAggregateIds`` parameter of ``persist``:

.. includecode:: ../code/EventRoutingDoc.scala
   :snippet: custom-routing

Here, ``ExampleEvent`` is routed to destinations with ``aggregateId``\ s ``Some("a2")`` and ``Some("a3")`` in addition to the default routing destinations with ``aggregateId``\s ``Some("a1")`` and ``None``.

.. _ref-event-driven-communication:

Event-driven communication
--------------------------

Event-driven communication is one form of :ref:`overview-event-collaboration` and covered in the :ref:`guide-event-driven-communication` section of the :ref:`user-guide`.

.. _reliable-delivery:

Reliable delivery
-----------------

Reliable, event-based remote communication between event-sourced actors should be done via a :ref:`replicated-event-log`. For reliable communication with other services that cannot connect to a replicated event log, event-sourced actors should use the ConfirmedDelivery_ trait:

.. includecode:: ../code/ReliableDeliveryDoc.scala
   :snippet: reliable-delivery

``ConfirmedDelivery`` supports the reliable delivery of messages to destinations by enabling applications to re-deliver messages until delivery is confirmed by destinations. In the example above, the reliable delivery of a message is initiated by sending a ``DeliverCommand`` to ``ExampleActor``.

The handler of the generated ``DeliverEvent`` calls ``deliver`` to deliver a ``ReliableMessage`` to ``destination``. The ``deliveryId`` is an identifier to correlate ``ReliableMessage`` with a ``Confirmation`` message. The ``deliveryId`` can be any application-defined id. Here, the event's sequence number is used which can be obtained with ``lastSequenceNumber``.

The ``destination`` confirms the delivery of the message by sending a ``Confirmation`` reply to the event-sourced actor from which it generates a ``ConfirmationEvent``. The actor uses the ``persistConfirmation`` method to persist the confirmation event together with the delivery id. After successful persistence of the confirmation event, the corresponding reliable message is removed from the internal buffer of unconfirmed messages.

When the actor is re-started, unconfirmed reliable messages are automatically re-delivered to their ``destination``\ s. The example actor additionally schedules ``redeliverUnconfirmed`` calls to periodically re-deliver unconfirmed messages. This is done within the actor's command handler.

.. note::
   In the above example a pattern guard is used for idempotent confirmation processing by ensuring that the ``deliveryId`` of the ``Confirmation`` message is still unconfirmed. This pattern may only be applied if the ``stateSync`` member of the ``EventsourcedActor`` is set to ``true``. For further details on ``stateSync`` see section :ref:`state-sync`.

.. note::
   If a snapshot is taken unconfirmed messages are stored in the snapshot along with the destination ``ActorPath``. That is why the actual ``ActorPath`` of the destination must not change between restarts of the actor, if, for example, the destination actor is within the same application and the application is restarted. That is why the destination actor must be named explicitly instead of having a name generated by the ``ActorSystem``.

.. _ref-conditional-requests:

Conditional requests
--------------------

Conditional requests are covered in the :ref:`conditional-requests` section of the :ref:`user-guide`.

.. _command-stashing:

Command stashing
----------------

``EventsourcedView`` and ``EventsourcedActor`` override ``stash()`` and ``unstashAll()`` of ``akka.actor.Stash`` so that application-specific subclasses can safely stash and unstash commands. Stashing of events is not allowed. Hence, ``stash()`` must only be used in a command handler, using it in an event handler will throw ``StashError``. On the other hand, ``unsatshAll()`` can be used anywhere i.e. in a command handler, persist handler or event handler. The following is a trivial usage example which calls ``stash()`` in the command handler and ``unstashAll()`` in the persist handler:

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: command-stash

The ``UserManager`` maintains a persistent ``users`` map. User can be added to the map by sending a ``CreateUser`` command and updated by sending and ``UpdateUser`` command. Should these commands arrive in wrong order i.e. ``UpdateUser`` before a corresponding ``CreateUser``, the ``UserManager`` stashes ``UpdateUser`` and unstashes it after having successfully processed another ``CreateUser`` command.

In the above implementation, an ``UpdateUser`` command might be repeatedly stashed and unstashed if the corresponding ``CreateUser`` command is preceded by other unrelated ``CreateUser`` commands. Assuming that out-of-order user commands are rare, the performance impact is limited. Alternatively, one could record stashed user ids in transient actor state and conditionally call ``unstashAll()`` by checking that state.

Behavior changes
----------------

Event-sourced components distinguish command processing from event processing. Consequently, applications should be able to change the behavior of command handlers and event handlers independent of each other, at runtime. Command handling behavior can be changed with ``commandContext.become()`` and ``commandContext.unbecome()``, event handling behavior with ``eventContext.become()`` and ``eventContext.unbecome()`` (for details, see the BehaviorContext_ API docs):

.. includecode:: ../code/EventSourcingDoc.scala
   :snippet: behavior-changes

This works for all event-sourcing abstractions except for ``EventsourcedProcessor``. Its ``eventContext`` does not allow behavior changes as ``EventsourcedProcessor`` implements default ``onEvent`` behavior that should be changed by applications. An attempt to change that behavior will throw an ``UnsupportedOperationException``. Changing an ``EventsourcedProcessor``'s ``processEvent`` behavior is not supported yet.

.. note::
   Command and event handling behaviors are managed by internal behavior stacks. Eventuate does **not** include these behavior stacks into :ref:`snapshots` when applications ``save`` actor state. Although the state of an event handling behavior stack can be recovered by replaying events from scratch, that stack is not automatically recovered when a snapshot is loaded. Applications are therefore responsible to restore the required command and event handling behavior from application-specific snapshot details in the ``onSnapshot`` handler. Of course, this is only necessary if the required behavior differs from the default ``onEvent`` and ``onCommand`` behavior.

Failure handling
----------------

Event-sourced components register themselves at an EventLog_ actor in order to be notified about changes in the event log. Directly after registration, during recovery, they read from the event log in order to recover internal state from past events. After recovery has completed, the event log actor **pushes** newly written events to registered actors so that they can update application state with minimal latency. If a registered actor is restarted, it recovers again from the event log and continues to process push-updates after recovery has completed.

An EventLog_ actor processes write requests from :ref:`ref-event-sourced-actors`, :ref:`ref-event-sourced-processors` and :ref:`replication-endpoints`. If a write succeeds it pushes the written events to registered actors (under consideration of :ref:`event-routing` rules) and handles the next write request. Writing to a storage backend may also fail for several reasons. In the following, it is assumed that writes are made to a remote storage backend such as the :ref:`cassandra-storage-backend`.

A write failure reported from a storage backend driver does not necessarily mean that the events have not been written to the storage backend. For example, a write could have been actually applied to the remote storage backend but the ACK message got lost. This usually causes the driver to report a timeout. If an event log actor would simply continue with the next write request, after having informed the event emitter about the failure, the emitter and and other registered actors would erroneously assume that the emitted events do not exist in the event log. However, these events may become visible to newly registered actors that are about to recover or to replication endpoints that read events for replication.

This would violate the event ordering and consistency guarantees made by Eventuate because some registered actors would see an event stream with missing events. The following describes two options to deal with that situation:

#. After a failed write, the event log actor notifies all registered actors to restart themselves so that another recovery phase would find out whether the events have been actually written or not. This is fine if the write failure was actually a lost ACK and the storage backend is immediately available for subsequent reads (neglecting a potentially high read load). If the write failure was because of a longer-lasting problem, such as a longer network partition that disconnects the application from the storage backend, registered actors would fail to recover and would be therefore be unavailable for in-memory reads.

#. The event log actor itself tries to find out whether the write was successful or not, either by reading from the storage backend or by retrying the write until it succeeds, before continuing with the next write request. In this case, the log actor would inform the event emitter either about a failed write if it can guarantee that the write has not been applied to the storage backend or about a successful write if retrying the write finally succeeded. Retrying writes can only be made to storage backends that support idempotent writes. With this strategy, registered actors don't need be restarted and remain available for in-memory reads.

In Eventuate, the second approach is taken. Should there be a longer-lasting problem with the storage backend, it may take a longer time for an event log actor to make a decision about the success or failure of a write. During that time, it will reject further writes in order to avoid being overloaded with pending write requests. This is an application of the `circuit breaker`_ design pattern.

Consequently, a write failure reported by an event log actor means that the write was actually **not** applied to the storage backend. This additional guarantee comes at the cost of potentially long write reply delays but allows registered actors to remain available for in-memory reads during storage backend unavailability. It also provides clearer semantics of write failures.

.. _circuit-breaker:

Circuit breaker
~~~~~~~~~~~~~~~

The strategy described above can be implemented by wrapping a CassandraEventLog_ in a CircuitBreaker_ actor. This is the default when creating the log actor for a :ref:`cassandra-storage-backend`. Should the event log actor need to retry a write ``eventuate.log.circuit-breaker.open-after-retries`` times or more, the circuit breaker opens. If open, it rejects all requests by replying with a failure message that contains an EventLogUnavailableException_. If retrying the write finally succeeds, the circuit breaker closes again. The maximum number of write retries can be configured with ``eventuate.log.cassandra.write-retry-max`` and the delay between write retries with ``eventuate.log.write-timeout``. If the maximum number of retries is reached, the event log actor gives up and stops itself which also stops all registered actors.

.. _persist-failure-handling:

``persist`` failure handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Asynchronous ``persist`` operations send write requests to an EventLog_ actor. The write reply is passed as argument to the persist handler (see section :ref:`command-handler`). If the persist handler is called with a ``Failure`` one can safely assume that the events have not been written to the storage backend. As already explained above, a consequence of this additional guarantee is that persist handler callbacks may be delayed indefinitely.

For an ``EventsourcedActor`` with ``stateSync`` set to ``true``, this means that further commands sent to that actor will be stashed until the current write completes. In this case, it is the responsibility of the application not to overload that actor with further commands. For example, an application could use timeouts for command replies and prevent sending further commands to that actor if a timeout occurred. After an application-defined delay, command sending can be resumed. This is comparable to using an application-level circuit breaker. Alternatively, an application could restart an event-sourced actor on command timeout and continue sending new commands to that actor after recovery succeeded. This however may take a while depending on the unavailability duration of the storage backend.

``EventsourcedActor``\ s with ``stateSync`` set to ``false`` do not stash commands but rather send write requests immediately to the event log actor. If the log actor is busy retrying a write and the :ref:`circuit-breaker` opens, later persist operations will be completed immediately with an ``EventLogUnavailableException`` failure, regardless whether the event-sourced actor has persist operations in progress or not. A persist operation of an ``EventsourcedActor`` with ``stateSync`` set to ``true`` will only be completed with an ``EventLogUnavailableException`` failure if that actor had no persist operation in progress at the time the circuit breaker opened.

.. _persist-on-event-failure-handling:

``persistOnEvent`` failure handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``EventsourcedActor``\ s can also persist events in the :ref:`event-handler` if they additionally extend PersistOnEvent_. An asynchronous ``persistOnEvent`` operation may also fail for reasons explained in :ref:`persist-failure-handling`. If a ``persistOnEvent`` operation fails, the actor is automatically restarted by throwing a ``PersistOnEventException``.

Recovery failure handling
~~~~~~~~~~~~~~~~~~~~~~~~~

As explained in section :ref:`state-recovery`, event-sourced components are stopped if their recovery fails. Applications should either define a custom ``onRecovery`` completion handler to obtain information about recovery failure details or just watch these actors if recovery failure details are not relevant.

Batch write failure handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Events are written in batches. When using the :ref:`cassandra-storage-backend`, there's a *warn threshold* and *fail threshold* for batch sizes. The default settings in ``cassandra.yaml`` are::

    # Caution should be taken on increasing the size of this threshold as it can
    # lead to node instability.
    batch_size_warn_threshold_in_kb: 5

    # Fail any batch exceeding this value. 50kb (10x warn threshold) by default.
    batch_size_fail_threshold_in_kb: 50

When the size of an event batch exceeds the *fail threshold*, the batch write fails with::

    com.datastax.driver.core.exceptions.InvalidQueryException: Batch too large

The corresponding entry in the Cassandra system log is::

    ERROR <timestamp> Batch of prepared statements for [eventuate.log_<id>] is of size 103800, exceeding specified threshold of 51200 by 52600. (see batch_size_fail_threshold_in_kb)

.. note::
   If Eventuate is the only writer to the Cassandra cluster then it is safe to increase these thresholds to higher values as Eventuate only makes single-partition batch writes (see also `CASSANDRA-8825`_).

If other applications additionally make multi-partition batch writes to the same Cassandra cluster then is recommended to reduce

.. includecode:: ../conf/common.conf
   :snippet: write-batch-size

and

.. includecode:: ../conf/common.conf
   :snippet: index-update-limit

to a smaller value like ``32``, for example, or even smaller. Failed replication writes or index writes are re-tried automatically by Eventuate. Failed ``persist`` operations must be re-tried by the application.

Batch replication failure handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

During replication, events are batch-transferred over the network. The maximum number of events per batch can be configured with:

.. includecode:: ../conf/common.conf
   :snippet: write-batch-size

The maximum batch size in bytes the transport will accept is limited. If this limit is exceeded, batch transfer will fail. In this case, applications should either increase

.. includecode:: ../conf/common.conf
   :snippet: maximum-frame-size

or decrease the event batch size.

.. note::
   Batch sizes in Eventuate are currently defined in units of events whereas ``maximum-frame-size`` is defined in bytes. This mismatch will be removed in a later release (see also `ticket 166`_).

Custom serialization
--------------------

.. _event-serialization:

Custom event serialization
~~~~~~~~~~~~~~~~~~~~~~~~~~

Custom serializers for application-defined events can be configured with Akka's `serialization extension`_. For example, an application that wants to use a custom ``MyDomainEventSerializer`` for events of type ``MyDomainEvent`` (both defined in package ``com.example``) should add the following configuration to ``application.conf``:

.. includecode:: ../conf/serializer.conf
   :snippet: custom-event-serializer

``MyDomainEventSerializer`` must extend Akka's Serializer_ trait. Please refer to Akka's `serialization extension`_ documentation for further details.

Eventuate stores application-defined events as ``payload`` of DurableEvent_\ s. ``DurableEvent`` itself is serialized with DurableEventSerializer_, a `Protocol Buffers`_ based serializer that delegates ``payload`` serialization to a custom serializer. If no custom serializer is configured, Akka's default serializer is used.

.. _replication-filter-serialization:

Custom replication filter serialization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In the same way as for application-defined events, custom serializers for :ref:`replication-filters` can also be configured via Akka's `serialization extension`_. For example, an application that wants to use a custom ``MyReplicationFilterSerializer`` for replication filters of type ``MyReplicationFilter`` (both defined in package ``com.example``) should add the following configuration to ``application.conf``:

.. includecode:: ../conf/serializer.conf
   :snippet: custom-filter-serializer

Custom replication filter serialization also works if the custom filter is part of a composite filter that has been composed with ``and`` or ``or`` combinators (see ReplicationFilter_ API). If no custom filter serializer is configured, Akka's default serializer is used.

.. _snapshot-serialization:

Custom snapshot serialization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Applications can also configure custom serializers for snapshots in the same way as for application-defined events and replication filters (see sections :ref:`event-serialization` and :ref:`replication-filter-serialization`).

Custom snapshot serialization also works for state managed with ``ConcurrentVersions[A, B]``. A custom serializer configured for type parameter ``A`` is used whenever a snapshot of type ``ConcurrentVersions[A, B]`` is saved (see also :ref:`tracking-conflicting-versions`).

Event-sourced actors that extend ``ConfirmedDelivery`` for :ref:`reliable-delivery` of messages to destinations will also include unconfirmed messages as ``deliveryAttempts`` in a Snapshot_. The ``message`` field of a DeliveryAttempt_ can also be custom-serialized by configuring a serializer.

Custom CRDT serialization
~~~~~~~~~~~~~~~~~~~~~~~~~

Custom serializers can also be configured for the type parameter ``A`` of ``MVRegister[A]``, ``LWWRegister[A]`` and ``ORSet[A]`` :ref:`commutative-replicated-data-types`. These serializers are used for both persistent CRDT operations and CRDT snapshots.

Resolution of serializers when deserializing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When eventuate serializes application-defined events, :ref:`replication-filters` or snapshots it includes the ``identifier`` of the Akka serializer and the class or string based manifest_ when available. When deserializing these application-defined payloads a serializer is selected as follows:

- If a class-based manifest is included, the serializer that is configured in the Akka configuration for this class is selected
- In case of a string-based manifest or no manifest the serializer is selected by the included ``identifier``

.. [#] The ``customDestinationAggregateIds`` parameter is described in section :ref:`event-routing`.
.. [#] Writes from different event-sourced actors that have ``stateSync`` set to ``true`` are still batched, but not the writes from a single event-sourced actor.
.. [#] Event replay can optionally start from :ref:`snapshots` of actor state.
.. [#] Event-sourced processors can additionally route events between event logs.
.. [#] The routing destinations of a DurableEvent_ can be obtained with its ``destinationAggregateIds`` method.

.. _CQRS: http://martinfowler.com/bliki/CQRS.html
.. _stashed: http://doc.akka.io/docs/akka/2.4/scala/actors.html#stash
.. _watch: http://doc.akka.io/docs/akka/2.4/scala/actors.html#deathwatch-scala
.. _serialization extension: http://doc.akka.io/docs/akka/2.4/scala/serialization.html
.. _Serializer: http://doc.akka.io/api/akka/2.4/#akka.serialization.Serializer
.. _manifest: http://doc.akka.io/docs/akka/2.4/scala/serialization.html#Serializer_with_String_Manifest
.. _Protocol Buffers: https://developers.google.com/protocol-buffers/
.. _plausible clocks: https://github.com/RBMHTechnology/eventuate/issues/68
.. _Cassandra: http://cassandra.apache.org/
.. _circuit breaker: http://martinfowler.com/bliki/CircuitBreaker.html
.. _ticket 166: https://github.com/RBMHTechnology/eventuate/issues/166
.. _CASSANDRA-8825: https://issues.apache.org/jira/browse/CASSANDRA-8825

.. _ConfirmedDelivery: ../latest/api/index.html#com.rbmhtechnology.eventuate.ConfirmedDelivery
.. _DurableEvent: ../latest/api/index.html#com.rbmhtechnology.eventuate.DurableEvent
.. _DurableEventSerializer: ../latest/api/index.html#com.rbmhtechnology.eventuate.serializer.DurableEventSerializer
.. _EventsourcedActor: ../latest/api/index.html#com.rbmhtechnology.eventuate.EventsourcedActor
.. _EventsourcedView: ../latest/api/index.html#com.rbmhtechnology.eventuate.EventsourcedView
.. _EventsourcedWriter: ../latest/api/index.html#com.rbmhtechnology.eventuate.EventsourcedWriter
.. _EventsourcedProcessor: ../latest/api/index.html#com.rbmhtechnology.eventuate.EventsourcedProcessor
.. _StatefulProcessor: ../latest/api/index.html#com.rbmhtechnology.eventuate.StatefulProcessor
.. _ReplicationFilter: ../latest/api/index.html#com.rbmhtechnology.eventuate.ReplicationFilter
.. _Snapshot: ../latest/api/index.html#com.rbmhtechnology.eventuate.Snapshot
.. _DeliveryAttempt: ../latest/api/index.html#com.rbmhtechnology.eventuate.ConfirmedDelivery$$DeliveryAttempt
.. _PersistOnEvent: ../latest/api/index.html#com.rbmhtechnology.eventuate.PersistOnEvent
.. _BehaviorContext: ../latest/api/index.html#com.rbmhtechnology.eventuate.BehaviorContext
.. _EventLogUnavailableException: ../latest/api/index.html#com.rbmhtechnology.eventuate.log.EventLogUnavailableException
.. _CircuitBreaker: ../latest/api/index.html#com.rbmhtechnology.eventuate.log.CircuitBreaker
.. _EventLog: ../latest/api/index.html#com.rbmhtechnology.eventuate.log.EventLog
.. _CassandraEventLog: ../latest/api/index.html#com.rbmhtechnology.eventuate.log.cassandra.CassandraEventLog

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.imagepipeline.common;

import android.support.annotation.IntDef;

import com.facebook.common.util.HashCodeUtil;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Locale;

/**
 * Options for rotation.
 *
 * <p> These options are applied to JPEG images only.
 *
 * <p> Describes how the image should be rotated, whether following image meta-data or a specified
 * amount.
 *
 * <p> These options are only relevant for JPEG images. Fresco doesn't support rotation of other
 * image formats.
 *
 * <p> The options also include whether the rotation can be deferred until the bitmap is rendered.
 * This should be be false if a post-processor is used which needs to operate on the bitmap
 * correctly oriented but can otherwise generally be true, particularly if using drawee.
 */
public class RotationOptions {

  @IntDef(flag=false, value={
      NO_ROTATION,
      ROTATE_90,
      ROTATE_180,
      ROTATE_270,
      USE_EXIF_ROTATION_ANGLE,
      DISABLE_ROTATION
  })
  @Retention(RetentionPolicy.SOURCE)
  private @interface Rotation {}

  @IntDef(flag=false, value={
      NO_ROTATION,
      ROTATE_90,
      ROTATE_180,
      ROTATE_270
  })
  @Retention(RetentionPolicy.SOURCE)
  public @interface RotationAngle {}

  public static final int NO_ROTATION = 0;
  public static final int ROTATE_90 = 90;
  public static final int ROTATE_180 = 180;
  public static final int ROTATE_270 = 270;
  private static final int USE_EXIF_ROTATION_ANGLE = -1;
  private static final int DISABLE_ROTATION = -2;

  private final @Rotation int mRotation;
  private final boolean mDeferUntilRendered;

  /**
   * Creates a new set of rotation options for JPEG images to use the rotation angle in the image
   * metadata.
   *
   * <p> This is the default option for requests which don't specify rotation options.
   *
   * <p> The rotation will not be deferred for defensiveness but that can improve performance. To
   * defer, use {@link #autoRotateAtRenderTime()}.
   */
  public static RotationOptions autoRotate() {
    return new RotationOptions(USE_EXIF_ROTATION_ANGLE, false);
  }

  /**
   * Creates a new set of rotation options for JPEG images to load image without any rotation.
   *
   */
  public static RotationOptions disableRotation() {
    return new RotationOptions(DISABLE_ROTATION, false);
  }

  /**
   * Creates a new set of rotation options for JPEG images to use the rotation angle in the image
   * metadata.
   *
   * <p> The rotation may be deferred until the image is rendered.
   */
  public static RotationOptions autoRotateAtRenderTime() {
    return new RotationOptions(USE_EXIF_ROTATION_ANGLE, true);
  }

  /**
   * Creates a new set of rotation options to use a specific rotation angle.
   *
   * <p> The rotation will be carried out in the pipeline.
   *
   * @param angle the angle to rotate - valid values are 0, 90, 180 and 270
   */
  public static RotationOptions forceRotation(@RotationAngle int angle) {
    return new RotationOptions(angle, false);
  }

  private RotationOptions(@Rotation int rotation, boolean canDeferUntilRendered) {
    this.mRotation = rotation;
    this.mDeferUntilRendered = canDeferUntilRendered;
  }

  public boolean useImageMetadata() {
    return mRotation == USE_EXIF_ROTATION_ANGLE;
  }

  public boolean rotationEnabled() {
    return mRotation != DISABLE_ROTATION;
  }

  /**
   * Gets the explicit angle to rotate to, if one was set.
   *
   * @throws IllegalStateException if the instance was create using one of the
   * {@code autoRotate()} constructors.
   */
  public @RotationAngle int getForcedAngle() {
    if (useImageMetadata()) {
      throw new IllegalStateException("Rotation is set to use EXIF");
    }
    return mRotation;
  }

  public boolean canDeferUntilRendered() {
    return mDeferUntilRendered;
  }

  @Override
  public int hashCode() {
    return HashCodeUtil.hashCode(mRotation, mDeferUntilRendered);
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) {
      return true;
    }
    if (!(other instanceof RotationOptions)) {
      return false;
    }
    RotationOptions that = (RotationOptions) other;
    return this.mRotation == that.mRotation &&
        this.mDeferUntilRendered == that.mDeferUntilRendered;
  }

  @Override
  public String toString() {
    return String.format((Locale) null, "%d defer:%b", mRotation, mDeferUntilRendered);
  }
}


text:
$(document).ready(function(){
  $('.home-btn').click(function(){
    window.location.replace(location.protocol + '//' + location.host + '/');
  });

  $('.download-project').click(function(){
    var $_GET = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
      function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
      }

      $_GET[decode(arguments[1])] = decode(arguments[2]);
    });

    var filePath = $_GET["path"];
    var project = $('.heading h1 a:first-child').text();

    filePath = filePath.split("/");

    window.open(location.protocol + '//' + location.host + '/workspaces/' + project + '/?project=' + project + '&fileDownload=' + filePath);
  });

  $('.name').click(function(){
    var filePath = $(this).attr('file-path');
    var fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    var fileExt = $(this).attr('file-extension');

    if (isImage(fileName)) {
    	$('.wrap').hide();

    	$('.add-file').remove();

    	$('.remove-file-container').append('
Remove File
');

    	$('.filename span').empty();
        $('.filename span').append(fileName);
        $('.filename').css('display', 'inline-block');

    	$('#viewer').append('');
    	$('#viewer').show();
    } else if (isVideo(fileName)) {
    	$('.wrap').hide();

    	$('.add-file').remove();

    	$('.remove-file-container').append('
Remove File
');

    	$('.filename span').empty();
        $('.filename span').append(fileName);
        $('.filename').css('display', 'inline-block');

    	$('#viewer').append('<video class="inside" src="/'+filePath+'" controls></video>');
    	$('#viewer').show();
    } else if (typeof filePath !== typeof undefined && filePath !== false) {

      $.get(
        "",
        { loadFile: filePath },
        function(data) {
        $('#editorBuffer').append(data);

      $('.wrap').hide();
      $('.add-file').remove();

      $('.remove-file-container').append('
Remove File
');

      $('.filename span').empty();
      $('.filename span').append(fileName);
      $('.filename').css('display', 'inline-block');

      $('#editor').show();
      $('#editor xmp').append($('#editorBuffer').html());
      var editor = ace.edit("editor");
      editor.setTheme("ace/theme/tomorrow");

      var modelist = ace.require("ace/ext/modelist");
      var mode = modelist.getModeForPath(filePath).mode
      editor.session.setMode(mode);
      editor.session.setUseWrapMode(true);
      editor.session.setWrapLimitRange();

      editor.setOptions({
	enableBasicAutocompletion: true,
	enableSnippets: true,
	enableLiveAutocompletion: true
      });

      editor.getSession().on('change', function(){
        $('#editorBuffer').empty();
        var append = encodeHtmlEntities(editor.getSession().getValue());
        $('#editorBuffer').append(append);
      });

        }
      );

    }
  });

  fullscreenMode();
  if($('.user-position').text() != "read_only"){
    addProject();
    addFile();
    removeFile();
    saveFile();
  }
});

function fullscreenMode() {
  var fullscreen = 0;

  $('.fullscreen').click(function(){
    var editor = ace.edit("editor");
    $('.fullscreen').empty();
    if(fullscreen == 0) {
      $('.fullscreen').append('');
      $('.page').addClass('fullscreen-mode');
      editor.resize()
      editor.session.setUseWrapMode(true);
      editor.session.setWrapLimitRange();
      fullscreen = 1;
    } else {
      $('.fullscreen').append('');
      $('.page').removeClass('fullscreen-mode');
      editor.resize()
      editor.session.setUseWrapMode(true);
      editor.session.setWrapLimitRange();
      fullscreen = 0;
    }

  });
}

function addProject() {
  $('.add-project').click(function(){
    $('.overlay').addClass('visible');
  });

  $('.remove-project').click(function(){
    $('.overlay2').addClass('visible');
  });

  $('.project-form').submit(function() {
   return false;
  });

  $('.check-pass').submit(function() {
   return false;
  });

  $('.exit-btn').click(function(){
    $('.overlay').removeClass('visible');
    $('.overlay2').removeClass('visible');
  });

  $('.project-name-btn').click(function(){
    var nameVal = $('.project-name').val();
    $.get(
                  "add-project/",
                  { createProject: nameVal },
                  function(data) {
                     location.reload();
                  }
               );
  });

  $('.password-check-btn').click(function(){
    var passwordVal = $('.password-check').val();
    var nameVal = $('.password-check').prop('project');
    $.get(
                  "/",
                  { passwordCheck: passwordVal },
                  function(data) {
                     if(data == "true"){
                     var nameVal = $('.password-check').attr('project');
                       $.get(
	                  "remove-project/",
	                  { removeProject: nameVal },
	                  function(data) {
	                     location.href = "?path=";
	                  }
	               );
                     } else {
                       $('.password-check').css('background-color', 'rgba(231, 76, 60, 0.1)');
                     }
                  }
               );
    });

}

function addFile() {
  $('.add-file').click(function(){
    $('.filename span form').css('display', 'inline-block');
    $('.filename').css('display', 'inline-block');
  });

  $('.upload-file').click(function(){
    //$('.overlay2').addClass('visible');
  });

  $('.filename-add').submit(function() {
   return false;
  });

  $('.file-name-btn').click(function(){
    var nameVal = $('.file-name').val();
    var $_GET = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
      function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
      }

      $_GET[decode(arguments[1])] = decode(arguments[2]);
    });

    $.get(
                  "add-file/",
                  { createFile: nameVal,
                    inPath: $_GET["path"] },
                  function(data) {
                     location.reload();
                  }
               );
  });

}

function removeFile() {
  $('.remove-file-container').click(function(){
    var nameVal = $('.filename span').html();
    var $_GET = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
      function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
      }

      $_GET[decode(arguments[1])] = decode(arguments[2]);
    });

    $.get(
                  "remove-file/",
                  { removeFile: nameVal,
                    inPath: $_GET["path"] },
                  function(data) {
                     location.reload();
                  }
               );

  });
}

function saveFile() {
   $('#editor').keyup(function(){
    var nameVal = $('.filename span').html();
    var $_GET = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
      function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
      }

      $_GET[decode(arguments[1])] = decode(arguments[2]);
    });

    $.get(
                  "save-file/",
                  { saveFile: nameVal,
                    inPath: $_GET["path"],
                    filedata: decodeHtmlEntities($('#editorBuffer').html()) },
                  function(data) {
                     //location.reload();
                  }
               );
  });
}

$(function(){

	var dropbox = $('.upload-file');

	var $_GET = {};

	    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
	      function decode(s) {
	        return decodeURIComponent(s.split("+").join(" "));
	      }

	      $_GET[decode(arguments[1])] = decode(arguments[2]);
	    });

	dropbox.filedrop({
		// The name of the $_FILES entry:
		paramname:'file',

		data: {
			inPath : $_GET["path"]
		},

		maxfiles: 1,
    		maxfilesize: 100, // in mb
		url: 'upload-file/',

    	error: function(err, file) {
			switch(err) {
				case 'BrowserNotSupported':
					alert('Your browser does not support HTML5 file uploads!');
					$('.upload-file').removeClass('visible');
					break;
				case 'TooManyFiles':
					alert('Too many files! Please select only one!');
					$('.upload-file').removeClass('visible');
					break;
				case 'FileTooLarge':
					alert(file.name+' is too large! Please upload files up to 100mb.');
					$('.upload-file').removeClass('visible');
					break;
				default:
					break;
			}
		},

		globalProgressUpdated: function(progress) {
                  $('.upload-file .progresss').css('width', progress+"%");
                },

		docOver: function() {
	          $('.upload-file').addClass('visible');
	        },

	        dragLeave: function() {
	          $('.upload-file').removeClass('visible');
	        },

	        afterAll: function() {
	          location.reload();
	        }

	});

});

function encodeHtmlEntities(str) {
    return $("
").text(str).html();
}

function decodeHtmlEntities(str) {
    return $("
").html(str).text();
}

function isImage(file) {
    var extension = file.substr( (file.lastIndexOf('.') +1) );
    switch(extension) {
        case 'jpg':
	case 'png':
	case 'gif':
	case 'svg':
	case 'tiff':
	case 'bmp':
	case 'webp':
	    return(true);
	    break;
	default:
	    return(false);
    }
};

function isVideo(file) {
    var extension = file.substr( (file.lastIndexOf('.') +1) );
    switch(extension) {
        case 'mp4':
        case 'mov':
        case 'avi':
        case 'mkv':
        case 'ogg':
        case 'webm':
	    return(true);
	    break;
	default:
	    return(false);
    }
};


text:
package cc.bitky.clustermanage.server.message.tcp;

import cc.bitky.clustermanage.server.message.MsgType;
import cc.bitky.clustermanage.server.message.base.BaseMessage;

/**
 * 设备回复: 充电状态
 */
public class TcpMsgResponseStatus extends BaseMessage {
    private ResSource resSource = ResSource.DEVICE;
    private int status;
    private long time;

    public TcpMsgResponseStatus(int groupId, int deviceId, int status) {
        super(groupId, deviceId);
        this.status = status;
        this.time = System.currentTimeMillis();
        setMsgId(MsgType.DEVICE_RESPONSE_STATUS);
    }

    public TcpMsgResponseStatus(int groupId, int boxId, int status, ResSource resSource) {
        this(groupId, boxId, status);
        this.resSource = resSource;
    }

    public ResSource getResSource() {
        return resSource;
    }

    public int getStatus() {
        return status;
    }

    public long getTime() {
        return time;
    }

    /**
     * 该 bean 的来源
     */
    public enum ResSource {
        /**
         * 设备
         */
        DEVICE,
        /**
         * 服务器
         */
        SERVER
    }
}


text:
package org.apache.camel.component.file.remote;

import java.util.HashMap;
import java.util.Map;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

/**
 *
 */
public class RemoteFileProduceOverruleOnlyOnceTest extends FtpServerTestSupport {

    @Test
    public void testFileToFtp() throws Exception {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(Exchange.FILE_NAME, "/sub/hello.txt");
        headers.put(Exchange.OVERRULE_FILE_NAME, "/sub/ruled.txt");
        template.sendBodyAndHeaders("direct:input", "Hello World", headers);

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedHeaderReceived(Exchange.FILE_NAME, "/sub/hello.txt");
        mock.expectedFileExists(FTP_ROOT_DIR + "/out/sub/ruled.txt", "Hello World");
        mock.expectedFileExists("target/out/sub/hello.txt", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    public void setUp() throws Exception {
        deleteDirectory("target/out");
        super.setUp();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:input")
                    .to("ftp://admin:admin@localhost:" + getPort() + "/out/")
                        .to("file://target/out", "mock:result");
            }
        };
    }
}


text:
package me.zhouzhuo810.zzapidoc.demand.dao;

import me.zhouzhuo810.zzapidoc.bug.entity.BugItemEntity;
import me.zhouzhuo810.zzapidoc.common.dao.BaseDao;
import me.zhouzhuo810.zzapidoc.demand.entity.DemandItemEntity;

/**
 * Created by admin on 2018/10/6.
 */
public interface DemandItemDao extends BaseDao<DemandItemEntity> {

}


text:
package main

import (
	"context"
	"os"

	"github.com/djthorpe/gopi/v3"
)

type app struct {
	gopi.Unit
	gopi.MediaManager
	gopi.Logger

	filename string
}

func (this *app) Define(cfg gopi.Config) error {
	return nil
}

func (this *app) New(cfg gopi.Config) error {
	this.Require(this.Logger, this.MediaManager)

	if args := cfg.Args(); len(args) != 1 {
		return gopi.ErrBadParameter.WithPrefix("Missing filename")
	} else if stat, err := os.Stat(args[0]); err != nil {
		return gopi.ErrBadParameter.WithPrefix(args[0])
	} else if stat.Mode().IsRegular() == false {
		return gopi.ErrBadParameter.WithPrefix(args[0])
	} else {
		this.filename = args[0]
	}

	// Return success
	return nil
}

func (this *app) Run(ctx context.Context) error {
	// Open the file, decode the audio
	if file, err := this.OpenFile(this.filename); err != nil {
		return err
	} else if err := this.Decode(ctx, file); err != nil {
		return err
	}

	// Return success
	return nil
}

func (this *app) Decode(ctx context.Context, file gopi.MediaInput) error {
	// Use the first video stream found
	streams := file.StreamsForFlag(gopi.MEDIA_FLAG_AUDIO)
	if len(streams) == 0 {
		return gopi.ErrNotFound.WithPrefix("Audio stream")
	} else {
		this.Print(file.StreamForIndex(streams[0]))
	}

	// Decode frames
	return file.Read(ctx, streams[0:1], func(ctx gopi.MediaDecodeContext, packet gopi.MediaPacket) error {
		return file.DecodeFrameIterator(ctx, packet, func(frame gopi.MediaFrame) error {
			this.Print("Decoded", ctx.Stream(), ctx.Frame(), " => ", frame)
			return nil
		})
	})
}


text:
<!DOCTYPE html>

Repo

Site


text:
class ImageProcessorPrivate;
class ImageProcessor : public QObject
{
    Q_OBJECT
    Q_ENUMS(ImageAlgorithm)
    Q_PROPERTY(QString sourceFile READ sourceFile)
    Q_PROPERTY(ImageAlgorithm algorithm READ algorithm)

public:
    ImageProcessor(QObject *parent = 0);
    ~ImageProcessor();

    enum ImageAlgorithm{
        Gray = 0,
        Binarize,
        Negative,
        Emboss,
        Sharpen,
        Soften,
        AlgorithmCount
    };

    QString sourceFile() const;
    ImageAlgorithm algorithm() const;
    void setTempPath(QString tempPath);

signals:
    void finished(QString newFile);
    void progress(int value);

public slots:
    void process(QString file, ImageAlgorithm algorithm);
    void abort(QString file, ImageAlgorithm algorithm);
    void abortAll();

private:
    ImageProcessorPrivate *m_d;
};

#endif // IMAGEPROCESSOR_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Everstore.Storage.Vanilla.Protocol
{
	internal struct DataStoreResponse
	{
		public readonly Header Header;
		public readonly IMessageResponse Body;

		public DataStoreResponse(Header header, IMessageResponse body)
		{
			this.Header = header;
			this.Body = body;
		}
	}
}


text:
package org.kj6682.kosimo.commons;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by luigi on 24.04.16.
 */
@Aspect
@Component
class FeatureAspect {

    @Autowired
    FeatureConfig featureConfig;

    @Around("execution(* org.kj6682.kosimo.*.*Controller.*(..))")
    public Object checkFeature(ProceedingJoinPoint joinPoint) throws Throwable {

        try {
            if(featureConfig.check(extractFeature(joinPoint).value())) {
                return joinPoint.proceed();
            }
            throw new UnsupportedOperationException("This feature is not yet implemented.");

        } catch (IllegalArgumentException iae) {
            iae.printStackTrace();
            throw iae;
        }
    }

    private Feature extractFeature(ProceedingJoinPoint joinPoint) throws Throwable {
        return extractMethod(joinPoint).getAnnotation(Feature.class);
    }

    private Method extractMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> targetClass = joinPoint.getTarget().getClass();
        return targetClass.getMethod(signature.getName(), signature.getParameterTypes());

    }

}


text:
package ninjascode.mysteryriddles.app.tasks;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;

import ninjascode.mysteryriddles.app.common.GlobalConstants;
import ninjascode.mysteryriddles.app.data.contracts.IUpdatePageData;
import ninjascode.mysteryriddles.app.data.services.RiddlesService;
import ninjascode.mysteryriddles.app.viewModels.RiddleViewModel;

/**
 * Created by svetla.ivanova on 10.7.2016 г..
 */
public class GetRandomRiddleTask {
    private RiddlesService service;
    private String getRandomResponse;
    private Context context;
    private IUpdatePageData page;
    RiddleViewModel model;

    public GetRandomRiddleTask(Context context, IUpdatePageData page){
        this.service = new RiddlesService();
        this.context = context;
        this.page = page;
    }

    public void execute(){
        Callback callback = new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                getRandomResponse = response.body().string();
                model = RiddleViewModel.FromModel(getRandomResponse);
                postToMainThread();
            }
        };

        try {
            service.getRandom(GlobalConstants.RANDOMRIDDLE, callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void postToMainThread(){
        Handler mainHandler = new Handler(context.getMainLooper());

        Runnable updatePage = new Runnable() {
            @Override
            public void run() {
                page.updatePageData(model);
            }
        };

        mainHandler.post(updatePage);
    }
}


text:
package org.openestate.io.immobiliare_it.xml;

import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for detailedSizeFloorType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="detailedSizeFloorType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="Intermedio"/>
 *     <enumeration value="Interrato"/>
 *     <enumeration value="Seminterrato"/>
 *     <enumeration value="PianoTerra"/>
 *     <enumeration value="Rialzato"/>
 *     <enumeration value="Multipiano"/>
 *     <enumeration value="Ultimo"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "detailedSizeFloorType")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public enum DetailedFloorSizeType {

    @XmlEnumValue("Intermedio")
    INTERMEDIO("Intermedio"),
    @XmlEnumValue("Interrato")
    INTERRATO("Interrato"),
    @XmlEnumValue("Seminterrato")
    SEMINTERRATO("Seminterrato"),
    @XmlEnumValue("PianoTerra")
    PIANO_TERRA("PianoTerra"),
    @XmlEnumValue("Rialzato")
    RIALZATO("Rialzato"),
    @XmlEnumValue("Multipiano")
    MULTIPIANO("Multipiano"),
    @XmlEnumValue("Ultimo")
    ULTIMO("Ultimo");
    private final String value;

    DetailedFloorSizeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static DetailedFloorSizeType fromValue(String v) {
        for (DetailedFloorSizeType c: DetailedFloorSizeType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
using namespace nv;

FloatImage * nv::createNormalMipmapMap(const FloatImage * img)
{
	nvDebugCheck(img != NULL);

	uint w = img->width();
	uint h = img->height();

	uint hw = w / 2;
	uint hh = h / 2;

	FloatImage dotImg;
	dotImg.allocate(1, w, h);

	FloatImage shImg;
	shImg.allocate(9, hw, hh);

	SampleDistribution distribution(256);
	const uint sampleCount = distribution.sampleCount();

	for (uint d = 0; d < sampleCount; d++)
	{
		const float * xChannel = img->channel(0);
		const float * yChannel = img->channel(1);
		const float * zChannel = img->channel(2);

		Vector3 dir = distribution.sampleDir(d);

		Sh2 basis;
		basis.eval(dir);

		for(uint i = 0; i < w*h; i++)
		{
			Vector3 normal(xChannel[i], yChannel[i], zChannel[i]);
			normal = normalizeSafe(normal, Vector3(zero), 0.0f);

			dotImg.setPixel(dot(dir, normal), d);
		}

		// @@ It would be nice to have a fastDownSample that took an existing image as an argument, to avoid allocations.
		AutoPtr<FloatImage> dotMip(dotImg.fastDownSample());

		for(uint p = 0; p < hw*hh; p++)
		{
			float f = dotMip->pixel(p);

			// Project irradiance to sh basis and accumulate.
			for (uint i = 0; i < 9; i++)
			{
				float & sum = shImg.channel(i)[p];
				sum += f * basis.elemAt(i);
			}
		}
	}

	FloatImage * normalMipmap = new FloatImage;
	normalMipmap->allocate(4, hw, hh);

	// Precompute the clamped cosine radiance transfer.
	Sh2 prt;
	prt.cosineTransfer();

	// Allocate outside the loop.
	Sh2 sh;

	for(uint p = 0; p < hw*hh; p++)
	{
		for (uint i = 0; i < 9; i++)
		{
			sh.elemAt(i) = shImg.channel(i)[p];
		}

		// Convolve sh irradiance by radiance transfer.
		sh *= prt;

		// Now sh(0) is the ambient occlusion.
		// and sh(1) is the normal direction.

		// Should we use SVD to fit only the normals to the SH?

	}

	return normalMipmap;
}


text:
namespace Microsoft.Azure.Commands.Kubernetes.Generated.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Contains information about SSH certificate public key data.
    /// </summary>
    public partial class ContainerServiceSshPublicKey
    {
        /// <summary>
        /// Initializes a new instance of the ContainerServiceSshPublicKey
        /// class.
        /// </summary>
        public ContainerServiceSshPublicKey()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ContainerServiceSshPublicKey
        /// class.
        /// </summary>
        /// <param name="keyData">Certificate public key used to authenticate
        /// with VMs through SSH. The certificate must be in PEM format with or
        /// without headers.</param>
        public ContainerServiceSshPublicKey(string keyData)
        {
            KeyData = keyData;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets certificate public key used to authenticate with VMs
        /// through SSH. The certificate must be in PEM format with or without
        /// headers.
        /// </summary>
        [JsonProperty(PropertyName = "keyData")]
        public string KeyData { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (KeyData == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "KeyData");
            }
        }
    }
}