text:
//snippet-sourcedescription:[SNSMessageFilterPolicy.java stores the filterPolicy field as a map.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-keyword:[Amazon Simple Notification Service]

package com.example.sns;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest;

/*
  You can use the addAttribute(), addAttributePrefix(), and addAttributeAnythingBut()
  methods to add attributes to your policy. These methods accept the attribute name as a string,
  and they are specialized to accept different value types. You can pass values as strings,
  lists of strings, numbers, or number ranges and you can also add the attributes anything-but
  and prefix.
 */

/**
 * Before running this Java V2 code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SNSMessageFilterPolicy {

    private final Map<String, Attribute> filterPolicy = new HashMap<>();

    public void addAttribute(final String attributeName, final String attributeValue) {
        filterPolicy.put(attributeName, new Attribute<>(AttributeType.String, attributeValue));
    }

    public void addAttribute(final String attributeName, final ArrayList<String> attributeValues) {
        final ArrayList<Attribute> attributes = new ArrayList<>();
        for (final String s : attributeValues) {
            attributes.add(new Attribute<>(AttributeType.String, s));
        }
        filterPolicy.put(attributeName, new Attribute<>(AttributeType.List, attributes));
    }

    public void addAttributePrefix(final String attributeName, final String prefix) {
        filterPolicy.put(attributeName, new Attribute<>(AttributeType.Prefix, prefix));
    }

    public void addAttributeAnythingBut(final String attributeName, final String value) {
        filterPolicy.put(attributeName, new Attribute<>(AttributeType.AnythingBut, value));
    }

    public <T extends Number> void addAttribute(final String attributeName, final String op, final T value) {
        filterPolicy.put(attributeName, new Attribute<>(AttributeType.Numeric, new NumericValue<>(op, value)));
    }

    public <T extends Number> void addAttributeRange(
            final String attributeName,
            final String lowerOp,
            final T lower,
            final String upperOp,
            final T upper) {
        filterPolicy.put(attributeName,
                new Attribute<>(AttributeType.Numeric, new NumericValue<>(lowerOp, lower, upperOp, upper)));
    }

    // This method produces a policy string from the contents of the filterPolicy map,
    // and then applies the policy to the specified subscription.
    public void apply(SnsClient snsClient, String subscriptionArn) {

        SetSubscriptionAttributesRequest request = SetSubscriptionAttributesRequest.builder()
                .subscriptionArn(subscriptionArn)
                .attributeName("FilterPolicy")
                .attributeValue(formatFilterPolicy())
                .build();

        snsClient.setSubscriptionAttributes(request);
    }

    private String formatFilterPolicy() {
        return filterPolicy.entrySet()
                .stream()
                .map(entry -> "\"" + entry.getKey() + "\": [" + entry.getValue() + "]")
                .collect(Collectors.joining(", ", "{", "}"));
    }

    private enum AttributeType {
        String, Numeric, Prefix, List, AnythingBut
    }

    private class Attribute<T> {
        final T value;
        final AttributeType type;

        Attribute(final AttributeType type, final T value) {
            this.value = value;
            this.type = type;
        }

        public String toString() {
            switch (type) {
                case Prefix:
                    return String.format("{\"prefix\":\"%s\"}", value.toString());
                case Numeric:
                    return String.format("{\"numeric\":%s}", value.toString());
                case List:
                    final List list = (List)value;
                    final ArrayList<T> values = new ArrayList<T>(list);
                    return values
                            .stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(","));
                case AnythingBut:
                    return String.format("{\"anything-but\":\"%s\"}", value);
                default:
                    return String.format("\"%s\"", value);
            }
        }
    }

    private class NumericValue<T extends Number> {
        private final T lower;
        private final T upper;
        private final String lowerOp;
        private final String upperOp;

        NumericValue(final String op, final T value) {
            lower = value;
            lowerOp = op;
            upper = null;
            upperOp = null;
        }

        NumericValue(final String lowerOp, final T lower, final String upperOp, final T upper) {
            this.lower = lower;
            this.lowerOp = lowerOp;
            this.upper = upper;
            this.upperOp = upperOp;
        }

        public String toString() {
            final StringBuilder s = new StringBuilder("[")
                    .append('\"')
                    .append(lowerOp)
                    .append("\",")
                    .append(lower);
            if (upper != null) {
                s.append(",\"")
                        .append(upperOp).
                        append("\",").
                        append(upper);
            }
            s.append("]");
            return s.toString();
        }
    }
}


text:
<?php

namespace Slashworks\AppBundle\Model\map;

use \RelationMap;
use \TableMap;

/**
 * This class defines the structure of the 'customer' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.src.Slashworks.AppBundle.Model.map
 */
class CustomerTableMap extends TableMap
{

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = 'src.Slashworks.AppBundle.Model.map.CustomerTableMap';

    /**
     * Initialize the table attributes, columns and validators
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('customer');
        $this->setPhpName('Customer');
        $this->setClassname('Slashworks\\AppBundle\\Model\\Customer');
        $this->setPackage('src.Slashworks.AppBundle.Model');
        $this->setUseIdGenerator(true);
        // columns
        $this->addPrimaryKey('id', 'Id', 'INTEGER', true, 10, null);
        $this->addColumn('name', 'Name', 'VARCHAR', true, 100, null);
        $this->addColumn('street', 'Street', 'VARCHAR', false, 50, null);
        $this->addColumn('zip', 'Zip', 'VARCHAR', false, 8, null);
        $this->addColumn('city', 'City', 'VARCHAR', false, 50, null);
        $this->addForeignKey('country_id', 'CountryId', 'INTEGER', 'country', 'id', true, 10, null);
        $this->addColumn('phone', 'Phone', 'VARCHAR', false, 20, null);
        $this->addColumn('fax', 'Fax', 'VARCHAR', false, 20, null);
        $this->addColumn('email', 'Email', 'VARCHAR', true, 50, null);
        $this->addColumn('legalform', 'Legalform', 'VARCHAR', false, 20, null);
        $this->addColumn('logo', 'Logo', 'VARCHAR', false, 255, null);
        $this->addColumn('created', 'Created', 'TIMESTAMP', true, null, null);
        $this->addColumn('notes', 'Notes', 'LONGVARCHAR', false, null, null);
        // validators
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
        $this->addRelation('Country', 'Slashworks\\AppBundle\\Model\\Country', RelationMap::MANY_TO_ONE, array('country_id' => 'id', ), null, 'CASCADE');
        $this->addRelation('RemoteApp', 'Slashworks\\AppBundle\\Model\\RemoteApp', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'SET NULL', 'CASCADE', 'RemoteApps');
        $this->addRelation('UserCustomerRelation', 'Slashworks\\AppBundle\\Model\\UserCustomerRelation', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'CASCADE', 'UserCustomerRelations');
    } // buildRelations()

} // CustomerTableMap

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"io/ioutil"
	"os"

	"github.com/Shopify/ejson"
)

func encryptAction(args []string) error {
	if len(args) < 1 {
		return fmt.Errorf("at least one file path must be given")
	}
	for _, filePath := range args {
		n, err := ejson.EncryptFileInPlace(filePath)
		if err != nil {
			return err
		}
		fmt.Printf("Wrote %d bytes to %s.\n", n, filePath)
	}
	return nil
}

func decryptAction(args []string, keydir, userSuppliedPrivateKey, outFile string) error {
	if len(args) != 1 {
		return fmt.Errorf("exactly one file path must be given")
	}
	decrypted, err := ejson.DecryptFile(args[0], keydir, userSuppliedPrivateKey)
	if err != nil {
		return err
	}

	target := os.Stdout
	if outFile != "" {
		target, err = os.Create(outFile)
		if err != nil {
			return err
		}
		defer func() { _ = target.Close() }()
	}

	_, err = target.Write(decrypted)
	return err
}

func keygenAction(args []string, keydir string, wFlag bool) error {
	pub, priv, err := ejson.GenerateKeypair()
	if err != nil {
		return err
	}

	if wFlag {
		keyFile := fmt.Sprintf("%s/%s", keydir, pub)
		err := writeFile(keyFile, append([]byte(priv), '\n'), 0440)
		if err != nil {
			return err
		}
		fmt.Println(pub)
	} else {
		fmt.Printf("Public Key:\n%s\nPrivate Key:\n%s\n", pub, priv)
	}
	return nil
}

// for mocking in tests
var (
	writeFile = ioutil.WriteFile
)


text:
#import "RCTConvert.h"
#import "RCTVideo.h"
#import "RCTBridgeModule.h"
#import "RCTEventDispatcher.h"
#import "UIView+React.h"

static NSString *const statusKeyPath = @"status";
static NSString *const playbackLikelyToKeepUpKeyPath = @"playbackLikelyToKeepUp";
static NSString *const playbackBufferEmptyKeyPath = @"playbackBufferEmpty";
static NSString *const readyForDisplayKeyPath = @"readyForDisplay";
static NSString *const playbackRate = @"rate";

@implementation RCTVideo
{
  AVPlayer *_player;
  AVPlayerItem *_playerItem;
  BOOL _playerItemObserversSet;
  BOOL _playerBufferEmpty;
  AVPlayerLayer *_playerLayer;
  AVPlayerViewController *_playerViewController;
  NSURL *_videoURL;

  /* Required to publish events */
  RCTEventDispatcher *_eventDispatcher;
  BOOL _playbackRateObserverRegistered;

  bool _pendingSeek;
  float _pendingSeekTime;
  float _lastSeekTime;

  /* For sending videoProgress events */
  Float64 _progressUpdateInterval;
  BOOL _controls;
  id _timeObserver;

  /* Keep track of any modifiers, need to be applied after each play */
  float _volume;
  float _rate;
  BOOL _muted;
  BOOL _paused;
  BOOL _repeat;
  BOOL _playbackStalled;
  BOOL _playInBackground;
  BOOL _playWhenInactive;
  NSString * _resizeMode;
  BOOL _fullscreenPlayerPresented;
  UIViewController * _presentingViewController;
}

- (instancetype)initWithEventDispatcher:(RCTEventDispatcher *)eventDispatcher
{
  if ((self = [super init])) {
    _eventDispatcher = eventDispatcher;

    _playbackRateObserverRegistered = NO;
    _playbackStalled = NO;
    _rate = 1.0;
    _volume = 1.0;
    _resizeMode = @"AVLayerVideoGravityResizeAspectFill";
    _pendingSeek = false;
    _pendingSeekTime = 0.0f;
    _lastSeekTime = 0.0f;
    _progressUpdateInterval = 250;
    _controls = NO;
    _playerBufferEmpty = YES;
    _playInBackground = false;
    _playWhenInactive = false;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
  }

  return self;
}

