text:
#ifndef ZYCORE_RESULT_HPP
#define ZYCORE_RESULT_HPP

#include "zycore/Optional.hpp"

namespace zycore
{

// ============================================================================================== //
// [Result]                                                                                //
// ============================================================================================== //

// ---------------------------------------------------------------------------------------------- //
// Marker types                                                                                //
// ---------------------------------------------------------------------------------------------- //

static const struct Error { Error() {} } kError;

// ---------------------------------------------------------------------------------------------- //
// Helper classes                                                                                //
// ---------------------------------------------------------------------------------------------- //

namespace internal
{

template<typename ResultT>
class ResultResultValueHolder
{
protected:
    Optional<ResultT> m_result;

    template<typename... ArgsT>
    explicit ResultResultValueHolder(ArgsT&&... args)
        : m_result(std::forward<ArgsT>(args)...)
    {}
};

template<>
class ResultResultValueHolder<void>
{
protected:
    ResultResultValueHolder(InPlace) {}
    ResultResultValueHolder(Empty) {}
};

template<typename ResultT>
class ResultErrorValueHolder
{
protected:
    Optional<ResultT> m_error;

    template<typename... ArgsT>
    explicit ResultErrorValueHolder(ArgsT&&... args)
        : m_error(std::forward<ArgsT>(args)...)
    {}
};

template<>
class ResultErrorValueHolder<void>
{
protected:
    ResultErrorValueHolder(InPlace) {}
    ResultErrorValueHolder(Empty) {}
};

} // namespace internal

// ---------------------------------------------------------------------------------------------- //
// [Result]                                                                                //
// ---------------------------------------------------------------------------------------------- //

/**
 * @brief   Class representing either failure or success, optionally holding either an operation
 *          result or an error descriptor.
 * @tparam  ResultT Type of the result.
 * @tparam  ErrorT  Type of the error.
 */
template<typename ResultT = void, typename ErrorT = void>
class Result final
    : public internal::ResultResultValueHolder<ResultT>
    , public internal::ResultErrorValueHolder<ErrorT>
{
public:
    /**
     * @brief   Constructor creating a result in error state.
     * @tparam  ArgsT   Argument types for in-place construction.
     * @param   error   @c kEmpty constant.
     * @param   args    Arguments passed to the constructor of the error value.
     */
    template<typename... ArgsT>
    Result(Error, ArgsT&&... args)
        : internal::ResultResultValueHolder<ResultT>(kEmpty)
        , internal::ResultErrorValueHolder<ErrorT>(kInPlace, std::forward<ArgsT>(args)...)
    {}

    /**
     * @brief   Constructor creating a result in success state.
     * @tparam  ArgsT   Argument types for in-place construction
     * @param   args    Arguments passed to the constructor of the result value.
     */
    template<typename... ArgsT>
    Result(ArgsT&&... args)
        : internal::ResultResultValueHolder<ResultT>(kInPlace, std::forward<ArgsT>(args)...)
        , internal::ResultErrorValueHolder<ErrorT>(kEmpty)
    {}
public:
    /**
     * @brief   Queries if the operation that lead to the result succeeded.
     * @return  @c true if the operation succeded and thus this result has a result value but no
     *          error value, @c false if not.
     */
    // Implementation capturing Result<ResultT, ErrorT> and Result<ResultT, void>
    template<typename ResultTT = ResultT, std::enable_if_t<!std::is_void<ResultTT>::value, int> = 0>
    bool succeeded() const
    {
        return this->m_result.hasValue();
    }

    /**
     * @copydoc succeeded()
     */
    // Implementation capturing Result<void, ErrorT>. Case Result<void, void> is handled by
    // a specialization of Result itself.
    template<typename ResultTT = ResultT,
        std::enable_if_t<std::is_void<ResultTT>::value && !std::is_void<ErrorT>::value, int> = 0>
    bool succeeded() const
    {
        return !this->m_error.hasValue();
    };

    /**
     * @brief   Convenience operator equivalent to @c succeeded.
     * @copydetauls succeeded
     */
    operator bool () const
    {
        return succeeded();
    }

    /**
     * @brief   Queries if the operation that lead to the result failed.
     * @return  @c true if the operation failed and thus this result has an error value but no
     *          result value, @c false if not.
     */
    bool failed() const
    {
        return !succeeded();
    }

    /**
     * @brief   Obtains the result value.
     * @return  The result value.
     * @warning Attepmt to obtain the result value of results in error state is undefined
     *          behaviour. Doing so will terminate the application.
     */
    template<typename ResultTT = ResultT, std::enable_if_t<!std::is_void<ResultTT>::value, int> = 0>
    ResultTT& result()
    {
        if (!succeeded()) fatalExit("attempt to obtain result of result in error state");
        return this->m_result.value();
    }

    /**
     * @brief   Obtains the error value.
     * @return  An ErrorT&
     */
    template<typename ErrorTT = ErrorT, std::enable_if_t<!std::is_void<ErrorTT>::value, int> = 0>
    ErrorTT& error()
    {
        if (!failed()) fatalExit("attempt to obtain error of result in success state");
        return this->m_error.value();
    }

    /**
     * @brief   Convenience operator equivalent to @result.
     * @copydetails result
     */
    template<typename ResultTT = ResultT, std::enable_if_t<!std::is_void<ResultTT>::value, int> = 0>
    explicit operator ResultTT& ()
    {
        return result();
    }
};

// ---------------------------------------------------------------------------------------------- //
// [Result<void, void>]                                                                           //
// ---------------------------------------------------------------------------------------------- //

/**
 * @brief   @copydoc Result
 */
template<>
class Result<void, void> final
{
    bool m_succeeded;
public:
    /**
     * @copydoc Result::Result(Error, ...)
     */
    explicit Result(Error)
        : m_succeeded(false)
    {}

