text:
package export

import (
	"fmt"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/client-go/tools/cache"

	virtv1 "kubevirt.io/api/core/v1"
	exportv1 "kubevirt.io/api/export/v1alpha1"
	"kubevirt.io/client-go/log"

	"kubevirt.io/kubevirt/pkg/controller"

	storagetypes "kubevirt.io/kubevirt/pkg/storage/types"
)

const (
	noVolumeVMReason = "VMNoVolumes"
)

func (ctrl *VMExportController) handleVMExport(obj interface{}) {
	if unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok && unknown.Obj != nil {
		obj = unknown.Obj
	}

	if vmExport, ok := obj.(*exportv1.VirtualMachineExport); ok {
		objName, err := cache.DeletionHandlingMetaNamespaceKeyFunc(vmExport)
		if err != nil {
			log.Log.Errorf(failedKeyFromObjectFmt, err, vmExport)
			return
		}
		log.Log.V(3).Infof(enqueuedForSyncFmt, objName)
		ctrl.vmExportQueue.Add(objName)
	}
}

func (ctrl *VMExportController) handleVM(obj interface{}) {
	if unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok && unknown.Obj != nil {
		obj = unknown.Obj
	}

	if vm, ok := obj.(*virtv1.VirtualMachine); ok {
		vmKey, _ := cache.MetaNamespaceKeyFunc(vm)
		keys, err := ctrl.VMExportInformer.GetIndexer().IndexKeys("vm", vmKey)
		if err != nil {
			utilruntime.HandleError(err)
			return
		}
		for _, key := range keys {
			log.Log.V(3).Infof("Adding VMExport due to vm %s", vmKey)
			ctrl.vmExportQueue.Add(key)
		}
	}
}

func (ctrl *VMExportController) handleVMI(obj interface{}) {
	if unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok && unknown.Obj != nil {
		obj = unknown.Obj
	}

	if vmi, ok := obj.(*virtv1.VirtualMachineInstance); ok {
		vm := ctrl.getVMFromVMI(vmi)
		if vm != nil {
			vmKey, _ := cache.MetaNamespaceKeyFunc(vm)
			keys, err := ctrl.VMExportInformer.GetIndexer().IndexKeys("vm", vmKey)
			if err != nil {
				utilruntime.HandleError(err)
				return
			}
			for _, key := range keys {
				log.Log.V(3).Infof("Adding VMExport due to VM %s", vmKey)
				ctrl.vmExportQueue.Add(key)
			}
			return
		}
		pvcs := ctrl.getPVCsFromVMI(vmi)
		for _, pvc := range pvcs {
			log.Log.V(3).Infof("Adding VMExport due to PVC %s/%s", pvc.Namespace, pvc.Name)
			ctrl.handlePVC(pvc)
		}
	}
}

func (ctrl *VMExportController) getPVCsFromVMI(vmi *virtv1.VirtualMachineInstance) []*corev1.PersistentVolumeClaim {
	var pvcs []*corev1.PersistentVolumeClaim
	for _, volume := range vmi.Spec.Volumes {
		pvcName := storagetypes.PVCNameFromVirtVolume(&volume)
		if pvc := ctrl.getPVCsFromName(vmi.Namespace, pvcName); pvc != nil {
			pvcs = append(pvcs, pvc)
		}
	}
	return pvcs
}

func (ctrl *VMExportController) getOwnerVMexportKey(obj metav1.Object) string {
	ownerRef := metav1.GetControllerOf(obj)
	var key string
	if ownerRef != nil {
		if ownerRef.Kind == exportGVK.Kind && ownerRef.APIVersion == exportGVK.GroupVersion().String() {
			key = controller.NamespacedKey(obj.GetNamespace(), ownerRef.Name)
		}
	}
	return key
}

func (ctrl *VMExportController) getVMFromVMI(vmi *virtv1.VirtualMachineInstance) *virtv1.VirtualMachine {
	ownerRef := metav1.GetControllerOf(vmi)
	if ownerRef != nil {
		if ownerRef.Kind == "VirtualMachine" && ownerRef.APIVersion == virtv1.GroupVersion.String() {
			if vm, exists, err := ctrl.getVm(vmi.Namespace, ownerRef.Name); !exists || err != nil {
				log.Log.V(3).Infof("Unable to get owner VM %s/%s for VMI %s/%s", vmi.Namespace, ownerRef.Name, vmi.Namespace, vmi.Name)
			} else {
				return vm
			}
		}
	}
	return nil
}

func (ctrl *VMExportController) isSourceInUseVM(vmExport *exportv1.VirtualMachineExport) (bool, string, error) {
	vmi, exists, err := ctrl.getVmi(vmExport.Namespace, vmExport.Spec.Source.Name)
	if err != nil {
		return false, "", err
	}
	if exists {
		return exists, fmt.Sprintf("Virtual Machine %s/%s is running", vmi.Namespace, vmi.Name), nil
	}
	return exists, "", nil
}

func (ctrl *VMExportController) getPVCFromSourceVM(vmExport *exportv1.VirtualMachineExport) (*sourceVolumes, error) {
	pvcs, allPopulated, err := ctrl.getPVCsFromVM(vmExport.Namespace, vmExport.Spec.Source.Name)
	if err != nil {
		return &sourceVolumes{}, err
	}
	log.Log.V(3).Infof("Number of volumes found for VM %s/%s, %d, allPopulated %t", vmExport.Namespace, vmExport.Spec.Source.Name, len(pvcs), allPopulated)
	if len(pvcs) > 0 && !allPopulated {
		return &sourceVolumes{
			volumes:          pvcs,
			inUse:            false,
			isPopulated:      allPopulated,
			availableMessage: fmt.Sprintf("Not all volumes in the Virtual Machine %s/%s are populated", vmExport.Namespace, vmExport.Spec.Source.Name)}, nil
	}
	inUse, availableMessage, err := ctrl.isSourceInUseVM(vmExport)
	if err != nil {
		return &sourceVolumes{}, err
	}
	return &sourceVolumes{
		volumes:          pvcs,
		inUse:            inUse,
		isPopulated:      allPopulated,
		availableMessage: availableMessage}, nil
}

func (ctrl *VMExportController) getPVCsFromVM(vmNamespace, vmName string) ([]*corev1.PersistentVolumeClaim, bool, error) {
	var pvcs []*corev1.PersistentVolumeClaim
	vm, exists, err := ctrl.getVm(vmNamespace, vmName)
	if err != nil {
		return nil, false, err
	}
	if !exists {
		return nil, false, nil
	}
	allPopulated := true
	for _, volume := range vm.Spec.Template.Spec.Volumes {
		pvcName := storagetypes.PVCNameFromVirtVolume(&volume)
		if pvcName == "" {
			continue
		}
		pvc, exists, err := ctrl.getPvc(vmNamespace, pvcName)
		if err != nil {
			return nil, false, nil
		}
		if exists {
			populated, err := ctrl.isPVCPopulated(pvc)
			if err != nil {
				return nil, false, err
			}
			pvcs = append(pvcs, pvc)
			if !populated {
				allPopulated = false
			}
			continue
		}
		if volume.DataVolume != nil {
			// PVC has not been created yet, otherwise exist would be true. Setting allPopulated to false will
			// trigger a requeue
			log.Log.V(2).Infof("Found data volume %s but PVC does not exist yet", volume.DataVolume.Name)
			allPopulated = false
		}
	}
	return pvcs, allPopulated, nil
}

func (ctrl *VMExportController) updateVMExportVMStatus(vmExport *exportv1.VirtualMachineExport, exporterPod *corev1.Pod, service *corev1.Service, sourceVolumes *sourceVolumes) (time.Duration, error) {
	var requeue time.Duration

	vmExportCopy := vmExport.DeepCopy()
	if err := ctrl.updateCommonVMExportStatusFields(vmExport, vmExportCopy, exporterPod, service, sourceVolumes); err != nil {
		return requeue, err
	}
	if len(sourceVolumes.volumes) == 0 {
		vmExportCopy.Status.Conditions = updateCondition(vmExportCopy.Status.Conditions, newReadyCondition(corev1.ConditionFalse, noVolumeVMReason, sourceVolumes.availableMessage))
		vmExportCopy.Status.Phase = exportv1.Skipped
	}
	if !sourceVolumes.isPopulated {
		requeue = requeueTime
	}
	if err := ctrl.updateVMExportStatus(vmExport, vmExportCopy); err != nil {
		return requeue, err
	}
	return requeue, nil
}

func (ctrl *VMExportController) isSourceVM(source *exportv1.VirtualMachineExportSpec) bool {
	return source != nil && source.Source.APIGroup != nil && *source.Source.APIGroup == virtv1.SchemeGroupVersion.Group && source.Source.Kind == "VirtualMachine"
}

func (ctrl *VMExportController) getVm(namespace, name string) (*virtv1.VirtualMachine, bool, error) {
	key := controller.NamespacedKey(namespace, name)
	obj, exists, err := ctrl.VMInformer.GetStore().GetByKey(key)
	if err != nil || !exists {
		return nil, exists, err
	}
	return obj.(*virtv1.VirtualMachine).DeepCopy(), true, nil
}