- (AVPlayerViewController*)createPlayerViewController:(AVPlayer*)player withPlayerItem:(AVPlayerItem*)playerItem {
    RCTVideoPlayerViewController* playerLayer= [[RCTVideoPlayerViewController alloc] init];
    playerLayer.showsPlaybackControls = NO;
    playerLayer.rctDelegate = self;
    playerLayer.view.frame = self.bounds;
    playerLayer.player = _player;
    playerLayer.view.frame = self.bounds;
    return playerLayer;
}

/* ---------------------------------------------------------
 **  Get the duration for a AVPlayerItem.
 ** ------------------------------------------------------- */

- (CMTime)playerItemDuration
{
    AVPlayerItem *playerItem = [_player currentItem];
    if (playerItem.status == AVPlayerItemStatusReadyToPlay)
    {
        return([playerItem duration]);
    }

    return(kCMTimeInvalid);
}

/* Cancels the previously registered time observer. */
-(void)removePlayerTimeObserver
{
    if (_timeObserver)
    {
        [_player removeTimeObserver:_timeObserver];
        _timeObserver = nil;
    }
}

#pragma mark - Progress

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - App lifecycle handlers

- (void)applicationWillResignActive:(NSNotification *)notification
{
  if (_playInBackground || _playWhenInactive || _paused) return;

  [_player pause];
  [_player setRate:0.0];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
  if (_playInBackground) {
    // Needed to play sound in background. See https://developer.apple.com/library/ios/qa/qa1668/_index.html
    [_playerLayer setPlayer:nil];
  }
}

- (void)applicationWillEnterForeground:(NSNotification *)notification
{
  [self applyModifiers];
  if (_playInBackground) {
    [_playerLayer setPlayer:_player];
  }
}

#pragma mark - Progress

- (void)sendProgressUpdate
{
   AVPlayerItem *video = [_player currentItem];
   if (video == nil || video.status != AVPlayerItemStatusReadyToPlay) {
     return;
   }

   CMTime playerDuration = [self playerItemDuration];
   if (CMTIME_IS_INVALID(playerDuration)) {
      return;
   }

   CMTime currentTime = _player.currentTime;
   const Float64 duration = CMTimeGetSeconds(playerDuration);
   const Float64 currentTimeSecs = CMTimeGetSeconds(currentTime);
   if( currentTimeSecs >= 0 && currentTimeSecs <= duration) {
        [_eventDispatcher sendInputEventWithName:@"onVideoProgress"
                                            body:@{
                                                     @"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(currentTime)],
                                                     @"playableDuration": [self calculatePlayableDuration],
                                                     @"atValue": [NSNumber numberWithLongLong:currentTime.value],
                                                     @"atTimescale": [NSNumber numberWithInt:currentTime.timescale],
                                                     @"target": self.reactTag
                                                 }];
   }
}

/*!
 * Calculates and returns the playable duration of the current player item using its loaded time ranges.
 *
 * \returns The playable duration of the current player item in seconds.
 */
- (NSNumber *)calculatePlayableDuration
{
  AVPlayerItem *video = _player.currentItem;
  if (video.status == AVPlayerItemStatusReadyToPlay) {
    __block CMTimeRange effectiveTimeRange;
    [video.loadedTimeRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      CMTimeRange timeRange = [obj CMTimeRangeValue];
      if (CMTimeRangeContainsTime(timeRange, video.currentTime)) {
        effectiveTimeRange = timeRange;
        *stop = YES;
      }
    }];
    Float64 playableDuration = CMTimeGetSeconds(CMTimeRangeGetEnd(effectiveTimeRange));
    if (playableDuration > 0) {
      return [NSNumber numberWithFloat:playableDuration];
    }
  }
  return [NSNumber numberWithInteger:0];
}

- (void)addPlayerItemObservers
{
  [_playerItem addObserver:self forKeyPath:statusKeyPath options:0 context:nil];
  [_playerItem addObserver:self forKeyPath:playbackBufferEmptyKeyPath options:0 context:nil];
  [_playerItem addObserver:self forKeyPath:playbackLikelyToKeepUpKeyPath options:0 context:nil];
  _playerItemObserversSet = YES;
}

/* Fixes https://github.com/brentvatne/react-native-video/issues/43
 * Crashes caused when trying to remove the observer when there is no
 * observer set */
- (void)removePlayerItemObservers
{
  if (_playerItemObserversSet) {
    [_playerItem removeObserver:self forKeyPath:statusKeyPath];
    [_playerItem removeObserver:self forKeyPath:playbackBufferEmptyKeyPath];
    [_playerItem removeObserver:self forKeyPath:playbackLikelyToKeepUpKeyPath];
    _playerItemObserversSet = NO;
  }
}

#pragma mark - Player and source

- (void)setSrc:(NSDictionary *)source
{
  [self removePlayerTimeObserver];
  [self removePlayerItemObservers];
  _playerItem = [self playerItemForSource:source];
  [self addPlayerItemObservers];

  [_player pause];
  [self removePlayerLayer];
  [_playerViewController.view removeFromSuperview];
  _playerViewController = nil;

  if (_playbackRateObserverRegistered) {
    [_player removeObserver:self forKeyPath:playbackRate context:nil];
    _playbackRateObserverRegistered = NO;
  }

  _player = [AVPlayer playerWithPlayerItem:_playerItem];
  _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

  [_player addObserver:self forKeyPath:playbackRate options:0 context:nil];
  _playbackRateObserverRegistered = YES;

  const Float64 progressUpdateIntervalMS = _progressUpdateInterval / 1000;
  // @see endScrubbing in AVPlayerDemoPlaybackViewController.m of https://developer.apple.com/library/ios/samplecode/AVPlayerDemo/Introduction/Intro.html
  __weak RCTVideo *weakSelf = self;
  _timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(progressUpdateIntervalMS, NSEC_PER_SEC)
                                                        queue:NULL
                                                   usingBlock:^(CMTime time) { [weakSelf sendProgressUpdate]; }
                   ];
  [_eventDispatcher sendInputEventWithName:@"onVideoLoadStart"
                                      body:@{@"src": @{
                                                 @"uri": [source objectForKey:@"uri"],
                                                 @"type": [source objectForKey:@"type"],
                                                 @"isNetwork":[NSNumber numberWithBool:(bool)[source objectForKey:@"isNetwork"]]},
                                             @"target": self.reactTag}];
}