    /**
     * @copydoc Result::Result(...)
     */
    Result()
        : m_succeeded(true)
    {}
public:
    /**
     * @copydoc Result::succeeded
     */
    bool succeeded() const { return m_succeeded;  }

    /**
     * @copydoc Result::failed
     */
    bool failed   () const { return !succeeded(); }

    /**
     * @copydoc Result::operator bool
     */
    operator bool () const { return succeeded();  }
};

// ============================================================================================== //

} // namespace zycore

#endif // ZYCORE_RESULT_HPP


text: mocha --check-leaks --reporter spec $(find test -name "*.js")

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
module Types where
import Graphics.GL.Pal
import Control.DeepSeq
import GHC.Generics
data Cube = Cube
  { cubeColor :: V4 GLfloat
  , cubeScale :: V3 GLfloat
  , cubePosition :: V3 GLfloat
  , cubeRotation :: Quaternion GLfloat
  } deriving (Show, Generic, NFData)

newCube :: Cube
newCube = Cube
  { cubeColor    = V4 1 1 1 1
  , cubeScale    = V3 1 1 1
  , cubePosition = V3 0 0 0
  , cubeRotation = axisAngle (V3 0 1 0) 0
  }


text:
package dynamodb

import (
	"context"
	"fmt"
	"strings"

	"github.com/Clever/wag/samples/v8/gen-go-db-only/db"
	"github.com/Clever/wag/samples/v8/gen-go-db-only/models"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
	"github.com/go-openapi/strfmt"
)

var _ = strfmt.DateTime{}

// TeacherSharingRuleTable represents the user-configurable properties of the TeacherSharingRule table.
type TeacherSharingRuleTable struct {
	DynamoDBAPI        dynamodbiface.DynamoDBAPI
	Prefix             string
	TableName          string
	ReadCapacityUnits  int64
	WriteCapacityUnits int64
}

// ddbTeacherSharingRulePrimaryKey represents the primary key of a TeacherSharingRule in DynamoDB.
type ddbTeacherSharingRulePrimaryKey struct {
	Teacher   string `dynamodbav:"teacher"`
	SchoolApp string `dynamodbav:"school_app"`
}

// ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp represents the district_school_teacher_app GSI.
type ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp struct {
	District         string `dynamodbav:"district"`
	SchoolTeacherApp string `dynamodbav:"school_teacher_app"`
}

// ddbTeacherSharingRule represents a TeacherSharingRule as stored in DynamoDB.
type ddbTeacherSharingRule struct {
	models.TeacherSharingRule
}

func (t TeacherSharingRuleTable) name() string {
	if t.TableName != "" {
		return t.TableName
	}
	return fmt.Sprintf("%s-teacher-sharing-rules", t.Prefix)
}

func (t TeacherSharingRuleTable) create(ctx context.Context) error {
	if _, err := t.DynamoDBAPI.CreateTableWithContext(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []*dynamodb.AttributeDefinition{
			{
				AttributeName: aws.String("district"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("school_app"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("school_teacher_app"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("teacher"),
				AttributeType: aws.String("S"),
			},
		},
		KeySchema: []*dynamodb.KeySchemaElement{
			{
				AttributeName: aws.String("teacher"),
				KeyType:       aws.String(dynamodb.KeyTypeHash),
			},
			{
				AttributeName: aws.String("school_app"),
				KeyType:       aws.String(dynamodb.KeyTypeRange),
			},
		},
		GlobalSecondaryIndexes: []*dynamodb.GlobalSecondaryIndex{
			{
				IndexName: aws.String("district_school_teacher_app"),
				Projection: &dynamodb.Projection{
					ProjectionType: aws.String("KEYS_ONLY"),
				},
				KeySchema: []*dynamodb.KeySchemaElement{
					{
						AttributeName: aws.String("district"),
						KeyType:       aws.String(dynamodb.KeyTypeHash),
					},
					{
						AttributeName: aws.String("school_teacher_app"),
						KeyType:       aws.String(dynamodb.KeyTypeRange),
					},
				},
				ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
					ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
					WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
				},
			},
		},
		ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
			ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
			WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
		},
		TableName: aws.String(t.name()),
	}); err != nil {
		return err
	}
	return nil
}

func (t TeacherSharingRuleTable) saveTeacherSharingRule(ctx context.Context, m models.TeacherSharingRule) error {
	data, err := encodeTeacherSharingRule(m)
	if err != nil {
		return err
	}
	_, err = t.DynamoDBAPI.PutItemWithContext(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(t.name()),
		Item:      data,
	})
	return err
}

func (t TeacherSharingRuleTable) getTeacherSharingRule(ctx context.Context, teacher string, school string, app string) (*models.TeacherSharingRule, error) {
	key, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{
		Teacher:   teacher,
		SchoolApp: fmt.Sprintf("%s_%s", school, app),
	})
	if err != nil {
		return nil, err
	}
	res, err := t.DynamoDBAPI.GetItemWithContext(ctx, &dynamodb.GetItemInput{
		Key:            key,
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(true),
	})
	if err != nil {
		return nil, err
	}

	if len(res.Item) == 0 {
		return nil, db.ErrTeacherSharingRuleNotFound{
			Teacher: teacher,
			School:  school,
			App:     app,
		}
	}

	var m models.TeacherSharingRule
	if err := decodeTeacherSharingRule(res.Item, &m); err != nil {
		return nil, err
	}

	return &m, nil
}

func (t TeacherSharingRuleTable) scanTeacherSharingRules(ctx context.Context, input db.ScanTeacherSharingRulesInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error {
	scanInput := &dynamodb.ScanInput{
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(!input.DisableConsistentRead),
		Limit:          input.Limit,
	}
	if input.StartingAfter != nil {
		exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter)
		if err != nil {
			return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error())
		}
		// must provide only the fields constituting the index
		scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"teacher": exclusiveStartKey["teacher"],
			"school_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)),
			},
		}
	}
	totalRecordsProcessed := int64(0)
	var innerErr error
	err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool {
		items, err := decodeTeacherSharingRules(out.Items)
		if err != nil {
			innerErr = fmt.Errorf("error decoding %s", err.Error())
			return false
		}
		for i := range items {
			if input.Limiter != nil {
				if err := input.Limiter.Wait(ctx); err != nil {
					innerErr = err
					return false
				}
			}
			isLastModel := lastPage && i == len(items)-1
			if shouldContinue := fn(&items[i], isLastModel); !shouldContinue {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	})
	if innerErr != nil {
		return innerErr
	}
	return err
}

