text:
[Rules](/rules) allow you to define arbitrary code which can be used to fulfill custom authentication and authorization requirements, log events, retrieve information from external services, and much more.

Rules can also be used to programatically redirect users before an authentication transaction is complete, allowing the implementation of custom authentication flows which require input on behalf of the user, such as:

* Requiring users to provide additional verification when logging in from unknown locations.
* Implementing custom verification mechanisms (e.g. proprietary multifactor authentication providers).
* Forcing users to change passwords.

## How to implement a redirect

To redirect a user from a rule, set the `context.redirect` property as follows:

```js
function (user, context, callback) {
    context.redirect = {
        url: "https://example.com/foo"
    };
    return callback(null, user, context);
}
```

Once all rules have finished executing, the user will be redirected to the specified URL.

## What to do after redirecting

An authentication transaction that has been interrupted by setting `context.redirect` can be resumed by redirecting the user to the following URL:

```text
https://${account.namespace}/continue
```

When a user has been redirected to the `/continue` endpoint, all rules will be run again.

To distinguish between user-initiated logins and resumed login flows, the `context.protocol` property can be checked:

```js
function (user, context, callback) {
    if (context.protocol === "redirect-callback") {
        // User was redirected to the /continue endpoint
    } else {
        // User is logging in directly
    }
}
```

## Securely processing results after redirecting

Suppose you would like to force users to change their passwords under specific conditions. You can write a rule that would have the following behavior:

1. The user attempts to log in and needs to change their password.
2. The user is redirected to an application-specific page with a JWT in the query string. This JWT ensures that only this user's password can be changed and **must be validated** by the application.
3. The user changes their password in the application-specific page by having the application call the [Auth0 API](/api/v2#!/Users/patch_users_by_id)
4. The application redirects back to `/continue`, with a JWT in the query string. This token must be issued for the same user that is attempting to log in, and must contain a `passwordChanged: true` claim.

```js
function(user, context, callback) {
  // Prerequisites:
  // 1. Implement a `mustChangePassword` function
  // 2. Set configuration variables for the following:
  // * CLIENT_ID
  // * CLIENT_SECRET
  // * ISSUER
  if (context.protocol !== "redirect-callback") {
    if (mustChangePassword(user)) {
      // User has initiated a login and is forced to change their password
      // Send user's information in a JWT to avoid tampering
      function createToken(clientId, clientSecret, issuer, user) {
        var options = {
          expiresInMinutes: 5,
          audience: clientId,
          issuer: issuer
        };
        return jwt.sign(user, new Buffer(clientSecret, "base64"), options);
      }
      var token = createToken(
        configuration.CLIENT_ID,
        configuration.CLIENT_SECRET,
        configuration.ISSUER, {
          sub: user.user_id,
          email: user.email
        }
      );
      context.redirect = {
        url: "https://example.com/change-pw?token=" + token
      };
    }
  } else {
    // User has been redirected to /continue?token=..., password change must be validated
    // The generated token must include a `passwordChanged` claim to confirm the password change
    function verifyToken(clientId, clientSecret, issuer, token, cb) {
      jwt.verify(
        token,
        new Buffer(clientSecret, "base64").toString("binary"), {
          audience: clientId,
          issuer: issuer
        },
        cb
      );
    }
    function postVerify(err, decoded) {
      if (err) {
        return callback(new UnauthorizedError("Password change failed"));
      } else if (decoded.sub !== user.user_id) {
        return callback(new UnauthorizedError("Token does not match the current user"));
      } else if (!decoded.passwordChanged) {
        return callback(new UnauthorizedError("Password change was not confirmed"));
      } else {
        // User's password has been changed successfully
        return callback(null, user, context);
      }
    }
    verifyToken(
      configuration.CLIENT_ID,
      configuration.CLIENT_SECRET,
      configuration.ISSUER,
      context.request.query.token,
      postVerify
    );
  }
}
```


text:
namespace Microsoft.Zelig.CodeGeneration.IR
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Zelig.Runtime.TypeSystem;

    public sealed class MethodRepresentationOperator : Operator
    {
        //
        // State
        //

        private MethodRepresentation m_md;

        //
        // Constructor Methods
        //

        private MethodRepresentationOperator( Debugging.DebugInfo  debugInfo    ,
                                              OperatorCapabilities capabilities ,
                                              OperatorLevel        level        ,
                                              MethodRepresentation md           ) : base( debugInfo, capabilities, level )
        {
            m_md = md;
        }

        //--//

        public static MethodRepresentationOperator New( Debugging.DebugInfo  debugInfo ,
                                                        MethodRepresentation md        ,
                                                        VariableExpression   lhs       )
        {
            OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative                   |
                                                OperatorCapabilities.DoesNotMutateExistingStorage       |
                                                OperatorCapabilities.DoesNotAllocateStorage             |
                                                OperatorCapabilities.DoesNotReadExistingMutableStorage  |
                                                OperatorCapabilities.DoesNotThrow                       |
                                                OperatorCapabilities.DoesNotReadThroughPointerOperands  |
                                                OperatorCapabilities.DoesNotWriteThroughPointerOperands |
                                                OperatorCapabilities.DoesNotCapturePointerOperands      ;

            MethodRepresentationOperator res = new MethodRepresentationOperator( debugInfo, capabilities, OperatorLevel.Lowest, md );

            res.SetLhs( lhs );

            return res;
        }

        public static MethodRepresentationOperator New( Debugging.DebugInfo  debugInfo ,
                                                        MethodRepresentation md        ,
                                                        VariableExpression   lhs       ,
                                                        Expression           rhsObject )
        {
            OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative                   |
                                                OperatorCapabilities.DoesNotMutateExistingStorage       |
                                                OperatorCapabilities.DoesNotAllocateStorage             |
                                                OperatorCapabilities.DoesNotReadExistingMutableStorage  |
                                                OperatorCapabilities.MayThrow                           |
                                                OperatorCapabilities.DoesNotReadThroughPointerOperands  |
                                                OperatorCapabilities.DoesNotWriteThroughPointerOperands |
                                                OperatorCapabilities.DoesNotCapturePointerOperands      ;

            MethodRepresentationOperator res = new MethodRepresentationOperator( debugInfo, capabilities, OperatorLevel.ConcreteTypes, md ); // 'rhsObject' may be null.

            res.SetLhs( lhs       );
            res.SetRhs( rhsObject );

            return res;
        }

        //--//

        //
        // Helper Methods
        //

        public override Operator Clone( CloningContext context )
        {
            MethodRepresentation md = context.ConvertMethod( m_md );

            return RegisterAndCloneState( context, new MethodRepresentationOperator( m_debugInfo, m_capabilities, m_level, md ) );
        }

        //--//

        public override void ApplyTransformation( TransformationContextForIR context )
        {
            context.Push( this );

            base.ApplyTransformation( context );

            context.Transform( ref m_md );

            context.Pop();
        }

        //--//

        //
        // Access Methods
        //

        public MethodRepresentation Method
        {
            get
            {
                return m_md;
            }
        }

        //--//

        //
        // Debug Methods
        //

        public override void InnerToString( System.Text.StringBuilder sb )
        {
            sb.Append( "MethodRepresentationOperator(" );

            base.InnerToString( sb );

            sb.AppendFormat( " {0}", m_md );

            sb.Append( ")" );
        }

        public override string FormatOutput( IIntermediateRepresentationDumper dumper )
        {
            if(this.Arguments.Length == 0)
            {
                return dumper.FormatOutput( "{0} = descriptor for static method {1}", this.FirstResult, m_md );
            }
            else
            {
                return dumper.FormatOutput( "{0} = descriptor for method {1} on {2}", this.FirstResult, m_md, this.FirstArgument );
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package aci

import (
	"archive/tar"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	specaci "github.com/appc/spec/aci"
	"github.com/appc/spec/schema"
)

var (
	// ErrChmod - Error message for error changing file permission
	ErrChmod = errors.New("Error changing file permissions")
	// ErrCopyingFile - Error message for error copying file
	ErrCopyingFile = errors.New("Error copying file")
	// ErrCreatingFile - Error message for error creating file
	ErrCreatingFile = errors.New("Error creating file")
	// ErrMkdirAll - Error message for error making directory
	ErrMkdirAll = errors.New("Error making directory")
	// ErrNext - Error message for error interating through tar file
	ErrNext = errors.New("Error iterating through tar file")
	// ErrUntar - Error message for error untarring file
	ErrUntar = errors.New("Error untarring file")
)

// Manifest returns the ImageManifest inside the ACI file
func Manifest(f io.ReadSeeker) (*schema.ImageManifest, error) {
	m, err := specaci.ManifestFromImage(f)
	if err != nil {
		return nil, err
	}
	return m, nil
}

// Extract expands the ACI file to a temporary directory, returning
// the directory path where the ACI was expanded or an error
func Extract(f io.ReadSeeker) (string, error) {
	fileMode := os.FileMode(0755)

	tr, err := specaci.NewCompressedTarReader(f)
	if err != nil {
		return "", err
	}
	defer tr.Close()

	// Extract archive to temporary directory
	dir, err := ioutil.TempDir("", "")
	if err != nil {
		return "", err
	}
	for {
		hdr, err := tr.Reader.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return "", fmt.Errorf("%v\n%v", ErrNext, err)
		}
		file := filepath.Join(dir, hdr.Name)

		switch hdr.Typeflag {
		case tar.TypeReg:
			w, err := os.Create(file)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrCreatingFile, file, err)
			}
			defer w.Close()
			_, err = io.Copy(w, tr)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrCopyingFile, file, err)
			}
			err = os.Chmod(file, fileMode)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrChmod, file, err)
			}
		case tar.TypeDir:
			err = os.MkdirAll(file, fileMode)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrMkdirAll, file, err)
			}
		default:
			return "", fmt.Errorf("%v: %v", ErrUntar, hdr.Name)
		}
	}
	return dir, nil
}

