text:
copyright:
  years: 2015, 2017
lastupdated: "2017-4-26"

---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}

# Usando uma cadeia de ferramentas
{: #toolchains-using}

As cadeias de ferramentas abertas estão disponíveis nos ambientes Public e Dedicated no {{site.data.keyword.Bluemix}}. É possível usar uma cadeia de ferramentas para ser produtivo em seu trabalho diário de desenvolvimento, implementação e operações. Após
configurar uma cadeia de ferramentas, é possível incluir, excluir ou configurar integrações de ferramenta e gerenciar acesso à cadeia de ferramentas.
{: shortdesc}

## Configurando uma integração de ferramenta
{: #configuring_a_tool_integration}

Se você tiver adiado a configuração de uma integração de ferramenta quando criou uma cadeia de ferramentas, um botão **Configurar** será mostrado em seu cartão. Se você configurou uma integração de ferramenta quando criou uma cadeia de ferramentas, será possível atualizar as definições de configuração.

1. No painel do DevOps, na página **Cadeias de ferramentas**, clique em uma cadeia de ferramentas para abrir sua página Visão geral. Como alternativa, na página Visão geral do app, no cartão do Continuous Delivery, clique em **Visualizar cadeia de ferramentas** e, em seguida, clique em **Visão geral**.
1. Se precisar configurar uma integração de ferramenta pela primeira vez, em seu cartão, clique em **Configurar**.

  ![Botão de configuração
](images/toolchain_tile_configure.png)

 Quando tiver finalizado a configuração da integração de ferramenta, clique em **Salvar integração**.

1. Se precisar atualizar a configuração de uma integração de ferramenta, em seu cartão, clique no menu para acessar as opções de configuração.

  ![Menu Configuração](images/toolchain_tile_menu.png)

 **Dica**: algumas das integrações de ferramenta são pré-configuradas e não requerem parâmetros de configuração. É possível atualizar as definições de configuração para apenas as integrações de ferramenta configuradas.

 Quando tiver finalizado a atualização das configurações, clique em **Salvar integração**.

## Incluindo uma integração de ferramenta
{: #adding_a_tool_integration}

É possível incluir e configurar integrações de ferramenta para sua cadeia de ferramentas. As integrações de ferramentas disponíveis são diferentes, dependendo de se você usa o {{site.data.keyword.Bluemix_notm}} Public ou o {{site.data.keyword.Bluemix_notm}} Dedicated.

1. No painel do DevOps, na página **Cadeias de ferramentas**, clique em uma cadeia de ferramentas para abrir sua página Visão geral. Como alternativa, na página Visão geral do app, no cartão do Continuous Delivery, clique em **Visualizar cadeia de ferramentas** e, em seguida, clique em **Visão geral**.
1. Para ver uma lista de integrações de ferramenta a serem incluídas, clique em **Incluir uma ferramenta**.
1. Clique em uma integração de ferramenta que deseja incluir.
1. Insira quaisquer informações necessárias para configurar a integração de ferramenta.
1. Clique em **Criar integração** para incluir a integração de ferramenta em sua cadeia de ferramentas.

## Excluindo uma integração de ferramenta
{: #deleting_a_tool_integration}

Se você excluir uma integração de ferramenta a partir de sua cadeia de ferramentas, a exclusão não poderá ser desfeita.

1. No painel do DevOps, na página **Cadeias de ferramentas**, clique em uma cadeia de ferramentas para abrir sua página Visão geral. Como alternativa, na página Visão geral do app, no cartão do Continuous Delivery, clique em **Visualizar cadeia de ferramentas** e, em seguida, clique em **Visão geral**.
1. No cartão da integração de ferramenta que desejar excluir, clique no menu para acessar as opções de configuração.
1. Para excluir a integração de ferramenta de sua cadeia de ferramentas, clique em **Excluir**.
1. Confirme clicando em **Excluir**.

## Gerenciando acesso
{: #managing_access}

É possível conceder aos usuários acesso a uma cadeia de ferramentas, incluindo-os na organização (org) à qual a cadeia de ferramentas está associada e à lista de controle de acesso da cadeia de ferramentas. Cada cadeia de ferramentas é associada a uma organização específica e qualquer usuário que seja membro dessa organização poderá ser incluído na lista de controle de acesso de qualquer uma das cadeias de ferramentas associadas. A organização na qual você está trabalhando atualmente é exibida na barra de menus. Para acessar um conjunto diferente de cadeias de ferramentas, alterne para uma organização diferente.

Se você estiver usando o {{site.data.keyword.Bluemix_notm}} Dedicated for {{site.data.keyword.ghe_short}}, ao incluir usuários em sua organização e espaços do {{site.data.keyword.Bluemix_notm}}, os usuários poderão efetuar login no {{site.data.keyword.ghe_short}} usando seus IDs e senhas do {{site.data.keyword.Bluemix_notm}}. Quando os usuários efetuarem login, as contas serão criadas para eles. Quando você incluir usuários em sua organização e espaços do {{site.data.keyword.Bluemix_notm}}, eles não serão incluídos automaticamente no repositório {{site.data.keyword.ghe_short}}. Alguém com privilégio do administrador para o repositório deverá inclui-los. Para obter mais informações, consulte [Usando o Dedicated GitHub Enterprise](/docs/services/ghededicated/index.html){: new_window}. Se você estiver usando sua própria versão gerenciada do {{site.data.keyword.ghe_short}}, siga seus procedimentos internos.

###Dicas para gerenciar o acesso a uma cadeia de ferramentas

* Para gerenciar o acesso à cadeia de ferramentas, no painel do DevOps, na página **Cadeias de ferramentas**, clique na cadeia de ferramentas a ser gerenciada e, em seguida, clique em **Gerenciar**. Como alternativa, na página Visão geral do app, no cartão do Continuous Delivery, clique em **Visualizar cadeia de ferramentas** e, em seguida, clique em **Gerenciar**.

* Para conceder acesso a todos os membros da organização da cadeia de ferramentas, clique em **Incluir organização**. Todos os membros dessa organização poderão visualizar a cadeia de ferramentas.

* É possível conceder privilégios de administrador para uma organização ou um usuário. Os administradores podem modificar e excluir a cadeia de ferramentas. Para conceder privilégios de administrador, marque a caixa de seleção **ADMINISTRADOR** da organização ou do usuário.

* Se você marcar a caixa de seleção **ADMINISTRADOR** de uma organização, todos os membros dessa organização se tornarão administradores. Se você incluir membros na organização depois de conceder privilégios de administrador para a organização, esses membros receberão o mesmo acesso que o resto da organização.

* Para conceder acesso a um usuário que é um membro da organização da cadeia de ferramentas, insira o ID do usuário e clique em **Incluir usuário**. O usuário pode visualizar a cadeia de ferramentas.

* Para conceder acesso a um usuário que não é um membro da organização da cadeia de ferramentas, siga estas etapas:

   a. Na barra de menus, clique em **Gerenciar > Conta > Organizações**.

   b. Clique em **Convidar membros da equipe**.

   c. Selecione a organização para a qual você deseja convidar o usuário e clique em **Avançar**.

   d. Selecione os espaços os quais você deseja permitir que o usuário acesse.

   e. Selecione a função a ser designada aos espaços selecionados na organização.

     **Nota**: por padrão, os gerenciadores da organização têm privilégios completos de administrador a todas as cadeias de ferramentas que estão associadas à organização. Para conceder privilégios completos de administrador ao usuário, selecione a função **Gerenciador**. As funções Gerente de faturamento e Auditor não afetam o acesso da cadeia de ferramentas. É possível mudar as funções posteriormente, na página Diretório da Equipe. Para obter mais informações, veja [Gerenciando membros da equipe e funções](/docs/admin/users_roles.html){: new_window}.

   f. Selecione a opção para confirmar que você assume a responsabilidade financeira por todos os encargos incorridos na conta.

   g. Insira o endereço de e-mail do usuário que você deseja convidar e clique em **Enviar**.

   h. Depois que o usuário for um membro da organização, retorne à página Gerenciar da cadeia de ferramentas e inclua o usuário na cadeia de ferramentas.

## Excluindo uma cadeia de ferramentas
{: #deleting_a_toolchain}

É possível excluir uma cadeia de ferramentas e especificar qual das integrações de ferramenta associadas deseja excluir. Quando você excluir uma cadeia de ferramentas, a exclusão não poderá ser desfeita.

1. No painel do DevOps, na página **Cadeias de ferramentas**, clique na cadeia de ferramentas a ser excluída. Como alternativa, na página Visão geral do app, no cartão do Continuous Delivery, clique em **Visualizar cadeia de ferramentas**.
1. Clique no menu **Mais ações**, que está próximo a **Visualizar app**.
1. Clique em **Excluir** e revise ou ajuste as integrações de ferramentas que você estiver excluindo.
1. Confirme a exclusão digitando o nome da cadeia de ferramentas e clicando em **Excluir**.

 **Dica**: ao excluir uma integração de ferramenta GitHub, {{site.data.keyword.ghe_short}} ou Git Repos and Issue Tracking, o repositório associado não será excluído do GitHub, do {{site.data.keyword.ghe_short}} ou do Git Repos and Issue Tracking. Deve-se remover manualmente o repositório.


text:
@interface CVShareInfoLabel : UILabel
{

}

@end

redpajama_set_name: RedPajamaGithub


text:
package pubsub

import (
	"errors"
	"fmt"
	"io"
	"strings"
	"sync"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/internal/optional"
	"github.com/golang/protobuf/ptypes"
	durpb "github.com/golang/protobuf/ptypes/duration"
	"golang.org/x/net/context"
	"golang.org/x/sync/errgroup"
	pb "google.golang.org/genproto/googleapis/pubsub/v1"
	fmpb "google.golang.org/genproto/protobuf/field_mask"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

// Subscription is a reference to a PubSub subscription.
type Subscription struct {
	c *Client

	// The fully qualified identifier for the subscription, in the format "projects/<projid>/subscriptions/<name>"
	name string

	// Settings for pulling messages. Configure these before calling Receive.
	ReceiveSettings ReceiveSettings

	mu            sync.Mutex
	receiveActive bool
}

// Subscription creates a reference to a subscription.
func (c *Client) Subscription(id string) *Subscription {
	return &Subscription{
		c:    c,
		name: fmt.Sprintf("projects/%s/subscriptions/%s", c.projectID, id),
	}
}

// String returns the globally unique printable name of the subscription.
func (s *Subscription) String() string {
	return s.name
}

// ID returns the unique identifier of the subscription within its project.
func (s *Subscription) ID() string {
	slash := strings.LastIndex(s.name, "/")
	if slash == -1 {
		// name is not a fully-qualified name.
		panic("bad subscription name")
	}
	return s.name[slash+1:]
}

// Subscriptions returns an iterator which returns all of the subscriptions for the client's project.
func (c *Client) Subscriptions(ctx context.Context) *SubscriptionIterator {
	it := c.subc.ListSubscriptions(ctx, &pb.ListSubscriptionsRequest{
		Project: c.fullyQualifiedProjectName(),
	})
	return &SubscriptionIterator{
		c: c,
		next: func() (string, error) {
			sub, err := it.Next()
			if err != nil {
				return "", err
			}
			return sub.Name, nil
		},
	}
}

// SubscriptionIterator is an iterator that returns a series of subscriptions.
type SubscriptionIterator struct {
	c    *Client
	next func() (string, error)
}

// Next returns the next subscription. If there are no more subscriptions, iterator.Done will be returned.
func (subs *SubscriptionIterator) Next() (*Subscription, error) {
	subName, err := subs.next()
	if err != nil {
		return nil, err
	}
	return &Subscription{c: subs.c, name: subName}, nil
}

// PushConfig contains configuration for subscriptions that operate in push mode.
type PushConfig struct {
	// A URL locating the endpoint to which messages should be pushed.
	Endpoint string

	// Endpoint configuration attributes. See https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions#pushconfig for more details.
	Attributes map[string]string
}

func (pc *PushConfig) toProto() *pb.PushConfig {
	return &pb.PushConfig{
		Attributes:   pc.Attributes,
		PushEndpoint: pc.Endpoint,
	}
}

// Subscription config contains the configuration of a subscription.
type SubscriptionConfig struct {
	Topic      *Topic
	PushConfig PushConfig

	// The default maximum time after a subscriber receives a message before
	// the subscriber should acknowledge the message. Note: messages which are
	// obtained via Subscription.Receive need not be acknowledged within this
	// deadline, as the deadline will be automatically extended.
	AckDeadline time.Duration

	// Whether to retain acknowledged messages. If true, acknowledged messages
	// will not be expunged until they fall out of the RetentionDuration window.
	RetainAckedMessages bool

	// How long to retain messages in backlog, from the time of publish. If
	// RetainAckedMessages is true, this duration affects the retention of
	// acknowledged messages, otherwise only unacknowledged messages are retained.
	// Defaults to 7 days. Cannot be longer than 7 days or shorter than 10 minutes.
	RetentionDuration time.Duration
}

func (cfg *SubscriptionConfig) toProto(name string) *pb.Subscription {
	var pbPushConfig *pb.PushConfig
	if cfg.PushConfig.Endpoint != "" || len(cfg.PushConfig.Attributes) != 0 {
		pbPushConfig = &pb.PushConfig{
			Attributes:   cfg.PushConfig.Attributes,
			PushEndpoint: cfg.PushConfig.Endpoint,
		}
	}
	var retentionDuration *durpb.Duration
	if cfg.RetentionDuration != 0 {
		retentionDuration = ptypes.DurationProto(cfg.RetentionDuration)
	}
	return &pb.Subscription{
		Name:                     name,
		Topic:                    cfg.Topic.name,
		PushConfig:               pbPushConfig,
		AckDeadlineSeconds:       trunc32(int64(cfg.AckDeadline.Seconds())),
		RetainAckedMessages:      cfg.RetainAckedMessages,
		MessageRetentionDuration: retentionDuration,
	}
}

func protoToSubscriptionConfig(pbSub *pb.Subscription, c *Client) (SubscriptionConfig, error) {
	rd, err := ptypes.Duration(pbSub.MessageRetentionDuration)
	if err != nil {
		return SubscriptionConfig{}, err
	}
	return SubscriptionConfig{
		Topic:       newTopic(c, pbSub.Topic),
		AckDeadline: time.Second * time.Duration(pbSub.AckDeadlineSeconds),
		PushConfig: PushConfig{
			Endpoint:   pbSub.PushConfig.PushEndpoint,
			Attributes: pbSub.PushConfig.Attributes,
		},
		RetainAckedMessages: pbSub.RetainAckedMessages,
		RetentionDuration:   rd,
	}, nil
}

// ReceiveSettings configure the Receive method.
// A zero ReceiveSettings will result in values equivalent to DefaultReceiveSettings.
type ReceiveSettings struct {
	// MaxExtension is the maximum period for which the Subscription should
	// automatically extend the ack deadline for each message.
	//
	// The Subscription will automatically extend the ack deadline of all
	// fetched Messages for the duration specified. Automatic deadline
	// extension may be disabled by specifying a duration less than 1.
	MaxExtension time.Duration

	// MaxOutstandingMessages is the maximum number of unprocessed messages
	// (unacknowledged but not yet expired). If MaxOutstandingMessages is 0, it
	// will be treated as if it were DefaultReceiveSettings.MaxOutstandingMessages.
	// If the value is negative, then there will be no limit on the number of
	// unprocessed messages.
	MaxOutstandingMessages int

	// MaxOutstandingBytes is the maximum size of unprocessed messages
	// (unacknowledged but not yet expired). If MaxOutstandingBytes is 0, it will
	// be treated as if it were DefaultReceiveSettings.MaxOutstandingBytes. If
	// the value is negative, then there will be no limit on the number of bytes
	// for unprocessed messages.
	MaxOutstandingBytes int

	// NumGoroutines is the number of goroutines Receive will spawn to pull
	// messages concurrently. If NumGoroutines is less than 1, it will be treated
	// as if it were DefaultReceiveSettings.NumGoroutines.
	//
	// NumGoroutines does not limit the number of messages that can be processed
	// concurrently. Even with one goroutine, many messages might be processed at
	// once, because that goroutine may continually receive messages and invoke the
	// function passed to Receive on them. To limit the number of messages being
	// processed concurrently, set MaxOutstandingMessages.
	NumGoroutines int
}

// DefaultReceiveSettings holds the default values for ReceiveSettings.
var DefaultReceiveSettings = ReceiveSettings{
	MaxExtension:           10 * time.Minute,
	MaxOutstandingMessages: 1000,
	MaxOutstandingBytes:    1e9, // 1G
	NumGoroutines:          1,
}

// Delete deletes the subscription.
func (s *Subscription) Delete(ctx context.Context) error {
	return s.c.subc.DeleteSubscription(ctx, &pb.DeleteSubscriptionRequest{Subscription: s.name})
}

// Exists reports whether the subscription exists on the server.
func (s *Subscription) Exists(ctx context.Context) (bool, error) {
	_, err := s.c.subc.GetSubscription(ctx, &pb.GetSubscriptionRequest{Subscription: s.name})
	if err == nil {
		return true, nil
	}
	if grpc.Code(err) == codes.NotFound {
		return false, nil
	}
	return false, err
}

// Config fetches the current configuration for the subscription.
func (s *Subscription) Config(ctx context.Context) (SubscriptionConfig, error) {
	pbSub, err := s.c.subc.GetSubscription(ctx, &pb.GetSubscriptionRequest{Subscription: s.name})
	if err != nil {
		return SubscriptionConfig{}, err
	}
	cfg, err := protoToSubscriptionConfig(pbSub, s.c)
	if err != nil {
		return SubscriptionConfig{}, err
	}
	return cfg, nil
}

// SubscriptionConfigToUpdate describes how to update a subscription.
type SubscriptionConfigToUpdate struct {
	// If non-nil, the push config is changed.
	PushConfig *PushConfig

	// If non-zero, the ack deadline is changed.
	AckDeadline time.Duration

	// If set, RetainAckedMessages is changed.
	RetainAckedMessages optional.Bool

	// If non-zero, RetentionDuration is changed.
	RetentionDuration time.Duration
}

// Update changes an existing subscription according to the fields set in cfg.
// It returns the new SubscriptionConfig.
//
// Update returns an error if no fields were modified.
func (s *Subscription) Update(ctx context.Context, cfg SubscriptionConfigToUpdate) (SubscriptionConfig, error) {
	req := s.updateRequest(&cfg)
	if len(req.UpdateMask.Paths) == 0 {
		return SubscriptionConfig{}, errors.New("pubsub: UpdateSubscription call with nothing to update")
	}
	rpsub, err := s.c.subc.UpdateSubscription(ctx, req)
	if err != nil {
		return SubscriptionConfig{}, err
	}
	return protoToSubscriptionConfig(rpsub, s.c)
}

func (s *Subscription) updateRequest(cfg *SubscriptionConfigToUpdate) *pb.UpdateSubscriptionRequest {
	psub := &pb.Subscription{Name: s.name}
	var paths []string
	if cfg.PushConfig != nil {
		psub.PushConfig = cfg.PushConfig.toProto()
		paths = append(paths, "push_config")
	}
	if cfg.AckDeadline != 0 {
		psub.AckDeadlineSeconds = trunc32(int64(cfg.AckDeadline.Seconds()))
		paths = append(paths, "ack_deadline_seconds")
	}
	if cfg.RetainAckedMessages != nil {
		psub.RetainAckedMessages = optional.ToBool(cfg.RetainAckedMessages)
		paths = append(paths, "retain_acked_messages")
	}
	if cfg.RetentionDuration != 0 {
		psub.MessageRetentionDuration = ptypes.DurationProto(cfg.RetentionDuration)
		paths = append(paths, "message_retention_duration")
	}
	return &pb.UpdateSubscriptionRequest{
		Subscription: psub,
		UpdateMask:   &fmpb.FieldMask{Paths: paths},
	}
}

func (s *Subscription) IAM() *iam.Handle {
	return iam.InternalNewHandle(s.c.subc.Connection(), s.name)
}

// CreateSubscription creates a new subscription on a topic.
//
// id is the name of the subscription to create. It must start with a letter,
// and contain only letters ([A-Za-z]), numbers ([0-9]), dashes (-),
// underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It
// must be between 3 and 255 characters in length, and must not start with
// "goog".
//
// cfg.Topic is the topic from which the subscription should receive messages. It
// need not belong to the same project as the subscription. This field is required.
//
// cfg.AckDeadline is the maximum time after a subscriber receives a message before
// the subscriber should acknowledge the message. It must be between 10 and 600
// seconds (inclusive), and is rounded down to the nearest second. If the
// provided ackDeadline is 0, then the default value of 10 seconds is used.
// Note: messages which are obtained via Subscription.Receive need not be
// acknowledged within this deadline, as the deadline will be automatically
// extended.
//
// cfg.PushConfig may be set to configure this subscription for push delivery.
//
// If the subscription already exists an error will be returned.
func (c *Client) CreateSubscription(ctx context.Context, id string, cfg SubscriptionConfig) (*Subscription, error) {
	if cfg.Topic == nil {
		return nil, errors.New("pubsub: require non-nil Topic")
	}
	if cfg.AckDeadline == 0 {
		cfg.AckDeadline = 10 * time.Second
	}
	if d := cfg.AckDeadline; d < 10*time.Second || d > 600*time.Second {
		return nil, fmt.Errorf("ack deadline must be between 10 and 600 seconds; got: %v", d)
	}

	sub := c.Subscription(id)
	_, err := c.subc.CreateSubscription(ctx, cfg.toProto(sub.name))
	if err != nil {
		return nil, err
	}
	return sub, nil
}

var errReceiveInProgress = errors.New("pubsub: Receive already in progress for this subscription")

// Receive calls f with the outstanding messages from the subscription.
// It blocks until ctx is done, or the service returns a non-retryable error.
//
// The standard way to terminate a Receive is to cancel its context:
//
//   cctx, cancel := context.WithCancel(ctx)
//   err := sub.Receive(cctx, callback)
//   // Call cancel from callback, or another goroutine.
//
// If the service returns a non-retryable error, Receive returns that error after
// all of the outstanding calls to f have returned. If ctx is done, Receive
// returns nil after all of the outstanding calls to f have returned and
// all messages have been acknowledged or have expired.
//
// Receive calls f concurrently from multiple goroutines. It is encouraged to
// process messages synchronously in f, even if that processing is relatively
// time-consuming; Receive will spawn new goroutines for incoming messages,
// limited by MaxOutstandingMessages and MaxOutstandingBytes in ReceiveSettings.
//
// The context passed to f will be canceled when ctx is Done or there is a
// fatal service error.
//
// Receive will automatically extend the ack deadline of all fetched Messages for the
// period specified by s.ReceiveSettings.MaxExtension.
//
// Each Subscription may have only one invocation of Receive active at a time.
func (s *Subscription) Receive(ctx context.Context, f func(context.Context, *Message)) error {
	s.mu.Lock()
	if s.receiveActive {
		s.mu.Unlock()
		return errReceiveInProgress
	}
	s.receiveActive = true
	s.mu.Unlock()
	defer func() { s.mu.Lock(); s.receiveActive = false; s.mu.Unlock() }()

	config, err := s.Config(ctx)
	if err != nil {
		if grpc.Code(err) == codes.Canceled {
			return nil
		}
		return err
	}
	maxCount := s.ReceiveSettings.MaxOutstandingMessages
	if maxCount == 0 {
		maxCount = DefaultReceiveSettings.MaxOutstandingMessages
	}
	maxBytes := s.ReceiveSettings.MaxOutstandingBytes
	if maxBytes == 0 {
		maxBytes = DefaultReceiveSettings.MaxOutstandingBytes
	}
	maxExt := s.ReceiveSettings.MaxExtension
	if maxExt == 0 {
		maxExt = DefaultReceiveSettings.MaxExtension
	} else if maxExt < 0 {
		// If MaxExtension is negative, disable automatic extension.
		maxExt = 0
	}
	numGoroutines := s.ReceiveSettings.NumGoroutines
	if numGoroutines < 1 {
		numGoroutines = DefaultReceiveSettings.NumGoroutines
	}
	// TODO(jba): add tests that verify that ReceiveSettings are correctly processed.
	po := &pullOptions{
		maxExtension: maxExt,
		maxPrefetch:  trunc32(int64(maxCount)),
		ackDeadline:  config.AckDeadline,
	}
	fc := newFlowController(maxCount, maxBytes)

	// Wait for all goroutines started by Receive to return, so instead of an
	// obscure goroutine leak we have an obvious blocked call to Receive.
	group, gctx := errgroup.WithContext(ctx)
	for i := 0; i < numGoroutines; i++ {
		group.Go(func() error {
			return s.receive(gctx, po, fc, f)
		})
	}
	return group.Wait()
}

func (s *Subscription) receive(ctx context.Context, po *pullOptions, fc *flowController, f func(context.Context, *Message)) error {
	// Cancel a sub-context when we return, to kick the context-aware callbacks
	// and the goroutine below.
	ctx2, cancel := context.WithCancel(ctx)
	// Call stop when Receive's context is done.
	// Stop will block until all outstanding messages have been acknowledged
	// or there was a fatal service error.
	// The iterator does not use the context passed to Receive. If it did, canceling
	// that context would immediately stop the iterator without waiting for unacked
	// messages.
	iter := newMessageIterator(context.Background(), s.c.subc, s.name, po)

	// We cannot use errgroup from Receive here. Receive might already be calling group.Wait,
	// and group.Wait cannot be called concurrently with group.Go. We give each receive() its
	// own WaitGroup instead.
	// Since wg.Add is only called from the main goroutine, wg.Wait is guaranteed
	// to be called after all Adds.
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		<-ctx2.Done()
		iter.stop()
		wg.Done()
	}()
	defer wg.Wait()

	defer cancel()
	for {
		msgs, err := iter.receive()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		for i, msg := range msgs {
			msg := msg
			// TODO(jba): call acquire closer to when the message is allocated.
			if err := fc.acquire(ctx, len(msg.Data)); err != nil {
				// TODO(jba): test that these "orphaned" messages are nacked immediately when ctx is done.
				for _, m := range msgs[i:] {
					m.Nack()
				}
				return nil
			}
			wg.Add(1)
			go func() {
				// TODO(jba): call release when the message is available for GC.
				// This considers the message to be released when
				// f is finished, but f may ack early or not at all.
				defer wg.Done()
				defer fc.release(len(msg.Data))
				f(ctx2, msg)
			}()
		}
	}
}

// TODO(jba): remove when we delete messageIterator.
type pullOptions struct {
	maxExtension time.Duration
	maxPrefetch  int32
	// ackDeadline is the default ack deadline for the subscription. Not
	// configurable.
	ackDeadline time.Duration
}


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.24  06/05/06            */
   /*                                                     */
   /*          MISCELLANEOUS FUNCTIONS HEADER FILE        */
   /*******************************************************/

/*************************************************************/
/* Purpose:                                                  */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*                                                           */
/* Revision History:                                         */
/*      6.23: Corrected compilation errors for files         */
/*            generated by constructs-to-c. DR0861           */
/*                                                           */
/*      6.24: Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*************************************************************/

#ifndef _H_miscfun

#define _H_miscfun

#ifdef LOCALE
#undef LOCALE
#endif

#ifdef _MISCFUN_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif

   LOCALE void                           MiscFunctionDefinitions(void *);
   LOCALE void                           CreateFunction(void *,DATA_OBJECT_PTR);
   LOCALE long int                       SetgenFunction(void *);
   LOCALE void                          *GensymFunction(void *);
   LOCALE void                          *GensymStarFunction(void *);
   LOCALE long                           RandomFunction(void *);
   LOCALE void                           SeedFunction(void *);
   LOCALE long int                       LengthFunction(void *);
   LOCALE void                           ConserveMemCommand(void *);
   LOCALE long int                       ReleaseMemCommand(void *);
   LOCALE long int                       MemUsedCommand(void *);
   LOCALE long int                       MemRequestsCommand(void *);
   LOCALE void                           OptionsCommand(void *);
   LOCALE void                           ExpandFuncCall(void *,DATA_OBJECT *);
   LOCALE void                           DummyExpandFuncMultifield(void *,DATA_OBJECT *);
   LOCALE void                          *CauseEvaluationError(void *);
   LOCALE intBool                        SetSORCommand(void *);
   LOCALE void                          *GetFunctionRestrictions(void *);
   LOCALE void                           AproposCommand(void *);
   LOCALE void                          *GensymStar(void *);
   LOCALE void                           GetFunctionListFunction(void *,DATA_OBJECT *);
   LOCALE void                           FuncallFunction(void *,DATA_OBJECT *);
   LOCALE double                         TimerFunction(void *);
   LOCALE double                         TimeFunction(void *);

#endif


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

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

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

/** Operation */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public enum Op {
  WRITE_BLOCK((byte)80),
  READ_BLOCK((byte)81),
  READ_METADATA((byte)82),
  REPLACE_BLOCK((byte)83),
  COPY_BLOCK((byte)84),
  BLOCK_CHECKSUM((byte)85),
  TRANSFER_BLOCK((byte)86),
  REQUEST_SHORT_CIRCUIT_FDS((byte)87),
  RELEASE_SHORT_CIRCUIT_FDS((byte)88),
  REQUEST_SHORT_CIRCUIT_SHM((byte)89),
  BLOCK_GROUP_CHECKSUM((byte)90),
  CUSTOM((byte)127);

  /** The code for this operation. */
  public final byte code;

  Op(byte code) {
    this.code = code;
  }

  private static final int FIRST_CODE = values()[0].code;
  /** Return the object represented by the code. */
  private static Op valueOf(byte code) {
    final int i = (code & 0xff) - FIRST_CODE;
    return i < 0 || i >= values().length? null: values()[i];
  }

  /** Read from in */
  public static Op read(DataInput in) throws IOException {
    return valueOf(in.readByte());
  }

  /** Write to out */
  public void write(DataOutput out) throws IOException {
    out.write(code);
  }
}


text:
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;

// Work around a regression in Visual Studio 2015 Update 3.
#if defined(_MSC_VER) && _MSC_VER == 1900
namespace boost
{
    template <> Display const volatile* get_pointer<Display const volatile>(Display const volatile* p) { return p; }
}
#endif

namespace
{
    auto_release_ptr<Display> create_display(
        const std::string&  name,
        const bpy::dict&    params)
    {
        return DisplayFactory::create(name.c_str(), bpy_dict_to_param_array(params));
    }
}

void bind_display()
{
    bpy::class_<Display, auto_release_ptr<Display>, bpy::bases<Entity>, boost::noncopyable>("Display", bpy::no_init)
        .def("__init__", bpy::make_constructor(create_display))
        ;
}


text:
@interface FileCaptureViewController : UIViewController

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace _20170106_02_SoftUni_Karaoke
{
    public class SoftUniKaraoke
    {
        public static void Main()
        {
            List<string> participants = Console.ReadLine()
                .Split(',')
                .Select(x => x.Trim())
                .ToList();

            List<string> songs = Console.ReadLine()
                .Split(',')
                .Select(x => x.Trim())
                .ToList();

            Dictionary<string, SortedSet<string>> participantsResult = new Dictionary<string, SortedSet<string>>();

            List<string> input = Console.ReadLine()
                .Split(',')
                .Select(x => x.Trim())
                .ToList();
            while (!input[0].Equals("dawn"))
            {
                if (!participants.Any(x => x.Equals(input[0])) || !songs.Any(x => x.Equals(input[1])))
                {
                    input = Console.ReadLine()
                        .Split(',')
                        .Select(x => x.Trim())
                        .ToList();
                    continue;
                }

                if (participantsResult.ContainsKey(input[0]))
                {
                    participantsResult[input[0]].Add(input[2]);
                }
                else
                {
                    participantsResult[input[0]] = new SortedSet<string>()
                    {
                        input[2]
                    };
                }

                input = Console.ReadLine()
                    .Split(',')
                    .Select(x => x.Trim())
                    .ToList();
            }

            if (participantsResult.Count == 0)
            {
                Console.WriteLine("No awards");
            }

            foreach (var participant in participantsResult.OrderByDescending(x => x.Value.Count))
            {
                Console.WriteLine($"{participant.Key}: {participant.Value.Count} awards");
                foreach (var award in participant.Value)
                {
                    Console.WriteLine($"--{award}");
                }
            }
        }
    }
}


text:
namespace ceenq.org.Services
{
    /// <summary>
    ///     Represents the type of query detected from the QueryType method
    /// </summary>
    public enum QueryType
    {
        None = 0,
        Passage = 1,
        WordSearch = 2
    }
}


text:
title: Window clearInterval Method
localeTitle: نافذة clearInterval الطريقة
---
## نافذة clearInterval الطريقة

يتم استخدام أسلوب "clearInterval ()" لمسح جهاز ضبط وقت باستخدام "setInterval ()".

 `    clearInterval(setInteval_ID);
`

لتتمكن من استخدام أسلوب "clearInterval ()" ، يجب استخدام متغير عام.

 `    myID = setInterval(function, milliseconds);
`

#### معلومات اكثر:

الوثائق: [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval)

بعض الأمثلة أكثر على [w3schools](https://www.w3schools.com/jsref/met_win_clearinterval.asp)


text:
import config
import re
import unittest

import thread_cert

LEADER = 1
REED = 2

SRV_0_ID = 0
SRV_0_ENT_NUMBER = '123'
SRV_0_SERVICE_DATA = 'foo'
SRV_0_SERVER_DATA = 'bar'

# Topology:
# LEADER -- REED
#

class TestREEDAddressSolicitRejected(thread_cert.TestCase):
    SUPPORT_NCP = False

    TOPOLOGY = {
        LEADER: {
            'mode': 'rsdn',
            'panid': 0xface
        },
        REED: {
            'mode': 'rsdn',
            'panid': 0xface,
            'router_selection_jitter': 1
        },
    }

    def testAddressSolicitRejectedBeforeSvrData(self):
        self.nodes[LEADER].start()
        self.nodes[LEADER].set_router_upgrade_threshold(1)
        self.simulator.go(5)
        self.assertEqual(self.nodes[LEADER].get_state(), 'leader')

        self.nodes[REED].start()
        self.simulator.go(5)
        self.assertEqual(self.nodes[REED].get_state(), 'child')

        self.nodes[REED].add_service(SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA,
                                     SRV_0_SERVER_DATA)
        self.nodes[REED].register_netdata()
        self.simulator.go(2)

        self.assertEqual(self.hasAloc(REED, SRV_0_ID), True)

    def testAddressSolicitRejectedAfterSvrData(self):
        self.nodes[LEADER].start()
        self.nodes[LEADER].set_router_upgrade_threshold(1)
        self.simulator.go(5)
        self.assertEqual(self.nodes[LEADER].get_state(), 'leader')

        self.nodes[REED].set_router_selection_jitter(120)
        self.nodes[REED].start()
        # set routerupgradethreshold=1 on REED so that it won't send ADDR_SOL.req
        self.nodes[REED].set_router_upgrade_threshold(1)
        self.simulator.go(5)
        self.assertEqual(self.nodes[REED].get_state(), 'child')

        # restore routerupgradethreshold to 16 and add service
        self.nodes[REED].set_router_upgrade_threshold(16)
        self.nodes[REED].add_service(SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA,
                                     SRV_0_SERVER_DATA)
        self.nodes[REED].register_netdata()
        self.simulator.go(130)
        self.assertEqual(self.hasAloc(REED, SRV_0_ID), True)

    def hasAloc(self, node_id, service_id):
        for addr in self.nodes[node_id].get_ip6_address(
                config.ADDRESS_TYPE.ALOC):
            m = re.match('.*:fc(..)$', addr, re.I)
            if m is not None:
                if m.group(
                        1) == str(service_id +
                                  10):  # for service_id=3 look for '...:fc13'
                    return True

        return False

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.apache.taverna.engine</groupId>
		<artifactId>apache-taverna-engine</artifactId>
		<version>3.1.1-incubating-SNAPSHOT</version>
	</parent>
	<artifactId>taverna-execution-api</artifactId>
	<packaging>bundle</packaging>
	<name>Apache Taverna Platform Execution Service API</name>
	<description>A Service for executing Taverna workflows</description>
	<dependencies>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-capability-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-report-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.taverna.language</groupId>
			<artifactId>taverna-scufl2-api</artifactId>
			<version>${taverna.language.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.taverna.language</groupId>
			<artifactId>taverna-databundle</artifactId>
			<version>${taverna.language.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.taverna.language</groupId>
			<artifactId>taverna-robundle</artifactId>
			<version>${taverna.language.version}</version>
		</dependency>
	</dependencies>
</project>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

	<TableLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1">
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:text="@string/body" />
		    <EditText
		        android:id="@+id/fragment_notification_service_body"
		        android:layout_width="0dp"
		        android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="@string/body"
		        android:layout_marginBottom="@dimen/activity_vertical_margin" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:text="@string/icon" />
            <RadioGroup android:id="@+id/fragment_notification_service_icon"
		        android:layout_width="fill_parent"
		        android:layout_height="wrap_content">
                <RadioButton android:id="@+id/fragment_notification_service_icon_nothing"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="@string/nothing" />
		        <RadioButton android:id="@+id/fragment_notification_service_icon_red"
		            android:layout_width="wrap_content"
		            android:layout_height="wrap_content"
		            android:text="Red" />
		        <RadioButton android:id="@+id/fragment_notification_service_icon_green"
		            android:layout_width="wrap_content"
		            android:layout_height="wrap_content"
		            android:text="Green" />
		        <RadioButton android:id="@+id/fragment_notification_service_icon_blue"
		            android:layout_width="wrap_content"
		            android:layout_height="wrap_content"
		            android:text="Blue" />
	       </RadioGroup>
        </TableRow>
	</TableLayout>

    <Button
        android:id="@+id/fragment_notification_service_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/send" />

</LinearLayout>


text:
package com.amazonaws.services.lookoutforvision.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartModelPackagingJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the project which contains the version of the model that you want to package.
     *

     */
    private String projectName;
    /**
     *

     * The version of the model within the project that you want to package.
     *

     */
    private String modelVersion;
    /**
     *

     * A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     *

     */
    private String jobName;
    /**
     *

     * The configuration for the model packaging job.
     *

     */
    private ModelPackagingConfiguration configuration;
    /**
     *

     * A description for the model packaging job.
     *

     */
    private String description;
    /**
     *

     * ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes only
     * once. You choose the value to pass. For example, An issue might prevent you from getting a response from
     * StartModelPackagingJob. In this case, safely retry your call to StartModelPackagingJob
     * by using the same ClientToken parameter value.
     *

     *

     * If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for you. This
     * prevents retries after a network error from making multiple dataset creation requests. You'll need to provide
     * your own value for other use cases.
     *

     *

     * An error occurs if the other input parameters are not the same as in the first request. Using a different value
     * for ClientToken is considered a new call to StartModelPackagingJob. An idempotency
     * token is active for 8 hours.
     *

     */
    private String clientToken;

    /**
     *

     * The name of the project which contains the version of the model that you want to package.
     *

     *
     * @param projectName
     *        The name of the project which contains the version of the model that you want to package.
     */

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    /**
     *

     * The name of the project which contains the version of the model that you want to package.
     *

     *
     * @return The name of the project which contains the version of the model that you want to package.
     */

    public String getProjectName() {
        return this.projectName;
    }

    /**
     *

     * The name of the project which contains the version of the model that you want to package.
     *

     *
     * @param projectName
     *        The name of the project which contains the version of the model that you want to package.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withProjectName(String projectName) {
        setProjectName(projectName);
        return this;
    }

    /**
     *

     * The version of the model within the project that you want to package.
     *

     *
     * @param modelVersion
     *        The version of the model within the project that you want to package.
     */

    public void setModelVersion(String modelVersion) {
        this.modelVersion = modelVersion;
    }

    /**
     *

     * The version of the model within the project that you want to package.
     *

     *
     * @return The version of the model within the project that you want to package.
     */

    public String getModelVersion() {
        return this.modelVersion;
    }

    /**
     *

     * The version of the model within the project that you want to package.
     *

     *
     * @param modelVersion
     *        The version of the model within the project that you want to package.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withModelVersion(String modelVersion) {
        setModelVersion(modelVersion);
        return this;
    }

    /**
     *

     * A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     *

     *
     * @param jobName
     *        A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     */

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    /**
     *

     * A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     *

     *
     * @return A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     */

    public String getJobName() {
        return this.jobName;
    }

    /**
     *

     * A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     *

     *
     * @param jobName
     *        A name for the model packaging job. If you don't supply a value, the service creates a job name for you.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withJobName(String jobName) {
        setJobName(jobName);
        return this;
    }

    /**
     *

     * The configuration for the model packaging job.
     *

     *
     * @param configuration
     *        The configuration for the model packaging job.
     */

    public void setConfiguration(ModelPackagingConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     *

     * The configuration for the model packaging job.
     *

     *
     * @return The configuration for the model packaging job.
     */

    public ModelPackagingConfiguration getConfiguration() {
        return this.configuration;
    }

    /**
     *

     * The configuration for the model packaging job.
     *

     *
     * @param configuration
     *        The configuration for the model packaging job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withConfiguration(ModelPackagingConfiguration configuration) {
        setConfiguration(configuration);
        return this;
    }

    /**
     *

     * A description for the model packaging job.
     *

     *
     * @param description
     *        A description for the model packaging job.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * A description for the model packaging job.
     *

     *
     * @return A description for the model packaging job.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * A description for the model packaging job.
     *

     *
     * @param description
     *        A description for the model packaging job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes only
     * once. You choose the value to pass. For example, An issue might prevent you from getting a response from
     * StartModelPackagingJob. In this case, safely retry your call to StartModelPackagingJob
     * by using the same ClientToken parameter value.
     *

     *

     * If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for you. This
     * prevents retries after a network error from making multiple dataset creation requests. You'll need to provide
     * your own value for other use cases.
     *

     *

     * An error occurs if the other input parameters are not the same as in the first request. Using a different value
     * for ClientToken is considered a new call to StartModelPackagingJob. An idempotency
     * token is active for 8 hours.
     *

     *
     * @param clientToken
     *        ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes
     *        only once. You choose the value to pass. For example, An issue might prevent you from getting a response
     *        from StartModelPackagingJob. In this case, safely retry your call to
     *        StartModelPackagingJob by using the same ClientToken parameter value.

     *

     *        If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for
     *        you. This prevents retries after a network error from making multiple dataset creation requests. You'll
     *        need to provide your own value for other use cases.
     *

     *

     *        An error occurs if the other input parameters are not the same as in the first request. Using a different
     *        value for ClientToken is considered a new call to StartModelPackagingJob. An
     *        idempotency token is active for 8 hours.
     */

    public void setClientToken(String clientToken) {
        this.clientToken = clientToken;
    }

    /**
     *

     * ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes only
     * once. You choose the value to pass. For example, An issue might prevent you from getting a response from
     * StartModelPackagingJob. In this case, safely retry your call to StartModelPackagingJob
     * by using the same ClientToken parameter value.
     *

     *

     * If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for you. This
     * prevents retries after a network error from making multiple dataset creation requests. You'll need to provide
     * your own value for other use cases.
     *

     *

     * An error occurs if the other input parameters are not the same as in the first request. Using a different value
     * for ClientToken is considered a new call to StartModelPackagingJob. An idempotency
     * token is active for 8 hours.
     *

     *
     * @return ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes
     *         only once. You choose the value to pass. For example, An issue might prevent you from getting a response
     *         from StartModelPackagingJob. In this case, safely retry your call to
     *         StartModelPackagingJob by using the same ClientToken parameter value.

     *

     *         If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for
     *         you. This prevents retries after a network error from making multiple dataset creation requests. You'll
     *         need to provide your own value for other use cases.
     *

     *

     *         An error occurs if the other input parameters are not the same as in the first request. Using a different
     *         value for ClientToken is considered a new call to StartModelPackagingJob. An
     *         idempotency token is active for 8 hours.
     */

    public String getClientToken() {
        return this.clientToken;
    }

    /**
     *

     * ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes only
     * once. You choose the value to pass. For example, An issue might prevent you from getting a response from
     * StartModelPackagingJob. In this case, safely retry your call to StartModelPackagingJob
     * by using the same ClientToken parameter value.
     *

     *

     * If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for you. This
     * prevents retries after a network error from making multiple dataset creation requests. You'll need to provide
     * your own value for other use cases.
     *

     *

     * An error occurs if the other input parameters are not the same as in the first request. Using a different value
     * for ClientToken is considered a new call to StartModelPackagingJob. An idempotency
     * token is active for 8 hours.
     *

     *
     * @param clientToken
     *        ClientToken is an idempotency token that ensures a call to StartModelPackagingJob completes
     *        only once. You choose the value to pass. For example, An issue might prevent you from getting a response
     *        from StartModelPackagingJob. In this case, safely retry your call to
     *        StartModelPackagingJob by using the same ClientToken parameter value.

     *

     *        If you don't supply a value for ClientToken, the AWS SDK you are using inserts a value for
     *        you. This prevents retries after a network error from making multiple dataset creation requests. You'll
     *        need to provide your own value for other use cases.
     *

     *

     *        An error occurs if the other input parameters are not the same as in the first request. Using a different
     *        value for ClientToken is considered a new call to StartModelPackagingJob. An
     *        idempotency token is active for 8 hours.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartModelPackagingJobRequest withClientToken(String clientToken) {
        setClientToken(clientToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getProjectName() != null)
            sb.append("ProjectName: ").append(getProjectName()).append(",");
        if (getModelVersion() != null)
            sb.append("ModelVersion: ").append(getModelVersion()).append(",");
        if (getJobName() != null)
            sb.append("JobName: ").append(getJobName()).append(",");
        if (getConfiguration() != null)
            sb.append("Configuration: ").append(getConfiguration()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getClientToken() != null)
            sb.append("ClientToken: ").append(getClientToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StartModelPackagingJobRequest == false)
            return false;
        StartModelPackagingJobRequest other = (StartModelPackagingJobRequest) obj;
        if (other.getProjectName() == null ^ this.getProjectName() == null)
            return false;
        if (other.getProjectName() != null && other.getProjectName().equals(this.getProjectName()) == false)
            return false;
        if (other.getModelVersion() == null ^ this.getModelVersion() == null)
            return false;
        if (other.getModelVersion() != null && other.getModelVersion().equals(this.getModelVersion()) == false)
            return false;
        if (other.getJobName() == null ^ this.getJobName() == null)
            return false;
        if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
            return false;
        if (other.getConfiguration() == null ^ this.getConfiguration() == null)
            return false;
        if (other.getConfiguration() != null && other.getConfiguration().equals(this.getConfiguration()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getClientToken() == null ^ this.getClientToken() == null)
            return false;
        if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getProjectName() == null) ? 0 : getProjectName().hashCode());
        hashCode = prime * hashCode + ((getModelVersion() == null) ? 0 : getModelVersion().hashCode());
        hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
        hashCode = prime * hashCode + ((getConfiguration() == null) ? 0 : getConfiguration().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
        return hashCode;
    }

    @Override
    public StartModelPackagingJobRequest clone() {
        return (StartModelPackagingJobRequest) super.clone();
    }

}


text:
lvGL 8.0.2 for Tock OS
===================================

Light and Versatile Graphics Library is a free and open-source graphics library providing everything you need to create embedded GUI with easy-to-use graphical elements, beautiful visual effects and low memory footprint.

See https://docs.littlevgl.com/en/html/index.html for documentation.

Using `lvgl` in Tock
--------------------

To use `lvgl`, add the following include to the application's
Makefile:

    EXTERN_LIBS += $(TOCK_USERLAND_BASE_DIR)/lvgl

Re-compiling `lvgl`
-----------------

Checkout the lvgl submodule in this directory

    $ git submodule init -- lvgl
    $ git submodule update

For faster build times, edit the `lvgl/lvgl.mk` file and comment the examples.
```
# include $(LVGL_DIR)/$(LVGL_DIR_NAME)/examples/examples.mk
include $(LVGL_DIR)/$(LVGL_DIR_NAME)/src/extra/extra.mk
include $(LVGL_DIR)/$(LVGL_DIR_NAME)/src/core/lv_core.mk
...
```

then run `make`

    $ cd lvgl
    $ make

Configure lvGL
--------------
Edit the ``lv_conf.h`` in this folder to set up some parameters and optionals


text:
package org.apache.camel.management.mbean;

import org.apache.camel.CamelContext;
import org.apache.camel.Expression;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedDelayerMBean;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.Delayer;

@ManagedResource(description = "Managed Delayer")
public class ManagedDelayer extends ManagedProcessor implements ManagedDelayerMBean {
    private final Delayer delayer;

    public ManagedDelayer(CamelContext context, Delayer delayer, ProcessorDefinition<?> definition) {
        super(context, delayer, definition);
        this.delayer = delayer;
    }

    public Delayer getDelayer() {
        return delayer;
    }

    public Long getDelay() {
        return delayer.getDelayValue();
    }

    public void constantDelay(Integer millis) {
        Expression delay = ExpressionBuilder.constantExpression(millis);
        delayer.setDelay(delay);
    }

    public int getDelayedCount() {
        return delayer.getDelayedCount();
    }

    public Boolean isAsyncDelayed() {
        return delayer.isAsyncDelayed();
    }

    @Override
    public Boolean isCallerRunsWhenRejected() {
        return delayer.isCallerRunsWhenRejected();
    }

}


text:
const char kProductTourBaseURL[] =
    "http://www.google.com/intl/%s/chrome/browser/mobile/tour/android.html";

const char kPrivacyNoticeBaseURL[] =
    "http://www.google.com/chrome/intl/%s/privacy.html";

WelcomeUI::WelcomeUI(content::WebUI* web_ui)
    : content::WebUIController(web_ui) {
  // Set up the chrome://welcome source.
  content::WebUIDataSource* html_source =
      content::WebUIDataSource::Create(chrome::kChromeUIWelcomeHost);
  html_source->SetUseJsonJSFormatV2();

  // Localized strings.
  html_source->AddLocalizedString("title",
      IDS_NEW_TAB_CHROME_WELCOME_PAGE_TITLE);
  html_source->AddLocalizedString("takeATour", IDS_FIRSTRUN_TAKE_TOUR);
  html_source->AddLocalizedString("firstRunSignedInTitle",
      IDS_FIRSTRUN_SIGNED_IN_TITLE);
  html_source->AddLocalizedString("firstRunSignedInDescription",
      IDS_FIRSTRUN_SIGNED_IN_DESCRIPTION);
  html_source->AddLocalizedString("settings", IDS_FIRSTRUN_SETTINGS_LINK);

  std::string locale = g_browser_process->GetApplicationLocale();
  std::string product_tour_url = base::StringPrintf(
      kProductTourBaseURL, locale.c_str());

  if (chrome::android::AccessibilityUtil::IsAccessibilityEnabled())
    product_tour_url += "?talkback";

  html_source->AddString("productTourUrl", product_tour_url);

  TabAndroid* tab = TabAndroid::FromWebContents(web_ui->GetWebContents());
  bool tos_visible = tab && tab->ShouldWelcomePageLinkToTermsOfService();
  html_source->AddBoolean("tosVisible", tos_visible);

  base::string16 tos_html;
  if (tos_visible) {
    std::string privacy_notice_url =
        base::StringPrintf(kPrivacyNoticeBaseURL, locale.c_str());
    tos_html = l10n_util::GetStringFUTF16(
        IDS_FIRSTRUN_TOS_EXPLANATION, base::UTF8ToUTF16(privacy_notice_url));
  }
  html_source->AddString("tosHtml", tos_html);

  // Add required resources.
  html_source->SetJsonPath("strings.js");
  html_source->SetDefaultResource(IDR_ABOUT_WELCOME_HTML);

  Profile* profile = Profile::FromWebUI(web_ui);
  content::WebUIDataSource::Add(profile, html_source);

  // Add message handlers.
  web_ui->AddMessageHandler(new WelcomeHandler());
}

WelcomeUI::~WelcomeUI() {
}


text:
import { Folder } from "./Folder";
import { SevenZArchiveEntry } from "./SevenZArchiveEntry";
import { SubStreamsInfo } from "./SevenZFile";
export declare class Archive {
    packPosition: number;
    packedSizes: Array<number>;
    folders: Array<Folder>;
    subStreamsInfo: SubStreamsInfo;
    files: Array<SevenZArchiveEntry>;
    streamMap: StreamMap;
    headerSize: number;
}
export declare class StreamMap {
    packStreamOffsets: Array<number>;
    folderFirstFileIndex: Array<number>;
    toString(): string;
}


text:
package backtype.storm.topology.base;

import backtype.storm.transactional.TransactionAttempt;

public abstract class BaseTransactionalBolt extends
		BaseBatchBolt<TransactionAttempt> {

	/**
	 *
	 */
	private static final long serialVersionUID = -7218335265354235240L;

}


text:
Simple command line scripts written in Ruby language

### add_days.rb

Looks when the file or directory was last modified and add
that information to the file or directory:

```
$ ruby add_days.rb
```

Before: some_file
After: 45_days_some_file

### sort_files.rb

```
$ ruby sort_files.rb /home/user
```

```
["."]

     filename                       days         size
-------------------------------------------------------
  1) sort_files.rb                  942 days     2 kb
  2) add_days.rb                    931 days     1 kb
  3) LICENSE                        0 days       1 kb
  4) README.md                      0 days      320 b
```


text:
@interface BoardViewController () {

    BOOL isUserTurn;
    BOOL isAnimating;
    BOOL isBlue;
    BOOL isShowingHelp;

    NSMutableArray *circles;
    NSMutableArray *redCircles;
    NSMutableArray *blueCircles;
    NSMutableArray *playerIDs;

    UIView *redCircle;
    UIView *blueCircle;

    UIView *playerIndicator;

    int dropChipHeight;
    int x1;
    int x2;
    int side;

    BOOL isLightTheme;
    BOOL isShowingResult;
}

@property (nonatomic) UIDynamicAnimator *animator;
@end

@implementation BoardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [GKManager helper].delegate = self;

    side = self.view.frame.size.width * .25;

    x1 = 100;
    x2 = 150;
    if (self.view.frame.size.width > 350) {
        x1 = 220;
        x2 = 360;
        self.menuButton.frame = CGRectMake(self.menuButton.frame.origin.x, self.menuButton.frame.origin.y, 80,50);
    }

	// Do any additional setup after loading the view.
}

- (void)viewWillDisappear:(BOOL)animated {

    UIView *screenShotView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 320)];

    int xCord = 15;
    int yCord = 0;

    for (int hole = 1; hole < 37; hole ++) {

        CircleView *circleView = [[CircleView alloc]initWithFrame:CGRectMake(xCord, yCord, 40, 40)];
        circleView.backgroundColor = [UIColor clearColor];
        circleView.layer.borderColor = [UIColor clearColor].CGColor;
        for (NSNumber *redNumbers in redCircles) {
            if ([redNumbers isEqualToNumber:[NSNumber numberWithInt:hole]]) {
                circleView.backgroundColor = [UIColor redColor];
                circleView.layer.borderColor = [UIColor redColor].CGColor;

            }
        }
        for (NSNumber *blueNumbers in blueCircles) {
            if ([blueNumbers isEqualToNumber:[NSNumber numberWithInt:hole]]) {
                circleView.backgroundColor = [UIColor blueColor];
                circleView.layer.borderColor = [UIColor blueColor].CGColor;

            }
        }

        circleView.layer.borderWidth = 2;
        circleView.layer.cornerRadius = 20;

        xCord = xCord + 50;

        if (hole == 6 || hole == 12 || hole == 18 || hole == 24 || hole == 30) {
            xCord = 15;
            yCord = yCord + 50;
        }

        [screenShotView addSubview:circleView];
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[GKManager helper].currentMatch.matchID]];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:path error:NULL];

    UIGraphicsBeginImageContext(screenShotView.bounds.size);
    [screenShotView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSData* data = UIImagePNGRepresentation(image);

    if (redCircles.count+blueCircles.count == 0) {
        data = UIImagePNGRepresentation([UIImage imageNamed:@"MenuDefault"]);
    }

    [data writeToFile:path atomically:YES];

    NSMutableData *imageData = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imageData];
    [archiver encodeObject:image forKey:@"ImageData"];
    [archiver finishEncoding];

    [[NSUserDefaults standardUserDefaults]setValue:imageData forKey:path];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)viewWillAppear:(BOOL)animated {

    if (isShowingHelp) {
        return;
    }

    redCircle = [[UIView alloc]initWithFrame:CGRectMake(x2, 50, side, side)];
    redCircle.layer.cornerRadius = side/2;
    redCircle.layer.borderWidth = side * .09375;
    redCircle.layer.borderColor = [UIColor whiteColor].CGColor;
    redCircle.backgroundColor = [UIColor redColor];
    [self.view addSubview:redCircle];

    blueCircle = [[UIView alloc]initWithFrame:CGRectMake(x1, 50, side, side)];
    blueCircle.layer.cornerRadius = side/2;
    blueCircle.layer.borderWidth = side * .09375;
    blueCircle.layer.borderColor = [UIColor whiteColor].CGColor;
    blueCircle.backgroundColor = [UIColor blueColor];
    [self.view addSubview:blueCircle];

    playerIndicator = [[UIView alloc]initWithFrame:CGRectMake(0, 0, side/2, 6)];
    playerIndicator.backgroundColor = [UIColor whiteColor];
    playerIndicator.hidden = YES;
    [self.view addSubview:playerIndicator];

    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"Theme"] isEqualToString:@"D"]) {
        self.view.backgroundColor = [UIColor colorWithRed:0.199478 green:0.199478 blue:0.199478 alpha:1];
        isLightTheme = NO;
    }
    else {
        self.view.backgroundColor = [UIColor whiteColor];
        isLightTheme = YES;
        blueCircle.layer.borderColor = [UIColor lightGrayColor].CGColor;
        redCircle.layer.borderColor = [UIColor lightGrayColor].CGColor;
        playerIndicator.backgroundColor = [UIColor lightGrayColor];
    }
    [[GKManager helper] turnBasedMatchmakerViewController:nil didFindMatch:self.matchToSet];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) newMatch:(GKTurnBasedMatch *)match {

    [self loadGameplayArraysFromArray:nil];
    isUserTurn = YES;
    [self loadCirclesWithAnimation:NO forColorBlue:NO];
    isBlue = YES;

    playerIndicator.hidden = NO;
    playerIndicator.frame = CGRectMake(x1 + side/4, blueCircle.frame.origin.y + side + 20, side/2, side *.075 );
}

- (void)loadMatch:(GKTurnBasedMatch*)match forTurn:(BOOL)isTurn fromGC:(BOOL)fromGC {
    isUserTurn = isTurn;
    [self loadGameplayArraysFromArray:[self arrayFromData:match.matchData]];

    if ([match.participants indexOfObject:match.currentParticipant] == 0) {
        isBlue = YES;
        if (!fromGC) {
            [self loadCirclesWithAnimation:YES forColorBlue:NO];
            [self showCircleForBlue:NO];
        }
        else {
            [self loadCirclesWithAnimation:NO forColorBlue:NO];
        }
    }
    else {
        isBlue = NO;
        if (!fromGC) {
            [self loadCirclesWithAnimation:YES forColorBlue:YES];
            [self showCircleForBlue:YES];
        }
        else {
            [self loadCirclesWithAnimation:NO forColorBlue:YES];
        }
    }

    for (GKTurnBasedParticipant *p in match.participants) {
        if (p.matchOutcome == GKTurnBasedMatchOutcomeWon) {
            if ([p isEqual:match.participants[0]]) {
                [self showWinnerViewForBlue:YES];
            }
            else {
                [self showWinnerViewForBlue:NO];
            }
        }
    }
    [self animateToCurrentPlayer];
   // [self changeCircleColorForMatch:match];
}

- (void) changeCircleColorForMatch:(GKTurnBasedMatch*)match {

    int index = 0;
    for (GKTurnBasedParticipant *player in match.participants) {
        if (player.matchOutcome == GKTurnBasedMatchOutcomeWon) {
            if (index == 0) {
                blueCircle.layer.borderColor = [UIColor greenColor].CGColor;
            }
            else {
                redCircle.layer.borderColor = [UIColor greenColor].CGColor;
            }

        }
        else if (player.matchOutcome == GKTurnBasedMatchOutcomeLost) {
            if (index == 0) {
                blueCircle.layer.borderColor = [UIColor redColor].CGColor;
            }
            else {
                redCircle.layer.borderColor = [UIColor redColor].CGColor;
            }
        }
        else if (player.matchOutcome == GKTurnBasedMatchOutcomeQuit) {
            blueCircle.layer.borderColor = [UIColor redColor].CGColor;
            redCircle.layer.borderColor = [UIColor redColor].CGColor;

        }

        index++;
    }

}

- (void) showCircleForBlue:(BOOL)blue {
    for (CircleView *circle in self.view.subviews) {
        if (circle.tag == 50) {
            if (blue) {
                if ([circle.holeNumber isEqualToNumber:[blueCircles lastObject]]) {
                    [self animateForCircle:circle forColorBlue:YES];
                }
            }
            else {
                if ([circle.holeNumber isEqualToNumber:[redCircles lastObject]]) {
                    [self animateForCircle:circle forColorBlue:NO];
                }
            }
        }
    }
}

- (void) animateForCircle:(CircleView*)circle forColorBlue:(BOOL)blue {
    CGPoint point = circle.frame.origin;

    UIView * chip = [[UIView alloc]initWithFrame:CGRectMake(point.x, dropChipHeight, self.view.frame.size.width * .125, self.view.frame.size.width * .125)];
    chip.layer.borderColor = [UIColor whiteColor].CGColor;
    if (isLightTheme) {
        chip.layer.borderColor = [UIColor blackColor].CGColor;
    }
    chip.layer.borderWidth = chip.frame.size.width/20;
    chip.layer.cornerRadius = chip.frame.size.width/2;
    [self.view addSubview:chip];

    if (blue) {
        chip.backgroundColor = [UIColor blueColor];
    }
    else {
        chip.backgroundColor = [UIColor redColor];
    }
    self.view.userInteractionEnabled = NO;
    [UIView animateWithDuration:1 animations:^{
        chip.frame = CGRectMake(point.x, point.y, self.view.frame.size.width * .125, self.view.frame.size.width * .125);
    } completion:^(BOOL finished) {
        if (blue) {
            circle.backgroundColor = [UIColor blueColor];
        }
        else {
            circle.backgroundColor = [UIColor redColor];
        }
        [chip removeFromSuperview];
        self.view.userInteractionEnabled = YES;
    }];
}

- (void)sendNotice:(NSString *)notice forMatch:(GKTurnBasedMatch *)match {

}
-(void)recieveEndGame:(GKTurnBasedMatch *)match {
    [self loadMatch:match forTurn:NO fromGC:NO];
}

- (void) animateToCurrentPlayer {

    if (isAnimating) {
        return;
    }

    isAnimating = YES;
    BOOL isPlayerBlue = NO;
    if ([[GKLocalPlayer localPlayer].playerID isEqualToString:((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[0]).playerID]) {
        isPlayerBlue = YES;
    }

    if (playerIndicator.hidden) {
        playerIndicator.hidden = NO;
        if (isPlayerBlue) {
            playerIndicator.frame = CGRectMake(x1 + side/4, blueCircle.frame.origin.y + side + 20, side/2, side *.075 );
        }
        else {
            playerIndicator.frame = CGRectMake(x2 + side/4, blueCircle.frame.origin.y + side + 20, side/2, side *.075);
        }
    }

    if ([[GKManager helper].currentMatch.participants indexOfObject:[GKManager helper].currentMatch.currentParticipant] == 0) {
        [UIView animateWithDuration:.5 animations:^{
            blueCircle.frame = CGRectMake(x1-side*.625, 50, side, side);
            if (isPlayerBlue) {
                playerIndicator.frame = CGRectMake(playerIndicator.frame.origin.x-side*.625, blueCircle.frame.origin.y + side + 20, side/2, side *.075);
            }
        } completion:^(BOOL finished) {
            [self.view sendSubviewToBack:redCircle];
            [UIView animateWithDuration:.5 animations:^{
                blueCircle.frame = CGRectMake(x1, 50, side, side);
                if (isPlayerBlue) {
                    playerIndicator.frame = CGRectMake(x1 + side/4, blueCircle.frame.origin.y + side + 20, side/2, side *.075);
                }
            } completion:^(BOOL finished) {
                isAnimating = NO;
            }];
        }];
    }
    else {
        [UIView animateWithDuration:.5 animations:^{
            redCircle.frame = CGRectMake(x2+side*.6250, 50, side, side);
            if (!isPlayerBlue) {
                playerIndicator.frame = CGRectMake(playerIndicator.frame.origin.x + side*.625, blueCircle.frame.origin.y + side + 20, side/2, side *.075);
            }
        } completion:^(BOOL finished) {
            [self.view sendSubviewToBack:blueCircle];
            [UIView animateWithDuration:.5 animations:^{
                redCircle.frame = CGRectMake(x2, 50, side, side);
                if (!isPlayerBlue) {
                    playerIndicator.frame = CGRectMake(x2 + side/4, blueCircle.frame.origin.y + side + 20, side/2, side *.075);
                }
            } completion:^(BOOL finished) {
                isAnimating = NO;
            }];
        }];
    }
}

- (void)sendTurnForWin:(BOOL)win{

    [self hideCircles];
    isUserTurn = NO;
    GKTurnBasedMatch * match = [GKManager helper].currentMatch;

    if (!win) {
        NSUInteger currentPlayerIndex = [match.participants indexOfObject:match.currentParticipant];
        NSMutableArray *nextParticipants = [NSMutableArray array];
        for (int i = 0; i < [match.participants count]; i++) {
            NSInteger indx = (i + currentPlayerIndex + 1) % [match.participants count];
            GKTurnBasedParticipant *participant = (match.participants)[indx];
            //1
            if (participant.matchOutcome == GKTurnBasedMatchOutcomeNone) {
                [nextParticipants addObject:participant];
            }
        }
        NSData *newData = [self getDataForMatch];
        if (newData) {
            [match endTurnWithNextParticipants:nextParticipants turnTimeout:3600 matchData:[self getDataForMatch] completionHandler:^(NSError *error) {
                NSLog(@"Turn Sent");
                [self animateToCurrentPlayer];
            }];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Oops" message:@"Looks like something went wrong. Please try again later." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }

    }
    else {
        [match endMatchInTurnWithMatchData:[self getDataForMatch] completionHandler:^(NSError *error) {
            NSLog(@"Game Over");
        }];
    }
}

- (NSData *) getDataForMatch {

    NSMutableArray *dataArray = [[NSMutableArray alloc]initWithObjects:redCircles,blueCircles,playerIDs, nil];

    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:dataArray forKey:@"GameData"];
    [archiver finishEncoding];

    return data;
}

- (NSMutableArray *) arrayFromData:(NSData *)data {
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSMutableArray *dataArray = [unarchiver decodeObjectForKey:@"GameData"];
    [unarchiver finishDecoding];
    return dataArray;
}

- (void) loadGameplayArraysFromArray:(NSMutableArray*)dataArray {
    if (dataArray.count == 3) {
        redCircles = dataArray[0];
        blueCircles = dataArray[1];
        playerIDs = dataArray[2];
    }
    if (dataArray.count !=3 || !redCircles) {
        redCircles = [[NSMutableArray alloc]init];
    }
    if (dataArray.count !=3 || !blueCircles) {
        blueCircles = [[NSMutableArray alloc]init];
    }
    if (dataArray.count !=3 || !playerIDs) {
        playerIDs = [[NSMutableArray alloc]init];
    }
    [self addCurrentPlayerToArray:playerIDs];

}

- (void) addCurrentPlayerToArray:(NSMutableArray*)array {

    BOOL isIncluded = NO;

    for (NSString * playerID in array) {
        GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
        if ([playerID isEqualToString:[localPlayer alias]]) {
            isIncluded = YES;
        }
    }

    if (!isIncluded) {
        [array addObject:[[GKLocalPlayer localPlayer] alias]];
    }

    playerIDs = array;
}

- (void) loadCirclesWithAnimation:(BOOL)animate forColorBlue:(BOOL)blue{

    circles = [[NSMutableArray alloc]init];

    int xCord = 15;
    int yCord = self.view.frame.size.height - 310;
    if (self.view.frame.size.width * .125 > 50) {
        yCord = self.view.frame.size.height - self.view.frame.size.height * .65;
        xCord = (self.view.frame.size.width - ((self.view.frame.size.width * .125 + 10)*6))/2 + 5;
    }

    dropChipHeight = yCord - self.view.frame.size.width * .125 - 10;

    int column = 1;
    int row = 1;

    for (CircleView *circle in self.view.subviews) {
        if (circle.tag == 50) {
            [circle removeFromSuperview];
        }
    }

    for (int hole = 1; hole < 37; hole ++) {

        CircleView *circleView = [[CircleView alloc]initWithFrame:CGRectMake(xCord, yCord, self.view.frame.size.width * .125, self.view.frame.size.width * .125)];
        circleView.delegate = self;

        circleView.tag = 50;
        circleView.column = column;
        circleView.row = row;
        circleView.holeNumber = [NSNumber numberWithInt:hole];
        circleView.holeNumberInt = hole;

        circleView.layer.borderColor = [UIColor darkGrayColor].CGColor;
        circleView.layer.borderWidth = circleView.frame.size.height/20;
        circleView.layer.cornerRadius = circleView.frame.size.height/2;

        for (NSNumber *redNumbers in redCircles) {
            if ([redNumbers isEqualToNumber:[NSNumber numberWithInt:hole]]) {
                circleView.isBlue = NO;
                circleView.isTaken = YES;
                circleView.backgroundColor = [UIColor redColor];

                if (animate && !blue) {
                    if ([redNumbers isEqualToNumber:[redCircles lastObject]]) {
                        circleView.backgroundColor = [UIColor clearColor];
                    }
                }
            }
        }
        for (NSNumber *blueNumbers in blueCircles) {
            if ([blueNumbers isEqualToNumber:[NSNumber numberWithInt:hole]]) {
                circleView.isBlue = YES;
                circleView.isTaken = YES;
                circleView.backgroundColor = [UIColor blueColor];

                if (animate && blue) {
                    if ([blueNumbers isEqualToNumber:[blueCircles lastObject]]) {
                        circleView.backgroundColor = [UIColor clearColor];
                    }
                }
            }
        }

        xCord = xCord + circleView.frame.size.height + 10;
        column++;

        if (hole == 6 || hole == 12 || hole == 18 || hole == 24 || hole == 30) {
            xCord = 15;
            if (self.view.frame.size.width * .125 > 50) {
                xCord = (self.view.frame.size.width - ((self.view.frame.size.width * .125 + 10)*6))/2 + 5;
            }
            yCord = yCord + circleView.frame.size.height + 10;
            column = 1;
            row++;
        }
        [self.view addSubview:circleView];
        [circles addObject:circleView];
    }
    [self hideCircles];
}

- (void) hideCircles {

    for (CircleView *circle in circles) {
        ((CircleView*)[self circleViewForColumn:circle.column]).layer.borderColor = [UIColor whiteColor].CGColor;
        if (circle.isTaken) {
            circle.layer.borderColor = [UIColor whiteColor].CGColor;
        }
    }
    [self loadAI];
}

- (void)loadAI {
    NSMutableArray *options = [NSMutableArray array];
    for (int i = 1; i <= 6; i++) {
        [options addObject:[self circleViewForColumn:i]];

    }

    NSMutableArray *tempRed = [NSMutableArray array];
    NSMutableArray *tempBlue = [NSMutableArray array];

    for (CircleView *circleView in circles) {
        if (circleView.isBlue) {
            [tempBlue addObject:circleView];
        }
        else if (circleView.isTaken) {
            [tempRed addObject:circleView];
        }
    }
}

- (void) circleTouched:(id)sender {

    if (!isUserTurn) {
        return;
    }

    CircleView * circleView = [self circleViewForColumn:((CircleView*)sender).column];

    if (!circleView) {
        return;
    }

    circleView.isTaken = YES;

    NSMutableDictionary *circleDic = [[NSMutableDictionary alloc]init];
    [circleDic setObject:[NSNumber numberWithInt:circleView.column] forKey:@"Column"];
    [circleDic setObject:[NSNumber numberWithInt:circleView.row] forKey:@"Row"];

    CGPoint point = circleView.frame.origin;

    UIView * chip = [[UIView alloc]initWithFrame:CGRectMake(point.x, dropChipHeight, self.view.frame.size.width * .125, self.view.frame.size.width * .125)];
    chip.layer.borderColor = [UIColor whiteColor].CGColor;
    if (isLightTheme) {
        chip.layer.borderColor = [UIColor blackColor].CGColor;
    }
    chip.layer.borderWidth = chip.frame.size.width/20;
    chip.layer.cornerRadius = chip.frame.size.width/2;
    [self.view addSubview:chip];

    if (isBlue) {
        chip.backgroundColor = [UIColor blueColor];
    }
    else {
        chip.backgroundColor = [UIColor redColor];
    }

    [UIView animateWithDuration:1 animations:^{
        chip.frame = CGRectMake(point.x, point.y, self.view.frame.size.width * .125, self.view.frame.size.width * .125);
    } completion:^(BOOL finished) {
        if (isBlue) {
            circleView.backgroundColor = [UIColor blueColor];
        }
        else {
            circleView.backgroundColor = [UIColor redColor];
        }
        [chip removeFromSuperview];
    }];

    if (isBlue) {
        circleView.isBlue = YES;

        [blueCircles addObject:circleView.holeNumber];
    }
    else {
        circleView.isBlue = NO;

        [redCircles addObject:circleView.holeNumber];
    }

    [self checkCirclesForWin];
}

- (CircleView *) circleViewForColumn:(int)column {

    NSMutableArray * columnCircles = [[NSMutableArray alloc]init];

    for (CircleView *circleView in circles) {
        if (circleView.column == column) {
            if (!circleView.isTaken) {
                [columnCircles addObject:circleView];
            }
        }
    }

    return [columnCircles lastObject];
}

- (void)checkCirclesForWin {

    NSMutableArray *blues = [[NSMutableArray alloc]init];
    NSMutableArray *reds = [[NSMutableArray alloc]init];

    int takenCount = 0;

    for (CircleView *circleView in circles) {
        if (circleView.isTaken) {
            takenCount++;
        }
        if (circleView.isBlue) {
            [blues addObject:circleView];
        }
        else if (circleView.isTaken) {
            [reds addObject:circleView];
        }
    }

    BOOL winner = NO;

    if ([C4Helper fourConnectedForCircles:blues]) {

        winner = YES;
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[0]).matchOutcome = GKTurnBasedMatchOutcomeWon;
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[1]).matchOutcome = GKTurnBasedMatchOutcomeLost;
        [self showWinnerViewForBlue:YES];
    }

    if ([C4Helper fourConnectedForCircles:reds]) {
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[0]).matchOutcome = GKTurnBasedMatchOutcomeLost;
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[1]).matchOutcome = GKTurnBasedMatchOutcomeWon;
        winner = YES;
        [self showWinnerViewForBlue:NO];
    }

    if (takenCount == 36) {
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[0]).matchOutcome = GKTurnBasedMatchOutcomeTied;
        ((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[1]).matchOutcome = GKTurnBasedMatchOutcomeTied;
        winner = YES;
        [CSNotificationView showInViewController:self
                                           style:CSNotificationViewStyleError
                                         message:@"Tied Game"];

    }

    [self sendTurnForWin:winner];
}