func (t TeacherSharingRuleTable) getTeacherSharingRulesByTeacherAndSchoolAppParseFilters(queryInput *dynamodb.QueryInput, input db.GetTeacherSharingRulesByTeacherAndSchoolAppInput) {
	for _, filterValue := range input.FilterValues {
		switch filterValue.AttributeName {
		case db.TeacherSharingRuleDistrict:
			queryInput.ExpressionAttributeNames["#DISTRICT"] = aws.String(string(db.TeacherSharingRuleDistrict))
			for i, attributeValue := range filterValue.AttributeValues {
				queryInput.ExpressionAttributeValues[fmt.Sprintf(":%s_value%d", string(db.TeacherSharingRuleDistrict), i)] = &dynamodb.AttributeValue{
					S: aws.String(attributeValue.(string)),
				}
			}
		}
	}
}

func (t TeacherSharingRuleTable) getTeacherSharingRulesByTeacherAndSchoolApp(ctx context.Context, input db.GetTeacherSharingRulesByTeacherAndSchoolAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error {
	if input.StartingAt != nil && input.StartingAfter != nil {
		return fmt.Errorf("Can specify only one of StartingAt or StartingAfter")
	}
	if input.Teacher == "" {
		return fmt.Errorf("Hash key input.Teacher cannot be empty")
	}
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		ExpressionAttributeNames: map[string]*string{
			"#TEACHER": aws.String("teacher"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":teacher": &dynamodb.AttributeValue{
				S: aws.String(input.Teacher),
			},
		},
		ScanIndexForward: aws.Bool(!input.Descending),
		ConsistentRead:   aws.Bool(!input.DisableConsistentRead),
	}
	if input.Limit != nil {
		queryInput.Limit = input.Limit
	}
	if input.StartingAt == nil {
		queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher")
	} else {
		queryInput.ExpressionAttributeNames["#SCHOOL_APP"] = aws.String("school_app")
		queryInput.ExpressionAttributeValues[":schoolApp"] = &dynamodb.AttributeValue{
			S: aws.String(fmt.Sprintf("%s_%s", input.StartingAt.School, input.StartingAt.App)),
		}
		if input.Descending {
			queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher AND #SCHOOL_APP <= :schoolApp")
		} else {
			queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher AND #SCHOOL_APP >= :schoolApp")
		}
	}
	if input.StartingAfter != nil {
		queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"school_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)),
			},
			"teacher": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Teacher),
			},
		}
	}
	if len(input.FilterValues) > 0 && input.FilterExpression != "" {
		t.getTeacherSharingRulesByTeacherAndSchoolAppParseFilters(queryInput, input)
		queryInput.FilterExpression = aws.String(input.FilterExpression)
	}

	totalRecordsProcessed := int64(0)
	var pageFnErr error
	pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool {
		// Only assume an empty page means no more results if there are no filters applied
		if (len(input.FilterValues) == 0 || input.FilterExpression == "") && len(queryOutput.Items) == 0 {
			return false
		}
		items, err := decodeTeacherSharingRules(queryOutput.Items)
		if err != nil {
			pageFnErr = err
			return false
		}
		hasMore := true
		for i := range items {
			if lastPage == true {
				hasMore = i < len(items)-1
			}
			if !fn(&items[i], !hasMore) {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	}

	err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn)
	if err != nil {
		return err
	}
	if pageFnErr != nil {
		return pageFnErr
	}

	return nil
}