// Validate makes sure the archive is valid. Otherwise,
// an error is returned
func Validate(f io.ReadSeeker) error {
	tr, err := specaci.NewCompressedTarReader(f)
	defer tr.Close()
	if err != nil {
		return err
	}

	if err := specaci.ValidateArchive(tr.Reader); err != nil {
		return err
	}
	return nil
}


text:
QUnit.module('JSHint | helpers/resolver.js');
QUnit.test('should pass jshint', function(assert) {
  assert.expect(1);
  assert.ok(true, 'helpers/resolver.js should pass jshint.');
});


text:
<?php

namespace IU\PHPCap;

use PHPUnit\Framework\TestCase;

use IU\PHPCap\RedCapProject;
use IU\PHPCap\PhpCapException;

/**
 * PHPUnit integration tests batch processing.
 */
class BatchesTest extends TestCase
{
    private static $config;
    private static $basicDemographyProject;
    private static $longitudinalDataProject;

    public static function setUpBeforeClass()
    {
        self::$config = parse_ini_file(__DIR__.'/../config.ini');
        self::$basicDemographyProject = new RedCapProject(
            self::$config['api.url'],
            self::$config['basic.demography.api.token']
        );
        self::$longitudinalDataProject = new RedCapProject(
            self::$config['api.url'],
            self::$config['longitudinal.data.api.token']
        );
    }

    public function testRecordIdBatches()
    {
        $expectedResult = self::$longitudinalDataProject->exportRecords($format = 'csv');

        # 100 records, so a batch size of 20 should return 5 batches
        $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(20);
        $this->assertEquals(5, count($recordIdBatches), '20 batch size test');

        $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(15);
        $this->assertEquals(7, count($recordIdBatches), '15 batch size test');
        $this->assertEquals(10, count($recordIdBatches[6]), '15 batch size last batch test');
    }

    public function testExportWithBatches()
    {
        $expectedResult = self::$longitudinalDataProject->exportRecords($format = 'csv');

        $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(10);

        $result = '';
        $isFirst = true;
        foreach ($recordIdBatches as $recordIdBatch) {
            $records = self::$longitudinalDataProject->exportRecordsAp(
                ['format' => 'csv', 'recordIds' => $recordIdBatch]
            );

            if ($isFirst) {
                $result .= $records;
                $isFirst = false;
            } else {
                # delete off the header line for all except
                # the first batch.
                $result .= substr($records, strpos($records, "\n") + 1);
            }
        }
        $this->assertEquals($expectedResult, $result, 'Batch result check.');
    }

    public function testExportWithBatchesWithFilterLogic()
    {
        $expectedResult = self::$longitudinalDataProject->exportRecordsAp(
            ['format' => 'csv', 'filterLogic' => '[age] >= 60']
        );

        $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(10, '[age] >= 60');

        $result = '';
        $isFirst = true;
        foreach ($recordIdBatches as $recordIdBatch) {
            # Need to repeat filterLogic, because otherwise all records for
            # people with age >= 60 will be returned, instead of all
            # records with age (defined and) >= 60 being returned
            $records = self::$longitudinalDataProject->exportRecordsAp(
                ['format' => 'csv', 'recordIds' => $recordIdBatch, 'filterLogic' => '[age] >= 60']
            );

            if ($isFirst) {
                $result .= $records;
                $isFirst = false;
            } else {
                # delete off the header line for all except
                # the first batch.
                $result .= substr($records, strpos($records, "\n") + 1);
            }
        }

        $this->assertEquals($expectedResult, $result, 'Batch result check.');
    }

    public function testNullBatches()
    {
        $caughtException = false;
        try {
            $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(null);
        } catch (PhpCapException $exception) {
            $caughtException = true;
            $code = $exception->getCode();
            $this->assertEquals(ErrorHandlerInterface::INVALID_ARGUMENT, $code, 'Exception code check.');
        }

        $this->assertTrue($caughtException, 'Exception caught check.');
    }

    public function testNonIntegerBatches()
    {
        $caughtException = false;
        try {
            $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches("two");
        } catch (PhpCapException $exception) {
            $caughtException = true;
            $code = $exception->getCode();
            $this->assertEquals(ErrorHandlerInterface::INVALID_ARGUMENT, $code, 'Exception code check.');
        }

        $this->assertTrue($caughtException, 'Exception caught check.');
    }

    public function testZeroBatches()
    {
        $caughtException = false;
        try {
            $recordIdBatches = self::$longitudinalDataProject->getRecordIdBatches(0);
        } catch (PhpCapException $exception) {
            $caughtException = true;
            $code = $exception->getCode();
            $this->assertEquals(ErrorHandlerInterface::INVALID_ARGUMENT, $code, 'Exception code check.');
        }

        $this->assertTrue($caughtException, 'Exception caught check.');
    }
}


text:
package org.chtijbug.drools.platform.persistence;

import org.chtijbug.drools.platform.persistence.pojo.PlatformRuntimeFilter;
import org.chtijbug.drools.platform.persistence.pojo.RuleFlowExecutionRecord;
import org.chtijbug.drools.platform.persistence.pojo.SessionExecutionRecord;

import java.util.List;

public interface PlatformRuntimeInstanceCustomRepository {
    List<SessionExecutionRecord> findAllSessionExecutionByFilter(PlatformRuntimeFilter filter);

    Integer countAllPlatformRuntimeInstanceByFilter(PlatformRuntimeFilter filter);

    List<Long> findAllRuleFlowGroupRecordId(long sessionDBid);

    RuleFlowExecutionRecord findRuleFlowGroupRecordById(long ruleFlowgoudid);
}


text:
#include "mitkMAPRegistrationWrapperObjectFactory.h"

#include <mitkProperties.h>
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>

#include "mitkRegistrationWrapperMapper2D.h"
#include "mitkRegistrationWrapperMapper3D.h"
#include "mitkMAPRegistrationWrapper.h"

typedef std::multimap<std::string, std::string> MultimapType;

mitk::MAPRegistrationWrapperObjectFactory::MAPRegistrationWrapperObjectFactory()
: CoreObjectFactoryBase()
{
  static bool alreadyDone = false;
  if (!alreadyDone)
  {
    MITK_INFO << "MAPRegistrationWrapperObjectFactory c'tor" << std::endl;

    alreadyDone = true;
  }

}

mitk::MAPRegistrationWrapperObjectFactory::~MAPRegistrationWrapperObjectFactory()
{
}

mitk::Mapper::Pointer
mitk::MAPRegistrationWrapperObjectFactory::
CreateMapper(mitk::DataNode* node, MapperSlotId slotId)
{
    mitk::Mapper::Pointer newMapper=NULL;

    if ( slotId == mitk::BaseRenderer::Standard2D )
    {
        std::string classname("MAPRegistrationWrapper");
        if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
        {
          newMapper = mitk::MITKRegistrationWrapperMapper2D::New();
          newMapper->SetDataNode(node);
        }
    }
    else if ( slotId == mitk::BaseRenderer::Standard3D )
    {
      std::string classname("MAPRegistrationWrapper");
      if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
      {
        newMapper = mitk::MITKRegistrationWrapperMapper3D::New();
        newMapper->SetDataNode(node);
      }
    }

    return newMapper;
};

void mitk::MAPRegistrationWrapperObjectFactory::SetDefaultProperties(mitk::DataNode* node)
{
  if(node==NULL)
    return;

  mitk::DataNode::Pointer nodePointer = node;

  if(node->GetData() ==NULL)
    return;

  if( dynamic_cast<mitk::MAPRegistrationWrapper*>(node->GetData())!=NULL )
  {
    mitk::MITKRegistrationWrapperMapperBase::SetDefaultProperties(node);
  }
}

const char* mitk::MAPRegistrationWrapperObjectFactory::GetFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);
  return fileExtension.c_str();
};

mitk::CoreObjectFactoryBase::MultimapType mitk::MAPRegistrationWrapperObjectFactory::GetFileExtensionsMap()
{
  return m_FileExtensionsMap;
}

const char* mitk::MAPRegistrationWrapperObjectFactory::GetSaveFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);
  return fileExtension.c_str();
}

mitk::CoreObjectFactoryBase::MultimapType mitk::MAPRegistrationWrapperObjectFactory::GetSaveFileExtensionsMap()
{
  return m_SaveFileExtensionsMap;
}

struct RegisterMAPRegistrationWrapperObjectFactoryHelper{
  RegisterMAPRegistrationWrapperObjectFactoryHelper()
    : m_Factory( mitk::MAPRegistrationWrapperObjectFactory::New() )
  {
    mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory );
  }

  ~RegisterMAPRegistrationWrapperObjectFactoryHelper()
  {
    mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory );
  }

  mitk::MAPRegistrationWrapperObjectFactory::Pointer m_Factory;
};