func (ctrl *VMExportController) getVmi(namespace, name string) (*virtv1.VirtualMachineInstance, bool, error) {
	key := controller.NamespacedKey(namespace, name)
	obj, exists, err := ctrl.VMIInformer.GetStore().GetByKey(key)
	if err != nil || !exists {
		return nil, exists, err
	}
	return obj.(*virtv1.VirtualMachineInstance).DeepCopy(), true, nil
}

redpajama_set_name: RedPajamaGithub


text:
@implementation ShardStatus

- (void)setServices:(NSArray *)services {
    _services = [services arrayOfObjectsWithClass:[Service class]];
}

@end


text:
package uk.gov.dvla.vehicles.presentation.common.webserviceclients.bruteforceprevention

import javax.inject.Inject
import play.api.libs.json.Json
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.TrackingId
import uk.gov.dvla.vehicles.presentation.common.LogFormats.DVLALogger
import uk.gov.dvla.vehicles.presentation.common.model.BruteForcePreventionModel
import uk.gov.dvla.vehicles.presentation.common.services.DateService
import uk.gov.dvla.vehicles.presentation.common.webserviceclients.healthstats.HealthStats

object BruteForcePreventionServiceImpl {
  final val ServiceName = "bruteforce-prevention-microservice"
}

final class BruteForcePreventionServiceImpl @Inject()(config: BruteForcePreventionConfig,
                                                      ws: BruteForcePreventionWebService,
                                                      healthStats: HealthStats,
                                                      dateService: DateService)
                          extends BruteForcePreventionService with DVLALogger {
  import BruteForcePreventionServiceImpl.ServiceName
  private val maxAttempts: Int = config.maxAttemptsHeader

  override def isVrmLookupPermitted(vrm: String, trackingId: TrackingId): Future[BruteForcePreventionModel] =
  // Feature toggle until all developers have Redis and the brute force micro service setup locally.
    if (config.isEnabled) {
      val returnedFuture = scala.concurrent.Promise[BruteForcePreventionModel]()
      ws.callBruteForce(vrm, trackingId).map { resp =>
        def permitted(): Unit = {
          Json.fromJson[BruteForcePreventionResponseDto](resp.json).asOpt match {
            case Some(model) =>
              val resultModel = BruteForcePreventionModel.fromResponse(
                permitted = true,
                model,
                dateService,
                maxAttempts
              )
              returnedFuture.success(resultModel)
            case _ =>
              logMessage(trackingId, Error, s"Brute force prevention service returned invalid Json: ${resp.json}")
              returnedFuture.failure(new Exception("TODO"))
          }
        }
        def notPermitted = BruteForcePreventionModel.fromResponse(permitted = false,
          BruteForcePreventionResponseDto(attempts = 0),
          dateService,
          maxAttempts = maxAttempts
        )
        resp.status match {
          case play.api.http.Status.OK => permitted()
          case play.api.http.Status.FORBIDDEN => returnedFuture.success(notPermitted)
          case _ => returnedFuture.failure(new Exception(s"unknownPermission '${resp.status}: ${resp.body}'"))
        }
      }.recover {
        case e: Throwable =>
          logMessage(trackingId, Error, s"Brute force prevention service throw exception: ${e.getStackTrace}")
          returnedFuture.failure(e)
      }
      healthStats.report(ServiceName) {
        returnedFuture.future
      }
    }
    else Future {
      // This code is only reached when brute force prevention is disabled, which should only be when we are running
      // locally (i.e. sbt sandbox or sbt run) and NEVER in production.
      val vrmAttempt2 = "ST05YYB"
      val vrmLocked = "ST05YYC"
      vrm match {
        case `vrmAttempt2` =>
          // Block access
          BruteForcePreventionModel.fromResponse(permitted = false,
            BruteForcePreventionResponseDto(attempts = maxAttempts),
            dateService,
            maxAttempts = maxAttempts
          )
        case `vrmLocked` =>
          // Block access with warning
          BruteForcePreventionModel.fromResponse(permitted = false,
            BruteForcePreventionResponseDto(attempts = maxAttempts - 1),
            dateService,
            maxAttempts = maxAttempts
          )
        case _ =>
          // Allow access
          BruteForcePreventionModel.fromResponse(permitted = true,
            BruteForcePreventionResponseDto(attempts = 0),
            dateService,
            maxAttempts = maxAttempts
          )
      }
    }

  override def reset(vrm: String, trackingId: TrackingId): Future[Int] =
  // Feature toggle until all developers have Redis and the brute force micro service setup locally.
    if (config.isEnabled) {
      val returnedFuture = scala.concurrent.Promise[Int]()
      ws.reset(vrm, trackingId).map { resp =>
        returnedFuture.success(resp.status)
      }.recover { case e: Throwable =>
        returnedFuture.failure(e)
      }
      healthStats.report(ServiceName) {
        returnedFuture.future
      }
    }
    else Future {
      play.api.http.Status.OK
    }
}


text:
    //
//  CVCashFlowViewController.m
//  CapitalVueHD
//
//  Created by jishen on 10/31/10.
//  Copyright 2010 SmilingMobile. All rights reserved.
//

#import "CVCashFlowViewController.h"
#import "CVLocalizationSetting.h"

@implementation CVCashFlowViewController

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	CVLocalizationSetting *local = [CVLocalizationSetting sharedInstance];

	self.titleLabel.text = [local localizedString:@"Cash Flow"];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark Overriden

- (NSDictionary *)loadEquitySheetData:(NSString *)equityCode {
	CVDataProvider *dp;
	CVParamInfo *paramInfo;
	NSDictionary *dict;
	dp = [CVDataProvider sharedInstance];

	paramInfo = [[CVParamInfo alloc] init];
	paramInfo.minutes = 15;
	paramInfo.parameters = equityCode;
	dict = [dp GetStockCashFlow:paramInfo];
	[paramInfo release];

	return dict;
}

- (NSString *)sheetConfigFile:(id)obj {
	CVLocalizationSetting *local = [CVLocalizationSetting sharedInstance];
	NSString *_langCode = [local localizedString:@"LangCode"];

	NSString *hydm;
	NSString *cfgFilePath;
	NSDictionary *dict;

	dict = (NSDictionary *)obj;

	hydm = [dict objectForKey:@"HYDM"];
	hydm = [hydm lowercaseString];
	if ([hydm isEqualToString:@"i31"]) {
		cfgFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"CashFlowTrust_%@",_langCode] ofType:@"plist"];
	} else if ([hydm isEqualToString:@"i11"]) {
		cfgFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"CashFlowInsurance_%@",_langCode] ofType:@"plist"];
	} else if ([hydm isEqualToString:@"i01"]) {
		cfgFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"CashFlowBank_%@",_langCode] ofType:@"plist"];
	} else if ([hydm isEqualToString:@"i21"]) {
		cfgFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"CashFlowSecurities_%@",_langCode] ofType:@"plist"];
	} else if ([hydm hasPrefix:@"i00"]) {
		cfgFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"CashFlowOther_%@",_langCode] ofType:@"plist"];
	} else {
		cfgFilePath = nil;
	}

	if (cfgFilePath) {
		cfgFilePath = [[[NSString alloc] initWithString:cfgFilePath] autorelease];
	}

	return cfgFilePath;
}

@end


text:
/* You can add global styles to this file, and also import other style files */
.activado{
    font-weight: bold;
}

a:link {
    text-decoration: none;
}


text:
package cz.meza.spring.boot.camel.route;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

/**
 *  Basic rest route.
 */
@Component
public class RestRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {

        //basic rest configuration
        restConfiguration()
                .contextPath("/example").apiContextPath("/api-doc")
                .apiProperty("api.title", "Spring boot camel example REST API")
                .apiProperty("api.version", "1.0")
                .apiProperty("cors", "true")
                .apiContextRouteId("doc-api")
                .bindingMode(RestBindingMode.json);

        rest("").description("Get basic information")
                .consumes(MediaType.TEXT_PLAIN_VALUE).produces(MediaType.TEXT_PLAIN_VALUE)
                .get("/info").description("Get info").to("direct:getInfo");

    }
}


text:
from typing import Text

from rasa.shared.exceptions import RasaCoreException

class AgentNotReady(RasaCoreException):
    """Raised if someone tries to use an agent that is not ready.

    An agent might be created, e.g. without an processor attached. But
    if someone tries to parse a message with that agent, this exception
    will be thrown.
    """

    def __init__(self, message: Text) -> None:
        """Initialize message attribute."""
        self.message = message
        super(AgentNotReady, self).__init__()

class ChannelConfigError(RasaCoreException):
    """Raised if a channel is not configured correctly."""

class InvalidTrackerFeaturizerUsageError(RasaCoreException):
    """Raised if a tracker featurizer is incorrectly used."""


text:
'use strict';

var App = angular.module('myApp.dashboard', ['ngRoute', 'firebase'])

// Declared route
App.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/dashboard', {
        templateUrl: 'dashboard/dashboard.html',
        controller: 'DashboardCtrl'
    });
}])

// Register controller
App.controller('DashboardCtrl', ['$scope', function($scope) {

	var ref = new Firebase("https://jimmyapp.firebaseio.com");

}]);


text:
    {!! Form::open(array('url'=>'/register', 'autocomplete' => 'off')) !!}