func (t TeacherSharingRuleTable) deleteTeacherSharingRule(ctx context.Context, teacher string, school string, app string) error {
	key, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{
		Teacher:   teacher,
		SchoolApp: fmt.Sprintf("%s_%s", school, app),
	})
	if err != nil {
		return err
	}
	_, err = t.DynamoDBAPI.DeleteItemWithContext(ctx, &dynamodb.DeleteItemInput{
		Key:       key,
		TableName: aws.String(t.name()),
	})
	if err != nil {
		return err
	}

	return nil
}

func (t TeacherSharingRuleTable) getTeacherSharingRulesByDistrictAndSchoolTeacherApp(ctx context.Context, input db.GetTeacherSharingRulesByDistrictAndSchoolTeacherAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error {
	if input.StartingAt != nil && input.StartingAfter != nil {
		return fmt.Errorf("Can specify only one of input.StartingAt or input.StartingAfter")
	}
	if input.District == "" {
		return fmt.Errorf("Hash key input.District cannot be empty")
	}
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		IndexName: aws.String("district_school_teacher_app"),
		ExpressionAttributeNames: map[string]*string{
			"#DISTRICT": aws.String("district"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":district": &dynamodb.AttributeValue{
				S: aws.String(input.District),
			},
		},
		ScanIndexForward: aws.Bool(!input.Descending),
		ConsistentRead:   aws.Bool(false),
	}
	if input.Limit != nil {
		queryInput.Limit = input.Limit
	}
	if input.StartingAt == nil {
		queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district")
	} else {
		queryInput.ExpressionAttributeNames["#SCHOOL_TEACHER_APP"] = aws.String("school_teacher_app")
		queryInput.ExpressionAttributeValues[":schoolTeacherApp"] = &dynamodb.AttributeValue{
			S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAt.School, input.StartingAt.Teacher, input.StartingAt.App)),
		}
		if input.Descending {
			queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district AND #SCHOOL_TEACHER_APP <= :schoolTeacherApp")
		} else {
			queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district AND #SCHOOL_TEACHER_APP >= :schoolTeacherApp")
		}
	}
	if input.StartingAfter != nil {
		queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"school_teacher_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAfter.School, input.StartingAfter.Teacher, input.StartingAfter.App)),
			},
			"district": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.District),
			},
			"school_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)),
			},
			"teacher": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Teacher),
			},
		}
	}

	totalRecordsProcessed := int64(0)
	var pageFnErr error
	pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool {
		if len(queryOutput.Items) == 0 {
			return false
		}
		items, err := decodeTeacherSharingRules(queryOutput.Items)
		if err != nil {
			pageFnErr = err
			return false
		}
		hasMore := true
		for i := range items {
			if lastPage == true {
				hasMore = i < len(items)-1
			}
			if !fn(&items[i], !hasMore) {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	}

	err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn)
	if err != nil {
		return err
	}
	if pageFnErr != nil {
		return pageFnErr
	}

	return nil
}
func (t TeacherSharingRuleTable) scanTeacherSharingRulesByDistrictAndSchoolTeacherApp(ctx context.Context, input db.ScanTeacherSharingRulesByDistrictAndSchoolTeacherAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error {
	scanInput := &dynamodb.ScanInput{
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(!input.DisableConsistentRead),
		Limit:          input.Limit,
		IndexName:      aws.String("district_school_teacher_app"),
	}
	if input.StartingAfter != nil {
		exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter)
		if err != nil {
			return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error())
		}
		// must provide the fields constituting the index and the primary key
		// https://stackoverflow.com/questions/40988397/dynamodb-pagination-with-withexclusivestartkey-on-a-global-secondary-index
		scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"teacher": exclusiveStartKey["teacher"],
			"school_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)),
			},
			"district": exclusiveStartKey["district"],
			"school_teacher_app": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAfter.School, input.StartingAfter.Teacher, input.StartingAfter.App)),
			},
		}
	}
	totalRecordsProcessed := int64(0)
	var innerErr error
	err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool {
		items, err := decodeTeacherSharingRules(out.Items)
		if err != nil {
			innerErr = fmt.Errorf("error decoding %s", err.Error())
			return false
		}
		for i := range items {
			if input.Limiter != nil {
				if err := input.Limiter.Wait(ctx); err != nil {
					innerErr = err
					return false
				}
			}
			isLastModel := lastPage && i == len(items)-1
			if shouldContinue := fn(&items[i], isLastModel); !shouldContinue {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	})
	if innerErr != nil {
		return innerErr
	}
	return err
}

