text:
<?php
namespace Futon;

class Authenticator
{
    protected $secret = null;
    protected $headerName = null;
    protected $values = [];
    protected $defaultValues = [];

    public function __construct(string $secret, $defaultValues = [], $headerName = 'Authorization')
    {
        $this->secret     = $secret;
        $this->headerName = $headerName;
        $this->values     = $defaultValues;
        $this->defaultValues = $defaultValues;
    }

    public function verify($token): bool
    {
        list($header, $payload, $signature) = explode('.', $token);
        $newSignature = hash_hmac("sha256", $this->secret, base64_decode($payload), true);

        if ($newSignature == base64_decode($signature)) {
            $this->values = json_decode(base64_decode($payload));
        } else {
            $this->values = $this->defaultValues;
        }
        return true;
    }

    public function issue(array $tokenData): string
    {

        $header    = '{"alg":"HS256","typ":"JWT"}';
        $payload   = json_encode($tokenData);
        $signature = hash_hmac("sha256", $this->secret, $payload, true);
        $token = base64_encode($header).'.'.base64_encode($payload).'.'.base64_encode($signature);
        header($this->headerName.': '.$token);
        $this->values = $tokenData;
        return $token;
    }

    public function __get($key)
    {
        return $this->values[$key];
    }

    public function __isset($key)
    {
        return isset($this->values[$key]);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2012 Eddie Ringle
  ~ All rights reserved.
  ~
  ~ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
  ~ following conditions are met:
  ~
  ~ Redistributions of source code must retain the above copyright notice, this list of conditions and the following
  ~ disclaimer.
  ~ Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
  ~ disclaimer in the documentation and/or other materials provided with the distribution.
  ~
  ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  ~ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  ~ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  ~ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  ~ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  ~ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  ~ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">
    <LinearLayout android:id="@+id/ll_issue_comment_author_area"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:background="#F5F5F5"
                  android:orientation="horizontal">
        <ImageView android:id="@+id/iv_issue_comment_gravatar"
                   android:layout_width="32dp"
                   android:layout_height="32dp"
                   android:layout_marginTop="10dp"
                   android:layout_marginRight="5dp"
                   android:layout_marginBottom="10dp"
                   android:layout_marginLeft="10dp"
                   android:padding="2dp"
                   android:background="@drawable/gravatar_border"/>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="5dp"
                android:orientation="vertical">
            <TextView android:id="@+id/tv_issue_comment_author"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textSize="11sp"
                      android:textStyle="bold"/>
            <TextView android:id="@+id/tv_issue_comment_meta"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textSize="10sp"
                      android:textColor="@color/light_text_color"/>
        </LinearLayout>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginBottom="5dp"
                android:background="#E5E5E5"/>
    </LinearLayout>
    <TextView android:id="@+id/tv_issue_comment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:textSize="12sp"
              android:padding="10dp"/>
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
import { ChevronLeftGlyph } from "../../";

export = ChevronLeftGlyph;


text:
A Vue, TypeScript ready boilerplate using class-style components

*Usage*
```bash
# Download vue-cli and Vuets template
npm i -g vue-cli
vue init akiralaine/vuets <PROJECT_NAME>

# Install dependencies
cd <PROJECT_NAME>
yarn (or npm i)
yarn run dev (or npm run dev)
```

### What's a class-style component?
Vuets uses [vue-class-component](https://github.com/vuejs/vue-class-component) to enable the following
```js
<script lang='ts'>
import Vue from 'vue'
import Component from 'vue-class-component'
import Intro from './components/Intro'

@Component({
  components: {
    Intro
  }
})
export default class App extends Vue {
  // data
  appName : string = 'vuets'

  // lifecycle hooks
  mounted () {
    this.printToConsole()
  }

  // methods
  printToConsole () {
    console.log('Welcome to Vuets')
  }

  // computed
  get properName () {
    return `${this.appName[0].toUpperCase()}${this.appName.slice(1)}`
  }
}
</script>
```

### What's different?
Data
--
Normal Syntax:
```js
data () {
  return {
    foo: 'bar'
  }
}
```
Class syntax:
```js
foo = 'bar'
```
Using types:
```js
foo : string = 'bar'
```

Methods
--
Methods are the same except they don't go in a `methods` object

Computed
--
Like methods, computed properties don't go in a `computed` object. But you must specify a `getter` like so:
```js
get someProp () {
  return 'hello'
}
```
using types:
```js
get sommeProp () : string {
  return 'hello'
}
```
Props / Watchers / Components
--
Unlike everything else, the above are specified in your `Component` decorator.
```jsx
import SomeComponent from './SomeComponent'

@Component({
  components: {
    SomeComponent
  }
  props: ['someProp'],
  watch: {
    'foo' (val) {
      console.log(val)
    }
  }
})
```


text:
package cloudformation

import (
	"errors"
	"net/http"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/service/ecs"
	"github.com/remind101/empire/pkg/cloudformation/customresources"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestRetryer(t *testing.T) {
	r := newRetryer()

	var min, max, total time.Duration
	for i := 0; i < r.NumMaxRetries; i++ {
		retryCount := i
		x := i
		if x > 8 {
			x = 8
		}

		min += time.Duration((1<<uint(x))*500) * time.Millisecond
		max += time.Duration((1<<uint(x))*1000) * time.Millisecond

		delay := r.RetryRules(&request.Request{
			RetryCount: retryCount,
			HTTPResponse: &http.Response{
				StatusCode: 503,
			},
		})
		total += delay
		t.Logf("delay(%d): %v", i, delay)
	}
	t.Logf("total(min): %v", min)
	t.Logf("total(max): %v", max)
	t.Logf("total(real): %v", total)

	assert.True(t, total > min)
	assert.True(t, total < max)
}

func TestECSServiceResource_Create(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("CreateService", &ecs.CreateServiceInput{
		ClientToken:  aws.String("dxRU5tYsnzt"),
		ServiceName:  aws.String("acme-inc-web-dxRU5tYsnzt"),
		Cluster:      aws.String("cluster"),
		DesiredCount: aws.Int64(1),
	}).Return(&ecs.CreateServiceOutput{
		Service: &ecs.Service{
			ServiceName: aws.String("acme-inc-web-dxRU5tYsnzt"),
			ServiceArn:  aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt"),
			Deployments: []*ecs.Deployment{&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")}},
		},
	}, nil)

	e.On("WaitUntilServicesStable", &ecs.DescribeServicesInput{
		Cluster:  aws.String("cluster"),
		Services: []*string{aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt")},
	}).Return(nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		StackId:     "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:   "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType: customresources.Create,
		ResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
		OldResourceProperties: &ECSServiceProperties{},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt", id)
	assert.Equal(t, data, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web-dxRU5tYsnzt"})

	e.AssertExpectations(t)
}

func TestECSServiceResource_Create_Canceled(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("CreateService", &ecs.CreateServiceInput{
		ClientToken:  aws.String("dxRU5tYsnzt"),
		ServiceName:  aws.String("acme-inc-web-dxRU5tYsnzt"),
		Cluster:      aws.String("cluster"),
		DesiredCount: aws.Int64(1),
	}).Return(&ecs.CreateServiceOutput{
		Service: &ecs.Service{
			ServiceName: aws.String("acme-inc-web-dxRU5tYsnzt"),
			ServiceArn:  aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt"),
			Deployments: []*ecs.Deployment{&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")}},
		},
	}, nil)

	ctx, cancel := context.WithCancel(ctx)
	e.On("WaitUntilServicesStable", &ecs.DescribeServicesInput{
		Cluster:  aws.String("cluster"),
		Services: []*string{aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt")},
	}).Return(nil).Run(func(mock.Arguments) {
		cancel()
		time.Sleep(1 * time.Second)
	})

	_, data, err := p.Provision(ctx, customresources.Request{
		StackId:     "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:   "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType: customresources.Create,
		ResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
		OldResourceProperties: &ECSServiceProperties{},
	})
	assert.Equal(t, context.Canceled, err)
	assert.Equal(t, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web-dxRU5tYsnzt"}, data)

	e.AssertExpectations(t)
}

func TestECSServiceResource_Update(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("UpdateService", &ecs.UpdateServiceInput{
		Service:        aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster:        aws.String("cluster"),
		DesiredCount:   aws.Int64(2),
		TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
	}).Return(
		&ecs.UpdateServiceOutput{
			Service: &ecs.Service{
				ServiceName: aws.String("acme-inc-web"),
				Deployments: []*ecs.Deployment{
					&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")},
					&ecs.Deployment{Id: aws.String("Old"), Status: aws.String("ACTIVE")},
				},
			},
		},
		nil,
	)

	id, data, err := p.Provision(ctx, customresources.Request{
		StackId:            "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:          "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType:        customresources.Update,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web",
		ResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("cluster"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(2),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("cluster"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(1),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:1"),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web", id)
	assert.Equal(t, data, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web"})

	e.AssertExpectations(t)
}

func TestECSServiceResource_Update_SameDesiredCount(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("UpdateService", &ecs.UpdateServiceInput{
		Service:        aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster:        aws.String("cluster"),
		TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
	}).Return(
		&ecs.UpdateServiceOutput{
			Service: &ecs.Service{
				ServiceName: aws.String("acme-inc-web"),
				Deployments: []*ecs.Deployment{
					&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")},
					&ecs.Deployment{Id: aws.String("Old"), Status: aws.String("ACTIVE")},
				},
			},
		},
		nil,
	)

	id, data, err := p.Provision(ctx, customresources.Request{
		StackId:            "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:          "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType:        customresources.Update,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web",
		ResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("cluster"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(2),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("cluster"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(2),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:1"),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web", id)
	assert.Equal(t, data, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web"})

	e.AssertExpectations(t)
}

func TestECSServiceResource_Update_RequiresReplacement(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("CreateService", &ecs.CreateServiceInput{
		ClientToken:    aws.String("dxRU5tYsnzt"),
		ServiceName:    aws.String("acme-inc-web-dxRU5tYsnzt"),
		Cluster:        aws.String("clusterB"),
		DesiredCount:   aws.Int64(2),
		TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
	}).Return(&ecs.CreateServiceOutput{
		Service: &ecs.Service{
			ServiceName: aws.String("acme-inc-web-dxRU5tYsnzt"),
			ServiceArn:  aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt"),
			Deployments: []*ecs.Deployment{&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")}},
		},
	}, nil)

	e.On("WaitUntilServicesStable", &ecs.DescribeServicesInput{
		Cluster:  aws.String("clusterB"),
		Services: []*string{aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt")},
	}).Return(nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		StackId:            "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:          "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType:        customresources.Update,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt",
		ResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("clusterB"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(2),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("clusterA"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(1),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:1"),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt", id)
	assert.Equal(t, data, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web-dxRU5tYsnzt"})

	e.AssertExpectations(t)
}

func TestECSServiceResource_Update_Placement(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("CreateService", &ecs.CreateServiceInput{
		ClientToken:    aws.String("dxRU5tYsnzt"),
		ServiceName:    aws.String("acme-inc-web-dxRU5tYsnzt"),
		Cluster:        aws.String("clusterA"),
		DesiredCount:   aws.Int64(2),
		TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
		PlacementConstraints: []*ecs.PlacementConstraint{
			{Type: aws.String("memberOf"), Expression: aws.String("attribute:ecs.instance-type =~ t2.*")},
		},
	}).Return(&ecs.CreateServiceOutput{
		Service: &ecs.Service{
			ServiceName: aws.String("acme-inc-web-dxRU5tYsnzt"),
			ServiceArn:  aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt"),
			Deployments: []*ecs.Deployment{&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")}},
		},
	}, nil)

	e.On("WaitUntilServicesStable", &ecs.DescribeServicesInput{
		Cluster:  aws.String("clusterA"),
		Services: []*string{aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt")},
	}).Return(nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		StackId:            "arn:aws:cloudformation:us-east-1:012345678901:stack/acme-inc/bc66fd60-32be-11e6-902b-50d501eb4c17",
		RequestId:          "411f3f38-565f-4216-a711-aeafd5ba635e",
		RequestType:        customresources.Update,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt",
		ResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("clusterA"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(2),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:2"),
			PlacementConstraints: []ECSPlacementConstraint{
				{Type: aws.String("memberOf"), Expression: aws.String("attribute:ecs.instance-type =~ t2.*")},
			},
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:        aws.String("clusterA"),
			ServiceName:    aws.String("acme-inc-web"),
			DesiredCount:   customresources.Int(1),
			TaskDefinition: aws.String("arn:aws:ecs:us-east-1:012345678910:task-definition/acme-inc:1"),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web-dxRU5tYsnzt", id)
	assert.Equal(t, data, map[string]string{"DeploymentId": "New", "Name": "acme-inc-web-dxRU5tYsnzt"})

	e.AssertExpectations(t)
}

func TestECSServiceResource_Delete(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("UpdateService", &ecs.UpdateServiceInput{
		Service:      aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster:      aws.String("cluster"),
		DesiredCount: aws.Int64(0),
	}).Return(
		&ecs.UpdateServiceOutput{
			Service: &ecs.Service{
				Deployments: []*ecs.Deployment{
					&ecs.Deployment{Id: aws.String("New"), Status: aws.String("PRIMARY")},
					&ecs.Deployment{Id: aws.String("Old"), Status: aws.String("ACTIVE")},
				},
			},
		},
		nil,
	)

	e.On("DeleteService", &ecs.DeleteServiceInput{
		Service: aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster: aws.String("cluster"),
	}).Return(&ecs.DeleteServiceOutput{}, nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType:        customresources.Delete,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web",
		ResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web", id)
	assert.Nil(t, data)

	e.AssertExpectations(t)
}

func TestECSServiceResource_Delete_NotActive(t *testing.T) {
	e := new(mockECS)
	p := newECSServiceProvisioner(&ECSServiceResource{
		ecs: e,
	})

	e.On("UpdateService", &ecs.UpdateServiceInput{
		Service:      aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster:      aws.String("cluster"),
		DesiredCount: aws.Int64(0),
	}).Return(&ecs.UpdateServiceOutput{}, awserr.New("ServiceNotActiveException", "Service was not ACTIVE", errors.New("")))

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType:        customresources.Delete,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web",
		ResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: customresources.Int(1),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web", id)
	assert.Nil(t, data)

	e.AssertExpectations(t)
}

func TestECSTaskDefinition_Create(t *testing.T) {
	e := new(mockECS)
	s := new(mockEnvironmentStore)
	p := newECSTaskDefinitionProvisioner(&ECSTaskDefinitionResource{
		ecs:              e,
		environmentStore: s,
	})

	s.On("fetch", "003483d3-74b8-465d-8c2e-06e005dda776").Return([]*ecs.KeyValuePair{
		{
			Name:  aws.String("FOO"),
			Value: aws.String("bar"),
		},
	}, nil)

	s.On("fetch", "ccc8a1ac-32f9-4576-bec6-4ca36520deb3").Return([]*ecs.KeyValuePair{
		{
			Name:  aws.String("BAR"),
			Value: aws.String("foo"),
		},
	}, nil)

	e.On("RegisterTaskDefinition", &ecs.RegisterTaskDefinitionInput{
		Family: aws.String("acme-inc-web-f3ASgQEwwCZ"),
		ContainerDefinitions: []*ecs.ContainerDefinition{
			{
				Environment: []*ecs.KeyValuePair{
					{
						Name:  aws.String("FOO"),
						Value: aws.String("bar"),
					},
					{
						Name:  aws.String("BAR"),
						Value: aws.String("foo"),
					},
				},
			},
		},
		PlacementConstraints: []*ecs.TaskDefinitionPlacementConstraint{
			{
				Type:       aws.String("memberOf"),
				Expression: aws.String("attribute:instance-type =~ t1.micro"),
			},
		},
	}).Return(&ecs.RegisterTaskDefinitionOutput{
		TaskDefinition: &ecs.TaskDefinition{
			TaskDefinitionArn: aws.String("arn:aws:ecs:us-east-1:012345678901:task-definition/acme-inc-web"),
		},
	}, nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType: customresources.Create,
		ResourceProperties: &ECSTaskDefinitionProperties{
			Family: aws.String("acme-inc-web"),
			ContainerDefinitions: []ContainerDefinition{
				{
					Environment: []string{
						"003483d3-74b8-465d-8c2e-06e005dda776",
						"ccc8a1ac-32f9-4576-bec6-4ca36520deb3",
					},
				},
			},
			PlacementConstraints: []ECSPlacementConstraint{
				{
					Type:       aws.String("memberOf"),
					Expression: aws.String("attribute:instance-type =~ t1.micro"),
				},
			},
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:task-definition/acme-inc-web", id)
	assert.Nil(t, data)

	e.AssertExpectations(t)
	s.AssertExpectations(t)
}

func TestECSTaskDefinition_Update(t *testing.T) {
	e := new(mockECS)
	s := new(mockEnvironmentStore)
	p := newECSTaskDefinitionProvisioner(&ECSTaskDefinitionResource{
		ecs:              e,
		environmentStore: s,
	})

	s.On("fetch", "003483d3-74b8-465d-8c2e-06e005dda776").Return([]*ecs.KeyValuePair{
		{
			Name:  aws.String("FOO"),
			Value: aws.String("bar"),
		},
	}, nil)

	s.On("fetch", "4f3f884b-8337-4847-9b81-141b5e322559").Return([]*ecs.KeyValuePair{
		{
			Name:  aws.String("BAR"),
			Value: aws.String("foo"),
		},
	}, nil)

	e.On("RegisterTaskDefinition", &ecs.RegisterTaskDefinitionInput{
		Family: aws.String("acme-inc-web-f3ASgQEwwCZ"),
		ContainerDefinitions: []*ecs.ContainerDefinition{
			{
				Environment: []*ecs.KeyValuePair{
					{
						Name:  aws.String("FOO"),
						Value: aws.String("bar"),
					},
					{
						Name:  aws.String("BAR"),
						Value: aws.String("foo"),
					},
				},
			},
		},
	}).Return(&ecs.RegisterTaskDefinitionOutput{
		TaskDefinition: &ecs.TaskDefinition{
			TaskDefinitionArn: aws.String("arn:aws:ecs:us-east-1:012345678901:task-definition/acme-inc-web"),
		},
	}, nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType: customresources.Update,
		ResourceProperties: &ECSTaskDefinitionProperties{
			Family: aws.String("acme-inc-web"),
			ContainerDefinitions: []ContainerDefinition{
				{
					Environment: []string{
						"003483d3-74b8-465d-8c2e-06e005dda776",
						"4f3f884b-8337-4847-9b81-141b5e322559",
					},
				},
			},
		},
		OldResourceProperties: &ECSTaskDefinitionProperties{
			Family: aws.String("acme-inc-web"),
			ContainerDefinitions: []ContainerDefinition{
				{
					Environment: []string{
						"003483d3-74b8-465d-8c2e-06e005dda776",
						"ccc8a1ac-32f9-4576-bec6-4ca36520deb3",
					},
				},
			},
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:task-definition/acme-inc-web", id)
	assert.Nil(t, data)

	e.AssertExpectations(t)
	s.AssertExpectations(t)
}

func TestECSEnvironment_Create(t *testing.T) {
	s := new(mockEnvironmentStore)
	p := newECSEnvironmentProvisioner(&ECSEnvironmentResource{
		environmentStore: s,
	})

	s.On("store", []*ecs.KeyValuePair{
		{
			Name:  aws.String("FOO"),
			Value: aws.String("bar"),
		},
	}).Return("56152438-5fef-4c96-bbe1-9cf92022ae75", nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType: customresources.Create,
		ResourceProperties: &ECSEnvironmentProperties{
			Environment: []*ecs.KeyValuePair{
				{
					Name:  aws.String("FOO"),
					Value: aws.String("bar"),
				},
			},
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "56152438-5fef-4c96-bbe1-9cf92022ae75", id)
	assert.Nil(t, data)

	s.AssertExpectations(t)
}

func TestECSEnvironment_Update_RequiresReplacement(t *testing.T) {
	s := new(mockEnvironmentStore)
	p := newECSEnvironmentProvisioner(&ECSEnvironmentResource{
		environmentStore: s,
	})

	s.On("store", []*ecs.KeyValuePair{
		{
			Name:  aws.String("FOO"),
			Value: aws.String("bar"),
		},
		{
			Name:  aws.String("BAR"),
			Value: aws.String("foo"),
		},
	}).Return("56152438-5fef-4c96-bbe1-9cf92022ae75", nil)

	id, data, err := p.Provision(ctx, customresources.Request{
		RequestType:        customresources.Update,
		PhysicalResourceId: "56152438-5fef-4c96-bbe1-9cf92022ae75",
		ResourceProperties: &ECSEnvironmentProperties{
			Environment: []*ecs.KeyValuePair{
				{
					Name:  aws.String("FOO"),
					Value: aws.String("bar"),
				},
				{
					Name:  aws.String("BAR"),
					Value: aws.String("foo"),
				},
			},
		},
		OldResourceProperties: &ECSEnvironmentProperties{
			Environment: []*ecs.KeyValuePair{
				{
					Name:  aws.String("BAR"),
					Value: aws.String("foo"),
				},
				{
					Name:  aws.String("FOO"),
					Value: aws.String("bar"),
				},
			},
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "56152438-5fef-4c96-bbe1-9cf92022ae75", id)
	assert.Nil(t, data)

	s.AssertExpectations(t)
}

func TestServiceRequiresReplacement(t *testing.T) {
	tests := []struct {
		new, old properties
		out      bool
	}{
		{
			&ECSServiceProperties{Cluster: aws.String("cluster"), TaskDefinition: aws.String("td:2"), DesiredCount: customresources.Int(1)},
			&ECSServiceProperties{Cluster: aws.String("cluster"), TaskDefinition: aws.String("td:1"), DesiredCount: customresources.Int(0)},
			false,
		},

		{
			&ECSServiceProperties{LoadBalancers: []LoadBalancer{{ContainerName: aws.String("web"), ContainerPort: customresources.Int(8080), LoadBalancerName: aws.String("elb")}}},
			&ECSServiceProperties{LoadBalancers: []LoadBalancer{{ContainerName: aws.String("web"), ContainerPort: customresources.Int(8080), LoadBalancerName: aws.String("elb")}}},
			false,
		},

		// Can't change clusters.
		{
			&ECSServiceProperties{Cluster: aws.String("clusterB")},
			&ECSServiceProperties{Cluster: aws.String("clusterA")},
			true,
		},

		// Can't change name.
		{
			&ECSServiceProperties{ServiceName: aws.String("acme-inc-B")},
			&ECSServiceProperties{ServiceName: aws.String("acme-inc-A")},
			true,
		},

		// Can't change role.
		{
			&ECSServiceProperties{Role: aws.String("roleB")},
			&ECSServiceProperties{Role: aws.String("roleA")},
			true,
		},

		// Can't change load balancers
		{
			&ECSServiceProperties{LoadBalancers: []LoadBalancer{{ContainerName: aws.String("web"), ContainerPort: customresources.Int(8080), LoadBalancerName: aws.String("elbB")}}},
			&ECSServiceProperties{LoadBalancers: []LoadBalancer{{ContainerName: aws.String("web"), ContainerPort: customresources.Int(8080), LoadBalancerName: aws.String("elbA")}}},
			true,
		},
	}

	for _, tt := range tests {
		out, err := requiresReplacement(tt.new, tt.old)
		assert.NoError(t, err)
		assert.Equal(t, tt.out, out)
	}
}

type mockECS struct {
	ecsClient
	mock.Mock
}

func (m *mockECS) CreateService(input *ecs.CreateServiceInput) (*ecs.CreateServiceOutput, error) {
	args := m.Called(input)
	return args.Get(0).(*ecs.CreateServiceOutput), args.Error(1)
}

func (m *mockECS) UpdateService(input *ecs.UpdateServiceInput) (*ecs.UpdateServiceOutput, error) {
	args := m.Called(input)
	return args.Get(0).(*ecs.UpdateServiceOutput), args.Error(1)
}

func (m *mockECS) DeleteService(input *ecs.DeleteServiceInput) (*ecs.DeleteServiceOutput, error) {
	args := m.Called(input)
	return args.Get(0).(*ecs.DeleteServiceOutput), args.Error(1)
}

func (m *mockECS) WaitUntilServicesStable(input *ecs.DescribeServicesInput) error {
	args := m.Called(input)
	return args.Error(0)
}

func (m *mockECS) RegisterTaskDefinition(input *ecs.RegisterTaskDefinitionInput) (*ecs.RegisterTaskDefinitionOutput, error) {
	args := m.Called(input)
	return args.Get(0).(*ecs.RegisterTaskDefinitionOutput), args.Error(1)
}

type mockEnvironmentStore struct {
	mock.Mock
}

func (m *mockEnvironmentStore) store(env []*ecs.KeyValuePair) (string, error) {
	args := m.Called(env)
	return args.String(0), args.Error(1)
}

func (m *mockEnvironmentStore) fetch(id string) ([]*ecs.KeyValuePair, error) {
	args := m.Called(id)
	return args.Get(0).([]*ecs.KeyValuePair), args.Error(1)
}


text:
require "test_helper"

module Folio
  class Console::SearchesControllerTest < ActionDispatch::IntegrationTest
    include Engine.routes.url_helpers

    # test "the truth" do
    #   assert true
    # end
  end
end


text:
import Data.List
import qualified Data.Map as Map
{-
Own types and typeclasses
-}

{-
# Algebraic data types
-}

-- | Value constructors: functions that ultimately return a value of a data type.
-- Shape is a TYPE, Circle isn't. Circle is VALUE CONSTRUCTOR for type
-- Type and the Constructor may have the same name or different names
data Shape1 = Circle1 Float Float Float | Rectangle1 Float Float Float Float
              deriving (Show)  -- multi-constructor

-- | Pattern matching for value constructors
surface1 :: Shape1 -> Float
surface1 (Circle1 _ _ r) = pi * r ^ 2
surface1 (Rectangle1 x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1)

-- | Currying for value constructors, since constructor is a func
circles1 = map (Circle1 10 20) [4,5,6,6]

-- | Conventionally, use the SAME name for the data type and the value constructor, if only one constructor
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)

-- | Nested pattern matching for value constructor
surface :: Shape -> Float
surface (Circle _ r) = pi * r ^ 2
surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)

{-
To EXPORT all the value constructors for a given type, just write ..
```
module Shapes
( Point(..)
, Shape(..)
) where
```

If opt not to export any value constructors for Shape, just writing Shape type in the export statement.
That way, someone importing our module could only make shapes by using the auxilliary functions.
-}

{-
# Record Syntax for value constructor

RECORD syntax creates functions (RECORDs) that lookup fields in the data type.
You can "get" and "set" attributes in RECORD.

namedtuple
-}
data Person = Person { firstName :: String
                     , lastName :: String
                     , age :: Int
                     , height :: Float
                     , phoneNumber :: String
                     , flavor :: String
                     } deriving (Show)

-- | Dict value constructor
data Car = Car {company :: String, model :: String, year :: Int} deriving (Show)
-- Use of value constructor
aCar = Car "Ford" "Mustang" 1967
aCarDict = Car {company="Ford", model="Mustang", year=1967}

showCar :: Car -> String
showCar (Car {company = c, model = m, year = y}) = "This " ++ c ++ " " ++ m ++ " was made in " ++ show y

{-
# Type parameters
## Type constructor
* From value constructor to TYPE CONSTRUCTOR
* DATA is a type constructor [GENERICS]
```
data <type> <type_param> = <dataConstructor>
```
, where type_param is type parameter and dataConstructor takes a <value>, e.g. `Maybe a`.

compared to typelass [INTERFACE], which is like interfaces:
```
class <typeclass> <type>
```
Let <type> implement the requried methods in <typeclass>.

e.g. "a" as the type parameter. Similar to Java generics
* Maybe a
* [a]

A list of stuff is a list of stuff and it doesn't matter what the type of that
stuff is, it can still work.

Polymorphic type: "Nothing" is polymorphic type

## Typeclass constraints in data
Strong convention in Haskell to never add typeclass (class) constraints in type (data)
declarations, since have to put them into the function type declarations
anyway.
-}

-- | Implementation of "Maybe"
-- "a" is a type parameter, thus Maybe' generates a type, e.g. Maybe Int
-- No value can have a type of Maybe, because that's not a type per se, it's a type constructor.
-- Nonthing, Just are data constructor
data Maybe' a = Nothing | Just a

-- | Maybe Num, the Num type is inferred (type inferrence)
-- | Just is-a type/data constructor, Maybe Num is-a type, Just 0 is-a value
aMaybe :: Num a => Maybe a
aMaybe = Just 0

-- | Car String String int, with variable types, although no practical usage.
data Car' a b c = CarConstruct' { company' :: a
                                , model' :: b
                                , year' :: c
                                } deriving (Show)

aCar' = CarConstruct' "Ford" "Mustang" 1967

tellCar' :: (Show a) => Car' String String a -> String
tellCar' (CarConstruct' {company' = c, model' = m, year' = y}) = "This " ++ c ++ " " ++ m ++ " was made in " ++ show y

{-
# Derived Instance
## Deriving typeclass
"typeclass" is like a INTERFACE, "type" implemnts the interface.
e.g. the Int type is an instance of the Eq typeclass.
deriving (<typeclass>)

Type vs. Typeclass
If treat "type" as value, "typeclass" becomes type function, takes type value and returns a new type; type constructor.

## Common typeclasses
Ord
* First comes in value constructor is smaller
* If equal, nested compare

Enum
* successor, predecessor: succ, pred

Bounded
* head smallest, tail largest;
* minBound, maxBound
-}

-- RECORD syntax
data Person' = Person' { firstName' :: String
                       , lastName' :: String
                       , age' :: Int
                       } deriving (Eq, Show, Read)

-- specify the expect type (:: Person') when multiple possible results
deserializePerson = read "Person' {firstName' =\"Michael\", lastName' =\"Diamond\", age' = 43}" :: Person'

data Circle = Ci { ciX :: Double
                 , ciY :: Double
                 , ciR :: Double  -- ciR :: Circle -> Double
                 } deriving(Show)

c0 = Circle {ciX = 0, ciY = 0, ciR =1}

areaCircle :: Circle -> Double
areaCircle c = pi * r * r
  where r = ciR c  -- record selector

-- | nullary constructor
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
           deriving (Eq, Ord, Show, Read, Bounded, Enum)

-- | ellipsis since Enum, .. will call succ for the Enum, Ord
partialDays = [Thursday .. Sunday]

-- | range since Bounded
entireDays = [minBound .. maxBound] :: [Day]

{-
# Type synonyms

SYN
Different name binding:
type String = [Char]

Type constructors vs. Value/Data constructors
Unable to do: TypeConstructor [(1,2),(4,5),(7,9)], since type constructor only takes type params
Able to do: [(1,2),(3,5),(8,9)] :: TypeConstructor Int Int
-}

type PhoneBook = [(String,String)]

-- | Type constructor, parameterized type synonyms, more like GENERICS
type AssocList k v = [(k,v)]

-- | Type constructor currying, since type constructor is a func
type IntMap v = Map.Map Int v
type IntMap' = Map.Map Int

-- | Implementation of "Either", value constructor

-- errors use the Left value constructor while results use Right, GENERICS
data Either' a b = Left' a | Right' b deriving (Eq, Ord, Read, Show)

-- | locker example
data LockerState = Taken | Free deriving (Show, Eq) -- not Enum, but like enumerate
type Code = String
type LockerMap = Map.Map Int (LockerState, Code)

lockerLookup :: Int -> LockerMap -> Either String Code  -- returns Either
lockerLookup lockerNumber map =
    case Map.lookup lockerNumber map of  -- Map.lookup returns Maybe
         Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!"
         Just (state, code) -> if state /= Taken then
                                   Right code
                               else
                                   Left $ "Locker " ++ show lockerNumber ++ " is already taken!"

lockers :: LockerMap
lockers = Map.fromList
    [(100,(Taken,"ZD39I"))
    ,(101,(Free,"JAH3I"))
    ,(103,(Free,"IQSA9"))
    ,(105,(Free,"QOTSA"))
    ,(109,(Taken,"893JJ"))
    ,(110,(Taken,"99292"))
    ]

{-
# Recursive Data Structures
Recursive type
-}
-- | Infix
-- infixr <fixity> <special_chars>; fixitity is the precedence level

-- | Implementation of "++"
infixr 5  .++
(.++) :: List a -> List a -> List a
Empty .++ ys = ys
(x :-: xs) .++ ys = x :-: (xs .++ ys)

-- | List, an implementation of "[a]"
data List' a = Empty' | Cons a (List' a) deriving (Show, Read, Eq, Ord)
-- Cons is another word for "(:)"

infixr 5 :-:
data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord)

-- | Tree
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

-- | construct tree
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
    | x == a = Node x left right
    | x < a  = Node a (treeInsert x left) right
    | x > a  = Node a left (treeInsert x right)

treeFromList xs = foldr treeInsert EmptyTree xs

-- | search tree
treeElem :: (Ord a) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
    | x == a = True
    | x < a  = treeElem x left
    | x > a  = treeElem x right

{-
# Own typeclasses
* typeclasses are like interfaces
* typeclass is not related class in OOP languages
* types that can behave in that way are made instances of that typeclass, IMPLEMENTS
* behavior of typeclasses is achieved by defining functions or just type declarations

## constraints
* class constraints in CLASS declarations are used for making a typeclass a subclass of another typeclass.
* class constraints in INSTANCE declarations are used to express requirements about the contents of some type
-}

-- | implementation of "Eq" typeclass
-- rename funcs, otherwise Ambiguous occurrence '=='
class Eq' a where  -- a type variable, equiv equitable
    (.==) :: a -> a -> Bool  -- type declarations
    (./=) :: a -> a -> Bool
    x .== y = not (x ./= y)  -- mutual recursion, thus only need to define == later in instance
    x ./= y = not (x .== y)

-- | types instances of typeclasses
data TrafficLight = Red | Yellow | Green

-- | instanc of (type) class
-- minimal complete definition: ==
instance Eq TrafficLight where
    Red == Red       = True
    Green == Green   = True
    Yellow == Yellow = True
    _ == _           = False  -- default, catch-all pattern

-- | deriving (Show) by hand, thus can customize show func
instance Show TrafficLight where
    show Red = "Red light"
    show Yellow = "Yellow light"
    show Green = "Green light"

-- | "subclasses typeclasses" is equiv to "class constraints"
class (Eq a) => Num' a where
    dummy :: a

-- | type constructor as instance of typeclass
-- unable to write "instance Eq Maybe where" since Maybe is not a type
instance (Eq m) => Eq (Maybe' m) where
    Just' x == Just' y   = x == y  -- (Eq m) typeclass constraint
    Nothing' == Nothing' = True
    _ == _               = False

{-
# yes-no typeclass
Example
-}
class YesNo a where
    yesno :: a -> Bool

instance YesNo Int where
    yesno 0 = False
    yesno _ = True

instance YesNo [a] where -- [] is type constructor, [a] is a type
    yesno [] = False
    yesno _  = True

instance YesNo Bool where
    yesno = id  -- identify func, (\a -> a)

instance YesNo (Maybe a) where
    yesno (Just _) = True
    yesno Nothing = False

yesnoIf :: (YesNo yn) => yn -> a -> a -> a
yesnoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult

{-
# Functor typeclass
* In mathematics, a functor is a type of mapping between categories which is applied in category theory.
* Functor is a typeclass, which takes a type constructor as param
* Types that can act like a BOX can be functors:
```
instance Functor [] where
    fmap = map

instance Functor Maybe where
    fmap f (Just x) = Just (f x)
    fmap f Nothing = Nothing

instance (Ord k) => Functor (Map.Map k) where
    fmap = M.map
```
-}

-- | implementation of "Functor"
class Functor' f where  -- f is a type constructor
     fmap' :: (a -> b) -> f a -> f b

instance Functor Tree where
    fmap f EmptyTree = EmptyTree
    fmap f (Node x leftsub rightsub) = Node (f x)
                                       (fmap f leftsub)
                                       (fmap f rightsub)

-- | "Either" a is a functor in the standard libraries
-- Curried type constructorsince since Functor takes 1-param type constructor
-- Only maps Right b, leaving Left a untouched
-- Impractical to map both Left a and Right b otherwise Left Right should be the same type
instance Functor (Either' a) where
    fmap f (Right' x) = Right' (f x)
    fmap f (Left' x) = Left' x

{-
# Kind
Type is the type of value
Kind is the type of type

> :k Interactive
Int :: *  -- star kind, a concrete type

> :k Maybe
Maybe :: * -> * -- take a concrete type and returns a concrete type

> :k Either
Either :: * -> * -> *

> :k Either String
Either String :: * -> * -- type constructor curried
-}

-- j is * -> *; t is * -> (* -> *) -> *
class Tofu t where
    tofu :: j a -> t a j

-- Frank is * -> (* -> *) -> *
data Frank a b  = Frank {frankField :: b a} deriving (Show)

instance Tofu Frank where
    tofu x = Frank x

-- Barry is (* -> *) -> * -> * -> *
data Barry t k p = Barry { yabba :: p, dabba :: t k }

instance Functor (Barry t k) where
     fmap f (Barry {yabba = pval, dabba = tkval}) = Barry {yabba = f pval, dabba = tkval}


text:
<script>
  log = ChromeSamples.log;

  function isWebBluetoothEnabled() {
    if (navigator.bluetooth) {
      return true;
    } else {
      ChromeSamples.setStatus('Web Bluetooth API is not available.\n' +
                              'Please make sure the Web Bluetooth flag is enabled.');
      return false;
    }
  }
</script>


text:
module Database.Seakale.Store.Internal where

import           Control.Monad.Identity
import           Control.Monad.Trans
import           Control.Monad.Trans.Free

import           Data.List hiding (insert, delete)
import           Data.Monoid
import           Data.String
import           Data.Typeable
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL

import           Database.Seakale.FromRow
import           Database.Seakale.ToRow
import           Database.Seakale.Types
import           Database.Seakale.Request.Internal

-- | A value together with its identifier.
data Entity a = Entity
  { entityID  :: EntityID a
  , entityVal :: a
  }

deriving instance (Show (EntityID a), Show a) => Show (Entity a)
deriving instance (Eq   (EntityID a), Eq   a) => Eq   (Entity a)

instance (FromRow backend k (EntityID a), FromRow backend l a, (k :+ l) ~ i)
  => FromRow backend i (Entity a) where
  fromRow = Entity `pmap` fromRow `papply` fromRow

instance (ToRow backend k (EntityID a), ToRow backend l a, (k :+ l) ~ i)
  => ToRow backend i (Entity a) where
  toRow backend (Entity i v) = toRow backend i `vappend` toRow backend v

data Relation backend k l a = Relation
  { relationName      :: RelationName
  , relationIDColumns :: Vector k Column
  , relationColumns   :: Vector l Column
  }

eqRelation :: Relation backend k l a -> Relation backend k l a -> Bool
eqRelation rel rel' =
  relationName rel == relationName rel'
  && relationIDColumns rel `eqVector` relationIDColumns rel'
  && relationColumns rel `eqVector` relationColumns rel'

newtype RelationName
  = RelationName { unRelationName :: BS.ByteString -> BS.ByteString }

instance IsString RelationName where
  fromString str = RelationName $ \prefix ->
    if BS.null prefix
      then fromString str
      else fromString str <> " AS " <> prefix

instance Eq RelationName where
  (==) rel1 rel2 = unRelationName rel1 "" == unRelationName rel2 ""

newtype Column = Column { unColumn :: BS.ByteString -> BS.ByteString }

instance IsString Column where
  fromString str = Column $ \prefix ->
    if BS.null prefix then fromString str else prefix <> "." <> fromString str

instance Eq Column where
  (==) col1 col2 = unColumn col1 "" == unColumn col2 ""

instance Show Column where
  show = show . flip unColumn ""

class (Typeable backend, Typeable k, Typeable l, Typeable a)
  => Storable backend (k :: Nat) (l :: Nat) a | a -> k, a -> l where
  data EntityID a :: *
  relation :: backend -> Relation backend k l a

data Condition backend a
  = forall n. Condition (BS.ByteString -> backend -> (Query n, QueryData n))

instance Monoid (Condition backend a) where
  mempty = Condition $ \_ _ -> (EmptyQuery, Nil)
  mappend = combineConditions "AND"

eqCondition :: backend -> Condition backend a -> Condition backend a -> Bool
eqCondition backend (Condition f) (Condition g) =
  let (condQ,  condD)  = f "" backend
      (condQ', condD') = g "" backend
  in condQ `eqQuery` condQ' && condD `eqVector` condD'

combineConditions :: BS.ByteString -> Condition backend a -> Condition backend a
                  -> Condition backend a
combineConditions op (Condition f) (Condition g) =
  Condition $ \prefix backend ->
    let (q1, qdat1) = f prefix backend
        (q2, qdat2) = g prefix backend
        q = case (q1, q2) of
              (EmptyQuery, _) -> q2
              (_, EmptyQuery) -> q1 `qappend` q2 -- just q1 would not compile
              _ -> parenthesiseQuery q1
                   `qappend` Plain (" " <> op <> " ") (parenthesiseQuery q2)
    in (q, qdat1 `vappend` qdat2)

buildCondition :: BS.ByteString -> BS.ByteString -> (backend -> Vector n Column)
               -> (backend -> QueryData n) -> Condition backend a
buildCondition op op' vec dat =
    Condition $ \prefix backend ->
      let dat' = dat backend
          cols = fmap (($ prefix) . unColumn) (vec backend)
          req  = go id cols dat'
      in (req, dat')
  where
    go :: (forall m. Query m -> Query m) -> Vector n BS.ByteString
       -> QueryData n -> Query n
    go _ Nil Nil = EmptyQuery
    go f (Cons x xs) (Cons mBS dat') =
      f $ Plain (x <> " " <> maybe op' (const op) mBS <> " ") $
            Hole $ go (Plain " AND ") xs dat'

buildCondition' :: BS.ByteString
                -> (backend -> Vector n Column) -> (backend -> Vector n Column)
                -> Condition backend a
buildCondition' op vec1 vec2 =
  Condition $ \prefix backend ->
    let q = mconcat . intersperse " AND "
          . map (\(col1, col2) -> unColumn col1 prefix
                                  <> " " <> op <> " "
                                  <> unColumn col2 prefix)
          $ zip (vectorToList (vec1 backend)) (vectorToList (vec2 backend))
    in (Plain q EmptyQuery, Nil)

data Order = Asc | Desc deriving (Show, Eq)

data SelectClauses backend a = SelectClauses
  { selectGroupBy :: backend -> [Column]
  , selectOrderBy :: backend -> [(Column, Order)]
  , selectLimit   :: Maybe Int
  , selectOffset  :: Maybe Int
  }

instance Monoid (SelectClauses backend a) where
  mempty = SelectClauses
    { selectGroupBy = const []
    , selectOrderBy = const []
    , selectLimit   = Nothing
    , selectOffset  = Nothing
    }
  mappend sc1 sc2 = SelectClauses
    { selectGroupBy = \backend ->
        selectGroupBy sc1 backend ++ selectGroupBy sc2 backend
    , selectOrderBy = \backend ->
        let pairs1  = selectOrderBy sc1 backend
            pairs2  = selectOrderBy sc2 backend
            cols2   = map fst pairs2
            pairs1' = filter ((`notElem` cols2) . fst) pairs1
        in pairs1' ++ pairs2
    , selectLimit  = maybe (selectLimit sc1) Just (selectLimit sc2)
    , selectOffset = maybe (selectOffset sc1) Just (selectOffset sc2)
    }

eqSelectClauses :: backend -> SelectClauses backend a -> SelectClauses backend a
                -> Bool
eqSelectClauses backend clauses clauses' =
  selectGroupBy clauses backend == selectGroupBy clauses' backend
  && selectOrderBy clauses backend == selectOrderBy clauses' backend
  && selectLimit clauses == selectLimit clauses'
  && selectOffset clauses == selectOffset clauses'

buildWhereClause :: Condition backend a -> BS.ByteString -> backend
                 -> BSL.ByteString
buildWhereClause (Condition f) prefix backend =
  let cond_ = uncurry formatQuery $ f prefix backend
  in if BSL.null cond_ then "" else " WHERE " <> cond_

buildOnClause :: Condition backend a -> BS.ByteString -> backend
              -> BSL.ByteString
buildOnClause (Condition f) prefix backend =
  let cond_ = uncurry formatQuery $ f prefix backend
  in if BSL.null cond_ then " ON 1=1" else " ON " <> cond_

buildColumnList :: [Column] -> BSL.ByteString
buildColumnList = BSL.fromChunks . intersperse ", " . map (($ "") . unColumn)

buildRelationName :: RelationName -> BSL.ByteString
buildRelationName relName = BSL.fromStrict $ unRelationName relName ""

buildSelectClauses :: SelectClauses backend a -> backend -> BSL.ByteString
buildSelectClauses SelectClauses{..} backend = mconcat
  [ if null (selectGroupBy backend)
      then ""
      else " GROUP BY " <> buildColumnList (selectGroupBy backend)
  , let build (col, Asc)  = unColumn col "" <> " ASC"
        build (col, Desc) = unColumn col "" <> " DESC"
        pairs = selectOrderBy backend
        list  = BSL.fromChunks $ intersperse ", " $ map build pairs
    in if null pairs
         then ""
         else " ORDER BY " <> list
  , maybe "" (\n -> " LIMIT " <> BSL.pack (show n)) selectLimit
  , maybe "" (\n -> " OFFSET " <> BSL.pack (show n)) selectOffset
  ]

buildSelectRequest :: backend -> Relation backend k l a -> Condition backend a
                   -> SelectClauses backend a -> BSL.ByteString
buildSelectRequest backend Relation{..} cond clauses =
  "SELECT " <> buildColumnList (vectorToList relationIDColumns) <> ", "
            <> buildColumnList (vectorToList relationColumns)
            <> " FROM " <> buildRelationName relationName
            <> buildWhereClause cond "" backend
            <> buildSelectClauses clauses backend

buildCountRequest :: backend -> Relation backend k l a -> Condition backend a
                  -> BSL.ByteString
buildCountRequest backend Relation{..} cond =
  "SELECT COUNT(*) FROM " <> buildRelationName relationName
                          <> buildWhereClause cond "" backend

data SelectF backend a
  = forall k l b. (Storable backend k l b, FromRow backend (k :+ l) (Entity b))
    => Select (Relation backend k l b) (Condition backend b)
              (SelectClauses backend b) ([Entity b] -> a)
  | forall k l b. Storable backend k l b
    => Count (Relation backend k l b) (Condition backend b) (Integer -> a)
  | SelectGetBackend (backend -> a)
  | SelectThrowError SeakaleError
  | SelectCatchError a (SeakaleError -> a)

instance Functor (SelectF backend) where
  fmap f = \case
    Select rel cond clauses g       -> Select rel cond clauses (f . g)
    Count  rel cond         g       -> Count  rel cond         (f . g)
    SelectGetBackend g              -> SelectGetBackend (f . g)
    SelectThrowError err            -> SelectThrowError err
    SelectCatchError action handler -> SelectCatchError (f action) (f . handler)

type SelectT backend = FreeT (SelectF backend)
type Select  backend = SelectT backend Identity

class MonadSeakaleBase backend m => MonadSelect backend m where
  select :: (Storable backend k l a, FromRow backend (k :+ l) (Entity a))
         => Relation backend k l a -> Condition backend a
         -> SelectClauses backend a -> m [Entity a]
  count :: Storable backend k l a => Relation backend k l a
        -> Condition backend a -> m Integer

instance Monad m => MonadSeakaleBase backend (FreeT (SelectF backend) m) where
  getBackend        = liftF $ SelectGetBackend id
  throwSeakaleError = liftF . SelectThrowError
  catchSeakaleError action handler =
    FreeT $ return $ Free $ SelectCatchError action handler

instance Monad m => MonadSelect backend (FreeT (SelectF backend) m) where
  select rel cond clauses = liftF $ Select rel cond clauses id
  count  rel cond         = liftF $ Count  rel cond         id

instance {-# OVERLAPPABLE #-} ( MonadSelect backend m, MonadTrans t
                              , MonadSeakaleBase backend (t m) )
  => MonadSelect backend (t m) where
  select rel cond clauses = lift $ select rel cond clauses
  count  rel cond         = lift $ count  rel cond

instance Monad m => MonadSelect backend (RequestT backend m) where
  select rel cond clauses = runSelectT $ select rel cond clauses
  count  rel cond         = runSelectT $ count  rel cond

runSelectT :: Monad m => SelectT backend m a -> RequestT backend m a
runSelectT = iterTM interpreter
  where
    interpreter :: Monad m => SelectF backend (RequestT backend m a)
                -> RequestT backend m a
    interpreter = \case
      Select rel cond clauses f -> do
        backend <- getBackend
        let req = buildSelectRequest backend rel cond clauses
        (cols, rows) <- query req
        case parseRows fromRow backend cols rows of
          Left err -> throwSeakaleError $ RowParseError err
          Right xs -> f xs

      Count rel cond f -> do
        backend <- getBackend
        let req = buildCountRequest backend rel cond
        (cols, rows) <- query req
        case parseRows fromRow backend cols rows of
          Left  err -> throwSeakaleError $ RowParseError err
          Right [x] -> f x
          Right _   ->
            throwSeakaleError $ RowParseError "Non-unique response to count"

      SelectGetBackend f              -> getBackend >>= f
      SelectThrowError err            -> throwSeakaleError err
      SelectCatchError action handler -> catchSeakaleError action handler

runSelect :: Select backend a -> Request backend a
runSelect = runSelectT

data UpdateSetter backend a
  = forall n. UpdateSetter (backend -> Vector n (Column, BS.ByteString))

instance Monoid (UpdateSetter backend a) where
  mempty = UpdateSetter $ const Nil
  mappend (UpdateSetter f) (UpdateSetter g) =
    UpdateSetter $ \backend -> f backend `vappend` g backend

eqUpdateSetter :: backend -> UpdateSetter backend a -> UpdateSetter backend a
               -> Bool
eqUpdateSetter backend (UpdateSetter f) (UpdateSetter g) =
  f backend `eqVector` g backend

data StoreF backend a
  = forall k l b. ( Storable backend k l b, ToRow backend l b
                  , FromRow backend k (EntityID b) )
    => Insert [b] ([EntityID b] -> a)
  | forall k l b. Storable backend k l b
    => Update (UpdateSetter backend b) (Condition backend b) (Integer -> a)
  | forall k l b. Storable backend k l b
    => Delete (Condition backend b) (Integer -> a)

instance Functor (StoreF backend) where
  fmap f = \case
    Insert dat         g -> Insert dat         (f . g)
    Update setter cond g -> Update setter cond (f . g)
    Delete        cond g -> Delete        cond (f . g)

type StoreT backend m = FreeT (StoreF backend) (SelectT backend m)
type Store  backend   = StoreT backend Identity

class MonadSelect backend m => MonadStore backend m where
  insert :: ( Storable backend k l b, ToRow backend l b
            , FromRow backend k (EntityID b) ) => [b] -> m [EntityID b]
  update :: Storable backend k l a => UpdateSetter backend a
         -> Condition backend a -> m Integer
  delete :: Storable backend k l a => Condition backend a -> m Integer

instance MonadSeakaleBase backend m
  => MonadSeakaleBase backend (FreeT (StoreF backend) m) where
  getBackend        = lift getBackend
  throwSeakaleError = lift . throwSeakaleError

  FreeT m `catchSeakaleError` handler = FreeT $
    liftM (fmap (`catchSeakaleError` handler)) m
      `catchSeakaleError` (runFreeT . handler)

instance MonadSelect backend m
  => MonadStore backend (FreeT (StoreF backend) m) where
  insert dat         = liftF $ Insert dat         id
  update setter cond = liftF $ Update setter cond id
  delete        cond = liftF $ Delete        cond id

instance {-# OVERLAPPABLE #-} ( MonadStore backend m, MonadTrans t
                              , MonadSeakaleBase backend (t m) )
  => MonadStore backend (t m) where
  insert dat         = lift $ insert dat
  update setter cond = lift $ update setter cond
  delete cond        = lift $ delete cond

instance Monad m => MonadStore backend (RequestT backend m) where
  insert             = runStoreT . insert
  update setter cond = runStoreT $ update setter cond
  delete             = runStoreT . delete

buildInsertRequest :: Relation backend k l a -> [QueryData l] -> BSL.ByteString
buildInsertRequest Relation{..} dat =
    let before  = Plain ("INSERT INTO "
                         <> BSL.toStrict (buildRelationName relationName)
                         <> " ("
                         <> BSL.toStrict (buildColumnList
                                          (vectorToList relationColumns))
                         <> ") VALUES ")
                        EmptyQuery
        between = buildBetween "(" ")" relationColumns
        after   = Plain (" RETURNING "
                         <> BSL.toStrict (buildColumnList
                                         (vectorToList relationIDColumns)))
                        EmptyQuery
        q = RepeatQuery before between ", " after

    in formatMany q Nil Nil dat

  where
    buildBetween :: BS.ByteString -> BS.ByteString -> Vector n a -> Query n
    buildBetween prefix suffix = \case
      Nil       -> Plain suffix EmptyQuery
      Cons _ xs -> Plain prefix $ Hole $ buildBetween ", " suffix xs

buildSetter :: backend -> UpdateSetter backend a -> BSL.ByteString
buildSetter backend (UpdateSetter f) =
  let pairs = vectorToList $ f backend
  in BSL.fromChunks $ intersperse ", " $
       map (\(col, value) -> unColumn col "" <> " = " <> value) pairs

buildUpdateRequest :: backend -> Relation backend k l a
                   -> UpdateSetter backend a -> Condition backend a
                   -> BSL.ByteString
buildUpdateRequest backend Relation{..} setter cond =
  "UPDATE " <> buildRelationName relationName <> " SET "
            <> buildSetter backend setter
            <> buildWhereClause cond "" backend

buildDeleteRequest :: backend -> Relation backend k l a -> Condition backend a
                   -> BSL.ByteString
buildDeleteRequest backend Relation{..} cond =
  "DELETE FROM " <> buildRelationName relationName
                 <> buildWhereClause cond "" backend

runStoreT :: forall backend m a. Monad m
          => StoreT backend m a -> RequestT backend m a
runStoreT = iterT interpreter . hoistFreeT runSelectT
  where
    interpreter :: Monad m => StoreF backend (RequestT backend m a)
                -> RequestT backend m a
    interpreter = \case
      Insert dat f -> _insert dat f
      Update setter cond f -> do
        backend <- getBackend
        let req = buildUpdateRequest backend (relation backend) setter cond
        f =<< execute req
      Delete cond f -> do
        backend <- getBackend
        let req = buildDeleteRequest backend (relation backend) cond
        f =<< execute req

    _insert :: forall k l b. ( Storable backend k l b, ToRow backend l b
                             , FromRow backend k (EntityID b) )
            => [b] -> ([EntityID b] -> RequestT backend m a)
            -> RequestT backend m a
    _insert dat f = do
        backend <- getBackend
        let req = buildInsertRequest
                    (relation backend :: Relation backend k l b)
                    (map (toRow backend) dat)
        (cols, rows) <- query req
        case parseRows fromRow backend cols rows of
          Left err -> throwSeakaleError $ RowParseError err
          Right xs -> f xs

runStore :: Store backend a -> Request backend a
runStore = runStoreT


text:
<!DOCTYPE html>

  <link type="text/html" rel="stylesheet" href="../blog-stylesheet.css">
  <link href='http://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
  <title>Jane S. Kim</title>

        Jane S. Kim

        Hello! My name is Jane

and I'm a student at

DevBootcamp in Chicago.

TECH

CULTURE

PROJECTS

Oct. 27, 2014

Blocks, Procs and Lambdas: More on Object Oriented Programming

<bold>BLOCKS</bold>

A Ruby <bold>block is any code that is executed using the syntax do and end or curly braces { }</bold>. In a previous blog post, we used blocks to iterate over arrays and hashes and blocks are also used to execute loops. Here are some examples of blocks:

>> [10, 20, 30].each { |number|

>>   puts number * 2

>> }

20, 40, 60

>> 3.times do

>>   puts "This block will print itself out three times."

>> end

"This block will print itself out three times."

"This block will print itself out three times."

"This block will print itself out three times."

We've been working with blocks for a while, and now we know how to officially identify them. Awesome! Now let's extend our knowledge of blocks and move into procs.

<bold>PROCS</bold>

<bold>Procs are saved blocks</bold>. When we create a block, we have the option of assigning it to a proc. This allows us to reuse this block without having to type it out all over again. In other words, procs allow us to name a block, call that name using specific syntax, and execute the code inside the block. Procs are useful because they help maintain important Ruby rule: Don't Repeat Yourself.

Here's the syntax for creating a proc using Proc.new. In our example below, we're converting integers to strings using the method #to_s and returning a destructive array using #collect! and #map!. You can call a proc inside parentheses using the symbol &.

>> return_string = Proc.new { |number| number.to_s }

>> [1, 2, 3].collect!(&return_string)

["1", "2", "3"]

>> [4, 5, 6].map!(&return_string)

["4", "5", "6"]

<bold>LAMBDAS</bold>

<bold>Lambdas are similar to procs in that you can designate a block of code and reuse it</bold>. When it comes to writing and calling a lambda, the syntax is very similar to a proc. Check out the example below:

>> name_of_lambda = lambda { |parameter| block }

>> double = lambda { |number| number * 2 }

>> [1,2,3].map!(&double)

[2,4,6]

>> [4,5,6].collect!(&double)

[8,10,12]

<bold>LAMBDAS VS. PROCS</bold>

Lambdas and procs are similar in many ways but they have a few important differences. First off, <bold>a lambda checks the number of arguments that are passed to it whereas a proc does not</bold>. In the instance where a wrong number of arguments are passed, a lambda will return an error message while a proc will assign nil to its missing arguments. Another important difference between a proc and a lambda is the way they pass control inside of a method. <bold>When a lambda returns its value, it passes control to the calling method first. When a proc returns its value, it returns the value first without going back to the calling method</bold>. Here's an example explaining this in greater detail:

>> def calling_method_proc

>>   control = Proc.new { return "The proc goes first." }

>>   control.call

>>   "The calling method is returned first."

>> end

>> def calling_method_lambda

>>   pass = lambda { return "This is a lambda test." }

>>   pass.call

>>   "The calling method is returned first."

>> end

>> puts calling_method_proc

"The proc goes first."

>> puts calling_method_lambda

"The calling method is returned first."

With this new knowledge in mind, we can write Ruby code that is more concise with less repetition, code that is more DRY. I learned a lot about blocks, procs and lambdas using CodeAcademy's excellent tutorial.

-CodeAcademy on Blocks, Procs and Lambdas

          Copyright 2014 Jane S. Kim | Powered by Octopress


text:
package org.apache.hadoop.hdfs.protocol;

import java.io.IOException;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.BatchedRemoteIterator;

/**
 * CachePoolIterator is a remote iterator that iterates cache pools.
 * It supports retrying in case of namenode failover.
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class CachePoolIterator
    extends BatchedRemoteIterator<String, CachePoolEntry> {

  private final ClientProtocol namenode;

  public CachePoolIterator(ClientProtocol namenode) {
    super("");
    this.namenode = namenode;
  }

  @Override
  public BatchedEntries<CachePoolEntry> makeRequest(String prevKey)
      throws IOException {
    return namenode.listCachePools(prevKey);
  }

  @Override
  public String elementToPrevKey(CachePoolEntry entry) {
    return entry.getInfo().getPoolName();
  }
}


text:
"""Translation related utilities. When imported, injects _ to builtins"""

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import os
import gettext

# Set up message catalog access
base_dir = os.path.realpath(os.path.join(__file__, '..', '..'))
trans = gettext.translation('notebook', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True)
_ = trans.gettext


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ARMAPI_Test
{
    public class InfoFields
    {
        public string meteredRegion { get; set; }
        public string meteredService { get; set; }
        public string project { get; set; }
        public string meteredServiceType { get; set; }
        public string serviceInfo1 { get; set; }
    }
}


text:
from .day import Day
from .event import Event
from .cosplayer import Cosplayer
from .photographer import Photographer
from .message import Message


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace DigitalPlatform.dp2.Statis
{
    /// <summary>
    /// Used in the new navigation events
    /// </summary>
    public class BrowserExtendedNavigatingEventArgs : CancelEventArgs
    {
        private Uri _Url;
        /// <summary>
        /// The URL to navigate to
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public Uri Url
        {
            get { return _Url; }
        }

        private string _Frame;
        /// <summary>
        /// The name of the frame to navigate to
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public string Frame
        {
            get { return _Frame; }
        }

        private UrlContext navigationContext;
        /// <summary>
        /// The flags when opening a new window
        /// </summary>
        public UrlContext NavigationContext
        {
            get { return this.navigationContext; }
        }

        private object _pDisp;
        /// <summary>
        /// The pointer to ppDisp
        /// </summary>
        public object AutomationObject
        {
            get { return this._pDisp; }
            set { this._pDisp = value; }
        }

        /// <summary>
        /// Creates a new instance of WebBrowserExtendedNavigatingEventArgs
        /// </summary>
        /// <param name="automation">Pointer to the automation object of the browser</param>
        /// <param name="url">The URL to go to</param>
        /// <param name="frame">The name of the frame</param>
        /// <param name="navigationContext">The new window flags</param>
        public BrowserExtendedNavigatingEventArgs(object automation, Uri url, string frame, UrlContext navigationContext)
            : base()
        {
            _Url = url;
            _Frame = frame;
            this.navigationContext = navigationContext;
            this._pDisp = automation;
        }
    }
}


text:
package template

const InstanceStorageClassContent = `apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: gp2
  labels:
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: EnsureExists
provisioner: kubernetes.io/aws-ebs
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
parameters:
  type: gp2
`
const InstanceStorageClassEncryptedContent = InstanceStorageClassContent + `
  encrypted: "true"
`


text:
bool EnsureBelow(const std::string &method_name, int64_t min_val, int64_t max_val) {
  for (int i = 0; i < 1000; ++i) {
    auto delay = ray::asio::testing::get_delay_us(method_name);
    if (delay > max_val || delay < min_val) {
      RAY_LOG(ERROR) << "delay=" << delay;
      return false;
    }
  }
  return true;
}

TEST(AsioChaosTest, Basic) {
  RayConfig::instance().testing_asio_delay_us() = "method1=10:100,method2=20:30";
  ray::asio::testing::init();
  ASSERT_TRUE(EnsureBelow("method1", 10, 100));
  ASSERT_TRUE(EnsureBelow("method2", 20, 30));
}

TEST(AsioChaosTest, WithGlobal) {
  RayConfig::instance().testing_asio_delay_us() = "method1=10:10,method2=20:30,*=100:200";
  ray::asio::testing::init();
  ASSERT_TRUE(EnsureBelow("method1", 10, 10));
  ASSERT_TRUE(EnsureBelow("method2", 20, 30));
  ASSERT_TRUE(EnsureBelow("others", 100, 200));
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
class Omnigraffle < Cask
  url 'http://www.omnigroup.com/download/latest/omnigraffle'
  homepage 'http://www.omnigroup.com/products/omnigraffle'
  version 'latest'
  no_checksum
  link 'OmniGraffle.app'
end


text:
@class THTransport;
@class THPacket;
@class THPath;

@protocol THTransportDelegate <NSObject>
-(void)transport:(THTransport*)transport handlePacket:(THPacket*)packet;
-(void)transportDidChangeActive:(THTransport*)transport;
@end

@interface THTransport : NSObject
@property (readonly) NSString* typeName;
@property (assign, nonatomic) id<THTransportDelegate> delegate;
@property (assign, atomic) BOOL available;
@property NSUInteger priority;
@property BOOL isBridge;
-(void)start;
-(THPath*)returnPathTo:(NSData*)address;
-(THPath*)pathTo:(NSDictionary*)pathInformation;
-(void)send:(NSData*)data to:(NSData*)address;
@end

typedef BOOL(^THInterfaceApproverBlock)(NSString* interface);

@interface THIPv4Transport : THTransport<GCDAsyncUdpSocketDelegate>

-(void)start;
-(void)startOnPort:(unsigned short)port;
-(NSArray*)gatherAvailableInterfacesApprovedBy:(THInterfaceApproverBlock)approver;
@property (readonly) NSUInteger port;
@end

@interface THRelayTransport : THTransport
-(id)initWithPath:(THPath*)path;
@end


text:
package com.bingzer.android.patterns.implementor;

public class ImplementorException extends Exception {
    public ImplementorException() {
    }

    public ImplementorException(String detailMessage) {
        super(detailMessage);
    }

    public ImplementorException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public ImplementorException(Throwable throwable) {
        super(throwable);
    }
}


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

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spi.Registry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class FileDataSetConsumerTest extends ContextTestSupport {

    protected FileDataSet dataSet;

    final String testDataFileName = "src/test/data/file-dataset-test.txt";

    final String resultUri = "mock://result";
    final String dataSetName = "foo";
    final String dataSetUri = "dataset://" + dataSetName;

    @Override
    protected Registry createRegistry() throws Exception {
        Registry answer = super.createRegistry();
        answer.bind("foo", dataSet);
        return answer;
    }

    @Test
    public void testDefaultListDataSet() throws Exception {
        MockEndpoint result = getMockEndpoint(resultUri);
        result.expectedMinimumMessageCount((int) dataSet.getSize());

        result.assertIsSatisfied();
    }

    @Test
    public void testDefaultListDataSetWithSizeGreaterThanListSize() throws Exception {
        MockEndpoint result = getMockEndpoint(resultUri);
        dataSet.setSize(20);
        result.expectedMinimumMessageCount((int) dataSet.getSize());

        result.assertIsSatisfied();
    }

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        dataSet = new FileDataSet(testDataFileName);
        assertEquals(1, dataSet.getSize(), "Unexpected DataSet size");
        super.setUp();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from(dataSetUri).to("mock://result");
            }
        };
    }
}


text:
namespace EmployeeTree.Web.Controllers
{
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web.Mvc;
    using EmployeeTree.Data;
    using EmployeeTree.Models;
    using EmployeeTree.Web.ViewModels;
    using System;
    using System.Collections.Generic;

    public class TeamController : Controller
    {
        private IEmployeeDbContext context;

        public TeamController(EmployeeDbContext context)
        {
            this.context = context;
        }

        // GET: Team
        public ActionResult Index(bool isAscending = false, string orderByColumn = null)
        {
            var teams = context.Teams.Include(t => t.Leader).Include(t => t.Project);

            ViewBag.IsAscending = isAscending;
            var teamsList = new List<Team>(teams);
            var orderFunc = GetOrderFunction(orderByColumn);
            var teamsSorted = isAscending ? teamsList.OrderBy(orderFunc) : teamsList.OrderByDescending(orderFunc);
            return View(teamsSorted.ToList());
        }

        private Func<Team, object> GetOrderFunction(string orderByColumn)
        {
            Func<Team, object> orderFunc;
            switch (orderByColumn)
            {
                case "Name":
                    orderFunc = team => team.Name;
                    break;
                case "Delivery":
                    orderFunc = team => team.Delivery;
                    break;
                case "Leader":
                    orderFunc = employee => employee.LeaderId;
                    break;
                case "Project":
                    orderFunc = employee => employee.ProjectId;
                    break;
                default:
                    orderFunc = team => team.Id;
                    break;
            }

            return orderFunc;
        }

        // GET: Team/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Team team = context.Teams.Find(id);
            if (team == null)
            {
                return HttpNotFound();
            }
            return View(team);
        }

        // GET: Team/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Team team = context.Teams.Find(id);
            if (team == null)
            {
                return HttpNotFound();
            }
            return View(team);
        }

        // POST: Team/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            var team = context.Teams.Find(id);
            if (team.Members != null)
            {
                foreach (var member in team.Members)
                {
                    member.ManagerId = null;
                }
            }

            context.Teams.Remove(team);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        // GET: Team/Create
        public ActionResult Create()
        {
            FillTheViewBags();
            return View();
        }

        // POST: Team/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Delivery,LeaderId,ProjectId, Members")] TeamWithEmployeesViewModel teamModel)
        {
            if (teamModel.Members != null)
            {
                var disinctEmployees = teamModel.Members.Distinct();
                if (disinctEmployees.Count() < teamModel.Members.Count)
                {
                    ModelState.AddModelError("", "Each employee may exists only once in a team.");
                }
            }
            if (teamModel.LeaderId != null)
            {
                var leader = context.Employees.Find(teamModel.LeaderId);
                if (teamModel.Members != null)
                {
                    foreach (var member in teamModel.Members)
                    {
                        var memberFromBase = context.Employees.Find(member.Id);
                        if (memberFromBase.Position > leader.Position)
                        {
                            ModelState.AddModelError("", "The leader of the team must be the employee with the highest position.");
                        }
                        if (member.Id == teamModel.LeaderId)
                        {
                            ModelState.AddModelError("LeaderId", "The leader cannot be duplicated as a member of the team");
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("LeaderId", "Leader of the team is required.");
            }

            if (teamModel.Delivery == 0)
            {
                ModelState.AddModelError("Delivery", "Delivery field is required");
            }

            var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
            var errors = ModelState.Where(m => m.Key.Contains("Members")).Select(m => m.Key);
            foreach (var error in errors)
            {
                ModelState[error].Errors.Clear();
            }

            if (!ModelState.IsValid)
            {
                FillTheViewBags();
                return View(teamModel);
            }

            //Creating a team and filling up its props
            var team = new Team();
            team.Name = teamModel.Name;
            team.Delivery = teamModel.Delivery;
            team.LeaderId = teamModel.LeaderId;
            team.ProjectId = teamModel.ProjectId;

            var teamLeader = context.Employees.Find(teamModel.LeaderId);
            teamLeader.Teams.Add(team);
            //Changing employees Manager and Delivery to be the same as their current team and after that adding them in the team
            if (teamModel.Members != null)
            {
                foreach (var employee in teamModel.Members)
                {
                    var teamMember = context.Employees.Find(employee.Id);
                    if (teamMember.ManagerId == null)
                    {
                        teamMember.ManagerId = team.LeaderId;
                    }
                    teamMember.Delivery = team.Delivery;
                    team.Members.Add(teamMember);
                }
            }

            context.Teams.Add(team);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            var teamEdit = context.Teams.Find(id);
            //Creating TeamModelView and filling it up
            var teamView = new TeamWithEmployeesViewModel();
            teamView.Name = teamEdit.Name;
            teamView.Id = teamEdit.Id;
            teamView.Members = teamEdit.Members.ToList();
            teamView.LeaderId = teamEdit.LeaderId;
            teamView.ProjectId = teamEdit.ProjectId;
            teamView.Delivery = teamEdit.Delivery;

            FillTheViewBagsWithSelected(teamView);
            return View(teamView);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Delivery,LeaderId, Leader,ProjectId, Members")] TeamWithEmployeesViewModel teamModel)
        {
            if (teamModel.Members != null)
            {
                var disinctEmployees = teamModel.Members.Distinct();
                if (disinctEmployees.Count() < teamModel.Members.Count)
                {
                    ModelState.AddModelError("", "Each employee may exists only once in a team.");
                }
            }
            if (teamModel.LeaderId != null)
            {
                var leader = context.Employees.Find(teamModel.LeaderId);
                if (teamModel.Members != null)
                {
                    foreach (var member in teamModel.Members)
                    {
                        var memberFromBase = context.Employees.Find(member.Id);
                        if (memberFromBase.Position > leader.Position)
                        {
                            ModelState.AddModelError("", "The leader of the team must be the employee with the highest position.");
                        }
                        if (member.Id == teamModel.LeaderId)
                        {
                            ModelState.AddModelError("LeaderId", "The leader cannot be duplicated as a member of the team");
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("LeaderId", "Leader of the team is required.");
            }

            if (teamModel.Delivery == 0)
            {
                ModelState.AddModelError("Delivery", "Delivery field is required");
            }
            var teamEditted = context.Teams.Find(teamModel.Id);
            var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
            var errors = ModelState.Where(m => m.Key.Contains("Members")).Select(m => m.Key);
            foreach (var error in errors)
            {
                ModelState[error].Errors.Clear();
            }

            if (!ModelState.IsValid)
            {
                teamModel.Members = teamEditted.Members.ToList();
                FillTheViewBagsWithSelected(teamModel);
                return View(teamModel);
            }

            //taking the current team from the context and updating its fields

            teamEditted.Name = teamModel.Name;
            teamEditted.ProjectId = teamModel.ProjectId;
            teamEditted.Delivery = teamModel.Delivery;

            if (teamEditted.LeaderId != teamModel.LeaderId)
            {
                var oldLeader = context.Employees.Find(teamEditted.LeaderId);
                oldLeader.Teams.Remove(teamEditted);
                var newLeader = context.Employees.Find(teamModel.LeaderId);
                newLeader.Teams.Add(teamEditted);
                teamEditted.LeaderId = teamModel.LeaderId;
            }

            if (teamModel.Members != null)
            {
                //Subtraction the Old from New team so we can get the teams who are removed from the project
                var subractOldFromNewMembers = teamEditted.Members.Except(teamModel.Members);
                var listWithMembersToRemove = subractOldFromNewMembers.ToList();
                listWithMembersToRemove.Remove(teamEditted.Leader);
                if (listWithMembersToRemove != null)
                {
                    foreach (var memberToRemove in listWithMembersToRemove)
                    {
                        //Finding the employee from the context and checking if he is the leader of team
                        //after that deleting if he is not cos the leader of team is still member of the team
                        var employeeToDelete = context.Employees.Find(memberToRemove.Id);
                        if (employeeToDelete.Id != teamEditted.LeaderId)
                        {
                            teamEditted.Members.Remove(employeeToDelete);
                        }
                    }
                }

                //Subtraction the New from Old team so we can get the teams who are added to the project
                var subractNewFromOldMemebers = teamModel.Members.Except(teamEditted.Members);
                if (subractNewFromOldMemebers != null)
                {
                    foreach (var memberToAdd in subractNewFromOldMemebers)
                    {
                        //Finding the member to add from the context and checking his ManagerId and
                        //if its null we are assigning him to the current team Leader as Manager and changing his delivery to the team ones
                        var employeeToAdd = context.Employees.Find(memberToAdd.Id);
                        if (employeeToAdd.ManagerId == null)
                        {
                            employeeToAdd.ManagerId = teamEditted.LeaderId;
                        }
                        employeeToAdd.Delivery = teamEditted.Delivery;
                        teamEditted.Members.Add(employeeToAdd);
                    }
                }
            }
            else
            {
                foreach (var member in teamEditted.Members)
                {
                    if (member.Id != teamEditted.LeaderId)
                    {
                        member.Teams.Remove(teamEditted);
                    }
                }
            }

            context.SaveChanges();
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Fill the ViewBags with Leaders("LeadersId"), Projects("ProjectsId") and Employees("FreeEmployees")
        /// </summary>
        private void FillTheViewBags()
        {
            /*Taking all the free leaders who are: 1) with position equal or higher then TL
                                                   2) TLs without team     */
            var freeLeaders = context.Employees.Where(e => e.Position >= Position.TeamLeader ||
                                                            (e.Teams.Count == 0 && e.Position == Position.TeamLeader))
                                                            .OrderBy(e => e.Position)
                                                            .ToList();
            /*Taking employees who are: 1) with position higher or equal to TL
             *                          2) Position less or equal to TL and got no team
             */
            var freeEmployees = context.Employees.Where(e => e.Position >= Position.TeamLeader ||
                                                            (e.Teams.Count == 0 && e.Position < Position.TeamLeader))
                                                            .OrderBy(e => e.Position)
                                                            .ToList();

            //Taking from the list above all the TL who are not leader to this team and checking if they are leaders in other team
            //because a TL can be Leader in only 1 team
            var leaders = freeLeaders.Where(l => l.Position == Position.TeamLeader).ToList();
            foreach (var leader in leaders)
            {
                if (context.Teams.Any(e => e.LeaderId == leader.Id))
                {
                    freeLeaders.Remove(leader);
                }
            }

            ViewBag.LeaderId = new SelectList(freeLeaders, "Id", "FullNamePositionAndEmail");
            ViewBag.ProjectId = new SelectList(context.Projects, "Id", "Name");
            ViewBag.FreeEmployees = new SelectList(freeEmployees, "Id", "FullNamePositionAndEmail");
        }

        /// <summary>
        /// Fill the ViewBags with Leaders("LeadersId"), Projects("ProjectsId") and Employees("FreeEmployees") and giving them selected values
        /// </summary>
        private void FillTheViewBagsWithSelected(TeamWithEmployeesViewModel teamView)
        {
            /*Taking all the free leaders who are: 1) with position equal or higher then TL
                                                   2) TLs without team     */
            var freeLeaders = context.Employees.Where(e => e.Position >= Position.TeamLeader ||
                                                            (e.Teams.Count == 0 && e.Position == Position.TeamLeader))
                                                            .OrderBy(e => e.Position)
                                                            .ToList();
            /*Taking employees who are: 1) with position higher then TL
             *                          2) Position less or equal to TL and got no team
             */
            var freeEmployees = context.Employees.Where(e => e.Position >= Position.TeamLeader ||
                                                            (e.Teams.Count == 0 && e.Position < Position.TeamLeader))
                                                            .OrderBy(e => e.Position)
                                                            .ToList();
                                                            //(e.Id == teamView.LeaderId))

            //Taking from the list above all the TL who are not leader to this team and checking if they are leaders in other team
            //because a TL can be Leader in only 1 team
            var leaders = freeLeaders.Where(l => l.Position == Position.TeamLeader && l.Id != teamView.LeaderId).ToList();
            foreach (var leader in leaders)
            {
                if (context.Teams.Any(e => e.LeaderId == leader.Id))
                {
                    freeLeaders.Remove(leader);
                }
            }

            ViewBag.LeaderId = new SelectList(freeLeaders, "Id", "FullNamePositionAndEmail", teamView.LeaderId);
            ViewBag.ProjectId = new SelectList(context.Projects, "Id", "Name", teamView.ProjectId);
            ViewBag.FreeEmployees = new SelectList(freeEmployees, "Id", "FullNamePositionAndEmail");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                context.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Bleeding Edge UX: The desktop experience inside the browser</title>

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<link rel="stylesheet" href="css/reveal.css">
		<link href="fonts/fa/css/font-awesome.css" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="css/theme/night.css" id="theme">
		<link rel="stylesheet" href="css/fullscreen-img.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">


text:
import Ember from 'ember';
import helperFactory from 'ember-moment/helpers/moment-to-now';
import makeBoundHelper from 'ember-moment/utils/make-bound-helper';
import config from '../config/environment';

const helper = helperFactory(!!Ember.get(config, 'moment.allowEmpty'));

export default makeBoundHelper(helper);


text:
var Cucumber = require('cucumber')
  , listener = Cucumber.Listener()
listener.hasHandlerForEvent = function() { return true }
listener.getHandlerForEvent = function() { return handler }

function handler(event, callback) {
    console.log('Event: ' + event.getName())
    callback()
}

module.exports = listener


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="String" xsi:noNamespaceSchemaLocation="../test_scenario.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<name>TestProject Type access</name>
	<description>Contains types with different visibility</description>
	<type>
		<name>sample.PublicClass</name>
		<property>public</property>
		<property>class</property>
	</type>
	<type>
		<name>sample.ProtectedClass</name>
		<property>protected</property>
		<property>class</property>
	</type>
	<type>
		<name>sample.PrivateClass</name>
		<property>private</property>
		<property>class</property>
	</type>
	<type>
		<name>sample.PublicFinalClass</name>
		<property>public</property>
		<property>final</property>
		<property>class</property>
	</type>
</project>


text:
/**
 * directives/checkbox.js
 *
 * Directives to render a semantic-ui checkbox
 * correctly.
 */

vpnChooserApp.directive('ngCheckBox', function ($timeout) {
    return {
        restrict: 'AE',
        require: '^ngModel ^ngDescription ^ngChange',
        template: '',
        scope: {
            model: '=ngModel',
            ngDescription: '@',
            checked: '@',
            ngChange: '&'
        },
        replace: true,
        controller: function($scope, $element) {
            if ($scope.checked == 'false' || $scope.checked == undefined) {
                $scope.checked = false;
            } else {
                $scope.checked = true;
                element.children()[0].setAttribute('checked', 'true');
            }

            $element.bind('click', function() {
                $scope.$apply(function() {
                    if ($scope.checked == true) {
                        $scope.checked = false;
                        $scope.model = false;
                        $element.children()[0].removeAttribute('checked');
                    } else {
                        $scope.checked = true;
                        $scope.model = true;
                        $element.children()[0].setAttribute('checked', 'true');
                    }
                    $timeout(function() {
                        $scope.ngChange();
                    }, 1);
                });
            });

            $scope.$watch('checked', function(val){
                if (val == undefined)
                    return;

                if (val == true){
                    $scope.model = true;
                    $element.children()[0].setAttribute('checked', 'true');
                } else {
                    $scope.model = false;
                    $element.children()[0].removeAttribute('checked');
                }
            });

            $scope.$watch('model', function(val) {
                if (val == undefined)
                    return;

                if (val == true){
                    $scope.checked = true;
                    $element.children()[0].setAttribute('checked', 'true');
                } else {
                    $scope.checked = false;
                    $element.children()[0].removeAttribute('checked');
                }
            });

        },
        templateUrl: 'src/partials/directives/checkbox.html'
    }
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Metafunctions</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Fusion 2.2">
<link rel="up" href="../query.html" title="Query">
<link rel="prev" href="functions/count_if.html" title="count_if">
<link rel="next" href="metafunctions/any.html" title="any">

Home
Libraries
People
FAQ
More

Metafunctions

any

all

none

find

find_if

count

count_if

Copyright © 2001-2006, 2011, 2012 Joel de Guzman,
      Dan Marsden, Tobias Schwinger

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


text:
from google.cloud import container_v1

def sample_set_addons_config():
    # Create a client
    client = container_v1.ClusterManagerClient()

    # Initialize request argument(s)
    request = container_v1.SetAddonsConfigRequest(
    )

    # Make the request
    response = client.set_addons_config(request=request)

    # Handle the response
    print(response)

# [END container_v1_generated_ClusterManager_SetAddonsConfig_sync]