Join Plock to explore your intereested and hearing from your friends.

        {!! Form::text('username', null, array('class'=>'form-control', 'placeholder'=>'Username')) !!}
        {!! Form::text('email', null, array('class'=>'form-control', 'placeholder'=>'Email')) !!}
        {!! Form::password('password', array('class'=>'form-control', 'placeholder'=>'Password')) !!}

    {!! Form::submit('Sign up', array('class'=>'btn btn-primary btn-block'))!!}
    {!! Form::close() !!}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation;

import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerMappingProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.azure.ProxyResource;

/**
 * Protection container mapping object.
 */
public class ProtectionContainerMappingInner extends ProxyResource {
    /**
     * The custom data.
     */
    @JsonProperty(value = "properties")
    private ProtectionContainerMappingProperties properties;

    /**
     * Resource Location.
     */
    @JsonProperty(value = "location")
    private String location;

    /**
     * Get the custom data.
     *
     * @return the properties value
     */
    public ProtectionContainerMappingProperties properties() {
        return this.properties;
    }

    /**
     * Set the custom data.
     *
     * @param properties the properties value to set
     * @return the ProtectionContainerMappingInner object itself.
     */
    public ProtectionContainerMappingInner withProperties(ProtectionContainerMappingProperties properties) {
        this.properties = properties;
        return this;
    }

    /**
     * Get resource Location.
     *
     * @return the location value
     */
    public String location() {
        return this.location;
    }

    /**
     * Set resource Location.
     *
     * @param location the location value to set
     * @return the ProtectionContainerMappingInner object itself.
     */
    public ProtectionContainerMappingInner withLocation(String location) {
        this.location = location;
        return this;
    }

}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { set } from '@ember/object';
import component from 'code-corps-ember/tests/pages/components/category-checkboxes';
import PageObject from 'ember-cli-page-object';

let page = PageObject.create(component);

moduleForComponent('category-checkboxes', 'Integration | Component | category checkboxes', {
  integration: true,
  beforeEach() {
    page.setContext(this);
  },
  afterEach() {
    page.removeContext();
  }
});

test('it works for unselecting selected categories', function(assert) {
  assert.expect(4);

  let option = { id: 1, name: 'Test' };
  let options = [option];
  let selection = [option];

  set(this, 'options', options);
  set(this, 'selection', selection);
  set(this, 'updateCategories', function() {
    assert.ok(true);
  });

  this.render(hbs`
    {{category-checkboxes
      options=options
      selection=selection
      updateCategories=updateCategories
    }}
  `);

  assert.equal(page.checkboxes.objectAt(0).label.name, 'Test', 'Renders the name');
  assert.ok(page.checkboxes.objectAt(0).isChecked, 'Checkbox is checked');
  page.checkboxes.objectAt(0).label.click();
  assert.notOk(page.checkboxes.objectAt(0).isChecked, 'Checkbox is not checked');
});

test('it works for selecting unselected categories', function(assert) {
  assert.expect(4);

  let option = { id: 1, name: 'Test' };
  let options = [option];
  let selection = [];

  set(this, 'options', options);
  set(this, 'selection', selection);
  set(this, 'updateCategories', function() {
    assert.ok(true);
  });

  this.render(hbs`
    {{category-checkboxes
      options=options
      selection=selection
      updateCategories=updateCategories
    }}
  `);

  assert.equal(page.checkboxes.objectAt(0).label.name, 'Test', 'Renders the name');
  assert.notOk(page.checkboxes.objectAt(0).isChecked, 'Checkbox is not checked');
  page.checkboxes.objectAt(0).label.click();
  assert.ok(page.checkboxes.objectAt(0).isChecked, 'Checkbox is checked');
});


text:
#import <TargetConditionals.h>
#import "ccMacros.h"
#import "Platforms/CCGL.h"

@class CCGLProgram;

/** vertex attrib flags */
enum {
	kCCVertexAttribFlag_None		= 0,

	kCCVertexAttribFlag_Position	= 1 << 0,
	kCCVertexAttribFlag_Color		= 1 << 1,
	kCCVertexAttribFlag_TexCoords	= 1 << 2,

	kCCVertexAttribFlag_PosColorTex = ( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color | kCCVertexAttribFlag_TexCoords ),
};

/** GL server side states */
typedef enum {
//	CC_GL_SCISSOR_TEST = 1 << 0,
//	CC_GL_STENCIL_TEST = 1 << 1,
//	CC_GL_DEPTH_TEST = 1 << 2,
	CC_GL_BLEND = 1 << 3,
//	CC_GL_DITHER = 1 << 4,

//	CC_GL_ALL = ( CC_GL_SCISSOR_TEST | CC_GL_STENCIL_TEST | CC_GL_DEPTH_TEST | CC_GL_BLEND | CC_GL_DITHER ),
	CC_GL_ALL = ( CC_GL_BLEND ),

} ccGLServerState;

#ifdef __cplusplus
extern "C" {
#endif

/** @file ccGLStateCache.h
*/

/** Invalidates the GL state cache.
 If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache.
 @since v2.0.0
 */
void ccGLInvalidateStateCache( void );

/** Uses the GL program in case program is different than the current one.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly.
 @since v2.0.0
 */
void ccGLUseProgram( GLuint program );

/** Deletes the GL program. If it is the one that is being used, it invalidates it.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly.
 @since v2.0.0
 */
void ccGLDeleteProgram( GLuint program );

/** Uses a blending function in case it not already used.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly.
 @since v2.0.0
 */
void ccGLBlendFunc(GLenum sfactor, GLenum dfactor);

/** sets the projection matrix as dirty
 @since v2.0.0
 */
void ccSetProjectionMatrixDirty( void );

/** Will enable the vertex attribs that are passed as flags.
 Possible flags:

	* kCCVertexAttribFlag_Position
	* kCCVertexAttribFlag_Color
	* kCCVertexAttribFlag_TexCoords

 These flags can be ORed. The flags that are not present, will be disabled.

 @since v2.0.0
 */
void ccGLEnableVertexAttribs( unsigned int flags );

/** If the active texture is not textureEnum, then it will active it.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly.
 @since v2.0.0
 */
void ccGLActiveTexture(GLenum textureEnum );

/** Returns the active texture.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glGetIntegerv(GL_ACTIVE_TEXTURE);
 @since v2.0.0
 */
GLenum ccGLGetActiveTexture( void );

/** If the texture is not already bound, it binds it.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
 @since v2.0.0
 */
void ccGLBindTexture2D(GLuint textureId );

/** It will delete a given texture. If the texture was bound, it will invalidate the cached.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
 @since v2.0.0
 */
void ccGLDeleteTexture(GLuint textureId);

/** It will enable / disable the server side GL states.
 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly.
 @since v2.0.0
 */
void ccGLEnable( ccGLServerState flags );

#ifdef __cplusplus
}
#endif


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>serial_port_base::stop_bits::type</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../serial_port_base__stop_bits.html" title="serial_port_base::stop_bits">
<link rel="prev" href="store.html" title="serial_port_base::stop_bits::store">
<link rel="next" href="value.html" title="serial_port_base::stop_bits::value">

Home
Libraries
People
FAQ
More

serial_port_base::stop_bits::type

enum type

          Values

one

onepointfive

two

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.solambda.swiffer.api;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Handler for the {@code RecordMarkerFailed} event.
 *

 * The annotated method may have the following parameters:
 *

 *

 * any parameter that is common to all event handlers (see {@link EventHandlerCommonParameter})
 *

 *

 * the default parameter is {@code input}: the optional details recorded with Marker.
 *

 *

 */
@Documented
@Retention(RUNTIME)
@Target(METHOD)
@EventHandler
public @interface OnRecordMarkerFailed {

    /**
     * The name of the failed Marker.
     *
     * @return name of the failed Marker
     */
    String value();

}


text:
layout: home
excerpt: "Meeplebox - Designing and playing games online on computer, tablet and phone"
tags: [Meeplebox, games, gamedesign]
image:
  feature: playing-cards.jpg
  credit: Gabriela Pinto
  creditlink: https://www.flickr.com/photos/gabrielap93/
---


text:
template <class T>
struct test
    : public std::priority_queue<T, std::vector<T, test_allocator<T> > >
{
    typedef std::priority_queue<T, std::vector<T, test_allocator<T> > > base;
    typedef typename base::container_type container_type;
    typedef typename base::value_compare value_compare;

    explicit test(const test_allocator<int>& a) : base(a) {}
    test(const value_compare& comp, const test_allocator<int>& a)
        : base(comp, a) {}
    test(const value_compare& comp, const container_type& c,
        const test_allocator<int>& a) : base(comp, c, a) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    test(const value_compare& comp, container_type&& c,
         const test_allocator<int>& a) : base(comp, std::move(c), a) {}
    test(test&& q, const test_allocator<int>& a) : base(std::move(q), a) {}
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
    test_allocator<int> get_allocator() {return c.get_allocator();}

    using base::c;
};