- (void)showWinnerViewForBlue:(BOOL)blue {

    if (isShowingResult) {
        return;
    }

    BOOL isCurrentPlayerBlue = NO;
    if ([[GKLocalPlayer localPlayer].playerID isEqualToString:((GKTurnBasedParticipant*)[GKManager helper].currentMatch.participants[0]).playerID]) {
        isCurrentPlayerBlue = YES;
    }

    if (blue && isCurrentPlayerBlue) {
        [CSNotificationView showInViewController:self style:CSNotificationViewStyleSuccess message:@"You won this match"];
    }
    else if (blue && !isCurrentPlayerBlue) {
        [CSNotificationView showInViewController:self style:CSNotificationViewStyleError message:@"You lost this match"];
    }
    else if (!blue && !isCurrentPlayerBlue) {
        [CSNotificationView showInViewController:self style:CSNotificationViewStyleSuccess message:@"You won this match"];
    }
    else if (!blue && isCurrentPlayerBlue) {
        [CSNotificationView showInViewController:self style:CSNotificationViewStyleSuccess message:@"You lost this match"];
    }

    isShowingResult = YES;

    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(okToShow) userInfo:nil repeats:NO];
}

- (void) okToShow {
    isShowingResult = NO;
}

- (IBAction)menu:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end


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

  angular.module('d3-angular-main',['ui.router', 'd3-angular-test'])
    .config(function ($stateProvider) {
      $stateProvider
        .state('main', {
          url: '/',
          controller: 'MainCtrl',
          templateProvider: function($templateCache) {
            return $templateCache.get('main/main.html');
          }
        });
    })
    .controller('MainCtrl', function ($scope) {
      $scope.awesomeThings = [
        'HTML5 Boilerplate',
        'AngularJS',
        'Karma'
      ];
    });
})();


