text:
package aws

import (
	"fmt"
	"log"
	"sort"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/elasticache"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsElastiCacheCommonSchema() map[string]*schema.Schema {

	return map[string]*schema.Schema{
		"availability_zones": {
			Type:     schema.TypeSet,
			Optional: true,
			ForceNew: true,
			Elem:     &schema.Schema{Type: schema.TypeString},
			Set:      schema.HashString,
		},
		"node_type": {
			Type:     schema.TypeString,
			Required: true,
		},
		"engine": {
			Type:     schema.TypeString,
			Required: true,
		},
		"engine_version": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
		},
		"parameter_group_name": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
		},
		"subnet_group_name": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
			ForceNew: true,
		},
		"security_group_names": {
			Type:     schema.TypeSet,
			Optional: true,
			Computed: true,
			ForceNew: true,
			Elem:     &schema.Schema{Type: schema.TypeString},
			Set:      schema.HashString,
		},
		"security_group_ids": {
			Type:     schema.TypeSet,
			Optional: true,
			Computed: true,
			Elem:     &schema.Schema{Type: schema.TypeString},
			Set:      schema.HashString,
		},
		// A single-element string list containing an Amazon Resource Name (ARN) that
		// uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
		// file will be used to populate the node group.
		//
		// See also:
		// https://github.com/aws/aws-sdk-go/blob/4862a174f7fc92fb523fc39e68f00b87d91d2c3d/service/elasticache/api.go#L2079
		"snapshot_arns": {
			Type:     schema.TypeSet,
			Optional: true,
			ForceNew: true,
			Elem:     &schema.Schema{Type: schema.TypeString},
			Set:      schema.HashString,
		},
		"snapshot_window": {
			Type:         schema.TypeString,
			Optional:     true,
			Computed:     true,
			ValidateFunc: validateOnceADayWindowFormat,
		},
		"snapshot_name": {
			Type:     schema.TypeString,
			Optional: true,
			ForceNew: true,
		},

		"maintenance_window": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
			StateFunc: func(val interface{}) string {
				// Elasticache always changes the maintenance
				// to lowercase
				return strings.ToLower(val.(string))
			},
			ValidateFunc: validateOnceAWeekWindowFormat,
		},
		"port": {
			Type:     schema.TypeInt,
			Required: true,
			ForceNew: true,
		},
		"notification_topic_arn": {
			Type:     schema.TypeString,
			Optional: true,
		},

		"snapshot_retention_limit": {
			Type:     schema.TypeInt,
			Optional: true,
			ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
				value := v.(int)
				if value > 35 {
					es = append(es, fmt.Errorf(
						"snapshot retention limit cannot be more than 35 days"))
				}
				return
			},
		},

		"apply_immediately": {
			Type:     schema.TypeBool,
			Optional: true,
			Computed: true,
		},

		"tags": tagsSchema(),
	}
}

func resourceAwsElasticacheCluster() *schema.Resource {
	resourceSchema := resourceAwsElastiCacheCommonSchema()

	resourceSchema["cluster_id"] = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
		ForceNew: true,
		StateFunc: func(val interface{}) string {
			// Elasticache normalizes cluster ids to lowercase,
			// so we have to do this too or else we can end up
			// with non-converging diffs.
			return strings.ToLower(val.(string))
		},
		ValidateFunc: validateElastiCacheClusterId,
	}

	resourceSchema["num_cache_nodes"] = &schema.Schema{
		Type:     schema.TypeInt,
		Required: true,
	}

	resourceSchema["az_mode"] = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Computed: true,
	}

	resourceSchema["availability_zone"] = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Computed: true,
		ForceNew: true,
	}

	resourceSchema["configuration_endpoint"] = &schema.Schema{
		Type:     schema.TypeString,
		Computed: true,
	}

	resourceSchema["cluster_address"] = &schema.Schema{
		Type:     schema.TypeString,
		Computed: true,
	}

	resourceSchema["replication_group_id"] = &schema.Schema{
		Type:     schema.TypeString,
		Computed: true,
	}

	resourceSchema["cache_nodes"] = &schema.Schema{
		Type:     schema.TypeList,
		Computed: true,
		Elem: &schema.Resource{
			Schema: map[string]*schema.Schema{
				"id": {
					Type:     schema.TypeString,
					Computed: true,
				},
				"address": {
					Type:     schema.TypeString,
					Computed: true,
				},
				"port": {
					Type:     schema.TypeInt,
					Computed: true,
				},
				"availability_zone": {
					Type:     schema.TypeString,
					Computed: true,
				},
			},
		},
	}

	return &schema.Resource{
		Create: resourceAwsElasticacheClusterCreate,
		Read:   resourceAwsElasticacheClusterRead,
		Update: resourceAwsElasticacheClusterUpdate,
		Delete: resourceAwsElasticacheClusterDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: resourceSchema,
	}
}

func resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticacheconn

	clusterId := d.Get("cluster_id").(string)
	nodeType := d.Get("node_type").(string)           // e.g) cache.m1.small
	numNodes := int64(d.Get("num_cache_nodes").(int)) // 2
	engine := d.Get("engine").(string)                // memcached
	engineVersion := d.Get("engine_version").(string) // 1.4.14
	port := int64(d.Get("port").(int))                // e.g) 11211
	subnetGroupName := d.Get("subnet_group_name").(string)
	securityNameSet := d.Get("security_group_names").(*schema.Set)
	securityIdSet := d.Get("security_group_ids").(*schema.Set)

	securityNames := expandStringList(securityNameSet.List())
	securityIds := expandStringList(securityIdSet.List())
	tags := tagsFromMapEC(d.Get("tags").(map[string]interface{}))

	req := &elasticache.CreateCacheClusterInput{
		CacheClusterId:          aws.String(clusterId),
		CacheNodeType:           aws.String(nodeType),
		NumCacheNodes:           aws.Int64(numNodes),
		Engine:                  aws.String(engine),
		EngineVersion:           aws.String(engineVersion),
		Port:                    aws.Int64(port),
		CacheSubnetGroupName:    aws.String(subnetGroupName),
		CacheSecurityGroupNames: securityNames,
		SecurityGroupIds:        securityIds,
		Tags:                    tags,
	}

	// parameter groups are optional and can be defaulted by AWS
	if v, ok := d.GetOk("parameter_group_name"); ok {
		req.CacheParameterGroupName = aws.String(v.(string))
	}

	if v, ok := d.GetOk("snapshot_retention_limit"); ok {
		req.SnapshotRetentionLimit = aws.Int64(int64(v.(int)))
	}

	if v, ok := d.GetOk("snapshot_window"); ok {
		req.SnapshotWindow = aws.String(v.(string))
	}

	if v, ok := d.GetOk("maintenance_window"); ok {
		req.PreferredMaintenanceWindow = aws.String(v.(string))
	}

	if v, ok := d.GetOk("notification_topic_arn"); ok {
		req.NotificationTopicArn = aws.String(v.(string))
	}

	snaps := d.Get("snapshot_arns").(*schema.Set).List()
	if len(snaps) > 0 {
		s := expandStringList(snaps)
		req.SnapshotArns = s
		log.Printf("[DEBUG] Restoring Redis cluster from S3 snapshot: %#v", s)
	}

	if v, ok := d.GetOk("snapshot_name"); ok {
		req.SnapshotName = aws.String(v.(string))
	}

	if v, ok := d.GetOk("az_mode"); ok {
		req.AZMode = aws.String(v.(string))
	}

	if v, ok := d.GetOk("availability_zone"); ok {
		req.PreferredAvailabilityZone = aws.String(v.(string))
	}

	preferred_azs := d.Get("availability_zones").(*schema.Set).List()
	if len(preferred_azs) > 0 {
		azs := expandStringList(preferred_azs)
		req.PreferredAvailabilityZones = azs
	}

	if v, ok := d.GetOk("replication_group_id"); ok {
		req.ReplicationGroupId = aws.String(v.(string))
	}

	resp, err := conn.CreateCacheCluster(req)
	if err != nil {
		return fmt.Errorf("Error creating Elasticache: %s", err)
	}

	// Assign the cluster id as the resource ID
	// Elasticache always retains the id in lower case, so we have to
	// mimic that or else we won't be able to refresh a resource whose
	// name contained uppercase characters.
	d.SetId(strings.ToLower(*resp.CacheCluster.CacheClusterId))

	pending := []string{"creating", "modifying", "restoring", "snapshotting"}
	stateConf := &resource.StateChangeConf{
		Pending:    pending,
		Target:     []string{"available"},
		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
		Delay:      30 * time.Second,
	}

	log.Printf("[DEBUG] Waiting for state to become available: %v", d.Id())
	_, sterr := stateConf.WaitForState()
	if sterr != nil {
		return fmt.Errorf("Error waiting for elasticache (%s) to be created: %s", d.Id(), sterr)
	}

	return resourceAwsElasticacheClusterRead(d, meta)
}

func resourceAwsElasticacheClusterRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticacheconn
	req := &elasticache.DescribeCacheClustersInput{
		CacheClusterId:    aws.String(d.Id()),
		ShowCacheNodeInfo: aws.Bool(true),
	}

	res, err := conn.DescribeCacheClusters(req)
	if err != nil {
		if eccErr, ok := err.(awserr.Error); ok && eccErr.Code() == "CacheClusterNotFound" {
			log.Printf("[WARN] ElastiCache Cluster (%s) not found", d.Id())
			d.SetId("")
			return nil
		}

		return err
	}

	if len(res.CacheClusters) == 1 {
		c := res.CacheClusters[0]
		d.Set("cluster_id", c.CacheClusterId)
		d.Set("node_type", c.CacheNodeType)
		d.Set("num_cache_nodes", c.NumCacheNodes)
		d.Set("engine", c.Engine)
		d.Set("engine_version", c.EngineVersion)
		if c.ConfigurationEndpoint != nil {
			d.Set("port", c.ConfigurationEndpoint.Port)
			d.Set("configuration_endpoint", aws.String(fmt.Sprintf("%s:%d", *c.ConfigurationEndpoint.Address, *c.ConfigurationEndpoint.Port)))
			d.Set("cluster_address", aws.String(fmt.Sprintf("%s", *c.ConfigurationEndpoint.Address)))
		}

		if c.ReplicationGroupId != nil {
			d.Set("replication_group_id", c.ReplicationGroupId)
		}

		d.Set("subnet_group_name", c.CacheSubnetGroupName)
		d.Set("security_group_names", flattenElastiCacheSecurityGroupNames(c.CacheSecurityGroups))
		d.Set("security_group_ids", flattenElastiCacheSecurityGroupIds(c.SecurityGroups))
		if c.CacheParameterGroup != nil {
			d.Set("parameter_group_name", c.CacheParameterGroup.CacheParameterGroupName)
		}
		d.Set("maintenance_window", c.PreferredMaintenanceWindow)
		d.Set("snapshot_window", c.SnapshotWindow)
		d.Set("snapshot_retention_limit", c.SnapshotRetentionLimit)
		if c.NotificationConfiguration != nil {
			if *c.NotificationConfiguration.TopicStatus == "active" {
				d.Set("notification_topic_arn", c.NotificationConfiguration.TopicArn)
			}
		}
		d.Set("availability_zone", c.PreferredAvailabilityZone)
		if *c.PreferredAvailabilityZone == "Multiple" {
			d.Set("az_mode", "cross-az")
		} else {
			d.Set("az_mode", "single-az")
		}

		if err := setCacheNodeData(d, c); err != nil {
			return err
		}
		// list tags for resource
		// set tags
		arn, err := buildECARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
		if err != nil {
			log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not setting Tags for cluster %s", *c.CacheClusterId)
		} else {
			resp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{
				ResourceName: aws.String(arn),
			})

			if err != nil {
				log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn)
			}

			var et []*elasticache.Tag
			if len(resp.TagList) > 0 {
				et = resp.TagList
			}
			d.Set("tags", tagsToMapEC(et))
		}
	}

	return nil
}

func resourceAwsElasticacheClusterUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticacheconn
	arn, err := buildECARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
	if err != nil {
		log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not updating Tags for cluster %s", d.Id())
	} else {
		if err := setTagsEC(conn, d, arn); err != nil {
			return err
		}
	}

	req := &elasticache.ModifyCacheClusterInput{
		CacheClusterId:   aws.String(d.Id()),
		ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)),
	}

	requestUpdate := false
	if d.HasChange("security_group_ids") {
		if attr := d.Get("security_group_ids").(*schema.Set); attr.Len() > 0 {
			req.SecurityGroupIds = expandStringList(attr.List())
			requestUpdate = true
		}
	}

	if d.HasChange("parameter_group_name") {
		req.CacheParameterGroupName = aws.String(d.Get("parameter_group_name").(string))
		requestUpdate = true
	}

	if d.HasChange("maintenance_window") {
		req.PreferredMaintenanceWindow = aws.String(d.Get("maintenance_window").(string))
		requestUpdate = true
	}

	if d.HasChange("notification_topic_arn") {
		v := d.Get("notification_topic_arn").(string)
		req.NotificationTopicArn = aws.String(v)
		if v == "" {
			inactive := "inactive"
			req.NotificationTopicStatus = &inactive
		}
		requestUpdate = true
	}

	if d.HasChange("engine_version") {
		req.EngineVersion = aws.String(d.Get("engine_version").(string))
		requestUpdate = true
	}

	if d.HasChange("snapshot_window") {
		req.SnapshotWindow = aws.String(d.Get("snapshot_window").(string))
		requestUpdate = true
	}

	if d.HasChange("node_type") {
		req.CacheNodeType = aws.String(d.Get("node_type").(string))
		requestUpdate = true
	}

	if d.HasChange("snapshot_retention_limit") {
		req.SnapshotRetentionLimit = aws.Int64(int64(d.Get("snapshot_retention_limit").(int)))
		requestUpdate = true
	}

	if d.HasChange("az_mode") {
		req.AZMode = aws.String(d.Get("az_mode").(string))
		requestUpdate = true
	}

	if d.HasChange("num_cache_nodes") {
		oraw, nraw := d.GetChange("num_cache_nodes")
		o := oraw.(int)
		n := nraw.(int)
		if v, ok := d.GetOk("az_mode"); ok && v.(string) == "cross-az" && n == 1 {
			return fmt.Errorf("[WARN] Error updateing Elasticache cluster (%s), error: Cross-AZ mode is not supported in a single cache node.", d.Id())
		}
		if n < o {
			log.Printf("[INFO] Cluster %s is marked for Decreasing cache nodes from %d to %d", d.Id(), o, n)
			nodesToRemove := getCacheNodesToRemove(d, o, o-n)
			req.CacheNodeIdsToRemove = nodesToRemove
		}

		req.NumCacheNodes = aws.Int64(int64(d.Get("num_cache_nodes").(int)))
		requestUpdate = true

	}

	if requestUpdate {
		log.Printf("[DEBUG] Modifying ElastiCache Cluster (%s), opts:\n%s", d.Id(), req)
		_, err := conn.ModifyCacheCluster(req)
		if err != nil {
			return fmt.Errorf("[WARN] Error updating ElastiCache cluster (%s), error: %s", d.Id(), err)
		}

		log.Printf("[DEBUG] Waiting for update: %s", d.Id())
		pending := []string{"modifying", "rebooting cache cluster nodes", "snapshotting"}
		stateConf := &resource.StateChangeConf{
			Pending:    pending,
			Target:     []string{"available"},
			Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
			Timeout:    80 * time.Minute,
			MinTimeout: 10 * time.Second,
			Delay:      30 * time.Second,
		}

		_, sterr := stateConf.WaitForState()
		if sterr != nil {
			return fmt.Errorf("Error waiting for elasticache (%s) to update: %s", d.Id(), sterr)
		}
	}

	return resourceAwsElasticacheClusterRead(d, meta)
}

func getCacheNodesToRemove(d *schema.ResourceData, oldNumberOfNodes int, cacheNodesToRemove int) []*string {
	nodesIdsToRemove := []*string{}
	for i := oldNumberOfNodes; i > oldNumberOfNodes-cacheNodesToRemove && i > 0; i-- {
		s := fmt.Sprintf("%04d", i)
		nodesIdsToRemove = append(nodesIdsToRemove, &s)
	}

	return nodesIdsToRemove
}

func setCacheNodeData(d *schema.ResourceData, c *elasticache.CacheCluster) error {
	sortedCacheNodes := make([]*elasticache.CacheNode, len(c.CacheNodes))
	copy(sortedCacheNodes, c.CacheNodes)
	sort.Sort(byCacheNodeId(sortedCacheNodes))

	cacheNodeData := make([]map[string]interface{}, 0, len(sortedCacheNodes))

	for _, node := range sortedCacheNodes {
		if node.CacheNodeId == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil || node.CustomerAvailabilityZone == nil {
			return fmt.Errorf("Unexpected nil pointer in: %s", node)
		}
		cacheNodeData = append(cacheNodeData, map[string]interface{}{
			"id":                *node.CacheNodeId,
			"address":           *node.Endpoint.Address,
			"port":              int(*node.Endpoint.Port),
			"availability_zone": *node.CustomerAvailabilityZone,
		})
	}

	return d.Set("cache_nodes", cacheNodeData)
}

type byCacheNodeId []*elasticache.CacheNode

func (b byCacheNodeId) Len() int      { return len(b) }
func (b byCacheNodeId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byCacheNodeId) Less(i, j int) bool {
	return b[i].CacheNodeId != nil && b[j].CacheNodeId != nil &&
		*b[i].CacheNodeId < *b[j].CacheNodeId
}

func resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticacheconn

	req := &elasticache.DeleteCacheClusterInput{
		CacheClusterId: aws.String(d.Id()),
	}
	err := resource.Retry(5*time.Minute, func() *resource.RetryError {
		_, err := conn.DeleteCacheCluster(req)
		if err != nil {
			awsErr, ok := err.(awserr.Error)
			// The cluster may be just snapshotting, so we retry until it's ready for deletion
			if ok && awsErr.Code() == "InvalidCacheClusterState" {
				return resource.RetryableError(err)
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Waiting for deletion: %v", d.Id())
	stateConf := &resource.StateChangeConf{
		Pending:    []string{"creating", "available", "deleting", "incompatible-parameters", "incompatible-network", "restore-failed", "snapshotting"},
		Target:     []string{},
		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "", []string{}),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
		Delay:      30 * time.Second,
	}

	_, sterr := stateConf.WaitForState()
	if sterr != nil {
		return fmt.Errorf("Error waiting for elasticache (%s) to delete: %s", d.Id(), sterr)
	}

	d.SetId("")

	return nil
}

func cacheClusterStateRefreshFunc(conn *elasticache.ElastiCache, clusterID, givenState string, pending []string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		resp, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{
			CacheClusterId:    aws.String(clusterID),
			ShowCacheNodeInfo: aws.Bool(true),
		})
		if err != nil {
			apierr := err.(awserr.Error)
			log.Printf("[DEBUG] message: %v, code: %v", apierr.Message(), apierr.Code())
			if apierr.Message() == fmt.Sprintf("CacheCluster not found: %v", clusterID) {
				log.Printf("[DEBUG] Detect deletion")
				return nil, "", nil
			}

			log.Printf("[ERROR] CacheClusterStateRefreshFunc: %s", err)
			return nil, "", err
		}

		if len(resp.CacheClusters) == 0 {
			return nil, "", fmt.Errorf("[WARN] Error: no Cache Clusters found for id (%s)", clusterID)
		}

		var c *elasticache.CacheCluster
		for _, cluster := range resp.CacheClusters {
			if *cluster.CacheClusterId == clusterID {
				log.Printf("[DEBUG] Found matching ElastiCache cluster: %s", *cluster.CacheClusterId)
				c = cluster
			}
		}

		if c == nil {
			return nil, "", fmt.Errorf("[WARN] Error: no matching Elastic Cache cluster for id (%s)", clusterID)
		}

		log.Printf("[DEBUG] ElastiCache Cluster (%s) status: %v", clusterID, *c.CacheClusterStatus)

		// return the current state if it's in the pending array
		for _, p := range pending {
			log.Printf("[DEBUG] ElastiCache: checking pending state (%s) for cluster (%s), cluster status: %s", pending, clusterID, *c.CacheClusterStatus)
			s := *c.CacheClusterStatus
			if p == s {
				log.Printf("[DEBUG] Return with status: %v", *c.CacheClusterStatus)
				return c, p, nil
			}
		}

		// return given state if it's not in pending
		if givenState != "" {
			log.Printf("[DEBUG] ElastiCache: checking given state (%s) of cluster (%s) against cluster status (%s)", givenState, clusterID, *c.CacheClusterStatus)
			// check to make sure we have the node count we're expecting
			if int64(len(c.CacheNodes)) != *c.NumCacheNodes {
				log.Printf("[DEBUG] Node count is not what is expected: %d found, %d expected", len(c.CacheNodes), *c.NumCacheNodes)
				return nil, "creating", nil
			}

			log.Printf("[DEBUG] Node count matched (%d)", len(c.CacheNodes))
			// loop the nodes and check their status as well
			for _, n := range c.CacheNodes {
				log.Printf("[DEBUG] Checking cache node for status: %s", n)
				if n.CacheNodeStatus != nil && *n.CacheNodeStatus != "available" {
					log.Printf("[DEBUG] Node (%s) is not yet available, status: %s", *n.CacheNodeId, *n.CacheNodeStatus)
					return nil, "creating", nil
				}
				log.Printf("[DEBUG] Cache node not in expected state")
			}
			log.Printf("[DEBUG] ElastiCache returning given state (%s), cluster: %s", givenState, c)
			return c, givenState, nil
		}
		log.Printf("[DEBUG] current status: %v", *c.CacheClusterStatus)
		return c, *c.CacheClusterStatus, nil
	}
}