int main()
{
    test<int> q(std::less<int>(), test_allocator<int>(3));
    assert(q.c.get_allocator() == test_allocator<int>(3));
    assert(q.c.size() == 0);
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_hal.h"
#include "stm32f0xx.h"
#include "stm32f0xx_it.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern TIM_HandleTypeDef htim3;
extern DMA_HandleTypeDef hdma_usart2_rx;
extern DMA_HandleTypeDef hdma_usart2_tx;
extern UART_HandleTypeDef huart2;

/******************************************************************************/
/*            Cortex-M0 Processor Interruption and Exception Handlers         */
/******************************************************************************/

/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  HAL_SYSTICK_IRQHandler();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F0xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f0xx.s).                    */
/******************************************************************************/

/**
* @brief This function handles DMA1 channel 1 interrupt.
*/
void DMA1_Ch1_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Ch1_IRQn 0 */

  /* USER CODE END DMA1_Ch1_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart2_rx);
  /* USER CODE BEGIN DMA1_Ch1_IRQn 1 */

  /* USER CODE END DMA1_Ch1_IRQn 1 */
}

/**
* @brief This function handles DMA1 channel 2 to 3 and DMA2 channel 1 to 2 interrupts.
*/
void DMA1_Ch2_3_DMA2_Ch1_2_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Ch2_3_DMA2_Ch1_2_IRQn 0 */

  /* USER CODE END DMA1_Ch2_3_DMA2_Ch1_2_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart2_tx);
  /* USER CODE BEGIN DMA1_Ch2_3_DMA2_Ch1_2_IRQn 1 */

  /* USER CODE END DMA1_Ch2_3_DMA2_Ch1_2_IRQn 1 */
}

/**
* @brief This function handles TIM3 global interrupt.
*/
void TIM3_IRQHandler(void)
{
  /* USER CODE BEGIN TIM3_IRQn 0 */

  /* USER CODE END TIM3_IRQn 0 */
  HAL_TIM_IRQHandler(&htim3);
  /* USER CODE BEGIN TIM3_IRQn 1 */

  /* USER CODE END TIM3_IRQn 1 */
}