- (AVPlayerItem*)playerItemForSource:(NSDictionary *)source
{
  bool isNetwork = [RCTConvert BOOL:[source objectForKey:@"isNetwork"]];
  bool isAsset = [RCTConvert BOOL:[source objectForKey:@"isAsset"]];
  NSString *uri = [source objectForKey:@"uri"];
  NSString *type = [source objectForKey:@"type"];

  NSURL *url = (isNetwork || isAsset) ?
    [NSURL URLWithString:uri] :
    [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:uri ofType:type]];

  if (isAsset) {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    return [AVPlayerItem playerItemWithAsset:asset];
  }

  return [AVPlayerItem playerItemWithURL:url];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   if (object == _playerItem) {

    if ([keyPath isEqualToString:statusKeyPath]) {
      // Handle player item status change.
      if (_playerItem.status == AVPlayerItemStatusReadyToPlay) {
        float duration = CMTimeGetSeconds(_playerItem.asset.duration);

        if (isnan(duration)) {
          duration = 0.0;
        }

        NSObject *width = @"undefined";
        NSObject *height = @"undefined";
        NSString *orientation = @"undefined";

        if ([_playerItem.asset tracksWithMediaType:AVMediaTypeVideo].count > 0) {
          AVAssetTrack *videoTrack = [[_playerItem.asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
          width = [NSNumber numberWithFloat:videoTrack.naturalSize.width];
          height = [NSNumber numberWithFloat:videoTrack.naturalSize.height];
          CGAffineTransform preferredTransform = [videoTrack preferredTransform];

          if ((videoTrack.naturalSize.width == preferredTransform.tx
            && videoTrack.naturalSize.height == preferredTransform.ty)
            || (preferredTransform.tx == 0 && preferredTransform.ty == 0))
          {
            orientation = @"landscape";
          } else
            orientation = @"portrait";
        }

        [_eventDispatcher sendInputEventWithName:@"onVideoLoad"
                                            body:@{@"duration": [NSNumber numberWithFloat:duration],
                                                   @"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(_playerItem.currentTime)],
                                                   @"canPlayReverse": [NSNumber numberWithBool:_playerItem.canPlayReverse],
                                                   @"canPlayFastForward": [NSNumber numberWithBool:_playerItem.canPlayFastForward],
                                                   @"canPlaySlowForward": [NSNumber numberWithBool:_playerItem.canPlaySlowForward],
                                                   @"canPlaySlowReverse": [NSNumber numberWithBool:_playerItem.canPlaySlowReverse],
                                                   @"canStepBackward": [NSNumber numberWithBool:_playerItem.canStepBackward],
                                                   @"canStepForward": [NSNumber numberWithBool:_playerItem.canStepForward],
                                                   @"naturalSize": @{
                                                        @"width": width,
                                                        @"height": height,
                                                        @"orientation": orientation
                                                        },
                                                   @"target": self.reactTag}];

        [self attachListeners];
        [self applyModifiers];
      } else if(_playerItem.status == AVPlayerItemStatusFailed) {
        [_eventDispatcher sendInputEventWithName:@"onVideoError"
                                            body:@{@"error": @{
                                                       @"code": [NSNumber numberWithInteger: _playerItem.error.code],
                                                       @"domain": _playerItem.error.domain},
                                                   @"target": self.reactTag}];
      }
    } else if ([keyPath isEqualToString:playbackBufferEmptyKeyPath]) {
      _playerBufferEmpty = YES;
    } else if ([keyPath isEqualToString:playbackLikelyToKeepUpKeyPath]) {
      // Continue playing (or not if paused) after being paused due to hitting an unbuffered zone.
      if ((!_controls || _playerBufferEmpty) && _playerItem.playbackLikelyToKeepUp) {
        [self setPaused:_paused];
      }
      _playerBufferEmpty = NO;
    }
   } else if (object == _playerLayer) {
      if([keyPath isEqualToString:readyForDisplayKeyPath] && [change objectForKey:NSKeyValueChangeNewKey]) {
        if([change objectForKey:NSKeyValueChangeNewKey]) {
          [_eventDispatcher sendInputEventWithName:@"onReadyForDisplay"
                                              body:@{@"target": self.reactTag}];
        }
    }
  } else if (object == _player) {
      if([keyPath isEqualToString:playbackRate]) {
          [_eventDispatcher sendInputEventWithName:@"onPlaybackRateChange"
                                              body:@{@"playbackRate": [NSNumber numberWithFloat:_player.rate],
                                                     @"target": self.reactTag}];
          if(_playbackStalled && _player.rate > 0) {
              [_eventDispatcher sendInputEventWithName:@"onPlaybackResume"
                                                  body:@{@"playbackRate": [NSNumber numberWithFloat:_player.rate],
                                                         @"target": self.reactTag}];
              _playbackStalled = NO;
          }
      }
  } else {
      [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  }
}

- (void)attachListeners
{
  // listen for end of file
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(playerItemDidReachEnd:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:[_player currentItem]];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(playbackStalled:)
                                               name:AVPlayerItemPlaybackStalledNotification
                                             object:nil];
}

- (void)playbackStalled:(NSNotification *)notification
{
  [_eventDispatcher sendInputEventWithName:@"onPlaybackStalled" body:@{@"target": self.reactTag}];
  _playbackStalled = YES;
}

- (void)playerItemDidReachEnd:(NSNotification *)notification
{
  [_eventDispatcher sendInputEventWithName:@"onVideoEnd" body:@{@"target": self.reactTag}];

  if (_repeat) {
    AVPlayerItem *item = [notification object];
    [item seekToTime:kCMTimeZero];
    [self applyModifiers];
  }
}

#pragma mark - Prop setters

- (void)setResizeMode:(NSString*)mode
{
  if( _controls )
  {
    _playerViewController.videoGravity = mode;
  }
  else
  {
    _playerLayer.videoGravity = mode;
  }
  _resizeMode = mode;
}

- (void)setPlayInBackground:(BOOL)playInBackground
{
  _playInBackground = playInBackground;
}

- (void)setPlayWhenInactive:(BOOL)playWhenInactive
{
  _playWhenInactive = playWhenInactive;
}

- (void)setPaused:(BOOL)paused
{
  if (paused) {
    [_player pause];
    [_player setRate:0.0];
  } else {
    [_player play];
    [_player setRate:_rate];
  }

  _paused = paused;
}

- (float)getCurrentTime
{
  return _playerItem != NULL ? CMTimeGetSeconds(_playerItem.currentTime) : 0;
}

- (void)setCurrentTime:(float)currentTime
{
  [self setSeek: currentTime];
}

- (void)setSeek:(float)seekTime
{
  int timeScale = 10000;

  AVPlayerItem *item = _player.currentItem;
  if (item && item.status == AVPlayerItemStatusReadyToPlay) {
    // TODO check loadedTimeRanges

    CMTime cmSeekTime = CMTimeMakeWithSeconds(seekTime, timeScale);
    CMTime current = item.currentTime;
    // TODO figure out a good tolerance level
    CMTime tolerance = CMTimeMake(1000, timeScale);

    if (CMTimeCompare(current, cmSeekTime) != 0) {
      [_player seekToTime:cmSeekTime toleranceBefore:tolerance toleranceAfter:tolerance completionHandler:^(BOOL finished) {
        [_eventDispatcher sendInputEventWithName:@"onVideoSeek"
                                            body:@{@"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(item.currentTime)],
                                                   @"seekTime": [NSNumber numberWithFloat:seekTime],
                                                   @"target": self.reactTag}];
      }];

      _pendingSeek = false;
    }

  } else {
    // TODO: See if this makes sense and if so, actually implement it
    _pendingSeek = true;
    _pendingSeekTime = seekTime;
  }
}

- (void)setRate:(float)rate
{
  _rate = rate;
  [self applyModifiers];
}

- (void)setMuted:(BOOL)muted
{
  _muted = muted;
  [self applyModifiers];
}

- (void)setVolume:(float)volume
{
  _volume = volume;
  [self applyModifiers];
}

- (void)applyModifiers
{
  if (_muted) {
    [_player setVolume:0];
    [_player setMuted:YES];
  } else {
    [_player setVolume:_volume];
    [_player setMuted:NO];
  }

  [self setResizeMode:_resizeMode];
  [self setRepeat:_repeat];
  [self setPaused:_paused];
  [self setControls:_controls];
}

- (void)setRepeat:(BOOL)repeat {
  _repeat = repeat;
}

- (BOOL)getFullscreen
{
    return _fullscreenPlayerPresented;
}

- (void)setFullscreen:(BOOL)fullscreen
{
    if( fullscreen && !_fullscreenPlayerPresented )
    {
        // Ensure player view controller is not null
        if( !_playerViewController )
        {
            [self usePlayerViewController];
        }
        // Set presentation style to fullscreen
        [_playerViewController setModalPresentationStyle:UIModalPresentationFullScreen];

        // Find the nearest view controller
        UIViewController *viewController = [self firstAvailableUIViewController];
        if( !viewController )
        {
            UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
            viewController = keyWindow.rootViewController;
            if( viewController.childViewControllers.count > 0 )
            {
                viewController = viewController.childViewControllers.lastObject;
            }
        }
        if( viewController )
        {
            _presentingViewController = viewController;
            [_eventDispatcher sendInputEventWithName:@"onVideoFullscreenPlayerWillPresent" body:@{@"target": self.reactTag}];
            [viewController presentViewController:_playerViewController animated:true completion:^{
                _playerViewController.showsPlaybackControls = YES;
                _fullscreenPlayerPresented = fullscreen;
                [_eventDispatcher sendInputEventWithName:@"onVideoFullscreenPlayerDidPresent" body:@{@"target": self.reactTag}];
            }];
        }
    }
    else if ( !fullscreen && _fullscreenPlayerPresented )
    {
        [self videoPlayerViewControllerWillDismiss:_playerViewController];
        [_presentingViewController dismissViewControllerAnimated:true completion:^{
            [self videoPlayerViewControllerDidDismiss:_playerViewController];
        }];
    }
}

- (void)usePlayerViewController
{
    if( _player )
    {
        _playerViewController = [self createPlayerViewController:_player withPlayerItem:_playerItem];
        [self addSubview:_playerViewController.view];
    }
}

- (void)usePlayerLayer
{
    if( _player )
    {
      _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
      _playerLayer.frame = self.bounds;
      _playerLayer.needsDisplayOnBoundsChange = YES;

      [_playerLayer addObserver:self forKeyPath:readyForDisplayKeyPath options:NSKeyValueObservingOptionNew context:nil];

      [self.layer addSublayer:_playerLayer];
      self.layer.needsDisplayOnBoundsChange = YES;
    }
}

- (void)setControls:(BOOL)controls
{
    if( _controls != controls || (!_playerLayer && !_playerViewController) )
    {
        _controls = controls;
        if( _controls )
        {
            [self removePlayerLayer];
            [self usePlayerViewController];
        }
        else
        {
            [_playerViewController.view removeFromSuperview];
            _playerViewController = nil;
            [self usePlayerLayer];
        }
    }
}

- (void)removePlayerLayer
{
    [_playerLayer removeFromSuperlayer];
    [_playerLayer removeObserver:self forKeyPath:readyForDisplayKeyPath];
    _playerLayer = nil;
}

#pragma mark - RCTVideoPlayerViewControllerDelegate

- (void)videoPlayerViewControllerWillDismiss:(AVPlayerViewController *)playerViewController
{
    if (_playerViewController == playerViewController && _fullscreenPlayerPresented)
    {
        [_eventDispatcher sendInputEventWithName:@"onVideoFullscreenPlayerWillDismiss" body:@{@"target": self.reactTag}];
    }
}

- (void)videoPlayerViewControllerDidDismiss:(AVPlayerViewController *)playerViewController
{
    if (_playerViewController == playerViewController && _fullscreenPlayerPresented)
    {
        _fullscreenPlayerPresented = false;
        _presentingViewController = nil;
        [self applyModifiers];
        [_eventDispatcher sendInputEventWithName:@"onVideoFullscreenPlayerDidDismiss" body:@{@"target": self.reactTag}];
    }
}

#pragma mark - React View Management

- (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
{
  // We are early in the game and somebody wants to set a subview.
  // That can only be in the context of playerViewController.
  if( !_controls && !_playerLayer && !_playerViewController )
  {
    [self setControls:true];
  }

  if( _controls )
  {
     view.frame = self.bounds;
     [_playerViewController.contentOverlayView insertSubview:view atIndex:atIndex];
  }
  else
  {
     RCTLogError(@"video cannot have any subviews");
  }
  return;
}

- (void)removeReactSubview:(UIView *)subview
{
  if( _controls )
  {
      [subview removeFromSuperview];
  }
  else
  {
    RCTLogError(@"video cannot have any subviews");
  }
  return;
}

- (void)layoutSubviews
{
  [super layoutSubviews];
  if( _controls )
  {
    _playerViewController.view.frame = self.bounds;

    // also adjust all subviews of contentOverlayView
    for (UIView* subview in _playerViewController.contentOverlayView.subviews) {
      subview.frame = self.bounds;
    }
  }
  else
  {
      [CATransaction begin];
      [CATransaction setAnimationDuration:0];
      _playerLayer.frame = self.bounds;
      [CATransaction commit];
  }
}

#pragma mark - Lifecycle

- (void)removeFromSuperview
{
  [_player pause];
  if (_playbackRateObserverRegistered) {
    [_player removeObserver:self forKeyPath:playbackRate context:nil];
    _playbackRateObserverRegistered = NO;
  }
  _player = nil;

  [self removePlayerLayer];

  [_playerViewController.view removeFromSuperview];
  _playerViewController = nil;

  [self removePlayerTimeObserver];
  [self removePlayerItemObservers];

  _eventDispatcher = nil;
  [[NSNotificationCenter defaultCenter] removeObserver:self];

  [super removeFromSuperview];
}

@end


text:
/**
 * @file
 *   This file implements the Thread network interface.
 */

#include "thread_netif.hpp"

#include "common/code_utils.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
#include "common/message.hpp"
#include "net/ip6.hpp"
#include "net/netif.hpp"
#include "net/udp6.hpp"
#include "thread/mle.hpp"
#include "thread/thread_tlvs.hpp"
#include "thread/thread_uri_paths.hpp"
#include "utils/slaac_address.hpp"

using ot::Encoding::BigEndian::HostSwap16;

namespace ot {

ThreadNetif::ThreadNetif(Instance &aInstance)
    : Netif(aInstance, OT_NETIF_INTERFACE_ID_THREAD)
    , mCoap(aInstance)
#if OPENTHREAD_ENABLE_DHCP6_CLIENT
    , mDhcp6Client(aInstance)
#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT
#if OPENTHREAD_ENABLE_DHCP6_SERVER
    , mDhcp6Server(aInstance)
#endif // OPENTHREAD_ENABLE_DHCP6_SERVER
#if OPENTHREAD_ENABLE_DNS_CLIENT
    , mDnsClient(aInstance.GetThreadNetif())
#endif // OPENTHREAD_ENABLE_DNS_CLIENT
#if OPENTHREAD_ENABLE_SNTP_CLIENT
    , mSntpClient(aInstance.GetThreadNetif())
#endif // OPENTHREAD_ENABLE_SNTP_CLIENT
    , mActiveDataset(aInstance)
    , mPendingDataset(aInstance)
    , mKeyManager(aInstance)
    , mLowpan(aInstance)
    , mMac(aInstance)
    , mMeshForwarder(aInstance)
    , mMleRouter(aInstance)
#if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE
    , mNetworkDataLocal(aInstance)
#endif
    , mNetworkDataLeader(aInstance)
#if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC
    , mNetworkDiagnostic(aInstance)
#endif
    , mIsUp(false)
#if OPENTHREAD_ENABLE_BORDER_AGENT
    , mBorderAgent(aInstance)
#endif
#if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD
    , mCommissioner(aInstance)
#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD
#if OPENTHREAD_ENABLE_DTLS
    , mDtls(aInstance)
    , mCoapSecure(aInstance)
#endif
#if OPENTHREAD_ENABLE_JOINER
    , mJoiner(aInstance)
#endif // OPENTHREAD_ENABLE_JOINER
#if OPENTHREAD_ENABLE_JAM_DETECTION
    , mJamDetector(aInstance)
#endif // OPENTHREAD_ENABLE_JAM_DETECTION
#if OPENTHREAD_FTD
    , mJoinerRouter(aInstance)
    , mLeader(aInstance)
    , mAddressResolver(aInstance)
#endif // OPENTHREAD_FTD
    , mChildSupervisor(aInstance)
    , mSupervisionListener(aInstance)
    , mAnnounceBegin(aInstance)
    , mPanIdQuery(aInstance)
    , mEnergyScan(aInstance)
#if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC
    , mTimeSync(aInstance)
#endif
{
    mCoap.SetInterceptor(&ThreadNetif::TmfFilter, this);
    memset(mSlaacAddresses, 0, sizeof(mSlaacAddresses));
}

void ThreadNetif::Up(void)
{
    VerifyOrExit(!mIsUp);

    // Enable the MAC just in case it was disabled while the Interface was down.
    mMac.SetEnabled(true);
#if OPENTHREAD_ENABLE_CHANNEL_MONITOR
    GetInstance().GetChannelMonitor().Start();
#endif
    mMeshForwarder.Start();
    GetIp6().AddNetif(*this);

    mIsUp = true;

    SubscribeAllNodesMulticast();
    mMleRouter.Enable();
    mCoap.Start(kCoapUdpPort);
#if OPENTHREAD_ENABLE_DNS_CLIENT
    mDnsClient.Start();
#endif
#if OPENTHREAD_ENABLE_SNTP_CLIENT
    mSntpClient.Start();
#endif
    GetNotifier().Signal(OT_CHANGED_THREAD_NETIF_STATE);

exit:
    return;
}

void ThreadNetif::Down(void)
{
    VerifyOrExit(mIsUp);

#if OPENTHREAD_ENABLE_DTLS
    mDtls.Stop();
#endif
#if OPENTHREAD_ENABLE_DNS_CLIENT
    mDnsClient.Stop();
#endif
#if OPENTHREAD_ENABLE_SNTP_CLIENT
    mSntpClient.Stop();
#endif
    mCoap.Stop();
    mMleRouter.Disable();
    RemoveAllExternalUnicastAddresses();
    UnsubscribeAllExternalMulticastAddresses();
    UnsubscribeAllRoutersMulticast();
    UnsubscribeAllNodesMulticast();

    mIsUp = false;
    GetIp6().RemoveNetif(*this);
    mMeshForwarder.Stop();
#if OPENTHREAD_ENABLE_CHANNEL_MONITOR
    GetInstance().GetChannelMonitor().Stop();
#endif
    GetNotifier().Signal(OT_CHANGED_THREAD_NETIF_STATE);

exit:
    return;
}

otError ThreadNetif::GetLinkAddress(Ip6::LinkAddress &address) const
{
    address.mType       = Ip6::LinkAddress::kEui64;
    address.mLength     = sizeof(address.mExtAddress);
    address.mExtAddress = mMac.GetExtAddress();
    return OT_ERROR_NONE;
}

otError ThreadNetif::RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, uint8_t *aPrefixMatch)
{
    otError  error;
    uint16_t rloc;

    SuccessOrExit(error = mNetworkDataLeader.RouteLookup(aSource, aDestination, aPrefixMatch, &rloc));

    if (rloc == mMleRouter.GetRloc16())
    {
        error = OT_ERROR_NO_ROUTE;
    }

exit:
    return error;
}

otError ThreadNetif::TmfFilter(const Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo, void *aContext)
{
    OT_UNUSED_VARIABLE(aMessage);

    return static_cast<ThreadNetif *>(aContext)->IsTmfMessage(aMessageInfo) ? OT_ERROR_NONE : OT_ERROR_NOT_TMF;
}

bool ThreadNetif::IsTmfMessage(const Ip6::MessageInfo &aMessageInfo)
{
    bool rval = true;

    // A TMF message must comply with following rules:
    // 1. The destination is a Mesh Local Address or a Link-Local Multicast Address or a Realm-Local Multicast Address,
    //    and the source is a Mesh Local Address. Or
    // 2. Both the destination and the source are Link-Local Addresses.
    VerifyOrExit(
        ((mMleRouter.IsMeshLocalAddress(aMessageInfo.GetSockAddr()) ||
          aMessageInfo.GetSockAddr().IsLinkLocalMulticast() || aMessageInfo.GetSockAddr().IsRealmLocalMulticast()) &&
         mMleRouter.IsMeshLocalAddress(aMessageInfo.GetPeerAddr())) ||
            ((aMessageInfo.GetSockAddr().IsLinkLocal() || aMessageInfo.GetSockAddr().IsLinkLocalMulticast()) &&
             aMessageInfo.GetPeerAddr().IsLinkLocal()),
        rval = false);
exit:
    return rval;
}

void ThreadNetif::UpdateSlaac(void)
{
    Utils::Slaac::UpdateAddresses(&GetInstance(), mSlaacAddresses, OT_ARRAY_LENGTH(mSlaacAddresses),
                                  otIp6CreateRandomIid, NULL);
}

} // namespace ot


text:
// Copyright 2012 Max Toro Q.
//
// 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.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using System.Web.Routing;

namespace MvcAccount {

   /// <summary>
   /// Holds settings that customize the behavior of MvcAccount.
   /// </summary>
   public class AccountConfiguration {

      static readonly AccountConfiguration Default = new AccountConfiguration();

      static readonly string requiredDependencyMessage =
         "An implementation of {0} must be provided in one of two ways: " + Environment.NewLine +
         "1. Using constructor injection on controllers." + Environment.NewLine +
         "2. Setting either {1} or DependencyResolver on " + typeof(AccountConfiguration).FullName + ", passed via the Configuration property of " + typeof(MvcCodeRouting.CodeRoutingSettings).FullName + ".";

      Func<AccountRepository> _AccountRepositoryResolver;
      Func<PasswordService> _PasswordServiceResolver;
      Func<FormsAuthenticationService> _FormsAuthenticationServiceResolver;
      Func<MailService> _MailServiceResolver;

      /// <summary>
      /// A delegate that returns an <see cref="AccountConfiguration"/> instance.
      /// This setting is required only when using <see cref="MvcAccount.Web.Security.AccountMembershipProvider"/>.
      /// </summary>
      public static Func<AccountConfiguration> ConfigurationResolver { get; set; }

      /// <summary>
      /// A delegate that returns an <see cref="AccountRepository"/> implementation.
      /// This setting is optional if using controller dependency injection,
      /// but required when using <see cref="MvcAccount.Web.Security.AccountMembershipProvider"/>.
      /// </summary>
      public Func<AccountRepository> AccountRepositoryResolver {
         get {
            if (_AccountRepositoryResolver == null && DependencyResolver != null) {
               _AccountRepositoryResolver = () => (AccountRepository)DependencyResolver(typeof(AccountRepository));
            }
            return _AccountRepositoryResolver;
         }
         set {
            _AccountRepositoryResolver = value;
         }
      }

      /// <summary>
      /// A delegate that returns a <see cref="PasswordService"/> implementation.
      /// This setting is optional if using controller dependency injection,
      /// but required when using <see cref="MvcAccount.Web.Security.AccountMembershipProvider"/>.
      /// </summary>
      public Func<PasswordService> PasswordServiceResolver {
         get {
            if (_PasswordServiceResolver == null && DependencyResolver != null) {
               _PasswordServiceResolver = () => (PasswordService)DependencyResolver(typeof(PasswordService));
            }
            return _PasswordServiceResolver;
         }
         set {
            _PasswordServiceResolver = value;
         }
      }

      /// <summary>
      /// A delegate that returns a <see cref="FormsAuthenticationService"/> instance.
      /// This setting is always optional since <see cref="FormsAuthenticationService"/> is
      /// a concrete type, but can be used to provide a specialized implementation.
      /// </summary>
      public Func<FormsAuthenticationService> FormsAuthenticationServiceResolver {
         get {
            if (_FormsAuthenticationServiceResolver == null && DependencyResolver != null) {
               _FormsAuthenticationServiceResolver = () => (FormsAuthenticationService)DependencyResolver(typeof(FormsAuthenticationService));
            }
            return _FormsAuthenticationServiceResolver;
         }
         set {
            _FormsAuthenticationServiceResolver = value;
         }
      }

      /// <summary>
      /// A delegate that returns a <see cref="MailService"/> instance.
      /// This setting is always optional since <see cref="MailService"/> is
      /// a concrete type, but can be used to provide a specialized implementation.
      /// </summary>
      public Func<MailService> MailServiceResolver {
         get {
            if (_MailServiceResolver == null && DependencyResolver != null) {
               _MailServiceResolver = () => (MailService)DependencyResolver(typeof(MailService));
            }
            return _MailServiceResolver;
         }
         set {
            _MailServiceResolver = value;
         }
      }

      /// <summary>
      /// A delegate for resoving dependencies. This setting can be used instead of
      /// <see cref="AccountRepositoryResolver"/> and <see cref="PasswordServiceResolver"/>.
      /// </summary>
      public Func<Type, object> DependencyResolver { get; set; }

      /// <summary>
      /// True to send email with link to verify the email address. The default is true.
      /// </summary>
      public bool EnableEmailVerification { get; set; }

      /// <summary>
      /// True to enable user when email is verified. The default is true.
      /// </summary>
      public bool EmailVerificationEnablesUser { get; set; }

      /// <summary>
      /// Max. number of consecutive invalid sign in attempts. The default is 5.
      /// </summary>
      public int MaxInvalidSignInAttempts { get; set; }

      /// <summary>
      /// True to disable user if <see cref="MaxInvalidSignInAttempts"/> is exceeded.
      /// User must be manually enabled by an administrator. The default is false.
      /// </summary>
      public bool DisableOnMaxInvalidSignInAttempts { get; set; }

      /// <summary>
      /// The amount of time that must pass before a new sign in attempt, if user exceeded
      /// the <see cref="MaxInvalidSignInAttempts"/>.
      /// Not used if <see cref="DisableOnMaxInvalidSignInAttempts"/> is true.
      /// The default is 10 minutes.
      /// </summary>
      public TimeSpan SignInAttemptWindow { get; set; }

      /// <summary>
      /// Min. length required for passwords. The default is 6.
      /// </summary>
      public int MinPasswordLength { get; set; }

      /// <summary>
      /// Max. length allowed for passwords. The default is 16.
      /// </summary>
      public int MaxPasswordLength { get; set; }

      /// <summary>
      /// The kind of <see cref="DateTime"/> to use. The default is <see cref="System.DateTimeKind.Local"/>.
      /// </summary>
      public DateTimeKind DateTimeKind { get; set; }

      /// <summary>
      /// Specifies the time after which persistent authentication cookies expire.
      /// The default is 7 days.
      /// </summary>
      /// <remarks>
      /// ASP.NET uses the same expiration for both persistent and non-persistent authentication cookies.
      /// This settings allows you to increase the expiration of persistent authentication cookies.
      /// </remarks>
      public TimeSpan PersistentCookieTimeout { get; set; }

      /// <summary>
      /// The amount of time a password reset verification link is usable. The default is 24 hours.
      /// </summary>
      public TimeSpan PasswordResetTicketExpiration { get; set; }

      /// <summary>
      /// The amount of time a email change verification link is usable. The default is 24 hours.
      /// </summary>
      public TimeSpan EmailChangeTicketExpiration { get; set; }

      /// <summary>
      /// The name of the website, used in verification and notification emails.
      /// If null the <see cref="Uri.Host"/> of the current HTTP request URL is used.
      /// </summary>
      public string SiteName { get; set; }

      /// <summary>
      /// A resource where users can ask for help (URL, email, telephone, etc.),
      /// used in verification and notification emails.
      /// </summary>
      public string HelpResource { get; set; }

      /// <summary>
      /// The name of the resource file (class key) in App_GlobalResources that contains localized string values.
      /// </summary>
      public string ResourceClassKey { get; set; }

      internal static AccountConfiguration Current(RequestContext requestContext = null) {

         Func<AccountConfiguration> configResolver = ConfigurationResolver;

         if (requestContext == null) {

            HttpContext httpContext = HttpContext.Current;

            if (httpContext != null) {
               requestContext = httpContext.Request.RequestContext;

            } else {

               if (configResolver == null) {
                  throw new InvalidOperationException(
                     "To use MvcAccount when System.Web.HttpContext.Current is null please set {0}.ConfigurationResolver".FormatInvariant(typeof(AccountConfiguration).FullName)
                  );
               }

               return configResolver();
            }
         }

         if (configResolver == null) {
            configResolver = () => Default;
         }

         return requestContext.RouteData.DataTokens["Configuration"] as AccountConfiguration
            ?? configResolver();
      }

      /// <summary>
      /// Initializes a new instance of the <see cref="AccountConfiguration"/> class.
      /// </summary>
      public AccountConfiguration() {
         Reset();
      }

      /// <summary>
      /// Resets the members of the configuration class to their default values.
      /// </summary>
      public void Reset() {

         this.EnableEmailVerification = true;
         this.EmailVerificationEnablesUser = true;
         this.MaxInvalidSignInAttempts = 5;
         this.DisableOnMaxInvalidSignInAttempts = false;
         this.SignInAttemptWindow = TimeSpan.FromMinutes(10);
         this.MinPasswordLength = 6;
         this.MaxPasswordLength = 16;
         this.DateTimeKind = DateTimeKind.Local;
         this.PersistentCookieTimeout = TimeSpan.FromDays(7);
         this.PasswordResetTicketExpiration = TimeSpan.FromHours(24);
         this.EmailChangeTicketExpiration = TimeSpan.FromHours(24);
         this.SiteName = null;
         this.HelpResource = null;
         this.ResourceClassKey = null;
      }

      /// <summary>
      /// Gets the current <see cref="DateTime"/>.
      /// </summary>
      /// <returns>The current <see cref="DateTime"/>, which depends on <see cref="AccountConfiguration.DateTimeKind"/>.</returns>
      /// <seealso cref="AccountConfiguration.DateTimeKind"/>
      [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Calling the member twice in succession creates different results.")]
      public DateTime GetNow() {

         return (this.DateTimeKind == DateTimeKind.Utc) ?
            DateTime.UtcNow
            : DateTime.Now;
      }

      internal AccountRepository RequireDependency(AccountRepository injectedDependency, bool throwIfMissing = true) {

         Func<AccountRepository> resolver = this.AccountRepositoryResolver;

         if (resolver != null) {
            return resolver();
         }

         if (injectedDependency != null) {
            return injectedDependency;
         }

         if (throwIfMissing) {
            throw CreateMissingDependencyException(typeof(AccountRepository), "AccountRepositoryResolver");
         }

         return null;
      }

      internal PasswordService RequireDependency(PasswordService injectedDependency) {

         Func<PasswordService> resolver = this.PasswordServiceResolver;

         if (resolver != null) {
            return resolver();
         }

         if (injectedDependency != null) {
            return injectedDependency;
         }

         throw CreateMissingDependencyException(typeof(PasswordService), "PasswordServiceResolver");
      }

      internal FormsAuthenticationService RequireDependency(FormsAuthenticationService injectedDependency) {

         Func<FormsAuthenticationService> resolver = this.FormsAuthenticationServiceResolver;

         FormsAuthenticationService instance = (resolver != null) ?
            resolver()
            : injectedDependency ?? new FormsAuthenticationService();

         instance.Configuration = this;

         return instance;
      }

      internal MailService RequireDependency(MailService injectedDependency) {

         Func<MailService> resolver = this.MailServiceResolver;

         MailService instance = (resolver != null) ?
            resolver()
            : injectedDependency ?? new MailService();

         return instance;
      }

      Exception CreateMissingDependencyException(Type dependencyType, string resolverProperty) {
         throw new InvalidOperationException(requiredDependencyMessage.FormatInvariant(dependencyType.FullName, resolverProperty));
      }
   }
}


text:
package ru.job4j.settask.simarrset;

/*
 * Class SimArrSetTest for test SimArrSet.
 * @author Nikolai Matveev
 * @since 13.02.2018
 * @version 0.1
 */

import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

public class SimArrSetTest {
    @Test
    public void addTest(){

        SimArrSet<String> result = new SimArrSet<>();
        result.add("1");
        result.add("2");

        Iterator it = result.iterator();

        assertThat(it.next(), is("1"));
        assertThat(it.hasNext(), is(true));
        assertThat(it.next(), is("2"));
        assertThat(it.hasNext(), is(false));

    }

    @Test
    public void whenAddDublicateThenDontSeeInResultTest(){

        SimArrSet<String> result = new SimArrSet<>();
        result.add("1");
        result.add("2");
        result.add("1");
        result.add("6");
        result.add("4");
        result.add("5");
        result.add("5");
        result.add("6");

        Iterator it = result.iterator();

        assertThat(it.next(), is("1"));
        assertThat(it.next(), is("2"));
        assertThat(it.next(), is("6"));
        assertThat(it.next(), is("4"));
        assertThat(it.next(), is("5"));

    }

    @Test
    public void iteratorStandartTest() {

        SimArrSet<String> result = new SimArrSet<>();
        result.add("1");
        result.add("2");
        result.add("3");
        result.add("4");
        result.add("5");
        result.add("6");
        result.add("7");
        result.add("8");
        result.add("9");
        result.add("10");
        result.add("11");

        Iterator it = result.iterator();
        assertThat(it.next(), is("1"));
        assertThat(it.next(), is("2"));
        assertThat(it.next(), is("3"));
        assertThat(it.next(), is("4"));
        assertThat(it.next(), is("5"));
        assertThat(it.next(), is("6"));
        assertThat(it.next(), is("7"));
        assertThat(it.next(), is("8"));
        assertThat(it.next(), is("9"));
        assertThat(it.next(), is("10"));
        assertThat(it.next(), is("11"));
//            assertThat(null, is(it.next()));

    }

    @Test
    public void hasNextTest() {
        SimArrSet<String> result = new SimArrSet<>();
        Iterator it = result.iterator();

        assertThat(it.hasNext(), is(false));

    }
    @Test(expected = NoSuchElementException.class)
    public void whenNextReturnExceptionTest() {
        SimArrSet<String> result = new SimArrSet<>();
        Iterator it = result.iterator();

        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));
        assertThat(null, is(it.next()));

    }

}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="tech, networking" name="keywords">
<meta content="Hugo" name="author">
<meta property="og:title" content="Clarifying DDoS-related terms - Hugo's Blog">
<meta property="og:url" content="http://blog.slabnet.com/post/clarifying-ddos-related-terms/">
<meta property="og:description" content="Mostly tech...mostly">
<meta property="og:type" content="website" />
<title>Clarifying DDoS-related terms | Hugo's Blog</title>