func buildECARN(identifier, partition, accountid, region string) (string, error) {
	if partition == "" {
		return "", fmt.Errorf("Unable to construct ElastiCache ARN because of missing AWS partition")
	}
	if accountid == "" {
		return "", fmt.Errorf("Unable to construct ElastiCache ARN because of missing AWS Account ID")
	}
	arn := fmt.Sprintf("arn:%s:elasticache:%s:%s:cluster:%s", partition, region, accountid, identifier)
	return arn, nil

}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'spec'
require 'spec/autorun'

require 'rubygems'
require 'ruby-debug'

require 'astrails/safe'

Spec::Runner.configure do |config|
  config.mock_with :rr
end

redpajama_set_name: RedPajamaGithub


text:
#include "profile.h"

#include <kdbhelper.h>

#include <kdb.h>     //actual namespaces
#include <kdbease.h> //elektraKeyGetRelativeName
#include <kdbos.h>   //elektraNamespace
#include <stdio.h>
#include <string.h>

#include <fnmatch.h>

#define PROFILEPATH "*/sw/*/*/#*/profile"
#define CURRENTPATH "*/sw/*/*/#*/current"

int elektraProfileOpen (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// plugin initialization logic
	KeySet * appendedKeys = NULL;
	elektraPluginSetData (handle, appendedKeys);
	return 1; // success
}

int elektraProfileClose (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// free all plugin resources and shut it down
	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (appendedKeys) ksDel (appendedKeys);
	return 1; // success
}

static Key * keyDupWithNS (const Key * origKey, elektraNamespace ns)
{
	Key * newKey = NULL;
	switch (ns)
	{
	case KEY_NS_SPEC:
		newKey = keyNew ("spec:/", KEY_END);
		break;
	case KEY_NS_DIR:
		newKey = keyNew ("dir:/", KEY_END);
		break;
	case KEY_NS_USER:
		newKey = keyNew ("user:/", KEY_END);
		break;
	case KEY_NS_SYSTEM:
		newKey = keyNew ("system:/", KEY_END);
		break;
	case KEY_NS_PROC:
		newKey = keyNew ("proc:/", KEY_END);
		break;
	case KEY_NS_META:
		newKey = keyNew ("meta:/", KEY_END);
		break;
	case KEY_NS_DEFAULT:
		newKey = keyNew ("default:/", KEY_END);
		break;
	case KEY_NS_CASCADING:
	default:
		newKey = keyNew ("/", KEY_END);
		break;
	}
	const char * relativeName = keyName (origKey);
	char * nextPtr = NULL;
	if (keyName (origKey)[0] == '/')
		++relativeName;
	else if ((nextPtr = strchr (keyName (origKey), '/')))
		relativeName = (++nextPtr);
	keyAddName (newKey, relativeName);
	return newKey;
}

static void linkProfileKeys (KeySet * swKS, KeySet * profileKeys, KeySet * appendedKeys)
{
	Key * profileCutKey = NULL;
	Key * profileKey = NULL;
	const char * profileString = NULL;

	for (elektraCursor it = 0; it < ksGetSize (profileKeys); ++it)
	{
		profileKey = ksAtCursor (profileKeys, it);
		profileString = keyString (profileKey);
		if (profileString)
		{
			profileCutKey = keyDup (profileKey, KEY_CP_ALL);
			keyAddName (profileCutKey, "..");
			Key * currentProfileKey = keyDup (profileCutKey, KEY_CP_ALL);
			keyAddBaseName (currentProfileKey, "current");
			keyAddBaseName (profileCutKey, profileString);
			KeySet * profileKS = ksCut (swKS, profileCutKey);
			Key * cur;

			for (elektraCursor itProfileKS = 0; itProfileKS < ksGetSize (profileKS); ++itProfileKS)
			{
				cur = ksAtCursor (profileKS, itProfileKS);
				if (!strcmp (keyName (cur), keyName (profileCutKey))) continue;
				Key * overrideKey = keyDupWithNS (currentProfileKey, KEY_NS_SPEC);
				const char * relativeName = elektraKeyGetRelativeName (cur, profileCutKey);
				keyAddName (overrideKey, relativeName);
				Key * lookupKey = keyDupWithNS (overrideKey, keyGetNamespace (currentProfileKey));
				if (ksLookup (swKS, lookupKey, KDB_O_NONE))
				{
					keyDel (lookupKey);
					keyDel (overrideKey);
					continue;
				}
				keyDel (lookupKey);
				keySetMeta (overrideKey, "override/#0", keyName (cur));
				ksAppendKey (swKS, keyDup (overrideKey, KEY_CP_ALL));
				ksAppendKey (appendedKeys, keyDup (overrideKey, KEY_CP_ALL));
				keyDel (overrideKey);
			}
			keyDel (currentProfileKey);
			keyDel (profileCutKey);
			ksAppend (swKS, profileKS);
			ksDel (profileKS);
		}
	}
}

static void linkDefaultKeys (KeySet * swKS, KeySet * profileParents, KeySet * appendedKeys)
{
	Key * profileParent = NULL;

	for (elektraCursor it = 0; it < ksGetSize (profileParents); ++it)
	{
		profileParent = ksAtCursor (profileParents, it);
		Key * defaultCutKey = keyDup (profileParent, KEY_CP_ALL);
		keyAddName (defaultCutKey, "%");
		KeySet * defaultKS = ksCut (swKS, defaultCutKey);
		Key * cur;
		Key * currentProfileKey = keyDup (profileParent, KEY_CP_ALL);
		keyAddName (currentProfileKey, "current");

		for (elektraCursor itDefaultKS = 0; itDefaultKS < ksGetSize (defaultKS); ++itDefaultKS)
		{
			cur = ksAtCursor (defaultKS, itDefaultKS);
			if (!strcmp (keyName (cur), keyName (defaultCutKey))) continue;
			const char * relativeName = elektraKeyGetRelativeName (cur, defaultCutKey);
			Key * overrideKey = keyDupWithNS (currentProfileKey, KEY_NS_SPEC);
			keyAddName (overrideKey, relativeName);
			Key * existingKey = keyDupWithNS (overrideKey, keyGetNamespace (profileParent));
			if (ksLookup (swKS, overrideKey, KDB_O_NONE) || ksLookup (swKS, existingKey, KDB_O_NONE))
			{
				keyDel (overrideKey);
				keyDel (existingKey);
				continue;
			}
			keyDel (existingKey);
			keySetMeta (overrideKey, "override/#0", keyName (cur));
			ksAppendKey (swKS, keyDup (overrideKey, KEY_CP_ALL));
			ksAppendKey (appendedKeys, keyDup (overrideKey, KEY_CP_ALL));
			keyDel (overrideKey);
		}
		keyDel (currentProfileKey);
		keyDel (defaultCutKey);
		ksAppend (swKS, defaultKS);
		ksDel (defaultKS);
	}
}

int elektraProfileGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	if (!elektraStrCmp (keyName (parentKey), "system:/elektra/modules/profile"))
	{
		KeySet * contract =
			ksNew (30, keyNew ("system:/elektra/modules/profile", KEY_VALUE, "profile plugin waits for your orders", KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports", KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports/open", KEY_FUNC, elektraProfileOpen, KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports/close", KEY_FUNC, elektraProfileClose, KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports/get", KEY_FUNC, elektraProfileGet, KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports/set", KEY_FUNC, elektraProfileSet, KEY_END),
			       keyNew ("system:/elektra/modules/profile/exports/error", KEY_FUNC, elektraProfileError, KEY_END),
#include ELEKTRA_README
			       keyNew ("system:/elektra/modules/profile/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, contract);
		ksDel (contract);

		return 1; // success
	}
	// get all keys
	Key * swKey = keyNew ("/sw", KEY_END);
	KeySet * swKS = ksCut (returned, swKey);
	keyDel (swKey);
	Key * cur;

	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (!appendedKeys) appendedKeys = ksNew (0, KS_END);
	KeySet * profileKeys = ksNew (0, KS_END);

	for (elektraCursor it = 0; it < ksGetSize (swKS); ++it)
	{
		cur = ksAtCursor (swKS, it);
		if (!fnmatch (PROFILEPATH, keyName (cur), FNM_PATHNAME))
		{
			ksAppendKey (profileKeys, cur);
		}
	}
	linkProfileKeys (swKS, profileKeys, appendedKeys);
	ksDel (profileKeys);
	ksDel (appendedKeys);
	KeySet * profileParents = ksNew (0, KS_END);

	for (elektraCursor it = 0; it < ksGetSize (swKS); ++it)
	{
		cur = ksAtCursor (swKS, it);
		if (!fnmatch (CURRENTPATH, keyName (cur), FNM_PATHNAME))
		{
			Key * profileParent = keyDup (cur, KEY_CP_ALL);
			keyAddName (profileParent, "..");
			ksAppendKey (profileParents, keyDup (profileParent, KEY_CP_ALL));
			keyDel (profileParent);
		}
	}
	linkDefaultKeys (swKS, profileParents, appendedKeys);
	ksDel (profileParents);
	ksAppend (returned, swKS);
	ksDel (swKS);

	return 1; // success
}

int elektraProfileSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// get all keys
	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (!appendedKeys) return 1;
	Key * cur;

	for (elektraCursor it = 0; it < ksGetSize (appendedKeys); ++it)
	{
		cur = ksAtCursor (appendedKeys, it);
		keyDel (ksLookup (returned, cur, KDB_O_POP));
	}
	ksDel (appendedKeys);
	elektraPluginSetData (handle, NULL);
	return 1; // success
}

int elektraProfileError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// set all keys

	return 1; // success
}

Plugin * ELEKTRA_PLUGIN_EXPORT
{
	// clang-format off
	return elektraPluginExport ("profile",
			ELEKTRA_PLUGIN_OPEN,	&elektraProfileOpen,
			ELEKTRA_PLUGIN_CLOSE,	&elektraProfileClose,
			ELEKTRA_PLUGIN_GET,	&elektraProfileGet,
			ELEKTRA_PLUGIN_SET,	&elektraProfileSet,
			ELEKTRA_PLUGIN_ERROR,	&elektraProfileError,
			ELEKTRA_PLUGIN_END);
}


text:
class CreateExtents < ActiveRecord::Migration
  def change
    create_table :extents do |t|
      t.string :name, :null => false
      t.text :display_name
      t.text :note
      t.integer :position

      t.timestamps
    end
  end
end


text:
package javax.net.ssl;

/**
 * The interface to be used to provide hostname verification functionality.
 * <p>
 * This is an extended verification option that implementers can provide. It is to be used
 * during a handshake if the URL's hostname does not match the peer's
 * identification hostname.
 */
public interface HostnameVerifier {
    /**
     * Verifies that the specified hostname is allowed within the specified SSL
     * session.
     *
     * @param hostname
     *            the hostname.
     * @param session
     *            the SSL session of the connection.
     * @return {@code true} if the specified hostname is allowed, otherwise
     *         {@code false}.
     */
    boolean verify(String hostname, SSLSession session);
}


text:
<?php

require 'framework/app/webroot/index.php';

?>