static RegisterMAPRegistrationWrapperObjectFactoryHelper registerMITKRegistrationWrapperIOFactoryHelper;


text:
//*****************************************************************************
//
// usci_b_spi.h - Driver for the USCI_B_SPI Module.
//
//*****************************************************************************

#ifndef __MSP430WARE_USCI_B_SPI_H__
#define __MSP430WARE_USCI_B_SPI_H__

#include "inc/hw_memmap.h"

#ifdef __MSP430_HAS_USCI_Bx__

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef __cplusplus
extern "C"
{
#endif

//******************************************************************************
//
// The following is a struct that is passed to USCI_B_SPI_initMaster()
//
//******************************************************************************
typedef struct USCI_B_SPI_initMasterParam {
        uint8_t selectClockSource;
        uint32_t clockSourceFrequency;
        uint32_t desiredSpiClock;
        uint8_t msbFirst;
        uint8_t clockPhase;
        uint8_t clockPolarity;
} USCI_B_SPI_initMasterParam;

//******************************************************************************
//
// The following is a struct that is passed to USCI_B_SPI_changeMasterParam()
//
//******************************************************************************
typedef struct USCI_B_SPI_ChangeMasterClockParam {
        uint32_t clockSourceFrequency;
        uint32_t desiredSpiClock;
} USCI_B_SPI_changeMasterClockParam;

//*****************************************************************************
//
// The following are values that can be passed to the clockPhase parameter for
// functions: USCI_B_SPI_masterInit(), USCI_B_SPI_slaveInit(), and
// USCI_B_SPI_changeClockPhasePolarity().
//
//*****************************************************************************
#define USCI_B_SPI_PHASE_DATA_CHANGED_ONFIRST_CAPTURED_ON_NEXT             0x00
#define USCI_B_SPI_PHASE_DATA_CAPTURED_ONFIRST_CHANGED_ON_NEXT           UCCKPH

//*****************************************************************************
//
// The following are values that can be passed to the msbFirst parameter for
// functions: USCI_B_SPI_masterInit(), and USCI_B_SPI_slaveInit().
//
//*****************************************************************************
#define USCI_B_SPI_MSB_FIRST                                              UCMSB
#define USCI_B_SPI_LSB_FIRST                                               0x00

//*****************************************************************************
//
// The following are values that can be passed to the clockPolarity parameter
// for functions: USCI_B_SPI_masterInit(), USCI_B_SPI_slaveInit(), and
// USCI_B_SPI_changeClockPhasePolarity().
//
//*****************************************************************************
#define USCI_B_SPI_CLOCKPOLARITY_INACTIVITY_HIGH                         UCCKPL
#define USCI_B_SPI_CLOCKPOLARITY_INACTIVITY_LOW                            0x00

//*****************************************************************************
//
// The following are values that can be passed to the selectClockSource
// parameter for functions: USCI_B_SPI_masterInit().
//
//*****************************************************************************
#define USCI_B_SPI_CLOCKSOURCE_ACLK                                UCSSEL__ACLK
#define USCI_B_SPI_CLOCKSOURCE_SMCLK                              UCSSEL__SMCLK

//*****************************************************************************
//
// The following are values that can be passed to the mask parameter for
// functions: USCI_B_SPI_enableInterrupt(), USCI_B_SPI_disableInterrupt(),
// USCI_B_SPI_getInterruptStatus(), and USCI_B_SPI_clearInterruptFlag() as well
// as returned by the USCI_B_SPI_getInterruptStatus() function.
//
//*****************************************************************************
#define USCI_B_SPI_TRANSMIT_INTERRUPT                                    UCTXIE
#define USCI_B_SPI_RECEIVE_INTERRUPT                                     UCRXIE

//*****************************************************************************
//
// The following are values that can be passed toThe following are values that
// can be returned by the USCI_B_SPI_isBusy() function.
//
//*****************************************************************************
#define USCI_B_SPI_BUSY                                                  UCBUSY
#define USCI_B_SPI_NOT_BUSY                                                0x00

//*****************************************************************************
//
// Prototypes for the APIs.
//
//*****************************************************************************
extern bool USCI_B_SPI_initMaster(uint16_t baseAddress,
                                  USCI_B_SPI_initMasterParam *param);

extern void USCI_B_SPI_changeMasterClock(uint16_t baseAddress,
                                         USCI_B_SPI_changeMasterClockParam *param);

extern bool USCI_B_SPI_slaveInit(uint16_t baseAddress,
                                 uint8_t msbFirst,
                                 uint8_t clockPhase,
                                 uint8_t clockPolarity);

extern void USCI_B_SPI_changeClockPhasePolarity(uint16_t baseAddress,
                                                uint8_t clockPhase,
                                                uint8_t clockPolarity);

extern void USCI_B_SPI_transmitData(uint16_t baseAddress,
                                    uint8_t transmitData);

extern uint8_t USCI_B_SPI_receiveData(uint16_t baseAddress);

extern void USCI_B_SPI_enableInterrupt(uint16_t baseAddress,
                                       uint8_t mask);

extern void USCI_B_SPI_disableInterrupt(uint16_t baseAddress,
                                        uint8_t mask);

extern uint8_t USCI_B_SPI_getInterruptStatus(uint16_t baseAddress,
                                             uint8_t mask);

extern void USCI_B_SPI_clearInterruptFlag(uint16_t baseAddress,
                                          uint8_t mask);

extern void USCI_B_SPI_enable(uint16_t baseAddress);

extern void USCI_B_SPI_disable(uint16_t baseAddress);

extern uint32_t USCI_B_SPI_getReceiveBufferAddressForDMA(uint16_t baseAddress);

extern uint32_t USCI_B_SPI_getTransmitBufferAddressForDMA(uint16_t baseAddress);

extern uint8_t USCI_B_SPI_isBusy(uint16_t baseAddress);

//*****************************************************************************
//
// The following are deprecated APIs.
//
//*****************************************************************************
extern bool USCI_B_SPI_masterInit(uint16_t baseAddress,
                                  uint8_t selectClockSource,
                                  uint32_t clockSourceFrequency,
                                  uint32_t desiredSpiClock,
                                  uint8_t msbFirst,
                                  uint8_t clockPhase,
                                  uint8_t clockPolarity);

extern void USCI_B_SPI_masterChangeClock(uint16_t baseAddress,
                                         uint32_t clockSourceFrequency,
                                         uint32_t desiredSpiClock);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif
#endif // __MSP430WARE_USCI_B_SPI_H__


text:
span.numfiles
{
    font-style: italic;

    position: absolute;
    right: 20px;

    color: #a0a0a0;
}

div.tree
{
    background-color: #fff !important;
}

div.treeView-header
{
    margin-bottom: 5px;
    padding: 5px;

    border-bottom: thin solid #f0f0f0;
    background-color: #f5f5f5;
}

div.treeView-header > a
{
    margin-left: 15px;
    padding: 3px 5px 3px 5px;

    border: thin solid #c0c0c0;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
    background-color: #d7d7d7;
}

ins.jstree_icon
{
    background-image: url('/content/data/icons/png/theme_dark.png') !important;
    background-repeat: no-repeat !important;
}

ins.jstree_icon.home
{
    background-position: -420px 0 !important;
}

ins.jstree_icon.admin
{
    background-position: -440px 0 !important;
}

ins.jstree_icon.reg
{
    background-position: -40px 0 !important;
}

/** PDF Files */
ins.jstree_icon.file1
{
    background-position: -60px -2px !important;
}

/** YOUTUBE Files */
ins.jstree_icon.file2
{
    background-position: -500px -3px !important;
}

/** HTML5VIDEO Files */
ins.jstree_icon.file3
{
    background-position: -500px -3px !important;
}

/** HTML5 Files */
ins.jstree_icon.file4
{
    background-position: -480px -2px !important;
}


text:
import { VNode } from "preact"
import { html } from "htm/preact"

export function noPaddedStory(content: VNode): VNode {
    return html`
        <style>
            .sb-main-padded {
                padding: 0 !important;
            }
        </style>
        ${content}
    `
}


text:
<?php

/**
 * Decode Exception
 *
 * @package     Nails
 * @subpackage  common
 * @category    Exceptions
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Common\Exception\Encrypt;

use Nails\Common\Exception\NailsException;

class DecodeException extends NailsException
{
}


text:
INPUT_ZIP=$1
SOURCE_STR=$2
TARGET_STR=$3
shift; shift; shift;

if [[ ! "$INPUT_ZIP" || ! -f "$INPUT_ZIP" || ! "$SOURCE_STR" || ! "$TARGET_STR" || $# -ne 0 ]]; then
    >&2 echo "usage: zip-tr.sh INPUT_ZIP SOURCE_STR TARGET_STR"
    exit 2
fi;

# Create a temporary directory and ensure cleanup.
# See https://stackoverflow.com/a/34676160/410889

# the temp directory used, within $DIR
WORK_DIR=`mktemp -d`

# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
  >&2 echo "Could not create temp dir"
  exit 1
fi

# deletes the temp directory
function cleanup {
  #rm -rf "$WORK_DIR"
  >&2 echo "Deleted temp working directory $WORK_DIR"
}

# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT

unzip -qq "$INPUT_ZIP" -d "${WORK_DIR}"
find "${WORK_DIR}" -type f -print0 | xargs -0 sed -i -e "s/${SOURCE_STR//\//\\/}/${TARGET_STR//\//\\/}/g"
cd "${WORK_DIR}"
zip -r - .


text:
import React from 'react'
import Article from '../app/article'
import Listing from '../app/listing'

import progJS from '../build/prog/quine/quine'
import progPython from '../build/prog/quine/quine_py'

export const pagePath = 'quine'
export const pageTitle = 'Python and JavaScript quine'

export default class extends React.Component {
    render() {
        return (

{pageTitle}

A program producing its complete source code as its only output.

Python

A Python quine using repr for escaping.

                <Listing program={progPython} />

JavaScript

Same thing in JavaScript via JSON formatting.

                <Listing program={progJS} />

        )
    }
}


text:
{% extends 'utilities/bulk_edit_form.html' %}
{% load form_helpers %}

{% block title %}Aggregate Bulk Edit{% endblock %}

{% block selected_objects_table %}

        Aggregate
        RIR
        Date Added
        Description

    {% for aggregate in selected_objects %}

            {{ aggregate }}
            {{ aggregate.rir }}
            {{ aggregate.date_added }}
            {{ aggregate.description }}

    {% endfor %}
{% endblock %}


text:
var users = [
  { 'mention_name': 'fecker', 'name': 'Feckin eejit', 'id': 1222 },
  { 'mention_name': 'buster', 'name': 'Buster Benign', 'id': 1223 },
  { 'mention_name': 'mary', 'name': 'Mary Magdeline', 'id': 1224 },
  { 'mention_name': 'jesus', 'name': 'Jesus Christ', 'id': 1225 },
  { 'mention_name': 'georgew', 'name': 'George W Busch', 'id': 1226 },
  { 'mention_name': 'tbabbot', 'name': 'Tony Babbot', 'id': 1227 }
],
_ = require('lodash');
require('regexp-escape');

module.exports = {
  getDummyApi: function() {
    return {
      roomClient: {
        sendNotification: null,
        getRoomMembers: function* () {
          return yield {
            items: users
          };
        }
      },
      room: {
        'id': 'test-room',
        'name': 'Unit Test Room'
      }
    };
  },
  getUserNotInGame: function(gameState) {
    var players = _.pluck(gameState.currentPlayers, 'id'),
        availablePlayers = _.pluck(users, 'id');

    availablePlayers = _.filter(availablePlayers, function(ap) {
      return !_.contains(players, ap);
    });

    if (availablePlayers.length === 0) {
      throw new Error('Unable to find a player not in the current game.');
    }

    return _.where(users, { id: _.sample(availablePlayers, 1)[0]})[0];
  },
  getUserInGame: function(gameState) {
    var players = _.pluck(gameState.currentPlayers, 'id'),
        availablePlayers = _.pluck(users, 'id');

    availablePlayers = _.filter(availablePlayers, function(ap) {
      return _.contains(players, ap);
    });

    if (availablePlayers.length === 0) {
      throw new Error('Unable to find a player in the current game.');
    }

    return _.where(users, { id: _.sample(availablePlayers, 1)[0]})[0];
  },
  regexifyMessage: function(msg) {
    return RegExp.escape(msg).replace(/%[sd]/g,'[^\\s]+');
  }
};


text:
package krasa.wicket;

import krasa.wicket.pages.TestPage;

import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class WicketApplication extends WebApplication {

	@Override
	public Class<TestPage> getHomePage() {
		return TestPage.class;
	}

	@Override
	public void init() {
		super.init();
		getComponentInstantiationListeners().add(new SpringComponentInjector(this));
	}

	public ApplicationContext getSpringContext() {
		return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	}

	public static WicketApplication getWicketApplication() {
		return ((WicketApplication) get());
	}

}


text:
[![CircleCI](https://circleci.com/gh/spaceapi-community/spaceapi-server-rs/tree/master.svg?style=shield)](https://circleci.com/gh/spaceapi-community/spaceapi-server-rs/tree/master)
[![Crates.io Version](https://img.shields.io/crates/v/spaceapi.svg)](https://crates.io/crates/spaceapi)
[![Crates.io Downloads](https://img.shields.io/crates/d/spaceapi.svg)](https://crates.io/crates/spaceapi)

This is an implementation of the [SpaceAPI](https://spaceapi.io/) v0.13 and v14
in Rust. It contains both the type definitions as well as tools for
serialization and deserialization to/from JSON using Serde.

- Crate Documentation: https://docs.rs/spaceapi/
- SpaceAPI Documentation: https://spaceapi.io/pages/docs.html

This library requires Rust 1.31.0 or newer.

## Usage

Add `spaceapi` to your `Cargo.toml`:

    [dependencies]
    spaceapi = "^0.8.1"

## Docs

You can build docs with `make docs`. Find them in the `target/doc/` directory.

## License

Licensed under either of

 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.


text:
package org.rs2server.cache;

import java.nio.ByteBuffer;

/**
 * Represents a single cache file.
 * @author Graham Edgecombe
 *
 */
public class CacheFile {

	/**
	 * The cache id.
	 */
	private int cache;

	/**
	 * The file id.
	 */
	private int file;

	/**
	 * The file data.
	 */
	private ByteBuffer data;

	/**
	 * Creates a cache file.
	 * @param cache The cache id.
	 * @param file The file id.
	 * @param data The file data.
	 */
	public CacheFile(int cache, int file, ByteBuffer data) {
		this.cache = cache;
		this.file = file;
		this.data = data;
	}

	/**
	 * Gets the cache id.
	 * @return The cache id.
	 */
	public int getCache() {
		return cache;
	}

	/**
	 * Gets the file id.
	 * @return The file id.
	 */
	public int getFile() {
		return file;
	}

	/**
	 * Gets the buffer.
	 * @return The buffer.
	 */
	public ByteBuffer getBuffer() {
		return data;
	}

	/**
	 * Gets the buffer as a byte array.
	 * @return The byte array.
	 */
	public byte[] getBytes() {
		byte[] bytes = new byte[data.limit()];
		data.position(0);
		data.get(bytes);
		return bytes;
	}

}


text:
package api

import (
	"github.com/jsix/gof/web"
	"go2o/src/core/domain/interface/ad"
	"go2o/src/core/infrastructure/format"
	"go2o/src/core/service/dps"
	"strings"
)

type partnerC struct {
	*BaseC
}

func (this *partnerC) Index(ctx *web.Context) {
	ctx.Response.Write([]byte("it's working!"))
}

// 获取广告数据
func (this *partnerC) Get_ad(ctx *web.Context) {
	partnerId := this.GetPartnerId(ctx)
	adName := ctx.Request.FormValue("ad_name")
	adv, data := dps.AdvertisementService.GetAdvertisementAndDataByName(partnerId, adName)
	if data != nil {
		// 图片广告
		if adv.Type == ad.TypeGallery {
			gv := data.(ad.ValueGallery)
			if gv != nil {
				for _, v := range gv {
					if strings.Index(v.ImageUrl, "http://") == -1 {
						v.ImageUrl = format.GetGoodsImageUrl(v.ImageUrl)
					}
				}
			}
			ctx.Response.JsonOutput(gv)
			return
		}
		ctx.Response.JsonOutput(data)
	} else {
		this.ErrorOutput(ctx, "没有广告数据")
	}
}


text:
(function() {
	'use strict';

	angular
		.module('app.dashboard')
		.controller('DashboardUsersController', DashboardUsersController);

	DashboardUsersController.$inject = ['User', 'ToastrNotify', 'EVENTS', '$rootRouter', '$scope'];

	function DashboardUsersController(User, ToastrNotify, EVENTS, $rootRouter, $scope) {
		var vm = this;

		vm.$routerOnActivate = onRouterActivated;
		vm.users = [];

		function onRouterActivated() {
			User.query({minified: false}).$promise
				.then(onUsersLoadingSuccess, onUsersLoadingFailed);

			function onUsersLoadingSuccess(data) {
				vm.users = data;
				vm.users.forEach(function(u) {
					var authoritiesString = "";
					u.authorities.forEach(function(a, index) {
						if (index === u.authorities.length - 1) {
							authoritiesString += a.name;
						} else {
							authoritiesString += a.name + ", ";
						}
					});
					u.authoritiesString = authoritiesString;
				});
			}

			function onUsersLoadingFailed(response) {
				ToastrNotify.error("Loading the users data failed. Please relaod the page", "Loading Failed");
			}
		}

		var logoutWatch = $scope.$on(EVENTS.logoutSuccess, function(event, date) {
			$rootRouter.navigate(['Book']);
		});

		$scope.$on('$destroy', function() {
			logoutWatch();
		});
	}
})();


text:
package com.github.bingoohuang.cqler.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data @AllArgsConstructor @NoArgsConstructor
public class Keyspace {
    String keyspaceName;
}


text:
require "monarch_migration/version"
require "thor"
require "time"
require "json"

# Convert camel case into snake case
class String
  def snakecase
    self.gsub(/::/, '/').
      gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
      gsub(/([a-z\d])([A-Z])/,'\1_\2').
      tr("-", "_").
      downcase
  end
end

module MonarchMigration
  class CLI < Thor
    desc "generate actionClassName column...", "generate migration file."
    def generate(action_and_class_name, *columns)
      unixtime = Time.now.to_i
      filename = "#{unixtime}_#{action_and_class_name.snakecase}.json"

      matches = action_and_class_name.match(%r{(.+?)Column(.+)})
      action = matches[1]
      class_name = matches[2]

      case action
      when "add" then
        up = get_up_in_add_column(class_name, columns)
      when "remove" then
        up = get_up_in_remove_column(class_name, columns)
      end

      json_object = {}
      json_object["up"] = up
      json_generate(filename, json_object)
    end

    private
    def get_up_in_add_column(class_name, columns)
      up = []
      columns.each{|column|
        u = "addcolumn #{class_name} #{column}"
        up.push(u)
      }
      return up
    end

    def get_up_in_remove_column(class_name, columns)
      up = []
      columns.each{|column|
        u = "removecolumn #{class_name} #{column}"
        up.push(u)
      }
      return up
    end

    def json_generate(filename, object)
      open(filename, "w") do |io|
        io.write(object.to_json)
      end
    end
  end
end


text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#ifndef DTKABSTRACTDATAREADER_H
#define DTKABSTRACTDATAREADER_H

#include "dtkAbstractObject.h"

class dtkAbstractData;
class dtkAbstractDataReaderPrivate;

// /////////////////////////////////////////////////////////////////
// dtkAbstractDataReader interface
// /////////////////////////////////////////////////////////////////

class DTKCORESUPPORT_EXPORT dtkAbstractDataReader : public dtkAbstractObject
{
    Q_OBJECT

public:
             dtkAbstractDataReader(void);
             dtkAbstractDataReader(const dtkAbstractDataReader& other);
    virtual ~dtkAbstractDataReader(void);

public:
    virtual QString description(void) const = 0;
    virtual QStringList handled(void) const = 0;

    bool enabled(void) const;
    void enable(void);
    void disable(void);

    dtkAbstractData *data(void) const;

    virtual void setData(dtkAbstractData *data);

signals:
    void started(const QString& message);
    void progressed(int step);
    void finished(void);

public slots:
    virtual bool canRead(const QString& file);
    virtual bool canRead(const QStringList& files);

    virtual bool read(const QString& file);
    virtual bool read(const QStringList& files);

    virtual bool readInformation(const QString& path);
    virtual bool readInformation(const QStringList& paths);

    virtual void setProgress(int value);

protected:
    const QString&     file(void)  const;
    const QStringList& files(void) const;

private:
    DTK_DECLARE_PRIVATE(dtkAbstractDataReader);
};

#endif


text:
This sample demonstrates how to run multiple geoprocessing tools in the background of an ArcGIS Engine application. It illustrates how the result of one tool execution can then be used as an input to another tool. It also shows how to provide the user with feedback while the tools are executing by listening to events fired by the geoprocessor.

```
Language:              C#, VB
Subject:               Geoprocessing
Organization:          Esri, http://www.esri.com
Date:                  10/17/2019
ArcObjects SDK:        10.8
Visual Studio:         2017, 2019
.NET Target Framework: 4.5
```

### Resources

* [ArcObjects .NET API Reference online](http://desktop.arcgis.com/en/arcobjects/latest/net/webframe.htm)
* [Sample Data Download](../../releases)
* [What's new](http://desktop.arcgis.com/en/arcobjects/latest/net/webframe.htm#91cabc68-2271-400a-8ff9-c7fb25108546.htm)
* [Download the ArcObjects SDK for .Net from MyEsri.com](https://my.esri.com/)

### Usage
1. Start Visual Studio, open the solution file, and compile the project.
1. In the Engine application that opens, select some cities using the Select tool or accept the preselected city of Los Angeles.
1. Specify a buffer distance or accept the default of 30 miles.
1. Click the Run button. The geoprocessing analysis starts. Progress is reported in the ListView control, and the final result is added to the map.
1. While the tools are executing, check that the application is still responsive by navigating around the map.

#### Additional information

Multiple, unrelated geoprocessing tools can be executed by calling the ExecuteAsync method for each tool from within the same method. For example, you can buffer a selected city by a distance to produce a result, then union the Highways and Zip Codes layer to produce another result. The output from the first tool does not affect the inputs to the second tool.

Another common scenario is where the output from one tool becomes an input parameter to another tool. In this sample, selected cities are buffered to output a result that is then used to clip features in the Zip Codes layer. Calling the ExecuteAsync method from within the same method does not work in this case since all input parameters must exist prior to tool execution. This sample works around that restriction.

Each tool is added to a Queue object. The first tool is de-queued and called for execution from within the btnRunGP_Click event handler. The second tool is then called for execution from within the ToolExecuted event handler but only if the first has completed successfully. This approach is scalable, as any number of tools can be added to the queue.

---------------------------------

#### Licensing
| Development licensing | Deployment licensing |
| ------------- | ------------- |
| Engine Developer Kit | Engine |
|  | ArcGIS Desktop Basic |
|  | ArcGIS Desktop Standard |
|  | ArcGIS Desktop Advanced |


text:
/* eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }] */

import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';

class Tables extends React.Component {

  /**
   * Renders the list of tables
   *
   * @returns {*}
   */
  renderTables() {
    if (!this.props.tables) {
      return null;
    }

    return this.props.tables.map((table) => {
      const name = table.TableName;
      const id = table.TableArn;

      const attributes = {};
      for (let i = 0; i < table.AttributeDefinitions.length; i++) {
        const attribute = table.AttributeDefinitions[i];
        attributes[attribute.AttributeName] = attribute;
      }

      const types = {
        S: 'String',
        N: 'Number',
      };

      const hk = table.KeySchema[0].AttributeName;
      const hkType = types[attributes[hk].AttributeType];

      const rk = table.KeySchema.length === 2 ? table.KeySchema[1].AttributeName : false;
      const rkType = rk ? types[attributes[rk].AttributeType] : false;

      const indices = table.GlobalSecondaryIndexes ? table.GlobalSecondaryIndexes.length : 0;
      const itemCount = table.ItemCount;

      return (

            <input type="radio" checked={this.props.table && table.TableName === this.props.table.TableName} onChange={() => {}} />

            <Link to={`/tables/${name}`}>{name}</Link>

          {hk} ({hkType})
          {rk || '-'} {rkType ? ` (${rkType})` : false}
          {itemCount}
          {indices}

      );
    });
  }

  render() {
    return (

              Name
              Partition Key
              Sort Key
              Item Count
              Indexes

            {this.renderTables()}

    );
  }
}

Tables.propTypes = {
  tables: PropTypes.arrayOf(
    PropTypes.shape({
      map: PropTypes.func,
      AttributeDefinitions: PropTypes.arrayOf(PropTypes.object),
      ItemCount: PropTypes.number,
      KeySchema: PropTypes.arrayOf(PropTypes.object),
      TableArn: PropTypes.string,
      TableName: PropTypes.string,
      TableSizeBytes: PropTypes.number,
    }),
  ),
  table: PropTypes.shape({
    map: PropTypes.func,
    AttributeDefinitions: PropTypes.arrayOf(PropTypes.object),
    ItemCount: PropTypes.number,
    KeySchema: PropTypes.arrayOf(PropTypes.object),
    TableArn: PropTypes.string,
    TableName: PropTypes.string,
    TableSizeBytes: PropTypes.number,
  }),
};

Tables.defaultProps = {
  tables: false,
  table: null,
};

export default Tables;


text:
class GetTopSitesFunction : public AsyncExtensionFunction {
 public:
  GetTopSitesFunction();
  virtual ~GetTopSitesFunction();
  virtual bool RunImpl() OVERRIDE;
  DECLARE_EXTENSION_FUNCTION_NAME("experimental.topSites.get")

 private:
  void OnMostVisitedURLsAvailable(
      const history::MostVisitedURLList& data);

  CancelableRequestConsumer topsites_consumer_;
};

#endif  // CHROME_BROWSER_HISTORY_TOP_SITES_EXTENSION_API_H_


text:
name: Missing glossary entry
about: Suggest a term to be added to our glossary

---

#### Suggested term
(insert here)

#### Suggested definition
(insert here)


text:
package refman;

import com.hazelcast.jet.core.AbstractProcessor;
import com.hazelcast.jet.Traverser;
import com.hazelcast.jet.Traversers;

import java.util.stream.IntStream;

class GenerateNumbersP extends AbstractProcessor {

    private final Traverser<Integer> traverser;

    GenerateNumbersP(int upperBound) {
        traverser = Traversers.traverseStream(IntStream.range(0, upperBound).boxed());
    }

    GenerateNumbersP(int upperBound, int processorCount, int processorIndex) {
        traverser = Traversers.traverseStream(
                IntStream.range(0, upperBound)
                         .filter(n -> n % processorCount == processorIndex)
                         .boxed());
    }

    @Override
    public boolean complete() {
        return emitFromTraverser(traverser);
    }
}


text:
title: Gravitar
---
# Gravitar

```{figure} ../../_static/videos/atari/gravitar.gif
:width: 120px
:name: Gravitar
```

This environment is part of the Atari environments. Please read that page first for general information.

|                   |                                     |
|-------------------|-------------------------------------|
| Action Space      | Discrete(18)                        |
| Observation Space | (210, 160, 3)                       |
| Observation High  | 255                                 |
| Observation Low   | 0                                   |
| Import            | `gymnasium.make("ALE/Gravitar-v5")` |

## Description
The player controls a small blue spacecraft. The game starts in a fictional solar system with several planets to explore. If the player moves his ship into a planet, he will be taken to a side-view landscape. Player has to destroy red bunkers [the AtariAge page](https://atariage.com/manual_html_page.php?SoftwareLabelID=223).

### Rewards
The exact reward dynamics depend on the environment and are usually documented in the game's manual. You can
find these manuals on [AtariAge](https://atariage.com/manual_html_page.php?SoftwareLabelID=223).

Atari environments are simulated via the Arcade Learning Environment (ALE) [[1]](#1).
### Action Space
The action space a subset of the following discrete set of legal actions:

| Num | Action        |
|-----|---------------|
| 0   | NOOP          |
| 1   | FIRE          |
| 2   | UP            |
| 3   | RIGHT         |
| 4   | LEFT          |
| 5   | DOWN          |
| 6   | UPRIGHT       |
| 7   | UPLEFT        |
| 8   | DOWNRIGHT     |
| 9   | DOWNLEFT      |
| 10  | UPFIRE        |
| 11  | RIGHTFIRE     |
| 12  | LEFTFIRE      |
| 13  | DOWNFIRE      |
| 14  | UPRIGHTFIRE   |
| 15  | UPLEFTFIRE    |
| 16  | DOWNRIGHTFIRE |
| 17  | DOWNLEFTFIRE  |

If you use v0 or v4 and the environment is initialized via `make`, the action space will usually be much smaller since most legal actions don't have
any effect. Thus, the enumeration of the actions will differ. The action space can be expanded to the full
legal space by passing the keyword argument `full_action_space=True` to `make`.

The reduced action space of an Atari environment may depend on the flavor of the game. You can specify the flavor by providing
the arguments `difficulty` and `mode` when constructing the environment. This documentation only provides details on the
action spaces of default flavors.
## Observations
By default, the environment returns the RGB image that is displayed to human players as an observation. However, it is
possible to observe
- The 128 Bytes of RAM of the console
- A grayscale image

instead. The respective observation spaces are
- `Box([0 ... 0], [255 ... 255], (128,), uint8)`
- `Box([[0 ... 0]
 ...
 [0  ... 0]], [[255 ... 255]
 ...
 [255  ... 255]], (250, 160), uint8)
`

respectively. The general article on Atari environments outlines different ways to instantiate corresponding environments
via `gymnasium.make`.
## Arguments

```
env = gymnasium.make("ALE/Gravitar-v5")
```

The various ways to configure the environment are described in detail in the article on Atari environments.

| Environment | Valid Modes   | Valid Difficulties | Default Mode |
|-------------|---------------|--------------------|--------------|
| Gravitar    | `[0, ..., 4]` | `[0]`              | `0`          |

You may use the suffix "-ram" to switch to the RAM observation space. In v0 and v4, the suffixes "Deterministic" and "NoFrameskip"
are available. These are no longer supported in v5. In order to obtain equivalent behavior, pass keyword arguments to `gymnasium.make` as outlined in
the general article on Atari environments.
The versions v0 and v4 are not contained in the "ALE" namespace. I.e. they are instantiated via `gymnasium.make("Gravitar-v0")`.

## Version History
A thorough discussion of the intricate differences between the versions and configurations can be found in the
general article on Atari environments.

| Version | `frameskip=` | `repeat_action_probability=` | `full_action_space=` |
|---------|--------------|------------------------------|----------------------|
| v0      | `(2, 5,)`    | `0.25`                       | `False`              |
| v4      | `(2, 5,)`    | `0.0`                        | `False`              |
| v5      | `5`          | `0.25`                       | `True`               |

> Version v5 follows the best practices outlined in [[2]](#2). Thus, it is recommended to transition to v5 and
> customize the environment using the arguments above, if necessary.


text:
package edu.harvard.we99.domain.results.analysis;

import edu.harvard.we99.domain.results.ResultStatus;
import edu.harvard.we99.domain.results.Sample;
import edu.harvard.we99.domain.results.WellResults;
import org.apache.commons.math3.stat.StatUtils;

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author alan orcharton
 *
 * Returns a list of compound WellResults normalized against positive and negative control wells.
 *
 */
public class NormalizeForPercentEffectFunction implements Function<List<WellResults>,List<WellResults>> {

    private final String label;
    private final Predicate<WellResults> positiveCtrlFilter;
    private final Predicate<WellResults> negativeCtrlFilter;
    private final Predicate<WellResults> compoundFilter;

    public NormalizeForPercentEffectFunction(
            String label,
            Predicate<WellResults> positiveCtrlFilter,
            Predicate<WellResults> negativeCtrlFilter,
            Predicate<WellResults>compoundFilter) {
        this.positiveCtrlFilter = positiveCtrlFilter;
        this.negativeCtrlFilter = negativeCtrlFilter;
        this.compoundFilter = compoundFilter;
        this.label = label;

    }

    //takes a list of well results gets the value and convert to a double[]
    private double[] getGroupResults(List<WellResults> group) {
        List<Double> collect = group.stream()
                .map(wr -> wr.getByLabel(label).getValue()).collect(Collectors.toList());
        double[] groupResults = new double[collect.size()];
        int i=0;
        for(Double d : collect) {
            groupResults[i++] = d;
        }
        return groupResults;
    }

    @Override
    public List<WellResults> apply(List<WellResults> wrList) {

        Predicate<WellResults> includedFilter = wellRes -> wellRes.getResultStatus() == ResultStatus.INCLUDED;

        Function<double[], Double> mean = StatUtils::mean;

        //filter positive controls
        List<WellResults> group1 = wrList.stream()
                .filter(positiveCtrlFilter.and(includedFilter))
                .collect(Collectors.toList());
        double[] group1Results = getGroupResults(group1);

        //mean of positive controls
        double positiveMean = mean.apply(group1Results);

        //filter negative controls
        List<WellResults> group2 = wrList.stream()
                .filter(negativeCtrlFilter.and(includedFilter))
                .collect(Collectors.toList());
        double[] group2Results = getGroupResults(group2);

        //mean of positive controls
        double negativeMean = mean.apply(group2Results);

        //filter compounds and map normalized values
        List<WellResults> normalizedCompounds = wrList.stream()
                                                .filter(compoundFilter)
                                                .map(wr -> {
                                                    Sample s = wr.getByLabel(label);
                                                    Double data = s.getValue();
                                                    Double normalized = 100 * (((data - negativeMean) / (positiveMean - negativeMean)));
                                                    s.setNormalized(normalized);
                                                    return wr;
                                                })
                                                .collect(Collectors.toList());

        return normalizedCompounds;
    }
}


text:
local function reducer(val1,val2)
	return val1 + val2
end

function sum_single_bin(stream,name)
	local function mapper(rec)
		return rec[name]
	end

	return stream : map(mapper) : reduce(reducer)
end


text:
<?php

namespace app\commands;

use yii\console\Controller;
use yii\base\Model;

use app\models\Engine;

use denebsoft\WebShopAPI\API;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class FindController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
    public function actionIndex($engine, $id_product)
    {
        echo $engine." ".$id_product."\n";

        $api = $this->createApi($engine);

        $info = $api->getProductByID($id_product);
        print_r($info['price']['price']);
        echo "\n";
        $price = $info['price']['price'];

        $price = preg_replace("/[^0-9,]/", "", $price);

        //$price = str_replace(' ', '', $price);
        //$price = str_replace(' ', '', $price);
        $price = str_replace(',', '.', $price);
        echo $price;
        echo "\n";

        echo "\n";

        echo "\n";

        echo "\n";

    }

    /**
     * @param unknown $engine
     * @throws \InvalidArgumentException
     * @return \denebsoft\WebShopAPI\API
     */
    private function createApi($engine)
    {
        $engineModel = Engine::findOne(['name' => $engine, 'status' => 1]);

        if (!$engineModel) {
            throw new \InvalidArgumentException('Incorrect engine: '.$engine);
        }

        return new API($engineModel->name, $engineModel->base_url, $engineModel->search_url, $engineModel->product_url);
    }
}


text:
define(function(require, exports, module) {
    var kity = require('./kity');
    var utils = require('./utils');

    var _initHooks = [];

    var Minder = kity.createClass('Minder', {
        constructor: function(options) {
            this._options = utils.extend({}, options);

            var initHooks = _initHooks.slice();

            var initHook;
            while (initHooks.length) {
                initHook = initHooks.shift();
                if (typeof(initHook) == 'function') {
                    initHook.call(this, this._options);
                }
            }

            this.fire('finishInitHook');
        }
    });

    Minder.version = '1.4.20';

    Minder.registerInitHook = function(hook) {
        _initHooks.push(hook);
    };

    module.exports = Minder;
});


text:
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/saltlab/art/master/plugins/testcasegenerator-plugin/core/src/main/resources/daisydiff/css/diff.css"></link>

This is a that will be used for tests.


text:
package org.jboss.test.gravia.runtime.osgi.sub.d;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.jboss.test.gravia.runtime.osgi.sub.d1.ServiceD1;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;

@Component(service = { ServiceD.class }, immediate = true)
public class ServiceD {

    static AtomicInteger INSTANCE_COUNT = new AtomicInteger();
    final String name = getClass().getSimpleName() + "#" + INSTANCE_COUNT.incrementAndGet();

    final AtomicReference<ServiceD1> ref = new AtomicReference<ServiceD1>();
    final CountDownLatch activateLatch = new CountDownLatch(1);
    final CountDownLatch deactivateLatch = new CountDownLatch(1);

    @Activate
    void activate(ComponentContext context) {
        activateLatch.countDown();
    }

    @Deactivate
    void deactivate() {
        deactivateLatch.countDown();
    }

    public boolean awaitActivate(long timeout, TimeUnit unit) throws InterruptedException {
        return activateLatch.await(timeout, unit);
    }

    public boolean awaitDeactivate(long timeout, TimeUnit unit) throws InterruptedException {
        return deactivateLatch.await(timeout, unit);
    }

    @Reference
    void bindServiceD1(ServiceD1 service) {
        ref.set(service);
    }

    void unbindServiceD1(ServiceD1 service) {
        ref.compareAndSet(service, null);
    }

    public ServiceD1 getServiceD1() {
        return ref.get();
    }

    public String doStuff(String msg) {
        ServiceD1 srv = ref.get();
        return name + ":" + srv.doStuff(msg);
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
/* erdos-tests.cc
 * Unit tests for Erdos numbers programming problem
 * Matt Olson 2015
 */

#include "erdos.h"
#include "gtest/gtest.h"

TEST(SplitString, SplitStringConstruction) {
    auto empty = SplitString {};
    auto text = std::string {"Foo bar baz"};
    auto full = SplitString {text};

    EXPECT_EQ("", empty.first);
    EXPECT_EQ("", empty.rest);
    EXPECT_EQ("", full.first);
    EXPECT_EQ(text, full.rest);
}

TEST(SplitString, SplitOnDelimiter) {
    auto prefix = std::string {"J. Random std::string"};
    auto suffix = std::string {"Esq."};
    auto delim = std::string {", "};
    auto input = SplitString {prefix + delim + suffix};
    auto split = input.split(delim);

    EXPECT_EQ(prefix, split.first);
    EXPECT_EQ(suffix, split.rest);
}

TEST(SplitString, SplitPreservesInput) {
    auto prefix = std::string {"J. Random std::string"};
    auto suffix = std::string {" Esq."};
    auto delim = std::string {", "};
    auto input = SplitString {prefix + delim + suffix};
    auto split = input.split(delim);

    EXPECT_EQ("", input.first);
    EXPECT_EQ(prefix + delim + suffix, input.rest);
}

std::string kTestLine {"Bar-Baz, F., Programmer, J. R., & Fancy Last Name, B. (2015).  The rest of this line doesn't matter."};

TEST(ParseStep, ParserInitialization) {
    auto init = ParseStep { kTestLine };

    EXPECT_EQ("", init.chunk());
}

TEST(ParseStep, ParseLastName) {
    auto init = ParseStep { kTestLine };
    auto last = init.parse();

    EXPECT_EQ("Bar-Baz", last.chunk());
}

TEST(ParseStep, ParseInitials) {
    auto last = ParseStep{kTestLine}.parse();
    auto first = last.parse();

    EXPECT_EQ("F.", first.chunk());
}

TEST(ParseStep, DetectLastAuthor)  {
    auto last = ParseStep{kTestLine}.parse(); // F. Bar-Baz
    auto first = last.parse();

    last = first.parse(); // J. R. Programmer
    EXPECT_EQ("Programmer", last.chunk());

    first = last.parse();
    EXPECT_EQ("J. R.", first.chunk());

    last = first.parse();
    EXPECT_EQ("Fancy Last Name", last.chunk());

    first = last.parse();
    EXPECT_EQ("B.", first.chunk());

    // parsing is idempotent on suffix
    last = first.parse();
    EXPECT_EQ(first.chunk(), last.chunk());
}

TEST(AuthorClass, AuthorCreation) {
    auto auth = std::make_shared<Author>("Bar-Baz, F.");

    EXPECT_EQ(auth->name(), "Bar-Baz, F.");
    EXPECT_TRUE(auth->edges().empty());
    EXPECT_EQ(auth->count(), 0);
}

TEST(AuthorClass, AuthorLinks) {
    auto foo = std::make_shared<Author>("Bar-Baz, F.");
    auto jrp = std::make_shared<Author>("Programmer, J.R.");

    foo->link(jrp);

    EXPECT_EQ(foo->edges().size(), 1);
    EXPECT_TRUE(foo->links(jrp));
    EXPECT_TRUE(jrp->edges().empty());
    EXPECT_FALSE(jrp->links(foo));

    foo->link(jrp); // no multiedges
    EXPECT_EQ(foo->edges().size(), 1);
}


text:
"""Cache lines from files.

This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
that name.
"""

import sys
import os

__all__ = ["getline", "clearcache", "checkcache"]

def getline(filename, lineno, module_globals=None):
    lines = getlines(filename, module_globals)
    if 1 <= lineno <= len(lines):
        return lines[lineno-1]
    else:
        return ''

# The cache

cache = {} # The cache

def clearcache():
    """Clear the cache entirely."""

    global cache
    cache = {}

def getlines(filename, module_globals=None):
    """Get the lines for a file from the cache.
    Update the cache if it doesn't contain an entry for this file already."""

    if filename in cache:
        return cache[filename][2]
    else:
        return updatecache(filename, module_globals)

def checkcache(filename=None):
    """Discard cache entries that are out of date.
    (This is not checked upon each call!)"""

    if filename is None:
        filenames = cache.keys()
    else:
        if filename in cache:
            filenames = [filename]
        else:
            return

    for filename in filenames:
        size, mtime, lines, fullname = cache[filename]
        if mtime is None:
            continue   # no-op for files loaded via a __loader__
        try:
            stat = os.stat(fullname)
        except os.error:
            del cache[filename]
            continue
        if size != stat.st_size or mtime != stat.st_mtime:
            del cache[filename]

def updatecache(filename, module_globals=None):
    """Update a cache entry and return its list of lines.
    If something's wrong, print a message, discard the cache entry,
    and return an empty list."""

    if filename in cache:
        del cache[filename]
    if not filename or (filename.startswith('<') and filename.endswith('>')):
        return []

    fullname = filename
    try:
        stat = os.stat(fullname)
    except OSError:
        basename = filename

        # Try for a __loader__, if available
        if module_globals and '__loader__' in module_globals:
            name = module_globals.get('__name__')
            loader = module_globals['__loader__']
            get_source = getattr(loader, 'get_source', None)

            if name and get_source:
                try:
                    data = get_source(name)
                except (ImportError, IOError):
                    pass
                else:
                    if data is None:
                        # No luck, the PEP302 loader cannot find the source
                        # for this module.
                        return []
                    cache[filename] = (
                        len(data), None,
                        [line+'\n' for line in data.splitlines()], fullname
                    )
                    return cache[filename][2]

        # Try looking through the module search path, which is only useful
        # when handling a relative filename.
        if os.path.isabs(filename):
            return []

        for dirname in sys.path:
            # When using imputil, sys.path may contain things other than
            # strings; ignore them when it happens.
            try:
                fullname = os.path.join(dirname, basename)
            except (TypeError, AttributeError):
                # Not sufficiently string-like to do anything useful with.
                continue
            try:
                stat = os.stat(fullname)
                break
            except os.error:
                pass
        else:
            return []
    try:
        with open(fullname, 'rU') as fp:
            lines = fp.readlines()
    except IOError:
        return []
    if lines and not lines[-1].endswith('\n'):
        lines[-1] += '\n'
    size, mtime = stat.st_size, stat.st_mtime
    cache[filename] = size, mtime, lines, fullname
    return lines


text:
"""
Examine a projection file (.prj) from a shapefile set
    - Check if the geographic coordinate system may be visualized by WorldMap
"""

class ProjectFileCheck:

# From WorldMap:  https://github.com/cga-harvard/cga-worldmap/blob/master/src/GeoNodePy/geonode/maps/forms.py
SRS_CHOICES = (
    ('EPSG:4326', 'EPSG:4326 (WGS 84 Lat/Long)'),
    ('EPSG:900913', 'EPSG:900913 (Web Mercator)'),
)


text:
#pragma once
#include <aws/kms/KMS_EXPORTS.h>
#include <aws/kms/KMSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/kms/model/GrantConstraints.h>
#include <aws/kms/model/GrantOperation.h>
#include <utility>

namespace Aws
{
namespace KMS
{
namespace Model
{

  /**
   */
  class AWS_KMS_API CreateGrantRequest : public KMSRequest
  {
  public:
    CreateGrantRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline const Aws::String& GetKeyId() const{ return m_keyId; }

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline void SetKeyId(const Aws::String& value) { m_keyIdHasBeenSet = true; m_keyId = value; }

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline void SetKeyId(Aws::String&& value) { m_keyIdHasBeenSet = true; m_keyId = std::move(value); }

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline void SetKeyId(const char* value) { m_keyIdHasBeenSet = true; m_keyId.assign(value); }

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline CreateGrantRequest& WithKeyId(const Aws::String& value) { SetKeyId(value); return *this;}

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline CreateGrantRequest& WithKeyId(Aws::String&& value) { SetKeyId(std::move(value)); return *this;}

    /**
     *
The unique identifier for the customer master key (CMK) that the grant
     * applies to.

To specify this value, use the globally unique key ID or the
     * Amazon Resource Name (ARN) of the key. Examples:

Globally
     * unique key ID: 12345678-1234-1234-1234-123456789012

Key ARN:
     * arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012

     *

     */
    inline CreateGrantRequest& WithKeyId(const char* value) { SetKeyId(value); return *this;}

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline const Aws::String& GetGranteePrincipal() const{ return m_granteePrincipal; }

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetGranteePrincipal(const Aws::String& value) { m_granteePrincipalHasBeenSet = true; m_granteePrincipal = value; }

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetGranteePrincipal(Aws::String&& value) { m_granteePrincipalHasBeenSet = true; m_granteePrincipal = std::move(value); }

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetGranteePrincipal(const char* value) { m_granteePrincipalHasBeenSet = true; m_granteePrincipal.assign(value); }

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithGranteePrincipal(const Aws::String& value) { SetGranteePrincipal(value); return *this;}

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithGranteePrincipal(Aws::String&& value) { SetGranteePrincipal(std::move(value)); return *this;}

    /**
     *
The principal that is given permission to perform the operations that the
     * grant permits.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, IAM roles, federated users, and assumed role users.
     * For examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithGranteePrincipal(const char* value) { SetGranteePrincipal(value); return *this;}

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline const Aws::String& GetRetiringPrincipal() const{ return m_retiringPrincipal; }

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetRetiringPrincipal(const Aws::String& value) { m_retiringPrincipalHasBeenSet = true; m_retiringPrincipal = value; }

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetRetiringPrincipal(Aws::String&& value) { m_retiringPrincipalHasBeenSet = true; m_retiringPrincipal = std::move(value); }

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline void SetRetiringPrincipal(const char* value) { m_retiringPrincipalHasBeenSet = true; m_retiringPrincipal.assign(value); }

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithRetiringPrincipal(const Aws::String& value) { SetRetiringPrincipal(value); return *this;}

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithRetiringPrincipal(Aws::String&& value) { SetRetiringPrincipal(std::move(value)); return *this;}

    /**
     *
The principal that is given permission to retire the grant by using
     * RetireGrant operation.

To specify the principal, use the Amazon
     * Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS
     * accounts (root), IAM users, federated users, and assumed role users. For
     * examples of the ARN syntax to use for specifying a principal, see AWS
     * Identity and Access Management (IAM) in the Example ARNs section of the
     * AWS General Reference.

     */
    inline CreateGrantRequest& WithRetiringPrincipal(const char* value) { SetRetiringPrincipal(value); return *this;}

    /**
     *
A list of operations that the grant permits.

     */
    inline const Aws::Vector<GrantOperation>& GetOperations() const{ return m_operations; }

    /**
     *
A list of operations that the grant permits.

     */
    inline void SetOperations(const Aws::Vector<GrantOperation>& value) { m_operationsHasBeenSet = true; m_operations = value; }

    /**
     *
A list of operations that the grant permits.

     */
    inline void SetOperations(Aws::Vector<GrantOperation>&& value) { m_operationsHasBeenSet = true; m_operations = std::move(value); }

    /**
     *
A list of operations that the grant permits.

     */
    inline CreateGrantRequest& WithOperations(const Aws::Vector<GrantOperation>& value) { SetOperations(value); return *this;}

    /**
     *
A list of operations that the grant permits.

     */
    inline CreateGrantRequest& WithOperations(Aws::Vector<GrantOperation>&& value) { SetOperations(std::move(value)); return *this;}

    /**
     *
A list of operations that the grant permits.

     */
    inline CreateGrantRequest& AddOperations(const GrantOperation& value) { m_operationsHasBeenSet = true; m_operations.push_back(value); return *this; }

    /**
     *
A list of operations that the grant permits.

     */
    inline CreateGrantRequest& AddOperations(GrantOperation&& value) { m_operationsHasBeenSet = true; m_operations.push_back(std::move(value)); return *this; }

    /**
     *
A structure that you can use to allow certain operations in the grant only
     * when the desired encryption context is present. For more information about
     * encryption context, see Encryption
     * Context in the AWS Key Management Service Developer Guide.

     */
    inline const GrantConstraints& GetConstraints() const{ return m_constraints; }

    /**
     *
A structure that you can use to allow certain operations in the grant only
     * when the desired encryption context is present. For more information about
     * encryption context, see Encryption
     * Context in the AWS Key Management Service Developer Guide.

     */
    inline void SetConstraints(const GrantConstraints& value) { m_constraintsHasBeenSet = true; m_constraints = value; }

    /**
     *
A structure that you can use to allow certain operations in the grant only
     * when the desired encryption context is present. For more information about
     * encryption context, see Encryption
     * Context in the AWS Key Management Service Developer Guide.

     */
    inline void SetConstraints(GrantConstraints&& value) { m_constraintsHasBeenSet = true; m_constraints = std::move(value); }

    /**
     *
A structure that you can use to allow certain operations in the grant only
     * when the desired encryption context is present. For more information about
     * encryption context, see Encryption
     * Context in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& WithConstraints(const GrantConstraints& value) { SetConstraints(value); return *this;}

    /**
     *
A structure that you can use to allow certain operations in the grant only
     * when the desired encryption context is present. For more information about
     * encryption context, see Encryption
     * Context in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& WithConstraints(GrantConstraints&& value) { SetConstraints(std::move(value)); return *this;}

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline const Aws::Vector<Aws::String>& GetGrantTokens() const{ return m_grantTokens; }

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline void SetGrantTokens(const Aws::Vector<Aws::String>& value) { m_grantTokensHasBeenSet = true; m_grantTokens = value; }

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline void SetGrantTokens(Aws::Vector<Aws::String>&& value) { m_grantTokensHasBeenSet = true; m_grantTokens = std::move(value); }

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& WithGrantTokens(const Aws::Vector<Aws::String>& value) { SetGrantTokens(value); return *this;}

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& WithGrantTokens(Aws::Vector<Aws::String>&& value) { SetGrantTokens(std::move(value)); return *this;}

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& AddGrantTokens(const Aws::String& value) { m_grantTokensHasBeenSet = true; m_grantTokens.push_back(value); return *this; }

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& AddGrantTokens(Aws::String&& value) { m_grantTokensHasBeenSet = true; m_grantTokens.push_back(std::move(value)); return *this; }

    /**
     *
A list of grant tokens.

For more information, see Grant
     * Tokens in the AWS Key Management Service Developer Guide.

     */
    inline CreateGrantRequest& AddGrantTokens(const char* value) { m_grantTokensHasBeenSet = true; m_grantTokens.push_back(value); return *this; }

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline CreateGrantRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline CreateGrantRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
A friendly name for identifying the grant. Use this value to prevent
     * unintended creation of duplicate grants when retrying this request.

When
     * this value is absent, all CreateGrant requests result in a new
     * grant with a unique GrantId even if all the supplied parameters are
     * identical. This can result in unintended duplicates when you retry the
     * CreateGrant request.

When this value is present, you can
     * retry a CreateGrant request with identical parameters; if the grant
     * already exists, the original GrantId is returned without creating a
     * new grant. Note that the returned grant token is unique with every
     * CreateGrant request, even when a duplicate GrantId is
     * returned. All grant tokens obtained in this way can be used interchangeably.

     */
    inline CreateGrantRequest& WithName(const char* value) { SetName(value); return *this;}

  private:
    Aws::String m_keyId;
    bool m_keyIdHasBeenSet;
    Aws::String m_granteePrincipal;
    bool m_granteePrincipalHasBeenSet;
    Aws::String m_retiringPrincipal;
    bool m_retiringPrincipalHasBeenSet;
    Aws::Vector<GrantOperation> m_operations;
    bool m_operationsHasBeenSet;
    GrantConstraints m_constraints;
    bool m_constraintsHasBeenSet;
    Aws::Vector<Aws::String> m_grantTokens;
    bool m_grantTokensHasBeenSet;
    Aws::String m_name;
    bool m_nameHasBeenSet;
  };

} // namespace Model
} // namespace KMS
} // namespace Aws


text:
using SlimCanvas;
using SlimCanvas.Droid;
using SlimCanvas.XF;
using SlimCanvas.XF.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(SlimCanvasXF), typeof(SlimCanvasXFDroid))]
namespace SlimCanvas.XF.Droid
{
    /// <summary>
    /// Create new Canvas in Xamarin Forms
    /// </summary>
    public class SlimCanvasXFDroid : ViewRenderer<SlimCanvasXF, SlimCanvasDroid>
    {
        /// <summary>
        /// Call befor Forms.Init
        /// </summary>
        public static void Initialize()
        {

        }

        SlimCanvasDroid slim;

        /// <summary>
        /// to be added
        /// </summary>
        /// <param name="e"></param>
        protected override void OnElementChanged(ElementChangedEventArgs<SlimCanvasXF> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                slim = new SlimCanvasDroid(this.Context);
                SetNativeControl(slim);
            }

            if (e.OldElement != null)
            {

            }

            if (e.NewElement != null)
            {
                e.NewElement.CanvasLoadedTrigger(slim.SlimCanvasPCL);
            }
        }
    }
}