<link rel="stylesheet" href="http://blog.slabnet.com//css/style.css">
<link rel="shortcut icon" href="http://blog.slabnet.com//wave.ico">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/solarized-dark.min.css">

Hugo's Blog

Clarifying DDoS-related terms

September 25, 2016 by Hugo

        DDoS

        reflection

        Internet

        amplification

        bcp38

        urpf

        networking

        security

        infosec

I’ll be writing a bit more about DDoS attacks and security, and so I thought it would be handy to jot down some commonly used terms in one place.  I’ll also look at how some of those terms are interrelated.

The terms

Spoofing

As relates to TCP/IP, “spoofing” really just refers to forging some part of IP communications.  You could, for example, spoof a source port to have response data thrown at a listening application that wasn’t expecting it, but generally we’re talking about forging the source IP address in an IP packet.

IP spoofing can be used to simply hide your identity in cases where replies back from the target are not necessary in order to complete an attack.

For example, TCP SYN floods cause resource exhaustion on the target by making it set up many half-open TCP connections.  The attacker does not need to actually ACK replies back from the server in order to exhaust server resources, so spoofing the source IP in the SYN flood packets means (a) the attacker’s true IP remains hidden from the target and (b) any replies the target generates to the attack traffic will not reach the attacker, so the attacker can expend relatively fewer resources while making the target expend both more processing and bandwidth resources.