text:
/**
 * Created by RSutcliffe on 5/25/17.
 * gulp Gulp.js configuration for basic web page testing
 * and node
 *
 * Steps for new machine/proj:
 * install gulp globally: npm install gulp-cli -g
 * install browserify globally: npm install browserify -g
 * install sass compiler globally: npm install node-sass -g
 * install http-server globally (optional): npm install http-server -g
 *
 * This gulp project setup is based on/ inspired by other gulp solutions below:
 * https://wehavefaces.net/gulp-browserify-the-gulp-y-way-bb359b3f9623
 * https://slicejack.com/introduction-to-postcss/
 * https://code.tutsplus.com/tutorials/gulp-as-a-development-web-server--cms-20903
 */

//module variables
var gulp = require('gulp'),
    fs = require('fs'),
    glob = require('glob'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    deporder = require('gulp-deporder'), //https://github.com/mkleehammer/gulp-deporder
    stripdebug = require('gulp-strip-debug'), //https://www.npmjs.com/package/gulp-strip-debug
    uglify = require('gulp-uglify'),
    strreamify = require('gulp-streamify'), //https://github.com/nfroidure/gulp-streamify
    htmlclean = require('gulp-htmlclean'),
    sass = require('gulp-sass'), //https://github.com/dlmanning/gulp-sass
    postcss = require('gulp-postcss'),
    //PostCSS Plugins (http://postcss.org/)
    cssimport = require('postcss-import'), //merge css w import statements
    cssnano = require('cssnano'),  //minify css files
    autoprefixer = require('autoprefixer'), //auto-prefix with vendor specifics

    runseq = require('run-sequence'), //https://www.npmjs.com/package/run-sequence
    gulpif = require('gulp-if'),
    replace = require('gulp-replace'), //https://www.npmjs.com/package/gulp-replace
    rev = require('gulp-rev'), //https://www.npmjs.com/package/gulp-rev
    watch = require('gulp-watch'), //https://www.npmjs.com/package/gulp-watch
    browserify = require('browserify'), //https://www.npmjs.com/package/gulp-cache-bust
    connect = require('gulp-connect'), //https://www.npmjs.com/package/gulp-connect
    source = require('vinyl-source-stream'), //https://www.viget.com/articles/gulp-browserify-starter-faq
    transform = require('vinyl-transform'),
    buffer = require('vinyl-buffer'), // https://www.npmjs.com/package/vinyl-buffer
    mustache= require('gulp-mustache'), // https://www.npmjs.com/package/gulp-mustache
    isProd = false,

    // folders
    folder = { src: 'src/', build: 'build/'};
var mainjsfile = "main.js"
var mymanifestfile = 'build/rev-manifest.json';

if(process.argv[process.argv.length-1] == '--prod' || process.argv[process.argv.length-1] == '--production'){
  console.log("running in prod mode")
  isProd = true
}
else {
  console.log("running in dev mode")
}
//########################################

gulp.task('build', function(cb) {
  //build is set to run js & css tasks first, then html.
  runseq('js','css', 'html', cb)

})
gulp.task('default', ['build', 'watch']) ; //plain ol' terminal gulp will build & watch for changes

gulp.task('web', ['build', 'webserver', 'watch']) //gulp web will build & watch AND set up webserver

// HTML processing
gulp.task('html', function() {
  var out = folder.build + "html"
  console.log("output folder is: " + out)
  return gulp.src(folder.src + 'html/**/*')
      .pipe(newer(out))
      .pipe(mustache(parseManifest(mymanifestfile),{},{}))
      .pipe(gulpif(isProd, htmlclean())) // minify code if production
      .pipe(gulp.dest(out))
      .pipe(connect.reload());
});

gulp.task("js", function () {
  //delete existing built js file
  if(fs.existsSync(mymanifestfile)){
    var oldfile = findValueInManifest(mainjsfile, mymanifestfile)
    if(oldfile != null){
      try {guk
        fs.unlinkSync('build/js/' + oldfile);
        console.log('successfully deleted build/js/' + oldfile);
      } catch(err) {
        console.log('could not delete file (does it exist?)' + oldfile)
      }
    }
  }

  var files = glob.sync(folder.src + 'js/**/*.js');
  return gulpif(isProd,browserify(files), browserify(files, {debug:true}))
        .bundle()
        .pipe(source(mainjsfile))
        .pipe(buffer())
        .pipe(gulpif(isProd, stripdebug()))
        .pipe(gulpif(isProd,uglify()))
        .pipe(rev()) //cache busting
        .pipe(gulp.dest('./build/js/'))
        .pipe(rev.manifest('build/rev-manifest.json', {base: './build', merge: true}))
        .pipe(gulp.dest('./build'))
        .pipe(connect.reload())
        .on("end", function(){
          if(oldfile != undefined){
            var newfile = findValueInManifest(parseKeyFromValue(oldfile), mymanifestfile) //this isn't getting new file
            console.log("the new file is: " + newfile)
            gulp.src(folder.build + 'html/**/*.html')
              .pipe(replace(oldfile, newfile))
              .pipe(gulp.dest('build/html'));
          }
  });
});

gulp.task('css', function () {
  /**
   * SASS/CSS files are organized as per here:
   * http://thesassway.com/beginner/how-to-structure-a-sass-project
   * Modules, Partials, Vendored Stylesheets
   *
   * the idea is that there is already 1 central css file that
   * imports everything so we do not need to loop through the css
   * folder directory
   *
   */
  //delete previously built css file
  if(fs.existsSync(mymanifestfile)){
    var oldfile = findValueInManifest('main.css', mymanifestfile)
    if(oldfile != null){
      try {
        fs.unlinkSync('build/css/' + oldfile);
        console.log('successfully deleted build/css/' + oldfile);
      } catch(err) {
        console.log('could not delete file (does it exist?) ' + oldfile);
      }
    }
  }
  var plugins = [
    cssimport,
    autoprefixer,
	  cssnano];

  //var files = glob.sync(folder.src + 'css/*.sass');
  var cssbuild = gulp.src(folder.src + 'css/main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss(plugins))
        .pipe(rev()) //cache busting
        .pipe(gulp.dest('./build/css/'))
        .pipe(rev.manifest('build/rev-manifest.json',{base: './build', merge: true}))
  return cssbuild.pipe(gulp.dest('./build'))

    .on('end', function(){
      if(oldfile != undefined){
        var newfile = findValueInManifest(parseKeyFromValue(oldfile), mymanifestfile)
        console.log("the new css file is: " + newfile)
        gulp.src(folder.build + 'html/**/*.html')
          .pipe(replace(oldfile, newfile))
          .pipe(gulp.dest('build/html'))
          .pipe(connect.reload());
      }
    })
});

// watch for changes (need to configure longer delay)
gulp.task('watch', function() {
  //html changes
  gulp.watch(folder.src + 'html/**/*', ['html']);
  // javascript changes
  gulp.watch(folder.src + 'js/**/*', ['js']);
  // css changes
  gulp.watch(folder.src + 'css/**/*', ['css']);
  return
});

//start a basic http webserver for testing
gulp.task('webserver', function() {
  connect.server({
    root: 'build',
    index: 'html\index.html',
    livereload: true
  });
});
//###########################################

function parseManifest(jsonfile){
  /**
 * Support function for gulp. Should probably
 * be its own module.
 *
 * Description: Parses, manifest file to a
 * mustache friendly json object
 */
    var manifest = JSON.parse(fs.readFileSync(jsonfile, 'utf8'));
    var newobj = {}
    for (var key in manifest){
        if (manifest.hasOwnProperty(key)) {
            // do stuff
            console.log(manifest[key])
            mainname = key.substring(0,key.indexOf('.'))
            suffixname = key.substring(key.indexOf('.')+1, key.length)
            if(!newobj.hasOwnProperty(mainname)){
                newobj[mainname] = {}
            }
            var subprop = newobj[mainname]
            subprop[suffixname] = manifest[key]
        }
    }

    return newobj
}

function findValueInManifest(key, jsonfile){
  var manifest = JSON.parse(fs.readFileSync(jsonfile, 'utf8'));
    if (manifest.hasOwnProperty(key)) {
      return manifest[key]
    }
    else { return null}
}

function parseKeyFromValue(value){
 /**
  * Take a |value| like main-1ceb2A4hl93f.js
  * and return |key| like main.js
  */

  var res = value.split("-");
  var name = "";
  for (i = 0; i < res.length -1; i++){
    name += res[i] + "-";
  }
  var suffix = value.split('.').pop();
  name = name.slice(0, -1) + "." + suffix;
  return name;
}


text:
/**
 * @license Angular v0.10.0
 * (c) 2010-2019 Google LLC. https://angular.io/
 * License: MIT
 */
!function(t){"function"==typeof define&&define.amd?define(t):t()}(function(){"use strict";
/**
     * @license
     * Copyright Google Inc. All Rights Reserved.
     *
     * Use of this source code is governed by an MIT-style license that can be
     * found in the LICENSE file at https://angular.io/license
     */Zone.__load_patch("notification",function(t,o,e){var n=t.Notification;if(n&&n.prototype){var i=Object.getOwnPropertyDescriptor(n.prototype,"onerror");i&&i.configurable&&e.patchOnProperties(n.prototype,null)}})});


text:
<template name="introduction">

Hello

      This is a music machine, developed according to the specifications given on this page -- namely:

Clear navigation allowing the user to move between pages and locate relevant information

Consistent style across the pages through the use of CSS

Responsive layout where the layout changes depending on the size of the browser window

Use of Bootstrap

Clearly stated purpose for each page

Clear landing page (this page :-)

At least 8 different tracks of audio and at least 2 sliders per track, mapped to 2 specific audio features.

      To give it a go, go to the playground, turn on the DAC, and play around with the tracks.

      Also, have a friend connect from another browser window and make music collaboratively! (Your actions will be instantly shared, except for controlling the DAC which is local to each user).

      Finally, if you want to use your own sounds, simply place them somewhere in the public/samples directory of the app. The server automatically adds any .wav files it finds there when it starts.

      Hope you enjoy it.. Have fun!

      Technical small-print:

JS libraries used: maxim.js

Meteor packages used: es5-shim, ecmascript, iron:router, twbs:bootstrap, random, jiku:bootstrap-toggle, fortawesome:fontawesome

</template>


text:
<?php

namespace AppBundle\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class CustomerAdmin extends AbstractAdmin
{
    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('customer_number', 'entity', ['label' => 'Kundennummer'])
            ->add('prefix', 'text', ['label' => 'Namensvorsatz'])
            ->add('firstname', 'text', ['label' => 'Vorname'])
            ->add('lastname', 'text', ['label' => 'Nachname']);
    }

    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('customer_number')
            ->add('firstname')
            ->add('lastname');
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('customer_number')
            ->addIdentifier('firstname')
            ->addIdentifier('lastname')
            ->addIdentifier('created_at')
            ->addIdentifier('updated_at')
        ;
    }

    /**
     * @param mixed $customer
     */
    public function prePersist($customer)
    {
        $customer->setCreatedAt(new \DateTime('now'));
        $customer->setUpdatedAt(new \DateTime('now'));
    }

    /**
     * @param mixed $customer
     */
    public function preUpdate($customer)
    {
        $customer->setUpdatedAt(new \DateTime('now'));
    }
}