// encodeTeacherSharingRule encodes a TeacherSharingRule as a DynamoDB map of attribute values.
func encodeTeacherSharingRule(m models.TeacherSharingRule) (map[string]*dynamodb.AttributeValue, error) {
	val, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRule{
		TeacherSharingRule: m,
	})
	if err != nil {
		return nil, err
	}
	// make sure composite attributes don't contain separator characters
	if strings.Contains(m.App, "_") {
		return nil, fmt.Errorf("app cannot contain '_': %s", m.App)
	}
	if strings.Contains(m.School, "_") {
		return nil, fmt.Errorf("school cannot contain '_': %s", m.School)
	}
	if strings.Contains(m.Teacher, "_") {
		return nil, fmt.Errorf("teacher cannot contain '_': %s", m.Teacher)
	}
	// add in composite attributes
	primaryKey, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{
		Teacher:   m.Teacher,
		SchoolApp: fmt.Sprintf("%s_%s", m.School, m.App),
	})
	if err != nil {
		return nil, err
	}
	for k, v := range primaryKey {
		val[k] = v
	}
	districtSchoolTeacherApp, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp{
		District:         m.District,
		SchoolTeacherApp: fmt.Sprintf("%s_%s_%s", m.School, m.Teacher, m.App),
	})
	if err != nil {
		return nil, err
	}
	for k, v := range districtSchoolTeacherApp {
		val[k] = v
	}
	return val, err
}

// decodeTeacherSharingRule translates a TeacherSharingRule stored in DynamoDB to a TeacherSharingRule struct.
func decodeTeacherSharingRule(m map[string]*dynamodb.AttributeValue, out *models.TeacherSharingRule) error {
	var ddbTeacherSharingRule ddbTeacherSharingRule
	if err := dynamodbattribute.UnmarshalMap(m, &ddbTeacherSharingRule); err != nil {
		return err
	}
	*out = ddbTeacherSharingRule.TeacherSharingRule
	// parse composite attributes from projected secondary indexes and fill
	// in model properties
	if v, ok := m["school_teacher_app"]; ok && v.S != nil {
		parts := strings.Split(*v.S, "_")
		if len(parts) != 3 {
			return fmt.Errorf("expected 3 parts: '%s'", *v.S)
		}
		out.School = parts[0]
		out.Teacher = parts[1]
		out.App = parts[2]
	}
	return nil
}

// decodeTeacherSharingRules translates a list of TeacherSharingRules stored in DynamoDB to a slice of TeacherSharingRule structs.
func decodeTeacherSharingRules(ms []map[string]*dynamodb.AttributeValue) ([]models.TeacherSharingRule, error) {
	teacherSharingRules := make([]models.TeacherSharingRule, len(ms))
	for i, m := range ms {
		var teacherSharingRule models.TeacherSharingRule
		if err := decodeTeacherSharingRule(m, &teacherSharingRule); err != nil {
			return nil, err
		}
		teacherSharingRules[i] = teacherSharingRule
	}
	return teacherSharingRules, nil
}