Similarly, any connectionless attack where garbage, volumetric data is thrown at a target could also use any random source IP address.  For example, a compromised host could be instructed to send random data at a target using a spoofed source IP address in order to not reveal the true IP of the compromised host.  This reduces the risk of the zombied attack host being exposed, and increases the chances that the attacker can use the bot again in future attacks.

Spoofing can also be used in reflection attacks.

Reflection

A reflection attack uses source address spoofing in order to have the attack bounce of off a “reflector” of some sort and on to the attack target.  The attacker uses spoofing to forge the source IP address of its traffic to be that of their target.  A request is then sent to the reflector, soliticing a response.  The response traffic, though, is sent not back to the attacker but rather on to the attack target.  This is because the reflector has no way of knowing the source of the traffic aside from the source IP address in the packets it receives, so all it can do is send responses to that IP address.

The most basic example of this would be sending an ICMP echo request (ping) to some host on the Internet and setting the source IP address to that of the attack target.  The pinged host will then send an ICMP echo reply to the source IP of the packet, which is the attack target.  This isn’t really a very efficient method on the attacker’s part, though, as they have to use the same amount of resources and bandwidth as the target, if not more.  A 1500-byte echo request sent from the attacker results in a 1500-byte echo reply generated by the reflector and that 1500-byte echo reply being received by the target.  So:

The attacker:

uses 1500 bytes of upload bandwidth

has to generate that 1500 byte echo request

The reflector:

uses 1500 bytes of download bandwith

has to generate a 1500 byte ICMP echo reply

uses 1500 bytes of upload bandwidth

The target just has to:

receive a 1500-byte echo reply

do some very basic processing to realize it has to discard it

To pack a bigger punch, reflection needs to be paired with amplification.

Amplification

This is where things start to get interesting on the volumetric DDoS front.  We’ve spoofed a source IP and sent a request to a server somewhere on the Internet so that the response gets sent to our target instead of back to us.  No how do we tip the scales to get a bigger attack?

We need two things to pull this off:

We need to be able to send a single packet to the reflector and have it reply with our attack traffic.

We need to hit on some protocol or service that will make the reflector generate a larger amount of traffic to send to the attacker than we sent to the reflector in the first place.

For #1, the idea here is that since we are spoofing our source address, something like TCP won’t work.  TCP requires a 3-step handshake between before the connection is open and data can go between client and server.  If we hit step 1 (SYN), but step 2 from the server back to the client (SYN-ACK) doesn’t come back to us but rather goes to the target, we can’t complete the TCP connection setup and so we can’t trigger a big bunch of data.  This is actually good design: it’s BAD for a single, small request from the client to be able to trigger a BIG response from the server, and the TCP 3-way handshake sidesteps that issue.  Connectionless protocols like UDP could work, though, as UDP-based protocols are more likely send the actual reply to a client request right from the word “go!”.

Requirement #2 is pretty obvious, but how do we pull that off?  Well, common targets have been identified that by design violate the best practice suggestion of not returning more than is received on the first request/packet.  A list of some of those:

NTP

CHARGEN

DNS, especially with EDNS

SSDP

SNMP

Now we can single a single packet to reflector with a spoofed source IP and have that reflector send up to almost 600 times that amount of traffic to our target.

BCP38

BC-whatnow?

BCP stands for Best Current Practice, which are documents put forth by the Internet Engineering Task Force (IETF) to, well, describe best current practices ;)

Basically, rather than documenting how protocols themselves should function, BCPs provide guidelines on recommended configurations and operation of those protocols in real-world scenarios.  For example, BCP46, Recommended Internet Service Provider Security Services and Procedures,  describes common security practices that ISPs should implement.  This isn’t about which protocols to use, but how to implement and configure the use of those protocols.  BCPs also have a regular RFC number, with BCP38 being RFC2827.

BCP38 is titled Network Ingress Filtering: Defeating Denial of Service Attacks which employ IP Source Address Spoofing.  Recognizing that source address spoofing can facilitate denial of service attacks, the IETF drafted BCP38 to cut source address spoofing off at the knees.

In a network that has implemented BCP38, when a packet with a spoofed source IP address reaches the ISP’s router, the router checks the source IP address of the packet.  If the source address has been legitimately assigned to the customer, then the packet is permitted.  If the source address is not in an address range that has been assigned to the customer, it is discarded/dropped.  The spoofed packet will never get to a DoS target or a reflector, because it is dropped as soon as it enters the ISP’s network.

Unicast Reverse Path Forwarding (uRPF)

Usually, configuring a router to accept or drop traffic, especially based on source address rather than destination, is accomplished through access control lists (ACLs), aka firewall filters.  In implementing BCP38, an ACL would be applied on the customer-facing interface of the ISP’s router, and would match source addresses of packets received on that interface.  That…starts to become a pain to manage. Aside from addressing an interface, you also now need to configure and apply an ACL for each customer-facing interface on every single access router in your network.  Sure, you can probably work this into your customer turn-up process and service provisioning, but it’s an extra step that either needs to be done manually or have some development and QA time thrown at it.  Couldn’t we just have an “enable source address spoof filtering” checkbox or something?

uRPF to the rescue!

Unicast Reverse Path Forwarding checks the source address of packet received on a router interface and then does a route lookup for that source address.  If a route for the source address is found and points out the interface on which the packet was received, the packet is forwarded.  If not, the packet is discarded.  We’ll get into more details below.

How do these all go together?

Each of the first three terms we covered - spoofing, reflection, and amplification -  builds on the ones before it.  I can spoof a packet without doing any reflection or amplification.  In order to reflect traffic, I need to spoof the source IP address in the traffic I send out.  But, I can still reflect traffic without that using amplification, as we saw in the original ping example.

Now: I can technically use amplification without spoofing and reflection, but that would really just be normal user traffic rather than attack traffic.  We mentioned DNS as a potential reflection vector.  Well, if I send a small DNS request to my DNS server and get a larger response back, technically that’s amplification (small request sent; large response triggered).  But, that’s not DoS traffic.

In order to use amplification in a DoS scenario, then, I need a reflector to amplify the attack traffic for me, and I need to use spoofing to direct the reflected response to the target rather than having it come back to me.

Where would one technique be used over another?

If all I care about is throwing traffic directly at a target and obfuscating my source address, I can just use spoofing.  TCP SYN floods would be an example, or cases where random volumetric data is launched at a target (though at least the latter would more commonly leverage reflected and amplified attacks).

If the attacker has access to services that are vulnerable to amplification, it generally doesn’t make too much sense to just use bare spoofing and reflection rather than just tossing more resources at the vector that provides amplification.  That said, an ICMP flood could be an example of a reflected attack that does not leverage amplification.

Finally, as mentioned above, an amplified attack requires both spoofing (to direct requests at the target rather than the attacker) and reflection (to provide the amplification) as well, and is the staple of large-scale volumetric DDoS attacks.

And BCP38 and uRPF?

BCP38 can’t prevent all denial of service attacks from happening, but it does prevent spoofing.  If attackers do not have access to networks that let them spoof source addresses, they are unable to cover their tracks.  If a host in a botnet assumes it can send out spoofed traffic, its attack traffic will not reach the target, and the attack is mitigated.  If the zombied host is able to detect that its spoofed traffic cannot get through, an attack operator may choose to simply send attack traffic directly to the target without spoofing.  This exposes the zombie host, though, so that abuse from the host can be reported and it can be cleaned up or neutralized so that it cannot be used in future attacks.  Since spoofing is also required for an amplified attack, a network that implements BCP38 cannot be used to launch an amplified reflected attack, which is where the big guns in volumetric DDoS come from.

Some examples might also help illustrate this.

Users X and Y are connected to RouterA on two different networks:

 -------------------------
| UserX                   |______________
| 2001:db8:a:1111::100/64 |               \  -----------------------
 -------------------------      ge-1/0/0.0 \| 2001:db8:a:1111::1/64 |
                                            |-----------------------|
                                            |        RouterA        |
                                            |-----------------------|
 -------------------------      ge-2/0/0.0 /| 2001:db8:a:ffff::1/64 |
| UserY                   |______________ /  -----------------------
| 2001:db8:a:ffff::100/64 |
 -------------------------

For our example, let’s assume this is a very simple router and just has these two connected networks and then a default route out another interface, ge-0/0/0.0, so its routing table looks like this:

Network                 Type        Next-Hop            Via Interface
::/0                    static      2001:db8:aaaa::a    ge-0/0/0.0
2001:db8:a:1111::1/128  Local       -                   ge-1/0/0.0
2001:db8:a:1111::/64    Direct      -                   ge-1/0/0.0
2001:db8:a:ffff::1/128  Local       -                   ge-2/0/0.0
2001:db8:a:ffff::/64    Direct      -                   ge-2/0/0.0

UserX thinks he’s super 1337 and wants to launch a TCP SYN flood attack against UserY without having his source IP being revealed.  This is simple spoofing without reflection or amplification.  He spoofs the source IP address in his attack packets and sets it to some other random IP; let’s say 2001:db8:bad:d00d::1337.

UserX sends the traffic with the spoofed source IP to his ISP gateway address of 2001:db8:a:1111::1, which is on RouterA.  Now, RouterA does have uRPF configured on the interface to which UserX is connected, so it does a route lookup on the source address.  For the spoofed attack packets, that would be 2001:db8:bad:d00d::1337.  RouterA finds that it does not have a route for that address going out that interface; it doesn’t even have a route for that destination at all aside from its default route.

Note that this also works in cases where a route for the source address is found, but on a different interface.  Suppose UserX takes a different tack and decides to use an amplified NTP reflection attack against UserY, so he picks UserY’s address as his spoofed source IP.  UserX crafts an NTP monlist query to a vulnerable NTP server that will serve as his reflector and amplify the attack traffic, and sends the packet on its way via his gateway on RouterA.

In this case when RouterA does a route lookup during its uRPF check it will find a route for the source IP in the packet, 2001:db8:a:ffff::100, because that address lives in UserY’s network of 2001:db8:a:ffff::/64 that is directly connected on its ge-2/0/0.0 interface.  But, UserX’s spoofed packet came in on ge-1/0/0.0, not on ge-2/0/0.0.  Since the route for the source address in the packet does not go via the input interface of the packet, RouterA discards the packet and the attack is neutralized.

Wrapping Up

DDoS attacks are a very broad subject and there are lots of nuances to deal with.  This post aimed to just start scratching the surface and to provide an introductory reference for some of these terms, and I will be digging into this topic in more detail in future posts.

    Please enable JavaScript to view the comments powered by Disqus.

© 2017 Hugo Slabbert. Some rights reserved. Please attribute properly and link back.


text:
#include "drmP.h"

#include "nouveau_drv.h"
#include "nouveau_ramht.h"
#include "nouveau_software.h"

#include "nv50_display.h"

struct nv50_software_priv {
	struct nouveau_software_priv base;
};

struct nv50_software_chan {
	struct nouveau_software_chan base;
	struct {
		struct nouveau_gpuobj *object;
	} vblank;
};

static int
mthd_dma_vblsem(struct nouveau_channel *chan, u32 class, u32 mthd, u32 data)
{
	struct nv50_software_chan *pch = chan->engctx[NVOBJ_ENGINE_SW];
	struct nouveau_gpuobj *gpuobj;

	gpuobj = nouveau_ramht_find(chan, data);
	if (!gpuobj)
		return -ENOENT;

	if (nouveau_notifier_offset(gpuobj, NULL))
		return -EINVAL;

	pch->vblank.object = gpuobj;
	pch->base.vblank.offset = ~0;
	return 0;
}