text:
'''An example of linked panning with three scatter plots.

.. bokeh-example-metadata::
    :apis: bokeh.plotting.Figure.scatter
    :refs: :ref:`ug_basic_scatters_markers`
    :keywords: scatter, linked panning

'''
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show

x = list(range(21))
y0 = x
y1 = [20-xx for xx in x]
y2 = [abs(xx-10) for xx in x]

# create a new plot
s1 = figure(width=250, height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)

# create a new plot and share both ranges
s2 = figure(width=250, height=250, x_range=s1.x_range, y_range=s1.y_range, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

# create a new plot and share only one range
s3 = figure(width=250, height=250, x_range=s1.x_range, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)

p = gridplot([[s1, s2, s3]], toolbar_location=None)

show(p)


text:
package org.jfree.ui;

import java.awt.Component;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

public class SortButtonRenderer implements TableCellRenderer {
    public static final int DOWN = 1;
    public static final int NONE = 0;
    public static final int UP = 2;
    private JButton ascendingButton;
    private JLabel ascendingLabel;
    private JButton descendingButton;
    private JLabel descendingLabel;
    private JButton normalButton;
    private JLabel normalLabel;
    private int pressedColumn;
    private boolean useLabels;

    public SortButtonRenderer() {
        this.pressedColumn = -1;
        this.pressedColumn = -1;
        this.useLabels = UIManager.getLookAndFeel().getID().equals("Aqua");
        Border border = UIManager.getBorder("TableHeader.cellBorder");
        if (this.useLabels) {
            this.normalLabel = new JLabel();
            this.normalLabel.setHorizontalAlignment(10);
            this.ascendingLabel = new JLabel();
            this.ascendingLabel.setHorizontalAlignment(10);
            this.ascendingLabel.setHorizontalTextPosition(UP);
            this.ascendingLabel.setIcon(new BevelArrowIcon(DOWN, false, false));
            this.descendingLabel = new JLabel();
            this.descendingLabel.setHorizontalAlignment(10);
            this.descendingLabel.setHorizontalTextPosition(UP);
            this.descendingLabel.setIcon(new BevelArrowIcon(NONE, false, false));
            this.normalLabel.setBorder(border);
            this.ascendingLabel.setBorder(border);
            this.descendingLabel.setBorder(border);
            return;
        }
        this.normalButton = new JButton();
        this.normalButton.setMargin(new Insets(NONE, NONE, NONE, NONE));
        this.normalButton.setHorizontalAlignment(10);
        this.ascendingButton = new JButton();
        this.ascendingButton.setMargin(new Insets(NONE, NONE, NONE, NONE));
        this.ascendingButton.setHorizontalAlignment(10);
        this.ascendingButton.setHorizontalTextPosition(UP);
        this.ascendingButton.setIcon(new BevelArrowIcon(DOWN, false, false));
        this.ascendingButton.setPressedIcon(new BevelArrowIcon(DOWN, false, true));
        this.descendingButton = new JButton();
        this.descendingButton.setMargin(new Insets(NONE, NONE, NONE, NONE));
        this.descendingButton.setHorizontalAlignment(10);
        this.descendingButton.setHorizontalTextPosition(UP);
        this.descendingButton.setIcon(new BevelArrowIcon(NONE, false, false));
        this.descendingButton.setPressedIcon(new BevelArrowIcon(NONE, false, true));
        this.normalButton.setBorder(border);
        this.ascendingButton.setBorder(border);
        this.descendingButton.setBorder(border);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (table == null) {
            throw new NullPointerException("Table must not be null.");
        }
        JComponent component;
        SortableTableModel model = (SortableTableModel) table.getModel();
        int cc = table.convertColumnIndexToModel(column);
        boolean isSorting = model.getSortingColumn() == cc;
        boolean isAscending = model.isAscending();
        JTableHeader header = table.getTableHeader();
        boolean isPressed = cc == this.pressedColumn;
        if (this.useLabels) {
            JLabel label = getRendererLabel(isSorting, isAscending);
            label.setText(value == null ? "" : value.toString());
            component = label;
        } else {
            JButton button = getRendererButton(isSorting, isAscending);
            button.setText(value == null ? "" : value.toString());
            button.getModel().setPressed(isPressed);
            button.getModel().setArmed(isPressed);
            component = button;
        }
        if (header != null) {
            component.setForeground(header.getForeground());
            component.setBackground(header.getBackground());
            component.setFont(header.getFont());
        }
        return component;
    }

    private JButton getRendererButton(boolean isSorting, boolean isAscending) {
        if (!isSorting) {
            return this.normalButton;
        }
        if (isAscending) {
            return this.ascendingButton;
        }
        return this.descendingButton;
    }

    private JLabel getRendererLabel(boolean isSorting, boolean isAscending) {
        if (!isSorting) {
            return this.normalLabel;
        }
        if (isAscending) {
            return this.ascendingLabel;
        }
        return this.descendingLabel;
    }

    public void setPressedColumn(int column) {
        this.pressedColumn = column;
    }
}


text:
<?php

include_once('_init.php');

$title = "Login";

$content = "
	<form action='{$root_directory}/' method='post'>
		<input type='text' placeholder='Nutzername' name='username' />
		<input type='password' placeholder='Passwort' name='password' />
		<input type='submit' value='Anmelden' class='button' />
	</form>";

$content_class = "login";
$hide_navigation = true;

?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PronoFoot.Data.Model;

namespace PronoFoot.Business.Models
{
    public class FixtureModel
    {
        public int FixtureId { get; set; }
        public int DayId { get; set; }
        public DateTime Date { get; set; }
        public int HomeTeamId { get; set; }
        public int? HomeTeamGoals { get; set; }
        public int AwayTeamId { get; set; }
        public int? AwayTeamGoals { get; set; }

        public bool CanBeForecast
        {
            get { return TimeZoneInfo.ConvertTimeToUtc(this.Date, TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time")) > DateTime.UtcNow; }
        }

        public FixtureModel()
        {
        }

        public FixtureModel(Fixture fixture)
        {
            this.FixtureId = fixture.FixtureId;
            this.DayId = fixture.DayId;
            this.Date = fixture.Date;
            this.HomeTeamId = fixture.HomeTeamId;
            this.HomeTeamGoals = fixture.HomeTeamGoals;
            this.AwayTeamId = fixture.AwayTeamId;
            this.AwayTeamGoals = fixture.AwayTeamGoals;
        }
    }
}


text:
#ifndef LANTERN_CAMERA_H
#define LANTERN_CAMERA_H

#include "vector3.h"

namespace lantern
{
	/** Class representing camera in 3D world */
	class camera final
	{
	public:
		/** Constructs camera with specified params
		* @param position Initial camera position
		* @param forward Initial camera direction, might be not normalized
		* @param fake_up Fake up vector which will be used to construct the real up vector from the forward vector, might be not normalized
		* @param horizontal_fov Camera's horizontal field of view in radians
		* @param aspect_ratio Viewport aspect ratio, used to calculate vertical field of view
		* @param near_plane_z Near plane z-coordinate
		* @param far_plane_z Far plane z-coordinate
		*/
		camera(
			vector3f const& position,
			vector3f const& forward,
			vector3f const& fake_up,
			float const horizontal_fov,
			float const aspect_ratio,
			float const near_plane_z,
			float const far_plane_z);

		/** Gets camera position
		* @returns Current position
		*/
		vector3f get_position() const;

		/** Sets camera position
		* @param position New camera position
		*/
		void set_position(vector3f const& position);

		/** Gets camera's z-axis coordinates
		* @returns Z-axis (forward vector)
		*/
		vector3f get_forward() const;

		/** Gets camera's x-axis coordinates
		* @returns X-axis (right vector)
		*/
		vector3f get_right() const;

		/** Gets camera's y-axis coordinates
		* @returns Y-axis (up vector)
		*/
		vector3f get_up() const;

		/** Gets horizontal field of view
		* @returns Horizontal field of view in radians
		*/
		float get_horizontal_fov() const;

		/** Gets vertical field of view
		* @returns Vertical field of view in radians
		*/
		float get_vertical_fov() const;

		/** Gets aspect ratio
		* @returns Aspect ratio (height / width)
		*/
		float get_aspect_ratio() const;

		/** Gets near plane z-coordinate
		* @returns Near plane z-coordinate
		*/
		float get_near_plane_z() const;

		/** Gets far plane z-coordinate
		* @returns Far plane z-coordinate
		*/
		float get_far_plane_z() const;

		/** Moves camera along its right vector
		* @param distance Distance to move
		*/
		void move_right(float const distance);

		/** Moves camera along its -right vector
		* @param distance Distance to move
		*/
		void move_left(float const distance);

		/** Moves camera along its up vector
		* @param distance Distance to move
		*/
		void move_up(float const distance);

		/** Moves camera along its -up vector
		* @param distance Distance to move
		*/
		void move_down(float const distance);

		/** Moves camera along its forward vector
		* @param distance Distance to move
		*/
		void move_forward(float const distance);

		/** Moves camera along its -forward vector
		* @param distance Distance to move
		*/
		void move_backward(float const distance);

		/** Rotates camera around y-axis
		* @param radians Radians to rotate for
		*/
		void yaw(float const radians);

		/** Rotates camera around x-axis
		* @param radians Radians to rotate for
		*/
		void pitch(float const radians);

	private:
		/** Current position */
		vector3f m_position;

		/** Current forward vector */
		vector3f m_forward;

		/** Current right vector */
		vector3f m_right;

		/** Current up vector */
		vector3f m_up;

		/** Horizontal field of view */
		float const m_horizontal_fov;

		/** Vertical field of view */
		float const m_vertical_fov;

		/** Aspect ratio */
		float const m_aspect_ratio;

		/** Near plane z-coordinate */
		float const m_near_plane_z;

		/** Far plane z-coordiante */
		float const m_far_plane_z;

		/** Creates coordinate system base on forward and fake up vector
		* @param fake_up Temp up vector
		*/
		void establish_coordinate_system(vector3f const& fake_up);
	};
}

#endif // LANTERN_CAMERA_H


text:
import math
import random

class NeuralNetwork(object):

    def __init__(self, learning_rate=0.5, debug=False):
        """
        Train NeuralNetwork by fixed learning rate
        """
        self.neuron_layers = []
        self.learning_rate = learning_rate
        self.debug = debug

    def train(self, dataset):
        for inputs, outputs in dataset:
            self.feed_forward(inputs)
            self.feed_backword(outputs)
            self.update_weights(self.learning_rate)

    def feed_forward(self, inputs):
        s = inputs
        for (i, l) in enumerate(self.neuron_layers):
            s = l.feed_forward(s)
            if self.debug:
                print "Layer %s:" % (i+1), " output:%s" % s
        return s

    def feed_backword(self, outputs):
        layer_num = len(self.neuron_layers)
        l = layer_num
        previous_deltas = []
        while l != 0:
            current_layer = self.neuron_layers[l - 1]
            if len(previous_deltas) == 0:
                for i in range(len(current_layer.neurons)):
                    error = -(outputs[i] - current_layer.neurons[i].output)
                    current_layer.neurons[i].calculate_delta(error)
            else:
                previous_layer = self.neuron_layers[l]
                for i in range(len(current_layer.neurons)):
                    error = 0
                    for j in range(len(previous_deltas)):
                        error += previous_deltas[j] * previous_layer.neurons[j].weights[i]
                    current_layer.neurons[i].calculate_delta(error)
            previous_deltas = current_layer.get_deltas()
            if self.debug:
                print "Layer %s:" % l, "deltas:%s" % previous_deltas
            l -= 1

    def update_weights(self, learning_rate):
        for l in self.neuron_layers:
            l.update_weights(learning_rate)

    def calculate_total_error(self, dataset):
        """
        Return mean squared error of dataset
        """
        total_error = 0
        for inputs, outputs in dataset:
            actual_outputs = self.feed_forward(inputs)
            for i in range(len(outputs)):
                total_error += (outputs[i] - actual_outputs[i]) ** 2
        return total_error / len(dataset)

    def get_output(self, inputs):
       return self.feed_forward(inputs)

    def add_layer(self, neruon_layer):
        self.neuron_layers.append(neruon_layer)

    def dump(self):
        for (i, l) in enumerate(self.neuron_layers):
            print "Dump layer: %s" % (i+1)
            l.dump()

class NeuronLayer(object):

    def __init__(self, input_num, neuron_num, init_weights=[], bias=1):
        self.neurons = []
        weight_index = 0
        for i in range(neuron_num):
            n = Neuron(input_num)
            for j in range(input_num):
                if weight_index < len(init_weights):
                    n.weights[j] = init_weights[weight_index]
                    weight_index += 1
            n.bias = bias
            self.neurons.append(n)

    def feed_forward(self, inputs):
        outputs = []
        for n in self.neurons:
            outputs.append(n.calculate_output(inputs))
        return outputs

    def get_deltas(self):
        return [n.delta for n in self.neurons]

    def update_weights(self, learning_rate):
        for n in self.neurons:
            n.update_weights(learning_rate)

    def dump(self):
        for (i, n) in enumerate(self.neurons):
            print "-Dump neuron: %s" % (i+1)
            n.dump()

class Neuron(object):

    def __init__(self, weight_num):
        self.weights = []
        self.bias = 0
        self.output = 0
        self.delta = 0
        self.inputs = []
        for i in range(weight_num):
            self.weights.append(random.random())

    def calculate_output(self, inputs):
        self.inputs = inputs
        if len(inputs) != len(self.weights):
            raise Exception("Input number not fit weight number")
        self.output = 0
        for (i, w) in enumerate(self.weights):
            self.output += w * inputs[i]
        self.output = self.activation_function(self.output + self.bias)
        return self.output

    def activation_function(self, x):
        """Using sigmoid function"""
        return 1 / (1 + math.exp(-x))

    def calculate_delta(self, error):
        """ Using g' of sigmoid """
        self.delta = error * self.output * (1 - self.output)

    def update_weights(self, learning_rate):
        for (i, w) in enumerate(self.weights):
            new_w = w - learning_rate * self.delta * self.inputs[i]
            self.weights[i] = new_w
        self.bias = self.bias - learning_rate * self.delta

    def dump(self):
        print "-- weights:", self.weights
        print "-- bias:", self.bias


text:
/**
 * Kuali Coeus Unit Correspondent Implementations
 */
/**
 * @author Kuali Coeus Development Team
 *
 */
package org.kuali.coeus.common.impl.unit.crrspndnt;


text:
package com.orhanobut.dialogplus;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;

public class ListHolder implements HolderAdapter, AdapterView.OnItemClickListener {

  private int backgroundResource;

  private ListView listView;
  private OnHolderListener listener;
  private View.OnKeyListener keyListener;
  private View headerView;
  private View footerView;
  private ViewGroup footerContainer;
  private ViewGroup headerContainer;

  @Override public void addHeader(@NonNull View view) {
    addHeader(view, false);
  }

  @Override public void addHeader(@NonNull View view, boolean fixed) {
    if (fixed) {
      headerContainer.addView(view);
    } else {
      listView.addHeaderView(view);
    }
    headerView = view;
  }

  @Override public void addFooter(@NonNull View view) {
    addFooter(view, false);
  }

  @Override public void addFooter(@NonNull View view, boolean fixed) {
    if (fixed) {
      footerContainer.addView(view);
    } else {
      listView.addFooterView(view);
    }
    footerView = view;
  }

  @Override public void setAdapter(@NonNull BaseAdapter adapter) {
    listView.setAdapter(adapter);
  }

  @Override public void setBackgroundResource(int colorResource) {
    this.backgroundResource = colorResource;
  }

  @Override @NonNull
  public View getView(@NonNull LayoutInflater inflater, ViewGroup parent) {
    View view = inflater.inflate(R.layout.dialog_list, parent, false);
    View outMostView = view.findViewById(R.id.dialogplus_outmost_container);
    outMostView.setBackgroundResource(backgroundResource);
    listView = view.findViewById(R.id.dialogplus_list);
    listView.setOnItemClickListener(this);
    listView.setOnKeyListener(new View.OnKeyListener() {
      @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyListener == null) {
          throw new NullPointerException("keyListener should not be null");
        }
        return keyListener.onKey(v, keyCode, event);
      }
    });
    headerContainer = view.findViewById(R.id.dialogplus_header_container);
    footerContainer = view.findViewById(R.id.dialogplus_footer_container);
    return view;
  }

  @Override public void setOnItemClickListener(OnHolderListener listener) {
    this.listener = listener;
  }

  @Override public void setOnKeyListener(View.OnKeyListener keyListener) {
    this.keyListener = keyListener;
  }

  @Override @NonNull
  public View getInflatedView() {
    return listView;
  }

  @Override public View getHeader() {
    return headerView;
  }

  @Override public View getFooter() {
    return footerView;
  }

  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (listener == null) {
      return;
    }
    //ListView counts header as position as well. For consistency we don't
    listener.onItemClick(
        parent.getItemAtPosition(position),
        view,
        headerView != null ? --position : position
    );
  }
}