/**
* @brief This function handles USART2 global interrupt (combined with EXTI line 26 interrupt).
*/
void USART2_IRQHandler(void)
{
  /* USER CODE BEGIN USART2_IRQn 0 */

  /* USER CODE END USART2_IRQn 0 */
  HAL_UART_IRQHandler(&huart2);
  /* USER CODE BEGIN USART2_IRQn 1 */

  /* USER CODE END USART2_IRQn 1 */
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
<?php

/*
 * WHMCS module to receive bitcoin payment using BitBayar (Bitcoin payment processor)
 * Author : Gusti Tammam
 * URL : http://www.tammam.web.id
 * Release Date: 2015.04.17
 * License : http://opensource.org/licenses/MIT
 */
/*
 * WHMCS - The Complete Client Management, Billing & Support Solution
 * Copyright (c) WHMCS Ltd. All Rights Reserved,
 * Email: info@whmcs.com
 * Website: http://www.whmcs.com
 */
/*
 * BitBayar - Indonesian Bitcoin payment processor
 * Website: https://bitbayar.com
 */

function bitbayar_config() {
    $configarray = array(
     "FriendlyName" => array("Type" => "System", "Value"=>"BitBayar"),
     "apibitbayar" => array("FriendlyName" => "API Token Key", "Type" => "text", "Size" => "40", ),
     "instructions" => array("FriendlyName" => "BitBayar Instructions", "Type" => "textarea", "Rows" => "5", "Description" => "The instructions you want displaying to customers who choose this payment method - the invoice number will be shown underneath the text entered above", ),
    );
  return $configarray;
}

function bitbayar_link($params) {

  # Gateway Specific Variables
  $gatewayapi = $params['apibitbayar'];
  $callbackurl = $params['systemurl'] . "/modules/gateways/callback/bitbayar.php";
  $redirecturl = $params['systemurl'] . "/viewinvoice.php?id=" . $params['invoiceid'];

  # Invoice Variables
  $invoiceid = $params['invoiceid'];
  $description = $params["description"];
  $amount = $params['amount']; # Format: ##.##
  $currency = $params['currency']; # Currency Code

  # Client Variables
  $firstname = $params['clientdetails']['firstname'];
  $lastname = $params['clientdetails']['lastname'];
  $email = $params['clientdetails']['email'];
  $address1 = $params['clientdetails']['address1'];
  $address2 = $params['clientdetails']['address2'];
  $city = $params['clientdetails']['city'];
  $state = $params['clientdetails']['state'];
  $postcode = $params['clientdetails']['postcode'];
  $country = $params['clientdetails']['country'];
  $phone = $params['clientdetails']['phonenumber'];

  # System Variables
  $companyname = $params['companyname'];
  $systemurl = $params['systemurl'];
  $currency = $params['currency'];

  $data = array(
    'token'=>$gatewayapi,
    'invoice_id'=>$invoiceid,
    'rupiah'=>$amount,
    'memo'=>$description,
    'callback_url'=>$callbackurl,
    'url_success'=>$redirecturl,
    'url_failed'=>$redirecturl
  );
  $url = 'https://bitbayar.com/api/create_invoice';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  $return = curl_exec($ch);
  curl_close($ch);
  $data = json_decode($return);
  if($data->success){
    $paymenturl = $data->payment_url;
    $code = '

'.$params['instructions'];
    return $code;
    exit;
  }
  else{
    exit('BitBayar API Error: '.$data->error_message);
  }
}

?>


text:
@interface PNPushNotificationsRemoveRequest : PNBaseRequest

#pragma mark - Properties

// Stores reference on stringified push notification token
@property (nonatomic, readonly, strong) NSData *devicePushToken;

#pragma mark Class methods

+ (PNPushNotificationsRemoveRequest *)requestWithDevicePushToken:(NSData *)pushToken;

#pragma mark - Instance methods

- (id)initWithDevicePushToken:(NSData *)pushToken;

#pragma mark -

@end


text:
%doc
This library deals with the operating system environment, but not
all OS functions are here --- some are in the special sys plugin
library. Here, we only deal with the command line argument list
and environment variables.
%doc

using namespace angort;

static Value argList;

// we store this because in certain plugins the arglist is useful.

namespace angort {
char **sysArgv;
int sysArgc;
};

void setArgumentList(int argc,char *argv[]){
    ArrayList<Value>*list = Types::tList->set(&argList);

    sysArgc=argc;
    sysArgv=argv;

    for(int i=0;i<argc;i++){
        Value *v = list->append();
        Types::tString->set(v,argv[i]);
    }
}

%name env

%word rawargs (-- list) get command line arguments without stripping
This retrieves the full command line arguments passed to main(), without
doing the stripping of Angort-specific arguments performed by std$args.
{
    Value *v = a->pushval();
    v->copy(&argList);
}

%word getenv (name -- string/none) get environment variable
{
    Value *p;
    a->popParams(&p,"s");

    const char *s = getenv(p->toString().get());
    p = a->pushval();

    if(s)
        Types::tString->set(p,s);
    else
        p->setNone();
}

%word setenv (value name --) set environment variable
{
    Value *p[2];
    a->popParams(p,"ss");
    setenv(p[1]->toString().get(),p[0]->toString().get(),1);
}

%wordargs unsetenv s (name --) unset environment variable
{
    unsetenv(p0);
}


text:
export function objectOrFunction(x) {
  let type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

export function isFunction(x) {
  return typeof x === 'function';
}

export function isObject(x) {
  return x !== null && typeof x === 'object';
}

export function isMaybeThenable(x) {
  return x !== null && typeof x === 'object';
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net;

import android.content.Context;
import android.content.ContextWrapper;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.PathUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.net.TestUrlRequestListener.ResponseStep;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

/**
 * Test CronetUrlRequestContext.
 */
public class CronetUrlRequestContextTest extends CronetTestBase {
    // URLs used for tests.
    private static final String TEST_URL = "http://127.0.0.1:8000";
    private static final String URL_404 = "http://127.0.0.1:8000/notfound404";
    private static final String MOCK_CRONET_TEST_FAILED_URL =
            "http://mock.failed.request/-2";
    private static final String MOCK_CRONET_TEST_SUCCESS_URL =
            "http://mock.http/success.txt";

    CronetTestActivity mActivity;

    static class RequestThread extends Thread {
        public TestUrlRequestListener mListener;

        final CronetTestActivity mActivity;
        final String mUrl;
        final ConditionVariable mRunBlocker;

        public RequestThread(CronetTestActivity activity, String url,
                ConditionVariable runBlocker) {
            mActivity = activity;
            mUrl = url;
            mRunBlocker = runBlocker;
        }

        @Override
        public void run() {
            mRunBlocker.block();
            UrlRequestContext requestContext = mActivity.initRequestContext();
            mListener = new TestUrlRequestListener();
            UrlRequest urlRequest =
                    requestContext.createRequest(mUrl, mListener, mListener.getExecutor());
            urlRequest.start();
            mListener.blockForDone();
        }
    }

    /**
     * Listener that shutdowns the request context when request has succeeded
     * or failed.
     */
    class ShutdownTestUrlRequestListener extends TestUrlRequestListener {
        @Override
        public void onSucceeded(UrlRequest request, ExtendedResponseInfo info) {
            super.onSucceeded(request, info);
            mActivity.mUrlRequestContext.shutdown();
        }

        @Override
        public void onFailed(UrlRequest request,
                ResponseInfo info,
                UrlRequestException error) {
            super.onFailed(request, info, error);
            mActivity.mUrlRequestContext.shutdown();
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testConfigUserAgent() throws Exception {
        String userAgentName = "User-Agent";
        String userAgentValue = "User-Agent-Value";
        UrlRequestContextConfig config = new UrlRequestContextConfig();
        config.setUserAgent(userAgentValue);
        config.setLibraryName("cronet_tests");
        String[] commandLineArgs = {
                CronetTestActivity.CONFIG_KEY, config.toString()
        };
        mActivity = launchCronetTestAppWithUrlAndCommandLineArgs(TEST_URL,
                commandLineArgs);
        assertTrue(NativeTestServer.startNativeTestServer(
                getInstrumentation().getTargetContext()));
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                NativeTestServer.getEchoHeaderURL(userAgentName), listener,
                listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        assertEquals(userAgentValue, listener.mResponseAsString);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testDataReductionProxyEnabled() throws Exception {
        mActivity = launchCronetTestAppAndSkipFactoryInit();

        // Ensure native code is loaded before trying to start test server.
        UrlRequestContext.createContext(
                getInstrumentation().getTargetContext(),
                new UrlRequestContextConfig().setLibraryName("cronet_tests"))
                .shutdown();

        assertTrue(NativeTestServer.startNativeTestServer(
                getInstrumentation().getTargetContext()));
        if (!NativeTestServer.isDataReductionProxySupported()) {
            return;
        }
        String serverHostPort = NativeTestServer.getHostPort();

        // Enable the Data Reduction Proxy and configure it to use the test
        // server as its primary proxy, and to check successfully that this
        // proxy is OK to use.
        UrlRequestContextConfig config = new UrlRequestContextConfig();
        config.enableDataReductionProxy("test-key");
        config.setDataReductionProxyOptions(
                serverHostPort, "unused.net:9999",
                NativeTestServer.getFileURL("/secureproxychecksuccess.txt"));
        config.setLibraryName("cronet_tests");
        mActivity.mUrlRequestContext = UrlRequestContext.createContext(
                getInstrumentation().getTargetContext(), config);
        TestUrlRequestListener listener = new TestUrlRequestListener();

        // Construct and start a request that can only be returned by the test
        // server. This request will fail if the configuration logic for the
        // Data Reduction Proxy is not used.
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                "http://DomainThatDoesnt.Resolve/datareductionproxysuccess.txt",
                listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();

        // Verify that the request is successful and that the Data Reduction
        // Proxy logic configured to use the test server as its proxy.
        assertEquals(200, listener.mResponseInfo.getHttpStatusCode());
        assertEquals(serverHostPort, listener.mResponseInfo.getProxyServer());
        assertEquals(
                "http://DomainThatDoesnt.Resolve/datareductionproxysuccess.txt",
                listener.mResponseInfo.getUrl());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testShutdown() throws Exception {
        mActivity = launchCronetTestApp();
        TestUrlRequestListener listener = new ShutdownTestUrlRequestListener();
        // Block listener when response starts to verify that shutdown fails
        // if there are active requests.
        listener.setAutoAdvance(false);
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        try {
            mActivity.mUrlRequestContext.shutdown();
            fail("Should throw an exception");
        } catch (Exception e) {
            assertEquals("Cannot shutdown with active requests.",
                         e.getMessage());
        }

        listener.waitForNextStep();
        assertEquals(ResponseStep.ON_RESPONSE_STARTED, listener.mResponseStep);
        try {
            mActivity.mUrlRequestContext.shutdown();
            fail("Should throw an exception");
        } catch (Exception e) {
            assertEquals("Cannot shutdown with active requests.",
                         e.getMessage());
        }
        listener.startNextRead(urlRequest);

        listener.waitForNextStep();
        assertEquals(ResponseStep.ON_READ_COMPLETED, listener.mResponseStep);
        try {
            mActivity.mUrlRequestContext.shutdown();
            fail("Should throw an exception");
        } catch (Exception e) {
            assertEquals("Cannot shutdown with active requests.",
                         e.getMessage());
        }

        // May not have read all the data, in theory. Just enable auto-advance
        // and finish the request.
        listener.setAutoAdvance(true);
        listener.startNextRead(urlRequest);
        listener.blockForDone();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testShutdownDuringInit() throws Exception {
        final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
        final ConditionVariable block = new ConditionVariable(false);

        // Post a task to main thread to block until shutdown is called to test
        // scenario when shutdown is called right after construction before
        // context is fully initialized on the main thread.
        Runnable blockingTask = new Runnable() {
            public void run() {
                try {
                    block.block();
                } catch (Exception e) {
                    fail("Caught " + e.getMessage());
                }
            }
        };
        // Ensure that test is not running on the main thread.
        assertTrue(Looper.getMainLooper() != Looper.myLooper());
        new Handler(Looper.getMainLooper()).post(blockingTask);

        // Create new request context, but its initialization on the main thread
        // will be stuck behind blockingTask.
        final UrlRequestContext requestContext = activity.initRequestContext();
        // Unblock the main thread, so context gets initialized and shutdown on
        // it.
        block.open();
        // Shutdown will wait for init to complete on main thread.
        requestContext.shutdown();
        // Verify that context is shutdown.
        try {
            requestContext.stopNetLog();
            fail("Should throw an exception.");
        } catch (Exception e) {
            assertEquals("Context is shut down.", e.getMessage());
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitAndShutdownOnMainThread() throws Exception {
        final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
        final ConditionVariable block = new ConditionVariable(false);

        // Post a task to main thread to init and shutdown on the main thread.
        Runnable blockingTask = new Runnable() {
            public void run() {
                // Create new request context, loading the library.
                final UrlRequestContext requestContext = activity.initRequestContext();
                // Shutdown right after init.
                requestContext.shutdown();
                // Verify that context is shutdown.
                try {
                    requestContext.stopNetLog();
                    fail("Should throw an exception.");
                } catch (Exception e) {
                    assertEquals("Context is shut down.", e.getMessage());
                }
                block.open();
            }
        };
        new Handler(Looper.getMainLooper()).post(blockingTask);
        // Wait for shutdown to complete on main thread.
        block.block();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testMultipleShutdown() throws Exception {
        mActivity = launchCronetTestApp();
        try {
            mActivity.mUrlRequestContext.shutdown();
            mActivity.mUrlRequestContext.shutdown();
            fail("Should throw an exception");
        } catch (Exception e) {
            assertEquals("Context is shut down.",
                         e.getMessage());
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testShutdownAfterError() throws Exception {
        mActivity = launchCronetTestApp();
        TestUrlRequestListener listener = new ShutdownTestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                MOCK_CRONET_TEST_FAILED_URL, listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        assertTrue(listener.mOnErrorCalled);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testShutdownAfterCancel() throws Exception {
        mActivity = launchCronetTestApp();
        TestUrlRequestListener listener = new TestUrlRequestListener();
        // Block listener when response starts to verify that shutdown fails
        // if there are active requests.
        listener.setAutoAdvance(false);
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        try {
            mActivity.mUrlRequestContext.shutdown();
            fail("Should throw an exception");
        } catch (Exception e) {
            assertEquals("Cannot shutdown with active requests.",
                         e.getMessage());
        }
        listener.waitForNextStep();
        assertEquals(ResponseStep.ON_RESPONSE_STARTED, listener.mResponseStep);
        urlRequest.cancel();
        mActivity.mUrlRequestContext.shutdown();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testNetLog() throws Exception {
        Context context = getInstrumentation().getTargetContext();
        File directory = new File(PathUtils.getDataDirectory(context));
        File file = File.createTempFile("cronet", "json", directory);
        CronetUrlRequestContext requestContext = new CronetUrlRequestContext(
                context,
                new UrlRequestContextConfig().setLibraryName("cronet_tests"));
        // Start NetLog immediately after the request context is created to make
        // sure that the call won't crash the app even when the native request
        // context is not fully initialized. See crbug.com/470196.
        requestContext.startNetLogToFile(file.getPath(), false);

        // Start a request.
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest request = requestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        request.start();
        listener.blockForDone();
        requestContext.stopNetLog();
        assertTrue(file.exists());
        assertTrue(file.length() != 0);
        assertFalse(hasBytesInNetLog(file));
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testNetLogAfterShutdown() throws Exception {
        mActivity = launchCronetTestApp();
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        mActivity.mUrlRequestContext.shutdown();

        File directory = new File(PathUtils.getDataDirectory(
                getInstrumentation().getTargetContext()));
        File file = File.createTempFile("cronet", "json", directory);
        try {
            mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(),
                    false);
            fail("Should throw an exception.");
        } catch (Exception e) {
            assertEquals("Context is shut down.", e.getMessage());
        }
        assertFalse(hasBytesInNetLog(file));
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testNetLogStartMultipleTimes() throws Exception {
        mActivity = launchCronetTestApp();
        File directory = new File(PathUtils.getDataDirectory(
                getInstrumentation().getTargetContext()));
        File file = File.createTempFile("cronet", "json", directory);
        // Start NetLog multiple times.
        mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(), false);
        mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(), false);
        mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(), false);
        mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(), false);
        // Start a request.
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        mActivity.mUrlRequestContext.stopNetLog();
        assertTrue(file.exists());
        assertTrue(file.length() != 0);
        assertFalse(hasBytesInNetLog(file));
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testNetLogStopMultipleTimes() throws Exception {
        mActivity = launchCronetTestApp();
        File directory = new File(PathUtils.getDataDirectory(
                getInstrumentation().getTargetContext()));
        File file = File.createTempFile("cronet", "json", directory);
        mActivity.mUrlRequestContext.startNetLogToFile(file.getPath(), false);
        // Start a request.
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        // Stop NetLog multiple times.
        mActivity.mUrlRequestContext.stopNetLog();
        mActivity.mUrlRequestContext.stopNetLog();
        mActivity.mUrlRequestContext.stopNetLog();
        mActivity.mUrlRequestContext.stopNetLog();
        mActivity.mUrlRequestContext.stopNetLog();
        assertTrue(file.exists());
        assertTrue(file.length() != 0);
        assertFalse(hasBytesInNetLog(file));
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testNetLogWithBytes() throws Exception {
        Context context = getInstrumentation().getTargetContext();
        File directory = new File(PathUtils.getDataDirectory(context));
        File file = File.createTempFile("cronet", "json", directory);
        CronetUrlRequestContext requestContext = new CronetUrlRequestContext(
                context,
                new UrlRequestContextConfig().setLibraryName("cronet_tests"));
        // Start NetLog with logAll as true.
        requestContext.startNetLogToFile(file.getPath(), true);
        // Start a request.
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest request = requestContext.createRequest(
                TEST_URL, listener, listener.getExecutor());
        request.start();
        listener.blockForDone();
        requestContext.stopNetLog();
        assertTrue(file.exists());
        assertTrue(file.length() != 0);
        assertTrue(hasBytesInNetLog(file));
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    private boolean hasBytesInNetLog(File logFile) throws Exception {
        BufferedReader logReader = new BufferedReader(new FileReader(logFile));
        try {
            String logLine;
            while ((logLine = logReader.readLine()) != null) {
                if (logLine.contains("\"hex_encoded_bytes\"")) {
                    return true;
                }
            }
            return false;
        } finally {
            logReader.close();
        }
    }

    private void enableCache(int cacheType) throws Exception {
        String cacheTypeString = "";
        if (cacheType == UrlRequestContextConfig.HTTP_CACHE_DISK) {
            cacheTypeString = CronetTestActivity.CACHE_DISK;
        } else if (cacheType == UrlRequestContextConfig.HTTP_CACHE_DISK_NO_HTTP) {
            cacheTypeString = CronetTestActivity.CACHE_DISK_NO_HTTP;
        } else if (cacheType == UrlRequestContextConfig.HTTP_CACHE_IN_MEMORY) {
            cacheTypeString = CronetTestActivity.CACHE_IN_MEMORY;
        }
        String[] commandLineArgs = {CronetTestActivity.CACHE_KEY, cacheTypeString};
        mActivity = launchCronetTestAppWithUrlAndCommandLineArgs(null,
                commandLineArgs);
        assertTrue(NativeTestServer.startNativeTestServer(
                getInstrumentation().getTargetContext()));
    }

    private void checkRequestCaching(String url, boolean expectCached) {
        checkRequestCaching(url, expectCached, false);
    }

    private void checkRequestCaching(String url, boolean expectCached,
            boolean disableCache) {
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                url, listener, listener.getExecutor());
        if (disableCache) {
            urlRequest.disableCache();
        }
        urlRequest.start();
        listener.blockForDone();
        assertEquals(expectCached, listener.mResponseInfo.wasCached());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testEnableHttpCacheDisabled() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_DISABLED);
        String url = NativeTestServer.getFileURL("/cacheable.txt");
        checkRequestCaching(url, false);
        checkRequestCaching(url, false);
        checkRequestCaching(url, false);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testEnableHttpCacheInMemory() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_IN_MEMORY);
        String url = NativeTestServer.getFileURL("/cacheable.txt");
        checkRequestCaching(url, false);
        checkRequestCaching(url, true);
        NativeTestServer.shutdownNativeTestServer();
        checkRequestCaching(url, true);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testEnableHttpCacheDisk() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_DISK);
        String url = NativeTestServer.getFileURL("/cacheable.txt");
        checkRequestCaching(url, false);
        checkRequestCaching(url, true);
        NativeTestServer.shutdownNativeTestServer();
        checkRequestCaching(url, true);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testEnableHttpCacheDiskNoHttp() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_DISABLED);
        String url = NativeTestServer.getFileURL("/cacheable.txt");
        checkRequestCaching(url, false);
        checkRequestCaching(url, false);
        checkRequestCaching(url, false);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testDisableCache() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_DISK);
        String url = NativeTestServer.getFileURL("/cacheable.txt");

        // When cache is disabled, making a request does not write to the cache.
        checkRequestCaching(url, false, true /** disable cache */);
        checkRequestCaching(url, false);

        // When cache is enabled, the second request is cached.
        checkRequestCaching(url, false, true /** disable cache */);
        checkRequestCaching(url, true);

        // Shut down the server, next request should have a cached response.
        NativeTestServer.shutdownNativeTestServer();
        checkRequestCaching(url, true);

        // Cache is disabled after server is shut down, request should fail.
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest = mActivity.mUrlRequestContext.createRequest(
                url, listener, listener.getExecutor());
        urlRequest.disableCache();
        urlRequest.start();
        listener.blockForDone();
        assertNotNull(listener.mError);
        assertEquals("Exception in CronetUrlRequest: net::ERR_CONNECTION_REFUSED",
                listener.mError.getMessage());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testEnableHttpCacheDiskNewContext() throws Exception {
        enableCache(UrlRequestContextConfig.HTTP_CACHE_DISK);
        String url = NativeTestServer.getFileURL("/cacheable.txt");
        checkRequestCaching(url, false);
        checkRequestCaching(url, true);
        NativeTestServer.shutdownNativeTestServer();
        checkRequestCaching(url, true);

        // Shutdown original context and create another that uses the same cache.
        mActivity.mUrlRequestContext.shutdown();
        mActivity.mUrlRequestContext = UrlRequestContext.createContext(
                getInstrumentation().getTargetContext(), mActivity.getContextConfig());
        checkRequestCaching(url, true);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitContextAndStartRequest() {
        CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();

        // Immediately make a request after initializing the context.
        UrlRequestContext requestContext = activity.initRequestContext();
        TestUrlRequestListener listener = new TestUrlRequestListener();
        UrlRequest urlRequest =
                requestContext.createRequest(TEST_URL, listener, listener.getExecutor());
        urlRequest.start();
        listener.blockForDone();
        assertEquals(200, listener.mResponseInfo.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitContextStartTwoRequests() throws Exception {
        CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();

        // Make two requests after initializing the context.
        UrlRequestContext requestContext = activity.initRequestContext();
        int[] statusCodes = {0, 0};
        String[] urls = {TEST_URL, URL_404};
        for (int i = 0; i < 2; i++) {
            TestUrlRequestListener listener = new TestUrlRequestListener();
            UrlRequest urlRequest =
                    requestContext.createRequest(urls[i], listener, listener.getExecutor());
            urlRequest.start();
            listener.blockForDone();
            statusCodes[i] = listener.mResponseInfo.getHttpStatusCode();
        }
        assertEquals(200, statusCodes[0]);
        assertEquals(404, statusCodes[1]);
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitTwoContextsSimultaneously() throws Exception {
        final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();

        // Threads will block on runBlocker to ensure simultaneous execution.
        ConditionVariable runBlocker = new ConditionVariable(false);
        RequestThread thread1 = new RequestThread(activity, TEST_URL, runBlocker);
        RequestThread thread2 = new RequestThread(activity, URL_404, runBlocker);

        thread1.start();
        thread2.start();
        runBlocker.open();
        thread1.join();
        thread2.join();
        assertEquals(200, thread1.mListener.mResponseInfo.getHttpStatusCode());
        assertEquals(404, thread2.mListener.mResponseInfo.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitTwoContextsInSequence() throws Exception {
        final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();

        ConditionVariable runBlocker = new ConditionVariable(true);
        RequestThread thread1 = new RequestThread(activity, TEST_URL, runBlocker);
        RequestThread thread2 = new RequestThread(activity, URL_404, runBlocker);

        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();
        assertEquals(200, thread1.mListener.mResponseInfo.getHttpStatusCode());
        assertEquals(404, thread2.mListener.mResponseInfo.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInitDifferentContexts() throws Exception {
        // Test that concurrently instantiating Cronet context's upon various
        // different versions of the same Android Context does not cause crashes
        // like crbug.com/453845
        mActivity = launchCronetTestApp();
        CronetUrlRequestContext firstContext =
                new CronetUrlRequestContext(mActivity, mActivity.getContextConfig());
        CronetUrlRequestContext secondContext = new CronetUrlRequestContext(
                mActivity.getApplicationContext(), mActivity.getContextConfig());
        CronetUrlRequestContext thirdContext = new CronetUrlRequestContext(
                new ContextWrapper(mActivity), mActivity.getContextConfig());
        firstContext.shutdown();
        secondContext.shutdown();
        thirdContext.shutdown();
    }
}


text:
Function.RegisterNamespace("Test.Aura.BrowserUnsupportedUtilTest");

/**
 * This test shows that when the browser is mocked to be missing native utilities, the fallbacks implementation in
 * $A.util are used.
 */

[Fixture]
Test.Aura.BrowserUnsupportedUtilTest=function() {

    [Fixture]
    function browserUnsupportedTests() {
        var MockObject = {};
        for (var key in Object) { MockObject[key] = Object[key]; }
        MockObject.prototype = Object.create(Object.prototype);

        MockObject.keys = undefined;

        var MockFunction = function MockFunction() {};
        MockFunction.prototype = Object.create(Function.prototype);

        MockFunction.prototype.bind = undefined;

        var MockArray = function() {};
        MockArray.prototype = Object.create(Array.prototype);

        MockArray.prototype.forEach = undefined;
        MockArray.prototype.map = undefined;
        MockArray.prototype.reduce = undefined;
        MockArray.prototype.every = undefined;
        MockArray.prototype.some = undefined;
        MockArray.prototype.filter = undefined;
        MockArray.isArray = function(obj) {
            return (obj instanceof [].constructor);
        };

        var utilMock = function(override, delegate) {
            Mocks.GetMocks(Object.Global(),{
                exp:function() {},
                window:Object.Global(),
                document:{createDocumentFragment:function() {}},
                Json:function() {},
                Transport:function() {},
                Style:function() {},
                Bitset:{},
                NumberFormat:{},
                $A:{ns:{}},
                navigator:{userAgent:''},
                Array: override === MockArray ? override : Array,
                Function: override === MockFunction ? override : Function
            })(function(){
                var CurrentObject = window.Object;
                window.Object = override === MockObject ? MockObject : window.Object;
                // #import aura.util.Util
                try {
                    delegate(new $A.ns.Util());
                } finally {
                    window.Object = CurrentObject;
                }
            });
        };

        function doArrayErrorTest(methodName, isPredicate) {
            utilMock(MockArray, function(util){
                try {
                    util[methodName]({});
                    Assert.False(true, "Method should throw an error.");
                } catch (e) {
                    Assert.True(e instanceof TypeError);
                    Assert.Equal("$A.util." + methodName + " called on non-array.",  e.message);
                }

                try {
                    util[methodName]([], {});
                    Assert.False(true, "Method should throw an error.");
                } catch (e) {
                    Assert.True(e instanceof TypeError);
                    Assert.Equal(
                        "$A.util." + methodName + " called with non-function " + (isPredicate ? "predicate." : "callback."),
                        e.message
                    );
                }
            });
        }

        [Fact]
        function testForEach() {
            utilMock(MockArray, function(util){
                var actual = [];
                util.forEach(["A", "B", "C"], function(letter, index) {
                    actual.push(this + letter + index);
                }, "THIS_OBJECT");

                Assert.Equal(actual[0], "THIS_OBJECTA0");
                Assert.Equal(actual[1], "THIS_OBJECTB1");
                Assert.Equal(actual[2], "THIS_OBJECTC2");
            });
        }

        [Fact]
        function testForEachError() {
            doArrayErrorTest("forEach");
        }

        [Fact]
        function testMap() {
            utilMock(MockArray, function(util){
                var actual = util.map(["A", "B", "C"], function(letter, index) {
                    return this + letter + index;
                }, "THIS_OBJECT");

                Assert.Equal(actual[0], "THIS_OBJECTA0");
                Assert.Equal(actual[1], "THIS_OBJECTB1");
                Assert.Equal(actual[2], "THIS_OBJECTC2");
            });
        }

        [Fact]
        function testMapError() {
            doArrayErrorTest("map");
        }

        [Fact]
        function testReduce() {
            utilMock(MockArray, function(util){
                var actual = util.reduce(["A", "B", "C"], function(current, letter, index) {
                    current.push(letter + index);
                    return current;
                }, []);

                Assert.Equal(actual[0], "A0");
                Assert.Equal(actual[1], "B1");
                Assert.Equal(actual[2], "C2");
            });
        }

        [Fact]
        function testReduceError() {
            doArrayErrorTest("reduce");
        }

        [Fact]
        function testFilter() {
            utilMock(MockArray, function(util) {
                Assert.Equal(
                    [0, 2],
                    util.filter([0, 2, 3], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "Result should only contain even numbers."
                );

                Assert.Equal(
            		[],
                    util.every([1, 3, 5], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "All numbers were odd, result should be empty."
                );
            });
        }

        [Fact]
        function testFilterError() {
            doArrayErrorTest("filter", true);
        }

        [Fact]
        function testEvery() {
            utilMock(MockArray, function(util){
                Assert.True(
                    util.every([0, 2, 4], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "All elements + 1 should be odd."
                );

                Assert.False(
                    util.every([1, 2, 4], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "First elements + 1 should not be odd."
                );
            });
        }

        [Fact]
        function testEveryError() {
            doArrayErrorTest("every", true);
        }

        [Fact]
        function testSome() {
            utilMock(MockArray, function(util) {
                Assert.True(
                    util.some([1, 3, 4], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "Last element + 2 should be odd."
                );

                Assert.False(
                    util.some([1, 3, 5], function(element, index) {
                        return (this + element) % 2 === 1;
                    }, 1),
                    "No element + 1 should be odd."
                );
            });
        }

        [Fact]
        function testSomeError() {
            doArrayErrorTest("some", true);
        }

        [Fact]
        function testBind() {
            function multiplyBPlusCByA(a, b, c) {
                return a * (b + c);
            }

            utilMock(MockFunction, function(util) {
                var bPlusCTimes5 = util.bind(multiplyBPlusCByA, null, 5);
                Assert.Equal(20, bPlusCTimes5(1, 3));
                Assert.Equal(50, bPlusCTimes5(7, 3));

                var cPlus1Times5 = util.bind(bPlusCTimes5, null, 1);
                Assert.Equal(20, cPlus1Times5(3));
                Assert.Equal(25, cPlus1Times5(4));

                var bPlusCTime5Called = util.bind.call(null, multiplyBPlusCByA, null, 5);
                Assert.Equal(20, bPlusCTimes5(1, 3));
                Assert.Equal(50, bPlusCTimes5(7, 3));
            });
        }

        [Fact]
        function testBindError() {
            utilMock(MockFunction, function(util) {
                try {
                    util.bind({});
                    Assert.False(true, "Method should throw an error.");
                } catch (e) {
                    Assert.True(e instanceof TypeError);
                    Assert.Equal("$A.util.bind called on non-function.",  e.message);
                }
            });
        }

        [Fact]
        function testKeys() {
            utilMock(MockObject, function(util) {
                var testObjects = [{}, new function(){}, []], i;
                for (i = 0; i < testObjects.length; i++) {
                    testObjects[i]["hello"] = "world";
                    testObjects[i]["goodbye"] = "cruel world";
                }

                for (i = 0; i < testObjects.length; i++) {
                    var keys = util.keys(testObjects[i]);
                    Assert.Equal(2, keys.length);
                    Assert.Equal("hello", keys[0]);
                    Assert.Equal("goodbye", keys[1]);
                }
            });
        }

        [Fact]
        function testKeysError() {
            utilMock(MockObject, function(util) {
                try {
                    util.keys(1);
                    Assert.False(true, "Method should throw an error.");
                } catch (e) {
                    Assert.True(e instanceof TypeError);
                    Assert.Equal("$A.util.keys called on non-object.",  e.message);
                }
            });
        }
    }
}


text:
package samples.gae.web;

import java.util.EnumSet;
import java.util.Set;

import javax.validation.Valid;

import com.google.appengine.api.users.UserServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import samples.gae.security.AppRole;
import samples.gae.security.GaeUserAuthentication;
import samples.gae.users.GaeUser;
import samples.gae.users.UserRegistry;

/**
 * @author Luke Taylor
 */
@Controller
@RequestMapping(value = "/register.htm")
public class RegistrationController {

	@Autowired
	private UserRegistry registry;

	@RequestMapping(method = RequestMethod.GET)
	public RegistrationForm registrationForm() {
		return new RegistrationForm();
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(@Valid RegistrationForm form, BindingResult result) {
		if (result.hasErrors()) {
			return null;
		}

		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		GaeUser currentUser = (GaeUser) authentication.getPrincipal();
		Set<AppRole> roles = EnumSet.of(AppRole.USER);

		if (UserServiceFactory.getUserService().isUserAdmin()) {
			roles.add(AppRole.ADMIN);
		}

		GaeUser user = new GaeUser(currentUser.getUserId(), currentUser.getNickname(),
				currentUser.getEmail(), form.getForename(), form.getSurname(), roles,
				true);

		registry.registerUser(user);

		// Update the context with the full authentication
		SecurityContextHolder.getContext().setAuthentication(
				new GaeUserAuthentication(user, authentication.getDetails()));

		return "redirect:/home.htm";
	}
}


text:
package com.fishercoder.solutions;

/**
 * 188. Best Time to Buy and Sell Stock IV
 *
 * Say you have an array for which the ith element is the price of a given stock on day i.

 Design an algorithm to find the maximum profit. You may complete at most k transactions.

 Note:
 You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
 */
public class _188 {

    /**credit: https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java*/
    public int maxProfit(int k, int[] prices) {
        int len = prices.length;
        if (k >= len / 2) {
            return quickSolve(prices);
        }

        int[][] t = new int[k + 1][len];
        for (int i = 1; i <= k; i++) {
            int tmpMax =  -prices[0];
            for (int j = 1; j < len; j++) {
                t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax);
                tmpMax =  Math.max(tmpMax, t[i - 1][j - 1] - prices[j]);
            }
        }
        return t[k][len - 1];
    }

    private int quickSolve(int[] prices) {
        int len = prices.length;
        int profit = 0;
        for (int i = 1; i < len; i++) {
            // as long as there is a price gap, we gain a profit.
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }

}


text:
// The "reflect-metadata" module has no imports or exports, but can be imported by modules to load the polyfill.
export { };

declare global {
    namespace Reflect {
        /**
          * Applies a set of decorators to a target object.
          * @param decorators An array of decorators.
          * @param target The target object.
          * @returns The result of applying the provided decorators.
          * @remarks Decorators are applied in reverse order of their positions in the array.
          * @example
          *
          *     class Example { }
          *
          *     // constructor
          *     Example = Reflect.decorate(decoratorsArray, Example);
          *
          */
        function decorate(decorators: ClassDecorator[], target: Function): Function;
        /**
          * Applies a set of decorators to a property of a target object.
          * @param decorators An array of decorators.
          * @param target The target object.
          * @param propertyKey The property key to decorate.
          * @param attributes A property descriptor.
          * @remarks Decorators are applied in reverse order.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod() { }
          *         method() { }
          *     }
          *
          *     // property (on constructor)
          *     Reflect.decorate(decoratorsArray, Example, "staticProperty");
          *
          *     // property (on prototype)
          *     Reflect.decorate(decoratorsArray, Example.prototype, "property");
          *
          *     // method (on constructor)
          *     Object.defineProperty(Example, "staticMethod",
          *         Reflect.decorate(decoratorsArray, Example, "staticMethod",
          *             Object.getOwnPropertyDescriptor(Example, "staticMethod")));
          *
          *     // method (on prototype)
          *     Object.defineProperty(Example.prototype, "method",
          *         Reflect.decorate(decoratorsArray, Example.prototype, "method",
          *             Object.getOwnPropertyDescriptor(Example.prototype, "method")));
          *
          */
        function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: Object, propertyKey: string | symbol, attributes?: PropertyDescriptor): PropertyDescriptor;
        /**
          * A default metadata decorator factory that can be used on a class, class member, or parameter.
          * @param metadataKey The key for the metadata entry.
          * @param metadataValue The value for the metadata entry.
          * @returns A decorator function.
          * @remarks
          * If `metadataKey` is already defined for the target and target key, the
          * metadataValue for that key will be overwritten.
          * @example
          *
          *     // constructor
          *     @Reflect.metadata(key, value)
          *     class Example {
          *     }
          *
          *     // property (on constructor, TypeScript only)
          *     class Example {
          *         @Reflect.metadata(key, value)
          *         static staticProperty;
          *     }
          *
          *     // property (on prototype, TypeScript only)
          *     class Example {
          *         @Reflect.metadata(key, value)
          *         property;
          *     }
          *
          *     // method (on constructor)
          *     class Example {
          *         @Reflect.metadata(key, value)
          *         static staticMethod() { }
          *     }
          *
          *     // method (on prototype)
          *     class Example {
          *         @Reflect.metadata(key, value)
          *         method() { }
          *     }
          *
          */
        function metadata(metadataKey: any, metadataValue: any): {
            (target: Function): void;
            (target: Object, propertyKey: string | symbol): void;
        };
        /**
          * Define a unique metadata entry on the target.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param metadataValue A value that contains attached metadata.
          * @param target The target object on which to define metadata.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     Reflect.defineMetadata("custom:annotation", options, Example);
          *
          *     // decorator factory as metadata-producing annotation.
          *     function MyAnnotation(options): ClassDecorator {
          *         return target => Reflect.defineMetadata("custom:annotation", options, target);
          *     }
          *
          */
        function defineMetadata(metadataKey: any, metadataValue: any, target: Object): void;
        /**
          * Define a unique metadata entry on the target.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param metadataValue A value that contains attached metadata.
          * @param target The target object on which to define metadata.
          * @param propertyKey The property key for the target.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     Reflect.defineMetadata("custom:annotation", Number, Example, "staticProperty");
          *
          *     // property (on prototype)
          *     Reflect.defineMetadata("custom:annotation", Number, Example.prototype, "property");
          *
          *     // method (on constructor)
          *     Reflect.defineMetadata("custom:annotation", Number, Example, "staticMethod");
          *
          *     // method (on prototype)
          *     Reflect.defineMetadata("custom:annotation", Number, Example.prototype, "method");
          *
          *     // decorator factory as metadata-producing annotation.
          *     function MyAnnotation(options): PropertyDecorator {
          *         return (target, key) => Reflect.defineMetadata("custom:annotation", options, target, key);
          *     }
          *
          */
        function defineMetadata(metadataKey: any, metadataValue: any, target: Object, propertyKey: string | symbol): void;
        /**
          * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.hasMetadata("custom:annotation", Example);
          *
          */
        function hasMetadata(metadataKey: any, target: Object): boolean;
        /**
          * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method");
          *
          */
        function hasMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): boolean;
        /**
          * Gets a value indicating whether the target object has the provided metadata key defined.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @returns `true` if the metadata key was defined on the target object; otherwise, `false`.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.hasOwnMetadata("custom:annotation", Example);
          *
          */
        function hasOwnMetadata(metadataKey: any, target: Object): boolean;
        /**
          * Gets a value indicating whether the target object has the provided metadata key defined.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns `true` if the metadata key was defined on the target object; otherwise, `false`.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method");
          *
          */
        function hasOwnMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): boolean;
        /**
          * Gets the metadata value for the provided metadata key on the target object or its prototype chain.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.getMetadata("custom:annotation", Example);
          *
          */
        function getMetadata(metadataKey: any, target: Object): any;
        /**
          * Gets the metadata value for the provided metadata key on the target object or its prototype chain.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.getMetadata("custom:annotation", Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.getMetadata("custom:annotation", Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.getMetadata("custom:annotation", Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.getMetadata("custom:annotation", Example.prototype, "method");
          *
          */
        function getMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): any;
        /**
          * Gets the metadata value for the provided metadata key on the target object.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.getOwnMetadata("custom:annotation", Example);
          *
          */
        function getOwnMetadata(metadataKey: any, target: Object): any;
        /**
          * Gets the metadata value for the provided metadata key on the target object.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method");
          *
          */
        function getOwnMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): any;
        /**
          * Gets the metadata keys defined on the target object or its prototype chain.
          * @param target The target object on which the metadata is defined.
          * @returns An array of unique metadata keys.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.getMetadataKeys(Example);
          *
          */
        function getMetadataKeys(target: Object): any[];
        /**
          * Gets the metadata keys defined on the target object or its prototype chain.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns An array of unique metadata keys.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.getMetadataKeys(Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.getMetadataKeys(Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.getMetadataKeys(Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.getMetadataKeys(Example.prototype, "method");
          *
          */
        function getMetadataKeys(target: Object, propertyKey: string | symbol): any[];
        /**
          * Gets the unique metadata keys defined on the target object.
          * @param target The target object on which the metadata is defined.
          * @returns An array of unique metadata keys.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.getOwnMetadataKeys(Example);
          *
          */
        function getOwnMetadataKeys(target: Object): any[];
        /**
          * Gets the unique metadata keys defined on the target object.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns An array of unique metadata keys.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.getOwnMetadataKeys(Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.getOwnMetadataKeys(Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.getOwnMetadataKeys(Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.getOwnMetadataKeys(Example.prototype, "method");
          *
          */
        function getOwnMetadataKeys(target: Object, propertyKey: string | symbol): any[];
        /**
          * Deletes the metadata entry from the target object with the provided key.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @returns `true` if the metadata entry was found and deleted; otherwise, false.
          * @example
          *
          *     class Example {
          *     }
          *
          *     // constructor
          *     result = Reflect.deleteMetadata("custom:annotation", Example);
          *
          */
        function deleteMetadata(metadataKey: any, target: Object): boolean;
        /**
          * Deletes the metadata entry from the target object with the provided key.
          * @param metadataKey A key used to store and retrieve metadata.
          * @param target The target object on which the metadata is defined.
          * @param propertyKey The property key for the target.
          * @returns `true` if the metadata entry was found and deleted; otherwise, false.
          * @example
          *
          *     class Example {
          *         // property declarations are not part of ES6, though they are valid in TypeScript:
          *         // static staticProperty;
          *         // property;
          *
          *         static staticMethod(p) { }
          *         method(p) { }
          *     }
          *
          *     // property (on constructor)
          *     result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty");
          *
          *     // property (on prototype)
          *     result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property");
          *
          *     // method (on constructor)
          *     result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod");
          *
          *     // method (on prototype)
          *     result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method");
          *
          */
        function deleteMetadata(metadataKey: any, target: Object, propertyKey: string | symbol): boolean;
    }
}