static int
mthd_vblsem_offset(struct nouveau_channel *chan, u32 class, u32 mthd, u32 data)
{
	struct nv50_software_chan *pch = chan->engctx[NVOBJ_ENGINE_SW];

	if (nouveau_notifier_offset(pch->vblank.object, &data))
		return -ERANGE;

	pch->base.vblank.offset = data >> 2;
	return 0;
}

static int
mthd_vblsem_value(struct nouveau_channel *chan, u32 class, u32 mthd, u32 data)
{
	struct nv50_software_chan *pch = chan->engctx[NVOBJ_ENGINE_SW];
	pch->base.vblank.value = data;
	return 0;
}

static int
mthd_vblsem_release(struct nouveau_channel *chan, u32 class, u32 mthd, u32 data)
{
	struct nv50_software_priv *psw = nv_engine(chan->dev, NVOBJ_ENGINE_SW);
	struct nv50_software_chan *pch = chan->engctx[NVOBJ_ENGINE_SW];
	struct drm_device *dev = chan->dev;

	if (!pch->vblank.object || pch->base.vblank.offset == ~0 || data > 1)
		return -EINVAL;

	drm_vblank_get(dev, data);

	pch->base.vblank.head = data;
	list_add(&pch->base.vblank.list, &psw->base.vblank);
	return 0;
}

static int
mthd_flip(struct nouveau_channel *chan, u32 class, u32 mthd, u32 data)
{
	nouveau_finish_page_flip(chan, NULL);
	return 0;
}

static int
nv50_software_context_new(struct nouveau_channel *chan, int engine)
{
	struct nv50_software_priv *psw = nv_engine(chan->dev, NVOBJ_ENGINE_SW);
	struct nv50_display *pdisp = nv50_display(chan->dev);
	struct nv50_software_chan *pch;
	int ret = 0, i;

	pch = kzalloc(sizeof(*pch), GFP_KERNEL);
	if (!pch)
		return -ENOMEM;

	nouveau_software_context_new(&pch->base);
	pch->base.vblank.bo = chan->notifier_bo;
	chan->engctx[engine] = pch;

	/* dma objects for display sync channel semaphore blocks */
	for (i = 0; i < chan->dev->mode_config.num_crtc; i++) {
		struct nv50_display_crtc *dispc = &pdisp->crtc[i];
		struct nouveau_gpuobj *obj = NULL;

		ret = nouveau_gpuobj_dma_new(chan, NV_CLASS_DMA_IN_MEMORY,
					     dispc->sem.bo->bo.offset, 0x1000,
					     NV_MEM_ACCESS_RW,
					     NV_MEM_TARGET_VRAM, &obj);
		if (ret)
			break;

		ret = nouveau_ramht_insert(chan, NvEvoSema0 + i, obj);
		nouveau_gpuobj_ref(NULL, &obj);
	}

	if (ret)
		psw->base.base.context_del(chan, engine);
	return ret;
}

static void
nv50_software_context_del(struct nouveau_channel *chan, int engine)
{
	struct nv50_software_chan *pch = chan->engctx[engine];
	chan->engctx[engine] = NULL;
	kfree(pch);
}

static int
nv50_software_object_new(struct nouveau_channel *chan, int engine,
			 u32 handle, u16 class)
{
	struct drm_device *dev = chan->dev;
	struct nouveau_gpuobj *obj = NULL;
	int ret;

	ret = nouveau_gpuobj_new(dev, chan, 16, 16, 0, &obj);
	if (ret)
		return ret;
	obj->engine = 0;
	obj->class  = class;

	ret = nouveau_ramht_insert(chan, handle, obj);
	nouveau_gpuobj_ref(NULL, &obj);
	return ret;
}

static int
nv50_software_init(struct drm_device *dev, int engine)
{
	return 0;
}

static int
nv50_software_fini(struct drm_device *dev, int engine, bool suspend)
{
	return 0;
}

static void
nv50_software_destroy(struct drm_device *dev, int engine)
{
	struct nv50_software_priv *psw = nv_engine(dev, engine);

	NVOBJ_ENGINE_DEL(dev, SW);
	kfree(psw);
}

int
nv50_software_create(struct drm_device *dev)
{
	struct nv50_software_priv *psw = kzalloc(sizeof(*psw), GFP_KERNEL);
	if (!psw)
		return -ENOMEM;

	psw->base.base.destroy = nv50_software_destroy;
	psw->base.base.init = nv50_software_init;
	psw->base.base.fini = nv50_software_fini;
	psw->base.base.context_new = nv50_software_context_new;
	psw->base.base.context_del = nv50_software_context_del;
	psw->base.base.object_new = nv50_software_object_new;
	nouveau_software_create(&psw->base);

	NVOBJ_ENGINE_ADD(dev, SW, &psw->base.base);
	NVOBJ_CLASS(dev, 0x506e, SW);
	NVOBJ_MTHD (dev, 0x506e, 0x018c, mthd_dma_vblsem);
	NVOBJ_MTHD (dev, 0x506e, 0x0400, mthd_vblsem_offset);
	NVOBJ_MTHD (dev, 0x506e, 0x0404, mthd_vblsem_value);
	NVOBJ_MTHD (dev, 0x506e, 0x0408, mthd_vblsem_release);
	NVOBJ_MTHD (dev, 0x506e, 0x0500, mthd_flip);
	return 0;
}


text:
package org.apache.rocketmq.store.ha;

import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;

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

public class WaitNotifyObject {
    private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);

    protected final HashMap<Long/* thread id */, Boolean/* notified */> waitingThreadTable =
        new HashMap<Long, Boolean>(16);

    protected volatile boolean hasNotified = false;

    public void wakeup() {
        synchronized (this) {
            if (!this.hasNotified) {
                this.hasNotified = true;
                this.notify();
            }
        }
    }

    protected void waitForRunning(long interval) {
        synchronized (this) {
            if (this.hasNotified) {
                this.hasNotified = false;
                this.onWaitEnd();
                return;
            }

            try {
                this.wait(interval);
            } catch (InterruptedException e) {
                log.error("Interrupted", e);
            } finally {
                this.hasNotified = false;
                this.onWaitEnd();
            }
        }
    }

    protected void onWaitEnd() {
    }

    public void wakeupAll() {
        synchronized (this) {
            boolean needNotify = false;

            for (Map.Entry<Long,Boolean> entry : this.waitingThreadTable.entrySet()) {
                needNotify = needNotify || !entry.getValue();
                entry.setValue(true);
            }

            if (needNotify) {
                this.notifyAll();
            }
        }
    }

    public void allWaitForRunning(long interval) {
        long currentThreadId = Thread.currentThread().getId();
        synchronized (this) {
            Boolean notified = this.waitingThreadTable.get(currentThreadId);
            if (notified != null && notified) {
                this.waitingThreadTable.put(currentThreadId, false);
                this.onWaitEnd();
                return;
            }

            try {
                this.wait(interval);
            } catch (InterruptedException e) {
                log.error("Interrupted", e);
            } finally {
                this.waitingThreadTable.put(currentThreadId, false);
                this.onWaitEnd();
            }
        }
    }

    public void removeFromWaitingThreadTable() {
        long currentThreadId = Thread.currentThread().getId();
        synchronized (this) {
            this.waitingThreadTable.remove(currentThreadId);
        }
    }
}


text:
package simpleflashcards;

import java.util.*;

public class FlashEngine
{
    int numberCorrect;
    int totalNumber;

    int randNumber1;
    int randNumber2;

    int[][] multTable = new int[12][12];

    int answer;

    public FlashEngine()
    {
        numberCorrect = 0;
        totalNumber = 0;

        for(int j = 0; j <= 11; j++)
            for(int i = 0; i <= 11; i++)
                multTable[j][i] = (j+1) * (i+1);
    }

    public void newProblem(String operand)
    {
        if (operand.equals("+") || operand.equals("-") || operand.equals("*"))
        {
            randNumber1 = (int)(Math.random() * 12) + 1;
            randNumber2 = (int)(Math.random() * 12) + 1;
        }
	else if (operand.equals("/"))
        {
            randNumber2 = (int)(Math.random() * 12) + 1;
            randNumber1 = multTable[randNumber2-1][(int)(Math.random() *12)];
        }

        if (operand.equals("+"))
            answer = randNumber1 + randNumber2;
        else if (operand.equals("-"))
            answer = randNumber1 - randNumber2;
        else if (operand.equals("*"))
            answer = randNumber1 * randNumber2;
        else if (operand.equals("/"))
            answer = randNumber1 / randNumber2;
    }

    public int[] getNumbers()
    {
        return new int[]{randNumber1, randNumber2};
    }

    public int getAnswer()
    {
        return answer;
    }

    public boolean problemRight(int answer)
    {
        if (this.answer == answer)
        {
            numberCorrect++;
            totalNumber++;
            return true;
        }

        totalNumber++;
        return false;
    }

    public int getCorrect()
    {
        return numberCorrect;
    }

    public int getTotal()
    {
        return totalNumber;
    }

    public void reset()
    {
        numberCorrect = 0;
        totalNumber = 0;

    }
}


text:
var doSomething = require('the code from the left panel')

describe('the method', function () {
  beforeEach(function () {
    console.log('Main setup')
  })

  afterEach(function () {
    console.log('Main clean up')
  })

  context('under some conditions', function () {
    beforeEach(function () {
      console.log('Some conditions setup')
    })

    afterEach(function () {
      console.log('Some conditions clean up')
    })

    it('should behave like this', function () {
      doSomething()
    })
  })
})


text:
import React, { Component } from 'react';
import { Link,browserHistory } from 'react-router';

import Course from "./../components/Course";

import { connect } from "react-redux";
import { getCourse } from "./../actions";
import { animateScroll } from 'react-scroll';

class CourseContainer extends Component {

    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(nextProps) {

        if (nextProps.course.id == -1 && nextProps.allStatus.course == "success") {
            browserHistory.push(`/404`);
        }

        if (nextProps.allStatus.course == "success") {
            this.props.updateTitle(`${nextProps.course.title.rendered}`);
        }

        let isLoadingList = this.props.isLoading(nextProps.allStatus.course);
        this.props.updateLoadingState(isLoadingList);

    }

    componentWillMount() {

        this.props.updateLoadingState(true);
        animateScroll.scrollToTop();

    }

    componentDidUpdate() {

    }

    render() {

        return (
            <Course {...this.props}/>
        );

    }
}

function mapStateToProps(store) {
    return {
        course: store.courses.course.data,
        allStatus: {
            course: store.courses.course.status
        }
    };
}

export default connect(mapStateToProps, {getCourse})(CourseContainer);


text:
package mensaje;

import item.Item;
import item.ItemEquipo;

public class MensajeItem extends MensajeInteraccion {

	private ItemEquipo item;
	public MensajeItem(String que, String tipo,ItemEquipo item) {
		super(que, tipo);
		this.item = item;
	}
	public ItemEquipo getItem() {
		return item;
	}

}