text:
// Copyright 2020 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.cloud.healthcare.etl.model.mapping;

import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.time.Instant;

/**
 * Represents a mapped message with source time as an output from {@link
 * com.google.cloud.healthcare.etl.pipeline.MappingFn}.
 */
public class MappedFhirMessageWithSourceTime implements MappingOutput {

  private final String output;
  @Nullable private Instant sourceTime;

  public MappedFhirMessageWithSourceTime(String output) {
    this.output = output;
  }

  public MappedFhirMessageWithSourceTime(String output, Instant sourceTime) {
    this.output = output;
    this.sourceTime = sourceTime;
  }

  public MappedFhirMessageWithSourceTime(String output, String sourceTime) {
    this.output = output;
    this.sourceTime = Instant.parse(sourceTime);
  }

  public String getOutput() {
    return output;
  }

  public Optional<Instant> getSourceTime() {
    return Optional.ofNullable(sourceTime);
  }
}


text:
using Microsoft.AspNetCore.Rewrite.ApacheModRewrite;

namespace Microsoft.AspNetCore.Rewrite.Tests.ModRewrite;

public class RuleRegexParserTest
{
    [Fact]
    public void RuleRegexParser_ShouldThrowOnNull()
    {
        Assert.Throws<FormatException>(() => RuleRegexParser.ParseRuleRegex(null));
    }

    [Fact]
    public void RuleRegexParser_ShouldThrowOnEmpty()
    {
        Assert.Throws<FormatException>(() => RuleRegexParser.ParseRuleRegex(string.Empty));
    }

    [Fact]
    public void RuleRegexParser_RegularRegexExpression()
    {
        var results = RuleRegexParser.ParseRuleRegex("(.*)");
        Assert.False(results.Invert);
        Assert.Equal("(.*)", results.Operand);
    }
}


text:
<?php

class Robot
{
    private $position = null;
    private $direction = null;

    const MOVEDIRECTIONS = [[0, -1], [1, 0], [0, 1], [-1, 0]];
    const CHARDIRECTIONS = ["N" => 0, "E" => 1, "S" => 2, "W" => 3];

    public function __construct($x, $y, $startDirection)
    {
        if (!is_int($startDirection)) {
            $startDirection = self::CHARDIRECTIONS[$startDirection] ?? -1;
        }

        if (!Direction::isValidDirection($startDirection)) {
            throw new Exception("Invalid robot start direction");
        }

        $this->position = new Position($x, $y);
        $this->direction = $startDirection;
    }

    public function turnRight()
    {
        $this->direction = ($this->direction + 1) % 4;
    }

    public function turnLeft()
    {
        $this->direction = ($this->direction + 3) % 4; // +3 instead of -1 because a positive number is needed
    }

    public function moveToPosition($position)
    {
        $this->position = $position;
    }

    public function isOnCoordinates($x, $y)
    {
        return $this->position->x === $x && $this->position->y === $y;
    }

    public function getCurrentPosition()
    {
        return $this->position;
    }