text:
(function() {
	//4态复选框  1)未勾选;2)勾选;3)部分勾选;4)不可用(含前三种情况)
    jQuery.fn.checkbox4 = function(options) {
        options = options || {};

        var fun;

        if(typeof options === 'string'){
            fun = options;
            var args = arguments[1], obj = {};
            args !== undefined && (obj[options] = args);
            options = obj;
        }

        var settings = jQuery.extend(defaults, options);

        function check(){
            this.prop('checked', settings.check).trigger('change');
        }

        function partialCheck(){
            this.siblings('span').removeClass().addClass(settings.partialCheckedClass);
            //partial is another kind status of unchecked
            this.prop('checked', false).attr('data-partial', settings.partialCheck.join('|'));
        }

        function disabled(){
            this.prop('disabled', settings.disabled);
            var root = this.parent(),
                cls = settings.disabledClass;

            settings.disabled ? root.addClass(cls) :root.removeClass(cls);
        }

        return this.each(function() {
            var me = jQuery(this);

            //only do partialCheck
            if(fun){
                eval(fun + '.call(me)');
            	return;
            }
            me.removeAttr('data-partial');

            var replacement = jQuery('

');
            var element = jQuery('span', replacement);

            me.prop('checked') && element.addClass(settings.checkedClass);
            me.prop('disabled') && replacement.addClass(settings.disabledClass);

            element.on('click', function(event) {
                event.preventDefault();
                event.stopPropagation();
                if(me.parent().is('.' + settings.disabledClass)){
                    return;
                }
                var input = jQuery('input', replacement);
                input.prop('checked',!input.prop('checked'))
                	 .trigger('change');

                return false;
            });

            me.on('change', function(event) {
                var input = jQuery(this);
                input.removeAttr('data-partial');
                element.removeClass(settings.partialCheckedClass);

                if (input.prop('checked')) {
                    element.addClass(settings.checkedClass);
                } else {
                    element.removeClass(settings.checkedClass);
                }

                return true;
            });
            me.before(replacement).insertAfter(element);
        });
    }

    var defaults = {
        'className': 'jquery-checkbox4',
        'checkedClass': 'checked',
        'partialCheckedClass':'partial-checked',
        'disabledClass':'jquery-checkbox4-disabled'
    };
})();


text:
"""Tests for the forms of the account_keeping app."""
from django.test import TestCase
from django.utils.timezone import now

from mixer.backend.django import mixer

from .. import forms

class InvoiceFormTestCase(TestCase):
    """Tests for the ``InvoiceForm`` form."""
    longMessage = True

    def test_form(self):
        form = forms.InvoiceForm(branch=None, data={
            'invoice_type': 'd',
            'invoice_date': now().strftime('%Y-%m-%d'),
            'currency': mixer.blend('currency_history.Currency').pk,
            'branch': mixer.blend('account_keeping.Branch').pk,
            'vat': 0,
            'value_net': 0,
            'value_gross': 0,
        })
        self.assertFalse(form.errors)

class TransactionFormTestCase(TestCase):
    """Tests for the ``TransactionForm`` form."""
    longMessage = True

    def test_form(self):
        account = mixer.blend('account_keeping.Account')
        data = {
            'transaction_type': 'd',
            'transaction_date': now().strftime('%Y-%m-%d'),
            'account': account.pk,
            'payee': mixer.blend('account_keeping.Payee').pk,
            'category': mixer.blend('account_keeping.Category').pk,
            'currency': mixer.blend('currency_history.Currency').pk,
            'amount_net': 0,
            'amount_gross': 0,
            'vat': 0,
            'value_net': 0,
            'value_gross': 0,
            'mark_invoice': True,
        }
        form = forms.TransactionForm(data=data, branch=account.branch)
        self.assertFalse(form.errors)
        transaction = form.save()
        transaction.invoice = mixer.blend('account_keeping.Invoice',
                                          payment_date=None)
        transaction.invoice.save()
        self.assertFalse(transaction.invoice.payment_date)
        data.update({'invoice': transaction.invoice.pk})
        form = forms.TransactionForm(data=data, branch=account.branch)
        self.assertFalse(form.errors)
        transaction = form.save()
        self.assertTrue(transaction.invoice.payment_date)


text:
package org.snf4j.core.timer;

/**
 * A timer task object that is associated with scheduled operation initiated by {@link ITimer} implementation.
 *
 * @author SNF4J.ORG
 */
public interface ITimerTask {

	/**
	 * Cancels the associated scheduled operation.
	 */
	void cancelTask();
}


text:
'use strict';

var should = require('chai').should();
var Protocol = require('../../');
var builder = Protocol.Messages.builder;
var bitcore = require('bitcore');

describe('Messages Builder', function() {

  describe('@constructor', function() {

    it('should return commands based on default', function() {
      // instantiate
      var b = builder();
      should.exist(b);
    });

    it('should return commands with customizations', function() {
      // instantiate
      var b = builder({
        network: bitcore.Networks.testnet,
        Block: bitcore.Block,
        Transaction: bitcore.Transaction
      });
      should.exist(b);
    });

  });

});


text:
package org.apache.wss4j.common.saml.bean;

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

/**
 * Class SamlAttributeStatement represents a SAML attribute statement
 */
public class AttributeStatementBean {
    private SubjectBean subject;
    private List<AttributeBean> attributeBeans;

    /**
     * Constructor SamlAttributeStatement creates a new SamlAttributeStatement instance.
     */
    public AttributeStatementBean() {
        attributeBeans = new ArrayList<AttributeBean>();
    }

    /**
     * Constructor SamlAttributeStatement creates a new SamlAttributeStatement instance.
     * @param subject A new SubjectBean instance
     * @param attributeBeans A list of Attributes
     */
    public AttributeStatementBean(
        SubjectBean subject,
        List<AttributeBean> attributeBeans
    ) {
        this.subject = subject;
        this.attributeBeans = attributeBeans;
    }

    /**
     * Method getSamlAttributes returns the samlAttributes of this SamlAttributeStatement object.
     *
     * @return the samlAttributes (type List<SamlAttribute>) of this SamlAttributeStatement object.
     */
    public List<AttributeBean> getSamlAttributes() {
        return attributeBeans;
    }

    /**
     * Method setSamlAttributes sets the samlAttributes of this SamlAttributeStatement object.
     *
     * @param attributeBeans the samlAttributes of this SamlAttributeStatement object.
     *
     */
    public void setSamlAttributes(List<AttributeBean> attributeBeans) {
        this.attributeBeans = attributeBeans;
    }

    /**
     * Get the Subject
     * @return the Subject
     */
    public SubjectBean getSubject() {
        return subject;
    }

    /**
     * Set the Subject
     * @param subject the SubjectBean instance to set
     */
    public void setSubject(SubjectBean subject) {
        this.subject = subject;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof AttributeStatementBean)) {
            return false;
        }

        AttributeStatementBean that = (AttributeStatementBean) o;

        if (attributeBeans == null && that.attributeBeans != null) {
            return false;
        } else if (attributeBeans != null && !attributeBeans.equals(that.attributeBeans)) {
            return false;
        }

        if (subject == null && that.subject != null) {
            return false;
        } else if (subject != null && !subject.equals(that.subject)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = subject != null ? subject.hashCode() : 0;
        result = 31 * result + (attributeBeans != null ? attributeBeans.hashCode() : 0);
        return result;
    }
}


text:
<?php
echo '
IV. Oral Paper/Poster Presentation
';

if ($session->get('accom_ppr'))
{
	$accom_ppr = $session->get('accom_ppr');

	foreach ($accom_ppr as $ppr)
	{
		echo '
';
		echo '-';
		echo '     ';

		if ($ppr['author']) echo $ppr['author'], '. ';

		echo $ppr['title'], '. ';
		echo $ppr['activity'], '. ';
		echo $ppr['venue'], '. ';
		echo redate($ppr['start'], $ppr['end']), '. ';
		echo '  ';

		if ($ppr['attachment'])
		{
			$attachment = explode(' ', $ppr['attachment']);

			for ($i = 0; $i < count($attachment); $i++)
			{
				$session->set('attachment', $session->get_once('attachment')+1);
				echo '',
					'', $session->get('attachment'), ' ';
			}
		}

		echo '   ';

		echo 'get('accom_details')['accom_ID'], '" data-toggle="modal" data-target="#modal_paper" role="button" href="" action-url="', URL::site('faculty/accom/edit/ppr/'.$ppr['paper_ID']), '" ajax-url="', URL::site('extras/ajax/accom_details/ppr'), '">
			', '  ';
		echo '',
			'';
		echo '
';
	}
}
?>