text:
// -----------------------------------------------------------------------
// <copyright file="PointLight.cs" company="Kyle Kestell">
// <para>Copyright (c) 2012 Kyle Kestell</para>
// <para>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</para>
// <para>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</para>
// <para>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</para>
// </copyright>
// -----------------------------------------------------------------------

namespace Erebus.Entities.Lights
{
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    public class PointLight : Light
    {
        public PointLight(Vector3 position, Quaternion rotation, Vector3 scale, float radius, Color color, float intensity, bool castShadows, int shadowMapResolution, float depthBias)
            : base(position, rotation, scale, color, intensity, castShadows, shadowMapResolution, depthBias)
        {
            this.Radius = radius;
        }

        public float Radius { get; set; }

        public RenderTarget2D ShadowMapForward { get; set; }

        public RenderTarget2D ShadowMapBackward { get; set; }

        public RenderTarget2D ShadowMapLeft { get; set; }

        public RenderTarget2D ShadowMapRight { get; set; }

        public RenderTarget2D ShadowMapUp { get; set; }

        public RenderTarget2D ShadowMapDown { get; set; }

        public Matrix WorldMatrix
        {
            get
            {
                return Matrix.CreateScale(this.Radius / 100.0f) * Matrix.CreateTranslation(this.Position);
            }
        }

        public override void LoadContent(Engine engine)
        {
            this.ShadowMapForward = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);

            this.ShadowMapBackward = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);

            this.ShadowMapLeft = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);

            this.ShadowMapRight = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);

            this.ShadowMapUp = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);

            this.ShadowMapDown = new RenderTarget2D(
                engine.GraphicsDevice,
                this.ShadowMapResolution,
                this.ShadowMapResolution,
                false,
                SurfaceFormat.Single,
                DepthFormat.Depth24Stencil8);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CSS Position Test: sticky element with bottom offset specified with px unit</title>

  <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">
  <link rel="help" href="https://www.w3.org/TR/css-position-3/#sticky-pos">
  <link rel="match" href="reference/position-sticky-bottom-002-ref.html">

  <meta name="flags" content="">

Test passes if there are 3 filled green squares and no red.


text:
package org.apache.camel.component.corda;

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

import static org.apache.camel.component.corda.CordaConstants.OPERATION;
import static org.apache.camel.component.corda.CordaConstants.STATE_MACHINE_FEED;

public class CordaConsumerStateMachineFeedIntegrationTest extends CordaConsumerTestSupport {

    @Test
    public void stateMachineFeedTest() throws Exception {
        mockResult.expectedMinimumMessageCount(1);
        mockError.expectedMessageCount(0);
        MockEndpoint.assertIsSatisfied(context);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                errorHandler(deadLetterChannel("mock:error"));

                from(getUrl() + "&" + OPERATION.toLowerCase() + "=" + STATE_MACHINE_FEED)
                        .to("mock:result");
            }
        };
    }
}


text:
#ifndef COIN_SOMFVEC4D_H
#define COIN_SOMFVEC4D_H

#include <Inventor/fields/SoMField.h>
#include <Inventor/fields/SoSubField.h>
#include <Inventor/SbVec4d.h>

class COIN_DLL_API SoMFVec4d : public SoMField {
  typedef SoMField inherited;

  SO_MFIELD_HEADER(SoMFVec4d, SbVec4d, const SbVec4d &);

  SO_MFIELD_SETVALUESPOINTER_HEADER(SbVec4d);
  SO_MFIELD_SETVALUESPOINTER_HEADER(double);

public:
  static void initClass(void);

  void setValues(int start, int num, const double xyzw[][4]);
  void set1Value(int idx, double x, double y, double z, double w);
  void set1Value(int idx, const double xyzw[4]);
  void setValue(double x, double y, double z, double w);
  void setValue(const double xyzw[4]);

}; // SoMFVec4d

#endif // !COIN_SOMFVEC4D_H


text:
import { Component } from 'react'
import h from 'react-hyperscript'
import { HashRouter, Route } from 'react-router-dom'
import styled from 'styled-components'
import Header from './Header'
import AssessmentBoard from './AssessmentBoard'
import CertificateBoard from './CertificateBoard'
import ConceptBoard from './ConceptBoard'
import AssessmentCreation from './AssessmentCreation'
import AssessmentView from './AssessmentView'
import Modal from './Helpers/Modal'
import HelperBar from './Helpers/HelperBar'
import TxList from './Notifications/TxList'

// the main frame on which everything is displayed.
// It will call connect() when mounting the header)

export default class MainView extends Component {
  render () {
    return (
      h(HashRouter, [
        h('div', [
          h(Header),
          h(TxList),
          h(HelperBar),
          h(Modal),
          h(appContainer, [
            h(Route, {
              exact: true,
              path: '/',
              component: AssessmentBoard
            }),
            h(Route, {
              path: '/assessment/:id',
              component: AssessmentView
            }),
            h(Route, {
              exact: true,
              path: '/concepts/',
              component: ConceptBoard
            }),
            h(Route, {
              exact: true,
              path: '/concepts/:address/create',
              component: AssessmentCreation
            }),
            h(Route, {
              path: '/certificates',
              exact: true,
              component: CertificateBoard
            }),
            h(Route, {
              path: '/certificates/:address',
              component: CertificateBoard
            })
          ])
        ])
      ])
    )
  }
}

const appContainer = styled('div').attrs({ className: 'relative flex flex-column w-100 h-100' })``


text:
<?php

namespace UserAdminTest\ViewModel;

use DvsaCommon\Validator\EmailAddressValidator;
use UserAdmin\Controller\UserSearchController;
use UserAdmin\ViewModel\UserSearchViewModel;

/**
 * Unit tests for UserSearchViewModel.
 */
class UserSearchViewModelTest extends \Dvsa\Mot\Frontend\Test\TestCase
{
    /**
     * @var UserSearchViewModel
     */
    private $sut;

    public function setup()
    {
        $this->sut = new UserSearchViewModel(
            $this->buildUsers(),
            $this->buildCriteria()
        );
    }

    public function testDisplaySearchCriteria()
    {
        $criteria = 'Cheryl, Tunt, Stoke Gifford, L1 1PQ';
        $this->assertEquals($criteria, $this->sut->displaySearchCriteria());
    }

    public function testDisplayUserCount()
    {
        $this->assertEquals(4, $this->sut->getTotalResultNumber());
    }

    public function testIsAnythingFound()
    {
        $this->assertTrue($this->sut->isAnythingFound());
    }

    public function testGetSearchResult()
    {
        $this->assertEquals(4, count($this->sut->getSearchResult()));
    }

    public function testDisplayDobDaySearchCriteria()
    {
        $this->assertEquals('01', $this->sut->displayDobDaySearchCriteria());
    }

    public function testDisplayDobMonthSearchCriteria()
    {
        $this->assertEquals('01', $this->sut->displayDobMonthSearchCriteria());
    }

    public function testDisplayDobYearSearchCriteria()
    {
        $this->assertEquals('2015', $this->sut->displayDobYearSearchCriteria());
    }

    public function testHasSearchCriteria()
    {
        $this->assertTrue($this->sut->hasSearchCriteria());
    }

    /**
     * @dataProvider expandingAdditionalSearchCriteriaDataProvider
     */
    public function testExpadingAdditionalSearchCriteria(
        $firstName,
        $lastName,
        $email,
        $dobDay,
        $dobMonth,
        $dobYear,
        $town,
        $postcode,
        $result
    ) {
        $criteria = [
            UserSearchController::PARAM_FIRSTNAME => $firstName,
            UserSearchController::PARAM_LASTNAME => $lastName,
            UserSearchController::PARAM_EMAIL => $email,
            UserSearchController::PARAM_DOB_DAY => $dobDay,
            UserSearchController::PARAM_DOB_MONTH => $dobMonth,
            UserSearchController::PARAM_DOB_YEAR => $dobYear,
            UserSearchController::PARAM_TOWN => $town,
            UserSearchController::PARAM_POSTCODE => $postcode,
        ];

        $sut = new UserSearchViewModel(
            $this->buildUsers(),
            $criteria
        );

        $this->assertEquals($result, !empty($sut->getAdditionalSearchCriteria()));
    }

    public function expandingAdditionalSearchCriteriaDataProvider()
    {
        return [
            ['John', 'Smith', 'usersearchviewmodeltest@'.EmailAddressValidator::TEST_DOMAIN, null, null, null, null, null, true],
            ['John', 'Smith', null, 10, null, null, null, null, true],
            ['John', 'Smith', null, null, 10, null, null, null, true],
            ['John', 'Smith', null, null, null, 2015, null, null, true],
            ['John', 'Smith', null, null, null, null, 'Bristol', null, true],
            ['John', 'Smith', null, null, null, null, null, '1L 1PQ', true],
            ['John', 'Smith', null, null, null, null, null, null, false],
        ];
    }

    public function testDisplayDobSearchCriteriaNoBirth()
    {
        $criteria = $this->buildCriteria() + [UserSearchController::PARAM_DOB => '2015-01-01'];
        $this->sut = new UserSearchViewModel(
            $this->buildUsers(),
            $criteria
        );
        $this->assertEquals('1 January 2015', $this->sut->displayDobSearchCriteria());
    }

    private function buildCriteria()
    {
        return [
            'firstName' => 'Cheryl',
            'lastName' => 'Tunt',
            'middleName' => 'Thomas',
            'town' => 'Stoke Gifford',
            'postcode' => 'L1 1PQ',
            UserSearchController::PARAM_DOB_DAY => '01',
            UserSearchController::PARAM_DOB_MONTH => '01',
            UserSearchController::PARAM_DOB_YEAR => '2015',
        ];
    }

    private function buildUsers()
    {
        return [
            $this->buildPersonMock(),
            $this->buildPersonMock(),
            $this->buildPersonMock(),
            $this->buildPersonMock(),
        ];
    }

    private function buildPersonMock()
    {
        $stub = $this->getMockBuilder('DvsaCommon\Dto\Person\SearchPersonResultDto')
            ->disableOriginalConstructor()
            ->getMock();

        return $stub;
    }
}


text:
using System;

using Tauco.Dicom.Abstraction;
using Tauco.Dicom.Shared;

namespace Tauco.Dicom.Network
{
    /// <summary>
    /// Represents DICOM C-FIND request entity.
    /// </summary>
    /// <typeparam name="TInfo">Type of requested object</typeparam>
    internal class DicomFindRequest<TInfo> : IDicomFindRequest<TInfo> where TInfo : IDicomInfo
    {
        /// <summary>
        /// Collection containing constraints used for filtering requested items suitable for DICOM C-FIND requests.
        /// </summary>
        public IDicomWhereCollection DicomWhereCollection
        {
            get;
            set;
        }

        /// <summary>
        /// Method called once the request was fulfilled. Contains item obtained from the response.
        /// </summary>
        public Action<TInfo> ResponseCallback
        {
            get;
            set;
        }
    }
}