text:
class SnpsController < ApplicationController
  before_filter :find_snp, except: [:index, :json,:json_annotation]

  def index
    @snps = Snp.order(ranking: :desc)
    @snps_paginate = @snps.paginate(page: params[:page], per_page: 10)
    @title = 'Listing all SNPs'
  end

  def show
    @snp = Snp.includes(:snp_comments).
      where(name: params[:id].downcase).first || not_found

    if params[:format] == 'json'
      users = @snp.users
      json_results = users.map do |u|
        json_element(user_id: u.id, snp_name: @snp.name)
      end
      render json: json_results
      return
    end

    @title = @snp.name
    @comments = @snp.snp_comments.order('created_at ASC')
    @snp_comment = SnpComment.new

    if current_user
      # Refactor the following - fixes it for now. Problem with several genotypes. - Philipp
      @current_genotypes = current_user.genotypes
      if @current_genotypes != []
        @user_snp = @snp.user_snps.where(genotype_id: @current_genotypes.first.id).first
        @local_genotype = @user_snp.try(:local_genotype) || ''
      else
        @user_snp = nil
        @local_genotype = nil
      end
    end
  end

  def json
    # TODO: Refactor this. - Helge
    if params[:user_id].index(',')
      @user_ids = params[:user_id].split(',')
      @results = []
      @user_ids.each do |id|
        @new_param = {}
        @new_param[:user_id] = id
        @new_param[:snp_name] = params[:snp_name].downcase
        @results << json_element(@new_param)
      end
    elsif params[:user_id].index('-')
      @results = []
      @id_array = params[:user_id].split('-')
      @user_ids = (@id_array[0].to_i..@id_array[1].to_i).to_a
      @user_ids.each do |id|
        @new_param = {}
        @new_param[:user_id] = id
        @new_param[:snp_name] = params[:snp_name].downcase
        @results << json_element(@new_param)
      end
    else
      @results = json_element(params)
    end

    render json: @results
  end

  def make_annotation(result, snp, name)
    # TODO: Refactor this. - Helge
    result[name] = {}
    result[name]['name'] = snp.name
    result[name]['chromosome'] = snp.chromosome
    result[name]['position'] = snp.position
    result[name]['allele_frequency'] = snp.allele_frequency
    result[name]['genotype_frequency'] = snp.genotype_frequency
    result[name]['annotations'] = {}
    result[name]['annotations']['mendeley'] = []
    puts 'got snp-details'
    snp.mendeley_papers.each do |mp|
      @mendeley = {}
      @mendeley['author'] = mp.first_author
      @mendeley['title'] = mp.title
      @mendeley['publication_year'] = mp.pub_year
      @mendeley['number_of_readers'] = mp.reader
      @mendeley['open_access'] = mp.open_access
      @mendeley['url'] = mp.mendeley_url
      @mendeley['doi'] = mp.doi
      result[name]['annotations']['mendeley'] << @mendeley
    end
    puts 'got mendeley-details'
    result[name]['annotations']['plos'] = []
    snp.plos_papers.each do |mp|
      @plos = {}
      @plos['author'] = mp.first_author
      @plos['title'] = mp.title
      @plos['publication_date'] = mp.pub_date
      @plos['number_of_readers'] = mp.reader
      @plos['url'] = 'https://doi.org/' + mp.doi
      @plos['doi'] = mp.doi
      result[name]['annotations']['plos'] << @plos
    end
    puts 'got plos-details'
    result[name]['annotations']['snpedia'] = []
    snp.snpedia_papers.each do |mp|
      snpedia = {}
      snpedia['url'] = mp.url
      snpedia['summary'] = mp.summary
      result[name]['annotations']['snpedia'] << snpedia
    end
    puts 'got snpedia-details'
    result[name]['annotations']['pgp_annotations'] = []
    snp.pgp_annotations.each do |p|
      @pgp = {}
      @pgp['gene'] = p.gene
      @pgp['impact'] = p.qualified_impact
      @pgp['inheritance'] = p.inheritance
      @pgp['trait'] = p.trait
      @pgp['summary'] = p.summary
      result[name]['annotations']['pgp_annotations'] << @pgp
    end
    puts 'got pgp details'
    result[name]['annotations']['genome_gov_publications'] = []
    snp.genome_gov_papers.each do |g|
      @gov = {}
      @gov['title'] = g.title
      @gov['first_author'] = g.first_author
      @gov['pubmed_link'] = g.pubmed_link
      @gov['publication_date'] = g.pub_date
      @gov['journal'] = g.journal
      @gov['trait'] = g.trait
      @gov['pvalue'] = g.pvalue
      @gov['pvalue_description'] = g.pvalue_description
      @gov['confidence_interval'] = g.confidence_interval
      result[name]['annotations']['genome_gov_publications'] << @gov
    end
    puts 'got genome.gov details'
    return result
  end

  def json_annotation
    result = {}
    if params[:snp_name].index(',')
      snps = params[:snp_name].split(',')
      snps.each do |s|
        snp = Snp.find_by_name(s)
        # did we get a SNP?
        if snp
          result = make_annotation(result, snp, snp.name)
        else
          # empty dictionary, else we get a half-filled dictionary for EXISTS, DOESN'T EXIST, EXISTS
          result = {}
          result['error'] = 'Sorry, we couldn\'t find SNP' + s
          # just stop. Alternative: we could put in one error per SNP?
          break
        end
      end
    else
      snp = Snp.find_by_name(params[:snp_name].downcase)
      if snp
        puts snp.name
        result = make_annotation(result, snp, 'snp')
      else
        result['error'] = 'Sorry, we couldn\'t find SNP ' + params[:snp_name]
      end
    end

    @result = result
    render json: @result
  end

  private

  def json_element(params)
    # TODO: Refactor this. - Helge
    @result = {}
    begin
      @snp = params[:snp] || Snp.find_by_name(params[:snp_name].downcase)
      @result['snp'] = {}
      @result['snp']['name'] = @snp.name
      @result['snp']['chromosome'] = @snp.chromosome
      @result['snp']['position'] = @snp.position

      @user = User.find_by_id(params[:user_id])
      # Same hacky fix as above on line 35 - Philipp
      @genotypes = @user.genotypes
      if @genotypes != []
        @user_snps = @snp.user_snps.where(genotype_id: @genotypes.first.id)
      else
        @user_snps = []
      end
      @genotypes_array = []

      @user_snps.each do |us|
        @genotype_hash = {}
        @genotype_hash['genotype_id'] = us.genotype_id
        @genotype_hash['local_genotype'] = us.local_genotype
        @genotypes_array << @genotype_hash
      end

      @result['user'] = {}
      @result['user']['name'] = @user.name
      @result['user']['id'] = @user.id
      @result['user']['genotypes'] = @genotypes_array
    rescue
      @result = {}
      @result['error'] = "Sorry, we couldn't find any information for SNP "+params[:snp_name].to_s+" and user "+params[:user_id].to_s
    end
    return @result
  end

  def find_snp
    @snp = Snp.friendly.find(params[:id].downcase)
    @snp ||= Snp.find(params[:id])

    # If an old id or a numeric id was used to find the record, then
    # the request path will not match the post_path, and we should do
    # a 301 redirect that uses the current friendly id.
    if request.path != snp_path(@snp)
      if request.path.index('.json') == nil
        return redirect_to @snp, status: :moved_permanently
      end
    end
  end
end