    public function getPositionIfMoved($moveCommand)
    {
        $whichWay = $moveCommand === Command::FORWARD ? 1 : -1;

        return new Position(
                $this->position->x + self::MOVEDIRECTIONS[$this->direction][0] * $whichWay,
                $this->position->y + self::MOVEDIRECTIONS[$this->direction][1] * $whichWay
        );
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.42000
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

namespace WzComparerR2.Properties {
    using System;

    /// <summary>
    ///   一个强类型的资源类,用于查找本地化的字符串等。
    /// </summary>
    // 此类是由 StronglyTypedResourceBuilder
    // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
    // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
    // (以 /str 作为命令选项),或重新生成 VS 项目。
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   返回此类使用的缓存的 ResourceManager 实例。
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WzComparerR2.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   重写当前线程的 CurrentUICulture 属性,对
        ///   使用此强类型资源类的所有资源查找执行重写。
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap dir {
            get {
                object obj = ResourceManager.GetObject("dir", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap img {
            get {
                object obj = ResourceManager.GetObject("img", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap mp3 {
            get {
                object obj = ResourceManager.GetObject("mp3", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap num {
            get {
                object obj = ResourceManager.GetObject("num", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap Open {
            get {
                object obj = ResourceManager.GetObject("Open", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap Pause {
            get {
                object obj = ResourceManager.GetObject("Pause", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap Play {
            get {
                object obj = ResourceManager.GetObject("Play", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap png {
            get {
                object obj = ResourceManager.GetObject("png", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap Save {
            get {
                object obj = ResourceManager.GetObject("Save", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap Stop {
            get {
                object obj = ResourceManager.GetObject("Stop", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap str {
            get {
                object obj = ResourceManager.GetObject("str", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap uol {
            get {
                object obj = ResourceManager.GetObject("uol", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap vector {
            get {
                object obj = ResourceManager.GetObject("vector", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}


text:
layout: blog
title: Se
permalink: /se/
---
{% include category.html %}


text:
using System;
using System.Collections;

namespace Sooda.Caching
{
    public class SoodaNoCache : ISoodaCache
    {
        public bool DefaultSlidingExpiration
        {
            get { return false; }
            set { }
        }

        public TimeSpan DefaultExpirationTimeout
        {
            get { return TimeSpan.Zero; }
            set { }
        }

        SoodaCacheEntry ISoodaCache.Find(string className, object primaryKeyValue)
        {
            return null;
        }

        void ISoodaCache.Add(string className, object primaryKeyValue, SoodaCacheEntry entry, TimeSpan expirationTimeout, bool slidingExpiration)
        {
        }

        void ISoodaCache.Invalidate(string className, object primaryKeyValue, SoodaCacheInvalidateReason reason)
        {
        }

        void ISoodaCache.Clear()
        {
        }

        void ISoodaCache.Sweep()
        {
        }

        IList ISoodaCache.LoadCollection(string key)
        {
            return null;
        }

        void ISoodaCache.StoreCollection(string cacheKey, string rootClassName, IList primaryKeys, string[] dependentClasses, bool evictWhenItemRemoved, TimeSpan expirationTimeout, bool slidingExpiration)
        {
        }

        ISoodaCacheLock ISoodaCache.Lock()
        {
            return new DummySoodaCacheLock();
        }

        void ISoodaCache.Unlock(ISoodaCacheLock theLock)
        {
        }

        class DummySoodaCacheLock : ISoodaCacheLock
        {
            public void Dispose()
            {
            }
        }

        public void Evict(string className, object primaryKeyValue)
        {
        }

        public void EvictCollection(string cacheKey)
        {
        }
    }
}


text:
package org.jboss.resteasy.skeleton.key.idm.model.data;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class RoleMapping implements Serializable
{
   private static final long serialVersionUID = 1L;
   protected String id;
   protected String userid;
   protected Set<String> roles = new HashSet<String>();
   protected Set<String> surrogateIds = new HashSet<String>();

   public String getId()
   {
      return id;
   }

   public void setId(String id)
   {
      this.id = id;
   }

   public String getUserid()
   {
      return userid;
   }

   public void setUserid(String userid)
   {
      this.userid = userid;
   }

   public Set<String> getRoles()
   {
      return roles;
   }

   public void setRoles(Set<String> roles)
   {
      this.roles = roles;
   }

   public Set<String> getSurrogateIds()
   {
      return surrogateIds;
   }

   public void setSurrogateIds(Set<String> surrogateIds)
   {
      this.surrogateIds = surrogateIds;
   }
}


text:
package org.jenkinsci.plugins.p4.changes;

import hudson.model.Run;
import hudson.scm.RepositoryBrowser;
import hudson.scm.ChangeLogSet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.kohsuke.stapler.framework.io.WriterOutputStream;

import com.perforce.p4java.core.file.FileAction;
import com.perforce.p4java.core.file.IFileSpec;

public class P4ChangeSet extends ChangeLogSet<P4ChangeEntry> {

	private List<P4ChangeEntry> history;

	protected P4ChangeSet(Run<?, ?> run, RepositoryBrowser<?> browser,
			List<P4ChangeEntry> logs) {
		super(run, browser);
		this.history = Collections.unmodifiableList(logs);
	}

	public Iterator<P4ChangeEntry> iterator() {
		return history.iterator();
	}

	@Override
	public boolean isEmptySet() {
		return history.isEmpty();
	}

	public List<P4ChangeEntry> getHistory() {
		return history;
	}

	public Collection<P4ChangeEntry> getLogs() {
		return history;
	}

	public static void store(File file, List<Object> changes) {
		try {
			FileOutputStream o = new FileOutputStream(file);
			BufferedOutputStream b = new BufferedOutputStream(o);
			Charset c = Charset.forName("UTF-8");
			OutputStreamWriter w = new OutputStreamWriter(b, c);
			WriterOutputStream s = new WriterOutputStream(w);
			PrintStream stream = new PrintStream(s);

			stream.println("<?xml version='1.0' encoding='UTF-8'?>");
			stream.println("<changelog>");
			for (Object change : changes) {
				stream.println("\t<entry>");
				if (change instanceof String) {
					stream.println("\t\t<label>" + change + "</label>");
				} else if (change instanceof P4ChangeEntry) {
					P4ChangeEntry cl = (P4ChangeEntry) change;
					stream.println("\t\t<changenumber><changeInfo>"
							+ cl.getId() + "</changeInfo>");
					stream.println("\t\t<clientId>" + cl.getClientId()
							+ "</clientId>");

					stream.println("\t\t<msg>"
							+ StringEscapeUtils.escapeXml(cl.getMsg())
							+ "</msg>");
					stream.println("\t\t<changeUser>"
							+ StringEscapeUtils.escapeXml(cl.getAuthor()
									.getDisplayName()) + "</changeUser>");

					stream.println("\t\t<changeTime>"
							+ StringEscapeUtils.escapeXml(cl.getChangeTime())
							+ "</changeTime>");

					stream.println("\t\t<shelved>" + cl.isShelved()
							+ "</shelved>");

					stream.println("\t\t<files>");
					for (IFileSpec filespec : cl.getFiles()) {
						FileAction action = filespec.getAction();
						int revision = filespec.getEndRevision();

						// URL encode depot path
						String depotPath = filespec.getDepotPathString();
						String safePath = URLEncoder.encode(depotPath, "UTF-8");

						stream.println("\t\t<file endRevision=\"" + revision
								+ "\" action=\"" + action.name()
								+ "\" depot=\"" + safePath + "\" />");
					}
					stream.println("\t\t</files>");

					stream.println("\t\t</changenumber>");

				} else {
					stream.println("\t\t<changenumber>" + change
							+ "</changenumber>");
				}
				stream.println("\t</entry>");
			}
			stream.println("</changelog>");
			stream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}


text:
\hypertarget{classdoki_unity_1_1_modal_panel}{}\section{doki\+Unity.\+Modal\+Panel Class Reference}
\label{classdoki_unity_1_1_modal_panel}\index{doki\+Unity.\+Modal\+Panel@{doki\+Unity.\+Modal\+Panel}}

\hyperlink{classdoki_unity_1_1_modal_panel}{Modal\+Panel} is a template to create a pop up window to wait for player\textquotesingle{}s option input. \hyperlink{classdoki_unity_1_1_modal_panel}{Modal\+Panel} has a title, message, Yes button (and No button). External callback function could be passed to this window, and when responding button is clicked, the responding functions would be called.

Inheritance diagram for doki\+Unity.\+Modal\+Panel\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=2.000000cm]{classdoki_unity_1_1_modal_panel}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
void \hyperlink{classdoki_unity_1_1_modal_panel_ab6e6c7b12989582f10d1947a52e20051}{Choice} (string title, string message, Unity\+Action$<$ bool $>$ yes\+Event)
\begin{DoxyCompactList}\small\item\em Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function \end{DoxyCompactList}\item
void \hyperlink{classdoki_unity_1_1_modal_panel_a919e94df42bca242808a093c3d06e5b4}{Choice} (string title, string message, Unity\+Action$<$ bool, System.\+Object $>$ yes\+Event, System.\+Object yes\+Parameter)
\begin{DoxyCompactList}\small\item\em Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function and parameters should be passed to the function \end{DoxyCompactList}\item
void \hyperlink{classdoki_unity_1_1_modal_panel_aa967d929957bd4a42663cbdb1ed4127f}{Choice} (string title, string message, Unity\+Action$<$ bool $>$ yes\+Event, Unity\+Action$<$ bool $>$ no\+Event)
\begin{DoxyCompactList}\small\item\em Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function and no\+Button\textquotesingle{}s callback function \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
Text \hyperlink{classdoki_unity_1_1_modal_panel_a8bb32dc36292b9da60c7125f150d759d}{title\+Text}
\begin{DoxyCompactList}\small\item\em Pointer to the title\+Text Game\+Object \end{DoxyCompactList}\item
Text \hyperlink{classdoki_unity_1_1_modal_panel_a6c9c26430055c5e6beb1d7db2dfb6f68}{message\+Text}
\begin{DoxyCompactList}\small\item\em Pointer to the message\+Text Game\+Object \end{DoxyCompactList}\item
Button \hyperlink{classdoki_unity_1_1_modal_panel_a72113e073c692caa38601f17c6ffde6c}{yes\+Button}
\begin{DoxyCompactList}\small\item\em Pointer to the yes\+Button Game\+Object \end{DoxyCompactList}\item
Button \hyperlink{classdoki_unity_1_1_modal_panel_ab383aea9285e694802836034b933f1f5}{no\+Button}
\begin{DoxyCompactList}\small\item\em Pointer to the no\+Button Game\+Object \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
\hyperlink{classdoki_unity_1_1_modal_panel}{Modal\+Panel} is a template to create a pop up window to wait for player\textquotesingle{}s option input. \hyperlink{classdoki_unity_1_1_modal_panel}{Modal\+Panel} has a title, message, Yes button (and No button). External callback function could be passed to this window, and when responding button is clicked, the responding functions would be called.

\subsection{Member Function Documentation}
\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!Choice@{Choice}}
\index{Choice@{Choice}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{Choice(string title, string message, Unity\+Action$<$ bool $>$ yes\+Event)}{Choice(string title, string message, UnityAction< bool > yesEvent)}}]{\setlength{\rightskip}{0pt plus 5cm}void doki\+Unity.\+Modal\+Panel.\+Choice (
\begin{DoxyParamCaption}
\item[{string}]{title, }
\item[{string}]{message, }
\item[{Unity\+Action$<$ bool $>$}]{yes\+Event}
\end{DoxyParamCaption}
)}\hypertarget{classdoki_unity_1_1_modal_panel_ab6e6c7b12989582f10d1947a52e20051}{}\label{classdoki_unity_1_1_modal_panel_ab6e6c7b12989582f10d1947a52e20051}

Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function

\begin{DoxyParams}{Parameters}
{\em title} & Title of the window\\
\hline
{\em message} & Message insidethe window\\
\hline
{\em yes\+Event} & Callback function of yes\+Button\\
\hline
\end{DoxyParams}
\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!Choice@{Choice}}
\index{Choice@{Choice}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{Choice(string title, string message, Unity\+Action$<$ bool, System.\+Object $>$ yes\+Event, System.\+Object yes\+Parameter)}{Choice(string title, string message, UnityAction< bool, System.Object > yesEvent, System.Object yesParameter)}}]{\setlength{\rightskip}{0pt plus 5cm}void doki\+Unity.\+Modal\+Panel.\+Choice (
\begin{DoxyParamCaption}
\item[{string}]{title, }
\item[{string}]{message, }
\item[{Unity\+Action$<$ bool, System.\+Object $>$}]{yes\+Event, }
\item[{System.\+Object}]{yes\+Parameter}
\end{DoxyParamCaption}
)}\hypertarget{classdoki_unity_1_1_modal_panel_a919e94df42bca242808a093c3d06e5b4}{}\label{classdoki_unity_1_1_modal_panel_a919e94df42bca242808a093c3d06e5b4}

Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function and parameters should be passed to the function

\begin{DoxyParams}{Parameters}
{\em title} & Title of the window\\
\hline
{\em message} & Message inside the window\\
\hline
{\em yes\+Event} & Callback function of yes\+Button\\
\hline
{\em yes\+Parameter} & Parameter should be passed to the yes\+Button\textquotesingle{}s callback function\\
\hline
\end{DoxyParams}
\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!Choice@{Choice}}
\index{Choice@{Choice}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{Choice(string title, string message, Unity\+Action$<$ bool $>$ yes\+Event, Unity\+Action$<$ bool $>$ no\+Event)}{Choice(string title, string message, UnityAction< bool > yesEvent, UnityAction< bool > noEvent)}}]{\setlength{\rightskip}{0pt plus 5cm}void doki\+Unity.\+Modal\+Panel.\+Choice (
\begin{DoxyParamCaption}
\item[{string}]{title, }
\item[{string}]{message, }
\item[{Unity\+Action$<$ bool $>$}]{yes\+Event, }
\item[{Unity\+Action$<$ bool $>$}]{no\+Event}
\end{DoxyParamCaption}
)}\hypertarget{classdoki_unity_1_1_modal_panel_aa967d929957bd4a42663cbdb1ed4127f}{}\label{classdoki_unity_1_1_modal_panel_aa967d929957bd4a42663cbdb1ed4127f}

Show and customize the popup window\textquotesingle{}s title, message, yes\+Button\textquotesingle{}s callback function and no\+Button\textquotesingle{}s callback function

\begin{DoxyParams}{Parameters}
{\em title} & Title of the window\\
\hline
{\em message} & Message inside the window\\
\hline
{\em yes\+Event} & Callback function of yes\+Button\\
\hline
{\em no\+Event} & Callback function of no\+Button\\
\hline
\end{DoxyParams}

\subsection{Member Data Documentation}
\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!message\+Text@{message\+Text}}
\index{message\+Text@{message\+Text}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{message\+Text}{messageText}}]{\setlength{\rightskip}{0pt plus 5cm}Text doki\+Unity.\+Modal\+Panel.\+message\+Text}\hypertarget{classdoki_unity_1_1_modal_panel_a6c9c26430055c5e6beb1d7db2dfb6f68}{}\label{classdoki_unity_1_1_modal_panel_a6c9c26430055c5e6beb1d7db2dfb6f68}

Pointer to the message\+Text Game\+Object

\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!no\+Button@{no\+Button}}
\index{no\+Button@{no\+Button}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{no\+Button}{noButton}}]{\setlength{\rightskip}{0pt plus 5cm}Button doki\+Unity.\+Modal\+Panel.\+no\+Button}\hypertarget{classdoki_unity_1_1_modal_panel_ab383aea9285e694802836034b933f1f5}{}\label{classdoki_unity_1_1_modal_panel_ab383aea9285e694802836034b933f1f5}

Pointer to the no\+Button Game\+Object

\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!title\+Text@{title\+Text}}
\index{title\+Text@{title\+Text}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{title\+Text}{titleText}}]{\setlength{\rightskip}{0pt plus 5cm}Text doki\+Unity.\+Modal\+Panel.\+title\+Text}\hypertarget{classdoki_unity_1_1_modal_panel_a8bb32dc36292b9da60c7125f150d759d}{}\label{classdoki_unity_1_1_modal_panel_a8bb32dc36292b9da60c7125f150d759d}

Pointer to the title\+Text Game\+Object

\index{doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}!yes\+Button@{yes\+Button}}
\index{yes\+Button@{yes\+Button}!doki\+Unity\+::\+Modal\+Panel@{doki\+Unity\+::\+Modal\+Panel}}
\subsubsection[{\texorpdfstring{yes\+Button}{yesButton}}]{\setlength{\rightskip}{0pt plus 5cm}Button doki\+Unity.\+Modal\+Panel.\+yes\+Button}\hypertarget{classdoki_unity_1_1_modal_panel_a72113e073c692caa38601f17c6ffde6c}{}\label{classdoki_unity_1_1_modal_panel_a72113e073c692caa38601f17c6ffde6c}

Pointer to the yes\+Button Game\+Object

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
C\+:/\+\_\+\+Projects/dokidoki/src/doki\+Unity/\+Assets/dokidoki/\+Scripts/\+U\+I\+Manager/Modal\+Panel.\+cs\end{DoxyCompactItemize}


text:
/**
 */
package edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository;

/**
 *
 * A representation of the model object 'Panel'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.Panel#getComponentRepository Component Repository}

 *

 *
 * @see edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.ComponentRepositoryPackage#getPanel()
 * @model abstract="true"
 * @generated
 */
public interface Panel extends Component {
	/**
	 * Returns the value of the 'Component Repository' reference.
	 *
	 *

	 * If the meaning of the 'Component Repository' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Component Repository' reference.
	 * @see #setComponentRepository(Component)
	 * @see edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.ComponentRepositoryPackage#getPanel_ComponentRepository()
	 * @model required="true"
	 * @generated
	 */
	Component getComponentRepository();

	/**
	 * Sets the value of the '{@link edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.Panel#getComponentRepository Component Repository}' reference.
	 *
	 *
	 * @param value the new value of the 'Component Repository' reference.
	 * @see #getComponentRepository()
	 * @generated
	 */
	void setComponentRepository(Component value);

} // Panel


text:
function get()
    if not app.Shop.Enabled then
        http:redirect("/")
        return
    end

    if not session:isAdmin() then
        http:redirect("/")
        return
    end

    local data = {}

    data.category = db:singleQuery("SELECT id, name, description, created_at FROM castro_shop_categories WHERE id = ?", http.getValues.id)

    if data.category == nil then
        http:redirect("/subtopic/admin/shop")
        return
    end

    data.validationError = session:getFlash("validationError")
    data.success = session:getFlash("success")
    data.list = db:query("SELECT id, name, price FROM castro_shop_offers WHERE category_id = ?", http.getValues.id)

    http:render("shopoffers.html", data)
end


text:
namespace Codelet.Domain
{
  using System;

  /// <summary>
  /// Domain event arguments marker class.
  /// </summary>
  /// <typeparam name="TDomainModel">The type of the domain model.</typeparam>
  public class DomainEventArgs<TDomainModel> : EventArgs
    where TDomainModel : DomainModel
  {
  }
}


text:
using System;
using CommandLine;
using Microsoft.Azure.KeyVault.Models;
using Mjcheetham.KeyVaultCommandLine.Configuration.Model;
using Mjcheetham.KeyVaultCommandLine.Services;

namespace Mjcheetham.KeyVaultCommandLine.Commands
{
    [Verb("set", HelpText = Strings.Set_Verb_Help)]
    internal class SetCommand : Command
    {
        [Value(0, MetaName = "vault", Required = true, HelpText = Strings.Common_Param_Vault_Help)]
        public string Vault { get; set; }

        [Value(1, MetaName = "secret", Required = true, HelpText = Strings.Common_Param_Secret_Help)]
        public string Secret { get; set; }

        [Value(2, MetaName = "value", Required = true, HelpText = Strings.Set_Param_Value_Help)]
        public string Value { get; set; }

        public override void Execute()
        {
            var vaultConfig = ConfigurationManager.GetVaultConfig(Vault);
            if (vaultConfig == null)
            {
                WriteError($"Unknown vault '{Vault}'");
                return;
            }

            var authConfig = ConfigurationManager.GetAuthConfig(vaultConfig);
            if (authConfig == null)
            {
                WriteError($"No authentication methods have been configured for vault '{Vault}'; see `kv auth`");
                return;
            }

            IKeyVaultService kvService = CreateVaultService(authConfig);

            SecretBundle newSecret;
            try
            {
                newSecret = kvService.SetSecret(vaultConfig.GetVaultUri(), Secret, Value);
            }
            catch (Exception ex)
            {
                WriteError($"Failed to set secret '{Secret}' in vault '{Vault}'", ex);
                return;
            }

            if (Verbose)
            {
                Console.Out.WriteJson(newSecret);
            }
            else
            {
                WriteInfo($"Secret '{Secret}' was set successfully");
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>delete-instance — AWS CLI 1.0.0 documentation</title>
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" />

    <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" />
    <link rel="up" title="opsworks" href="index.html" />
    <link rel="next" title="delete-layer" href="delete-layer.html" />
    <link rel="prev" title="delete-app" href="delete-app.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" />

        AWS CLI

Home

Documentation

Forum

GitHub

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

opsworks »

          ← delete-app
          /

delete-layer →

Table Of Contents

delete-instance

Description

Synopsis

Options

Quick search

    <form class="form-search margin-top-1em" action="../../search.html" method="get">
        <input type="text" name="q" style="width: 105px" class="input-small search-query" />
        <button type="submit" class="btn btn-small">Search</button>
        <input type="hidden" name="check_keywords" value="yes" />
        <input type="hidden" name="area" value="default" />
    </form>

Feedback

Did you find this page useful? Do you have a suggestion? Give us feedback or
  send us a pull request on GitHub.

[ aws . opsworks ]

delete-instance¶

Description¶

Deletes a specified instance. You must stop an instance before you can delete it. For more information, see Deleting Instances .

Synopsis¶

  delete-instance
--instance-id <value>
[--delete-elastic-ip | --no-delete-elastic-ip]
[--delete-volumes | --no-delete-volumes]

Options¶

<tt class="docutils literal">--instance-id</tt> (string)

The instance ID.

<tt class="docutils literal">--delete-elastic-ip</tt> | <tt class="docutils literal">--no-delete-elastic-ip</tt> (boolean)

Whether to delete the instance Elastic IP address.

<tt class="docutils literal">--delete-volumes</tt> | <tt class="docutils literal">--no-delete-volumes</tt> (boolean)

Whether to delete the instance Amazon EBS volumes.

          ← delete-app
          /

delete-layer →

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

opsworks »

    © Copyright 2013, Amazon Web Services. Created using Sphinx.


text:
!> \file
!> \author Merryn Tawhai
!> \brief This module contains definition of constants
!>
!> \section LICENSE
!>
!>
!> Contributor(s):
!>
!>\Description
!> This module contains definition of constants (note that in the future this should be merged into a 'types' module
module other_consts

  use precision

  implicit none

  integer, parameter :: MAX_FILENAME_LEN = 255, MAX_STRING_LEN = 100, MAX_SUBNAME_LEN = 60

  real(dp), parameter :: PI = 3.14159265358979_dp
  real(dp), parameter :: TOLERANCE =EPSILON (EPSILON(1.0_dp))

  private

  public MAX_SUBNAME_LEN, MAX_STRING_LEN, MAX_FILENAME_LEN, PI,TOLERANCE

end module other_consts