text:
copyright:
  years: 2017 lastupdated: "2017-04-17"

---

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

# Configurando o SDK do Android
{: #android-sdk}

Construa os seus apps Android com o SDK do cliente do {{site.data.keyword.appid_short}}, inicialize o SDK, autentique usuários e faça solicitações
para recursos protegidos e desprotegidos.
{:shortdesc}

## Antes de Começar
{: #before-you-begin}

As seguintes informações são necessárias:
  * Uma instância de um serviço do {{site.data.keyword.appid_short_notm}}.
  * O seu ID do locatário.
    * Na guia **Credenciais de serviço** de seu painel de serviço, clique em **Visualizar credenciais**. Seu ID do locatário é exibido no campo **tenantID**. Esse valor é usado para inicializar o seu app.
  * A sua região do {{site.data.keyword.Bluemix}}. É possível localizar a sua região procurando na UI. O valor é usado para inicializar o seu app.

 Tabela 1. Regiões e valores do SDK correspondentes do {{site.data.keyword.Bluemix_notm}}

       Região do Bluemix
       Valor do SDK

       Sul dos Estados Unidos
       AppID.REGION_US_SOUTH

       Sydney
       AppID.REGION_SYDNEY

       United Kingdom
       AppID.REGION_UK

  * Um Projeto do Android
Studio, configurado para trabalhar com o Gradle.

## Instalando o SDK do cliente
{: #install-appid-sdk}

1. Crie um projeto Android Studio ou abra um projeto existente.
2.  Inclua o repositório do JitPack em seu arquivo raiz `build.gradle`.

  ```gradle
    allprojects {
	    repositories {
		    ...
		    maven { url 'https://jitpack.io' }
	    }
    }
  ```
  {:pre}

3. Abra o arquivo `build.gradle` para o seu aplicativo.

    **Nota**: certifique-se de abrir o arquivo para o seu app, não o arquivo `build.gradle` do projeto.
4. Localize a seção de dependências do arquivo e inclua uma dependência de compilação para o SDK do cliente do {{site.data.keyword.appid_short_notm}}:

  ```gradle
   dependencies {
       compile group: 'com.github.ibm-cloud-security:appid-clientsdk-android:1.+'
   }
  ```
  {:pre}

5. Localize a seção de defaultConfig e inclua as linhas de código a seguir:

  ```gradle
  defaultConfig {
  ...
  manifestPlaceholders = ['appIdRedirectScheme': android.defaultConfig.applicationId]
  }
  ```
  {:pre}

6. Sincronizar seu projeto com o Gradle. Clique em **Ferramentas** > **Android** > **Projeto de sincronização
com Arquivos do Gradle**.

## Inicializando o client SDK
{: #initialize-client-sdk}

Inicialize o SDK do cliente passando os parâmetros de contexto, ID do locatário e região para o método de inicialização. Um local comum, mas não obrigatório, para colocar o código de inicialização está no método onCreate da atividade principal em seu aplicativo Android.

  ```java
  AppID.getInstance().initialize(getApplicationContext(), <tenantId>, AppID.REGION_UK);
  ```
  {:pre}

1. Substitua "tenantId" pelo tenantId de serviço do {{site.data.keyword.appid_short_notm}}.
2. Substitua o AppID.REGION_UK pela sua região do {{site.data.keyword.Bluemix_notm}}.

## Autentique os usuários usando o widget de login
{: #authenticate-login-widget}

A configuração padrão do widget de login requer o uso do Facebook e do Google para autenticação. Se você configurar apenas um deles, o widget de login não será
ativado e o usuário será redirecionado para a tela de autenticação do IDP configurada.

Após o SDK do cliente do {{site.data.keyword.appid_short_notm}} ser inicializado, será possível autenticar os seus usuários executando o widget de login.

  ```java
  LoginWidget loginWidget = AppID.getInstance().getLoginWidget();
  loginWidget.launch(this, new AuthorizationListener() {
        @Override
        public void onAuthorizationFailure (AuthorizationException exception) {
          //Exception occurred
        }

        @Override
        public void onAuthorizationCanceled () {
          //Authentication canceled by the user
        }

        @Override
        public void onAuthorizationSuccess (AccessToken accessToken, IdentityToken identityToken) {
          //User authenticated
        }
      });
  ```
  {:pre}

## Acessando atributos do usuário
{: #accessing}

Ao obter um token de acesso, é possível obter acesso ao terminal protegido de atributos do usuário. É possível obter acesso usando os métodos de API a seguir:

  ```java
  void setAttribute(@NonNull String name, @NonNull String value, UserAttributeResponseListener listener);
  void setAttribute(@NonNull String name, @NonNull String value, @NonNull AccessToken accessToken, UserAttributeResponseListener listener);

  void getAttribute(@NonNull String name, UserAttributeResponseListener listener);
  void getAttribute(@NonNull String name, @NonNull AccessToken accessToken, UserAttributeResponseListener listener);

  void deleteAttribute(@NonNull String name, UserAttributeResponseListener listener);
  void deleteAttribute(@NonNull String name, @NonNull AccessToken accessToken, UserAttributeResponseListener listener);

  void getAllAttributes(@NonNull UserAttributeResponseListener listener);
  void getAllAttributes(@NonNull AccessToken accessToken, @NonNull UserAttributeResponseListener listener);
  ```
  {:pre}

Quando um token de acesso não for transmitido explicitamente, o {{site.data.keyword.appid_short_notm}} usará o último token recebido.

Por exemplo, é possível chamar esse código para configurar um novo atributo ou substituir um existente:

  ```java
  appId.getUserAttributeManager().setAttribute(name, value, useThisToken,new UserAttributeResponseListener() {
		@Override
		public void onSuccess(JSONObject attributes) {
			//attributes received in JSON format on successful response
		}

		@Override
		public void onFailure(UserAttributesException e) {
			//Exception occurred
		}
	});
  ```
  {:pre}

### Login anônimo
{: #anonymous notoc}

Com o {{site.data.keyword.appid_short_notm}} é possível efetuar login
[anonimamente](/docs/services/appid/user-profile.html#anonymous).

  ```java
  appId.loginAnonymously(getApplicationContext(), new AuthorizationListener() {
		@Override
		public void onAuthorizationFailure(AuthorizationException exception) {
			//Exception occurred
		}

		@Override
		public void onAuthorizationCanceled() {
			//Authentication canceled by the user
		}

		@Override
		public void onAuthorizationSuccess(AccessToken accessToken, IdentityToken identityToken) {
			//User authenticated
		}
	});
  ```
  {:pre}

### Autenticação progressiva
{: #progressive notoc}

Quando o usuário mantém um token de acesso anônimo, ele pode ser identificado passando-o para o método `loginWidget.launch`.

  ```java
  void launch (@NonNull final Activity activity, @NonNull final AuthorizationListener authorizationListener, String accessTokenString);
  ```
  {:pre}

Após um login anônimo, a autenticação progressiva ocorrerá mesmo se o widget de login for chamado sem passar um token de acesso porque o serviço usou o último
token recebido. Se você deseja limpar os seus tokens armazenados, execute o comando a seguir:

  ```java
  	appIDAuthorizationManager = new AppIDAuthorizationManager(this.appId);
  appIDAuthorizationManager.clearAuthorizationData();
  ```
  {:pre}

## Próximas etapas
{: #next-steps}

O {{site.data.keyword.appid_short_notm}} fornecerá uma configuração padrão quando você inicialmente configurar os seus provedores de identidade. É
possível usar a configuração padrão apenas no modo de desenvolvimento. Antes de publicar o seu aplicativo, atualize a configuração padrão do
[Facebook](/docs/services/appid/identity-providers.html#facebook) e do [Google](/docs/services/appid/identity-providers.html#google)
para as suas próprias credenciais.


text:
require "action_view"
require "rails"

module ActionView
  # = Action View Railtie
  class Railtie < Rails::Railtie
    config.action_view = ActiveSupport::OrderedOptions.new
    config.action_view.stylesheet_expansions = {}
    config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) }
    config.action_view.embed_authenticity_token_in_remote_forms = true

    initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
      ActiveSupport.on_load(:action_view) do
        ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
          app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
      end
    end

    initializer "action_view.cache_asset_ids" do |app|
      unless app.config.cache_classes
        ActiveSupport.on_load(:action_view) do
          ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
        end
      end
    end

    initializer "action_view.javascript_expansions" do |app|
      ActiveSupport.on_load(:action_view) do
        ActionView::Helpers::AssetTagHelper.register_javascript_expansion(
          app.config.action_view.delete(:javascript_expansions)
        )

        ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion(
          app.config.action_view.delete(:stylesheet_expansions)
        )
      end
    end

    initializer "action_view.set_configs" do |app|
      ActiveSupport.on_load(:action_view) do
        app.config.action_view.each do |k,v|
          send "#{k}=", v
        end
      end
    end

    initializer "action_view.caching" do |app|
      ActiveSupport.on_load(:action_view) do
        if app.config.action_view.cache_template_loading.nil?
          ActionView::Resolver.caching = app.config.cache_classes
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
'''
Pedagogical example realization of seq2seq recurrent neural networks, using TensorFlow and TFLearn.
More info at https://github.com/ichuang/tflearn_seq2seq
'''

from __future__ import division, print_function

import os
import sys
import tflearn
import argparse
import json

import numpy as np
import tensorflow as tf

from tensorflow.python.ops import seq2seq
from tensorflow.python.ops import rnn_cell

#-----------------------------------------------------------------------------

class SequencePattern(object):

    INPUT_SEQUENCE_LENGTH = 10
    OUTPUT_SEQUENCE_LENGTH = 10
    INPUT_MAX_INT = 9
    OUTPUT_MAX_INT = 9
    PATTERN_NAME = "sorted"

    def __init__(self, name=None, in_seq_len=None, out_seq_len=None):
        if name is not None:
            assert hasattr(self, "%s_sequence" % name)
            self.PATTERN_NAME = name
        if in_seq_len:
            self.INPUT_SEQUENCE_LENGTH = in_seq_len
        if out_seq_len:
            self.OUTPUT_SEQUENCE_LENGTH = out_seq_len

    def generate_output_sequence(self, x):
        '''
        For a given input sequence, generate the output sequence.  x is a 1D numpy array
        of integers, with length INPUT_SEQUENCE_LENGTH.

        Returns a 1D numpy array of length OUTPUT_SEQUENCE_LENGTH

        This procedure defines the pattern which the seq2seq RNN will be trained to find.
        '''
        return getattr(self, "%s_sequence" % self.PATTERN_NAME)(x)

    def maxmin_dup_sequence(self, x):
        '''
        Generate sequence with [max, min, rest of original entries]
        '''
        x = np.array(x)
        y = [ x.max(), x.min()] +  list(x[2:])
        return np.array(y)[:self.OUTPUT_SEQUENCE_LENGTH]	# truncate at out seq len

    def sorted_sequence(self, x):
        '''
        Generate sorted version of original sequence
        '''
        return np.array( sorted(x) )[:self.OUTPUT_SEQUENCE_LENGTH]

    def reversed_sequence(self, x):
        '''
        Generate reversed version of original sequence
        '''
        return np.array( x[::-1] )[:self.OUTPUT_SEQUENCE_LENGTH]

#-----------------------------------------------------------------------------

class TFLearnSeq2Seq(object):
    '''
    seq2seq recurrent neural network, implemented using TFLearn.
    '''
    AVAILABLE_MODELS = ["embedding_rnn", "embedding_attention"]
    def __init__(self, sequence_pattern, seq2seq_model=None, verbose=None, name=None, data_dir=None):
        '''
        sequence_pattern_class = a SequencePattern class instance, which defines pattern parameters
                                 (input, output lengths, name, generating function)
        seq2seq_model = string specifying which seq2seq model to use, e.g. "embedding_rnn"
        '''
        self.sequence_pattern = sequence_pattern
        self.seq2seq_model = seq2seq_model or "embedding_rnn"
        assert self.seq2seq_model in self.AVAILABLE_MODELS
        self.in_seq_len = self.sequence_pattern.INPUT_SEQUENCE_LENGTH
        self.out_seq_len = self.sequence_pattern.OUTPUT_SEQUENCE_LENGTH
        self.in_max_int = self.sequence_pattern.INPUT_MAX_INT
        self.out_max_int = self.sequence_pattern.OUTPUT_MAX_INT
        self.verbose = verbose or 0
        self.n_input_symbols = self.in_max_int + 1
        self.n_output_symbols = self.out_max_int + 2		# extra one for GO symbol
        self.model_instance = None
        self.name = name
        self.data_dir = data_dir

    def generate_trainig_data(self, num_points):
        '''
        Generate training dataset.  Produce random (integer) sequences X, and corresponding
        expected output sequences Y = generate_output_sequence(X).

        Return xy_data, y_data (both of type uint32)

        xy_data = numpy array of shape [num_points, in_seq_len + out_seq_len], with each point being X + Y
        y_data  = numpy array of shape [num_points, out_seq_len]
        '''
        x_data = np.random.randint(0, self.in_max_int, size=(num_points, self.in_seq_len))		# shape [num_points, in_seq_len]
        x_data = x_data.astype(np.uint32)						# ensure integer type

        y_data = [ self.sequence_pattern.generate_output_sequence(x) for x in x_data ]
        y_data = np.array(y_data)

        xy_data = np.append(x_data, y_data, axis=1)		# shape [num_points, 2*seq_len]
        return xy_data, y_data

    def sequence_loss(self, y_pred, y_true):
        '''
        Loss function for the seq2seq RNN.  Reshape predicted and true (label) tensors, generate dummy weights,
        then use seq2seq.sequence_loss to actually compute the loss function.
        '''
        if self.verbose > 2: print ("my_sequence_loss y_pred=%s, y_true=%s" % (y_pred, y_true))
        logits = tf.unstack(y_pred, axis=1)		# list of [-1, num_decoder_synbols] elements
        targets = tf.unstack(y_true, axis=1)		# y_true has shape [-1, self.out_seq_len]; unpack to list of self.out_seq_len [-1] elements
        if self.verbose > 2:
            print ("my_sequence_loss logits=%s" % (logits,))
            print ("my_sequence_loss targets=%s" % (targets,))
        weights = [tf.ones_like(yp, dtype=tf.float32) for yp in targets]
        if self.verbose > 4: print ("my_sequence_loss weights=%s" % (weights,))
        sl = seq2seq.sequence_loss(logits, targets, weights)
        if self.verbose > 2: print ("my_sequence_loss return = %s" % sl)
        return sl

    def accuracy(self, y_pred, y_true, x_in):		# y_pred is [-1, self.out_seq_len, num_decoder_symbols]; y_true is [-1, self.out_seq_len]
        '''
        Compute accuracy of the prediction, based on the true labels.  Use the average number of equal
        values.
        '''
        pred_idx = tf.to_int32(tf.argmax(y_pred, 2))		# [-1, self.out_seq_len]
        if self.verbose > 2: print ("my_accuracy pred_idx = %s" % pred_idx)
        accuracy = tf.reduce_mean(tf.cast(tf.equal(pred_idx, y_true), tf.float32), name='acc')
        return accuracy

    def model(self, mode="train", num_layers=1, cell_size=32, cell_type="BasicLSTMCell", embedding_size=20, learning_rate=0.0001,
              tensorboard_verbose=0, checkpoint_path=None):
        '''
        Build tensor specifying graph of operations for the seq2seq neural network model.

        mode = string, either "train" or "predict"
        cell_type = attribute of rnn_cell specifying which RNN cell type to use
        cell_size = size for the hidden layer in the RNN cell
        num_layers = number of RNN cell layers to use

        Return TFLearn model instance.  Use DNN model for this.
        '''
        assert mode in ["train", "predict"]

        checkpoint_path = checkpoint_path or ("%s%ss2s_checkpoint.tfl" % (self.data_dir or "", "/" if self.data_dir else ""))
        GO_VALUE = self.out_max_int + 1		# unique integer value used to trigger decoder outputs in the seq2seq RNN

        network = tflearn.input_data(shape=[None, self.in_seq_len + self.out_seq_len], dtype=tf.int32, name="XY")
        encoder_inputs = tf.slice(network, [0, 0], [-1, self.in_seq_len], name="enc_in")	# get encoder inputs
        encoder_inputs = tf.unstack(encoder_inputs, axis=1)					# transform into list of self.in_seq_len elements, each [-1]

        decoder_inputs = tf.slice(network, [0, self.in_seq_len], [-1, self.out_seq_len], name="dec_in")	# get decoder inputs
        decoder_inputs = tf.unstack(decoder_inputs, axis=1)					# transform into list of self.out_seq_len elements, each [-1]

        go_input = tf.multiply( tf.ones_like(decoder_inputs[0], dtype=tf.int32), GO_VALUE ) # insert "GO" symbol as the first decoder input; drop the last decoder input
        decoder_inputs = [go_input] + decoder_inputs[: self.out_seq_len-1]				# insert GO as first; drop last decoder input

        feed_previous = not (mode=="train")

        if self.verbose > 3:
            print ("feed_previous = %s" % str(feed_previous))
            print ("encoder inputs: %s" % str(encoder_inputs))
            print ("decoder inputs: %s" % str(decoder_inputs))
            print ("len decoder inputs: %s" % len(decoder_inputs))

        self.n_input_symbols = self.in_max_int + 1		# default is integers from 0 to 9
        self.n_output_symbols = self.out_max_int + 2		# extra "GO" symbol for decoder inputs

        single_cell = getattr(rnn_cell, cell_type)(cell_size, state_is_tuple=True)
        if num_layers==1:
            cell = single_cell
        else:
            cell = rnn_cell.MultiRNNCell([single_cell] * num_layers)

        if self.seq2seq_model=="embedding_rnn":
            model_outputs, states = seq2seq.embedding_rnn_seq2seq(encoder_inputs,	# encoder_inputs: A list of 2D Tensors [batch_size, input_size].
                                                                  decoder_inputs,
                                                                  cell,
                                                                  num_encoder_symbols=self.n_input_symbols,
                                                                  num_decoder_symbols=self.n_output_symbols,
                                                                  embedding_size=embedding_size,
                                                                  feed_previous=feed_previous)
        elif self.seq2seq_model=="embedding_attention":
            model_outputs, states = seq2seq.embedding_attention_seq2seq(encoder_inputs,	# encoder_inputs: A list of 2D Tensors [batch_size, input_size].
                                                                        decoder_inputs,
                                                                        cell,
                                                                        num_encoder_symbols=self.n_input_symbols,
                                                                        num_decoder_symbols=self.n_output_symbols,
                                                                        embedding_size=embedding_size,
                                                                        num_heads=1,
                                                                        initial_state_attention=False,
                                                                        feed_previous=feed_previous)
        else:
            raise Exception('[TFLearnSeq2Seq] Unknown seq2seq model %s' % self.seq2seq_model)

        tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + "seq2seq_model", model_outputs)	# for TFLearn to know what to save and restore

        # model_outputs: list of the same length as decoder_inputs of 2D Tensors with shape [batch_size x output_size] containing the generated outputs.
        if self.verbose > 2: print ("model outputs: %s" % model_outputs)
        network = tf.stack(model_outputs, axis=1)		# shape [-1, n_decoder_inputs (= self.out_seq_len), num_decoder_symbols]
        if self.verbose > 2: print ("packed model outputs: %s" % network)

        if self.verbose > 3:
            all_vars = tf.get_collection(tf.GraphKeys.VARIABLES)
            print ("all_vars = %s" % all_vars)

        with tf.name_scope("TargetsData"):			# placeholder for target variable (i.e. trainY input)
            targetY = tf.placeholder(shape=[None, self.out_seq_len], dtype=tf.int32, name="Y")

        network = tflearn.regression(network,
                                     placeholder=targetY,
                                     optimizer='adam',
                                     learning_rate=learning_rate,
                                     loss=self.sequence_loss,
                                     metric=self.accuracy,
                                     name="Y")

        model = tflearn.DNN(network, tensorboard_verbose=tensorboard_verbose, checkpoint_path=checkpoint_path)
        return model

    def train(self, num_epochs=20, num_points=100000, model=None, model_params=None, weights_input_fn=None,
              validation_set=0.1, snapshot_step=5000, batch_size=128, weights_output_fn=None):
        '''
        Train model, with specified number of epochs, and dataset size.

        Use specified model, or create one if not provided.  Load initial weights from file weights_input_fn,
        if provided. validation_set specifies what to use for the validation.

        Returns logits for prediction, as an numpy array of shape [out_seq_len, n_output_symbols].
        '''
        trainXY, trainY = self.generate_trainig_data(num_points)
        print ("[TFLearnSeq2Seq] Training on %d point dataset (pattern '%s'), with %d epochs" % (num_points,
                                                                                self.sequence_pattern.PATTERN_NAME,
                                                                                num_epochs))
        if self.verbose > 1:
            print ("  model parameters: %s" % json.dumps(model_params, indent=4))
        model_params = model_params or {}
        model = model or self.setup_model("train", model_params, weights_input_fn)

        model.fit(trainXY, trainY,
                  n_epoch=num_epochs,
                  validation_set=validation_set,
                  batch_size=batch_size,
                  shuffle=True,
                  show_metric=True,
                  snapshot_step=snapshot_step,
                  snapshot_epoch=False,
                  run_id="TFLearnSeq2Seq"
             )
        print ("Done!")
        if weights_output_fn is not None:
            weights_output_fn = self.canonical_weights_fn(weights_output_fn)
            model.save(weights_output_fn)
            print ("Saved %s" % weights_output_fn)
            self.weights_output_fn = weights_output_fn
        return model

    def canonical_weights_fn(self, iteration_num=0):
        '''
        Construct canonical weights filename, based on model and pattern names.
        '''
        if not type(iteration_num)==int:
            try:
                iteration_num = int(iteration_num)
            except Exception as err:
                return iteration_num
        model_name = self.name or "basic"
        wfn = "ts2s__%s__%s_%s.tfl" % (model_name, self.sequence_pattern.PATTERN_NAME, iteration_num)
        if self.data_dir:
            wfn = "%s/%s" % (self.data_dir, wfn)
        self.weights_filename = wfn
        return wfn

    def setup_model(self, mode, model_params=None, weights_input_fn=None):
        '''
        Setup a model instance, using the specified mode and model parameters.
        Load the weights from the specified file, if it exists.
        If weights_input_fn is an integer, use that the model name, and
        the pattern name, to construct a canonical filename.
        '''
        model_params = model_params or {}
        model = self.model_instance or self.model(mode=mode, **model_params)
        self.model_instance = model
        if weights_input_fn:
            if type(weights_input_fn)==int:
                weights_input_fn = self.canonical_weights_fn(weights_input_fn)
            if os.path.exists(weights_input_fn):
                model.load(weights_input_fn)
                print ("[TFLearnSeq2Seq] model weights loaded from %s" % weights_input_fn)
            else:
                print ("[TFLearnSeq2Seq] MISSING model weights file %s" % weights_input_fn)
        return model

    def predict(self, Xin, model=None, model_params=None, weights_input_fn=None):
        '''
        Make a prediction, using the seq2seq model, for the given input sequence Xin.
        If model is not provided, create one (or use last created instance).

        Return prediction, y

        prediction = array of integers, giving output prediction.  Length = out_seq_len
        y = array of shape [out_seq_len, out_max_int], giving logits for output prediction
        '''
        if not model:
            model = self.model_instance or self.setup_model("predict", model_params, weights_input_fn)

        if self.verbose: print ("Xin = %s" % str(Xin))

        X = np.array(Xin).astype(np.uint32)
        assert len(X)==self.in_seq_len
        if self.verbose:
            print ("X Input shape=%s, data=%s" % (X.shape, X))
            print ("Expected output = %s" % str(self.sequence_pattern.generate_output_sequence(X)))

        Yin = [0]*self.out_seq_len

        XY = np.append(X, np.array(Yin).astype(np.float32))
        XY = XY.reshape([-1, self.in_seq_len + self.out_seq_len])		# batch size 1
        if self.verbose > 1: print ("XY Input shape=%s, data=%s" % (XY.shape, XY))

        res = model.predict(XY)
        res = np.array(res)
        if self.verbose > 1: print ("prediction shape = %s" % str(res.shape))
        y = res.reshape(self.out_seq_len, self.n_output_symbols)
        prediction = np.argmax(y, axis=1)
        if self.verbose:
            print ("Predicted output sequence: %s" % str(prediction))
        return prediction, y

#-----------------------------------------------------------------------------

class VAction(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        curval = getattr(args, self.dest, 0) or 0
        values=values.count('v')+1
        setattr(args, self.dest, values + curval)

#-----------------------------------------------------------------------------

def CommandLine(args=None, arglist=None):
    '''
    Main command line.  Accepts args, to allow for simple unit testing.
    '''
    help_text = """
Commands:

train - give size of training set to use, as argument
predict - give input sequence as argument (or specify inputs via --from-file <filename>)

"""
    parser = argparse.ArgumentParser(description=help_text, formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument("cmd", help="command")
    parser.add_argument("cmd_input", nargs='*', help="input to command")
    parser.add_argument('-v', "--verbose", nargs=0, help="increase output verbosity (add more -v to increase versbosity)", action=VAction, dest='verbose')
    parser.add_argument("-m", "--model", help="seq2seq model name: either embedding_rnn (default) or embedding_attention", default=None)
    parser.add_argument("-r", "--learning-rate", type=float, help="learning rate (default 0.0001)", default=0.0001)
    parser.add_argument("-e", "--epochs", type=int, help="number of trainig epochs", default=10)
    parser.add_argument("-i", "--input-weights", type=str, help="tflearn file with network weights to load", default=None)
    parser.add_argument("-o", "--output-weights", type=str, help="new tflearn file where network weights are to be saved", default=None)
    parser.add_argument("-p", "--pattern-name", type=str, help="name of pattern to use for sequence", default=None)
    parser.add_argument("-n", "--name", type=str, help="name of model, used when generating default weights filenames", default=None)
    parser.add_argument("--in-len", type=int, help="input sequence length (default 10)", default=None)
    parser.add_argument("--out-len", type=int, help="output sequence length (default 10)", default=None)
    parser.add_argument("--from-file", type=str, help="name of file to take input data sequences from (json format)", default=None)
    parser.add_argument("--iter-num", type=int, help="training iteration number; specify instead of input- or output-weights to use generated filenames", default=None)
    parser.add_argument("--data-dir", help="directory to use for storing checkpoints (also used when generating default weights filenames)", default=None)
    # model parameters
    parser.add_argument("-L", "--num-layers", type=int, help="number of RNN layers to use in the model (default 1)", default=1)
    parser.add_argument("--cell-size", type=int, help="size of RNN cell to use (default 32)", default=32)
    parser.add_argument("--cell-type", type=str, help="type of RNN cell to use (default BasicLSTMCell)", default="BasicLSTMCell")
    parser.add_argument("--embedding-size", type=int, help="size of embedding to use (default 20)", default=20)
    parser.add_argument("--tensorboard-verbose", type=int, help="tensorboard verbosity level (default 0)", default=0)

    if not args:
        args = parser.parse_args(arglist)

    if args.iter_num is not None:
        args.input_weights = args.iter_num
        args.output_weights = args.iter_num + 1

    model_params = dict(num_layers=args.num_layers,
                        cell_size=args.cell_size,
                        cell_type=args.cell_type,
                        embedding_size=args.embedding_size,
                        learning_rate=args.learning_rate,
                        tensorboard_verbose=args.tensorboard_verbose,
                    )

    if args.cmd=="train":
        try:
            num_points = int(args.cmd_input[0])
        except:
            raise Exception("Please specify the number of datapoints to use for training, as the first argument")
        sp = SequencePattern(args.pattern_name, in_seq_len=args.in_len, out_seq_len=args.out_len)
        ts2s = TFLearnSeq2Seq(sp, seq2seq_model=args.model, data_dir=args.data_dir, name=args.name, verbose=args.verbose)
        ts2s.train(num_epochs=args.epochs, num_points=num_points, weights_output_fn=args.output_weights,
                   weights_input_fn=args.input_weights, model_params=model_params)
        return ts2s

    elif args.cmd=="predict":
        if args.from_file:
            inputs = json.loads(args.from_file)
        try:
            input_x = map(int, args.cmd_input)
            inputs = [input_x]
        except:
            raise Exception("Please provide a space-delimited input sequence as the argument")

        sp = SequencePattern(args.pattern_name, in_seq_len=args.in_len, out_seq_len=args.out_len)
        ts2s = TFLearnSeq2Seq(sp, seq2seq_model=args.model, data_dir=args.data_dir, name=args.name, verbose=args.verbose)
        results = []
        for x in inputs:
            prediction, y = ts2s.predict(x, weights_input_fn=args.input_weights, model_params=model_params)
            print("==> For input %s, prediction=%s (expected=%s)" % (x, prediction, sp.generate_output_sequence(x)))
            results.append([prediction, y])
        ts2s.prediction_results = results
        return ts2s

    else:
        print("Unknown command %s" % args.cmd)

#-----------------------------------------------------------------------------
# unit tests

def test_sp1():
    '''
    Test two different SequencePattern instances
    '''
    sp = SequencePattern("maxmin_dup")
    y = sp.generate_output_sequence(range(10))
    assert all(y==np.array([9, 0, 2, 3, 4, 5, 6, 7, 8, 9]))
    sp = SequencePattern("sorted")
    y = sp.generate_output_sequence([5,6,1,2,9])
    assert all(y==np.array([1, 2, 5, 6, 9]))
    sp = SequencePattern("reversed")
    y = sp.generate_output_sequence(range(10))
    assert all(y==np.array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]))

def test_sp2():
    '''
    Test two SequencePattern instance with lengths different from default
    '''
    sp = SequencePattern("sorted", in_seq_len=20, out_seq_len=5)
    x = np.random.randint(0, 9, 20)
    y = sp.generate_output_sequence(x)
    assert len(y)==5
    y_exp = sorted(x)[:5]
    assert all(y==y_exp)

def test_train1():
    '''
    Test simple training of an embedding_rnn seq2seq model
    '''
    sp = SequencePattern()
    ts2s = TFLearnSeq2Seq(sp)
    ofn = "test_%s" % ts2s.canonical_weights_fn(0)
    print ("using weights filename %s" % ofn)
    if os.path.exists(ofn):
        os.unlink(ofn)
    tf.reset_default_graph()
    ts2s.train(num_epochs=1, num_points=10000, weights_output_fn=ofn)
    assert os.path.exists(ofn)

def test_predict1():
    '''
    Test simple preductions using weights just produced (in test_train1)
    '''
    sp = SequencePattern()
    ts2s = TFLearnSeq2Seq(sp, verbose=1)
    wfn = "test_%s" % ts2s.canonical_weights_fn(0)
    print ("using weights filename %s" % wfn)
    tf.reset_default_graph()
    prediction, y = ts2s.predict(Xin=range(10), weights_input_fn=wfn)
    assert len(prediction==10)

def test_train_predict2():
    '''
    Test that the embedding_attention model works, with saving and loading of weights
    '''
    import tempfile
    sp = SequencePattern()
    tempdir = tempfile.mkdtemp()
    ts2s = TFLearnSeq2Seq(sp, seq2seq_model="embedding_attention", data_dir=tempdir, name="attention")
    tf.reset_default_graph()
    ts2s.train(num_epochs=1, num_points=1000, weights_output_fn=1, weights_input_fn=0)
    assert os.path.exists(ts2s.weights_output_fn)

    tf.reset_default_graph()
    ts2s = TFLearnSeq2Seq(sp, seq2seq_model="embedding_attention", data_dir="DATA", name="attention", verbose=1)
    prediction, y = ts2s.predict(Xin=range(10), weights_input_fn=1)
    assert len(prediction==10)

    os.system("rm -rf %s" % tempdir)

def test_train_predict3():
    '''
    Test that a model trained on sequencees of one length can be used for predictions on other sequence lengths
    '''
    import tempfile
    sp = SequencePattern("sorted", in_seq_len=10, out_seq_len=10)
    tempdir = tempfile.mkdtemp()
    ts2s = TFLearnSeq2Seq(sp, seq2seq_model="embedding_attention", data_dir=tempdir, name="attention")
    tf.reset_default_graph()
    ts2s.train(num_epochs=1, num_points=1000, weights_output_fn=1, weights_input_fn=0)
    assert os.path.exists(ts2s.weights_output_fn)

    tf.reset_default_graph()
    sp = SequencePattern("sorted", in_seq_len=20, out_seq_len=8)
    tf.reset_default_graph()
    ts2s = TFLearnSeq2Seq(sp, seq2seq_model="embedding_attention", data_dir="DATA", name="attention", verbose=1)
    x = np.random.randint(0, 9, 20)
    prediction, y = ts2s.predict(x, weights_input_fn=1)
    assert len(prediction==8)

    os.system("rm -rf %s" % tempdir)

def test_main1():
    '''
    Integration test - training
    '''
    import tempfile
    tempdir = tempfile.mkdtemp()
    arglist = "--data-dir %s -e 2 --iter-num=1 -v -v --tensorboard-verbose=1 train 5000" % tempdir
    arglist = arglist.split(' ')
    tf.reset_default_graph()
    ts2s = CommandLine(arglist=arglist)
    assert os.path.exists(ts2s.weights_output_fn)
    os.system("rm -rf %s" % tempdir)

def test_main2():
    '''
    Integration test - training then prediction
    '''
    import tempfile
    tempdir = tempfile.mkdtemp()
    arglist = "--data-dir %s -e 2 --iter-num=1 -v -v --tensorboard-verbose=1 train 5000" % tempdir
    arglist = arglist.split(' ')
    tf.reset_default_graph()
    ts2s = CommandLine(arglist=arglist)
    wfn = ts2s.weights_output_fn
    assert os.path.exists(wfn)

    arglist = "-i %s predict 1 2 3 4 5 6 7 8 9 0" % wfn
    arglist = arglist.split(' ')
    tf.reset_default_graph()
    ts2s = CommandLine(arglist=arglist)
    assert len(ts2s.prediction_results[0][0])==10

    os.system("rm -rf %s" % tempdir)

def test_main3():
    '''
    Integration test - training then prediction: attention model
    '''
    import tempfile
    wfn = "tmp_weights.tfl"
    if os.path.exists(wfn):
        os.unlink(wfn)
    arglist = "-e 2 -o tmp_weights.tfl -v -v -v -v -m embedding_attention train 5000"
    arglist = arglist.split(' ')
    tf.reset_default_graph()
    ts2s = CommandLine(arglist=arglist)
    assert os.path.exists(wfn)

    arglist = "-i tmp_weights.tfl -v -v -v -v -m embedding_attention predict 1 2 3 4 5 6 7 8 9 0"
    arglist = arglist.split(' ')
    tf.reset_default_graph()
    ts2s = CommandLine(arglist=arglist)
    assert len(ts2s.prediction_results[0][0])==10

#-----------------------------------------------------------------------------

if __name__=="__main__":
    CommandLine()


text:
package slamdata.engine

import slamdata.Predef._
import scala.AnyRef

import slamdata.engine.fp._
import slamdata.engine.analysis._
import slamdata.engine.std.Library

import scalaz.{Tree => _, Node => _, _}
import Scalaz._

sealed trait SemanticError {
  def message: String
}

object SemanticError {
  import slamdata.engine.sql._

  implicit val SemanticErrorShow = new Show[SemanticError] {
    override def show(value: SemanticError) = Cord(value.message)
  }

  final case class GenericError(message: String) extends SemanticError

  final case class DomainError(data: Data, hint: Option[String]) extends SemanticError {
    def message = "The data '" + data + "' did not fall within its expected domain" + hint.map(": " + _)
  }

  final case class FunctionNotFound(name: String) extends SemanticError {
    def message = "The function '" + name + "' could not be found in the standard library"
  }
  final case class FunctionNotBound(node: Node) extends SemanticError {
    def message = "A function was not bound to the node " + node
  }
  final case class TypeError(expected: Type, actual: Type, hint: Option[String]) extends SemanticError {
    def message = "Expected type " + expected + " but found " + actual + hint.map(": " + _).getOrElse("")
  }
  final case class VariableParseError(vari: VarName, value: VarValue, cause: slamdata.engine.sql.ParsingError) extends SemanticError {
    def message = "The variable " + vari + " should contain a SQL expression but was `" + value.value + "` (" + cause.message + ")"
  }
  final case class DuplicateRelationName(defined: String, duplicated: SqlRelation) extends SemanticError {
    private def nameOf(r: SqlRelation) = r match {
      case TableRelationAST(name, aliasOpt) => aliasOpt.getOrElse(name)
      case ExprRelationAST(_, alias)        => alias
      case JoinRelation(_, _, _, _)         => "unknown"
      case CrossRelation(_, _)              => "unknown"
    }

    def message = "Found relation with duplicate name '" + defined + "': " + defined
  }
  final case class NoTableDefined(node: Node) extends SemanticError {
    def message = "No table was defined in the scope of \'" + node.sql + "\'"
  }
  final case class MissingField(name: String) extends SemanticError {
    def message = "No field named '" + name + "' exists"
  }
  final case class MissingIndex(index: Int) extends SemanticError {
    def message = "No element exists at array index '" + index
  }
  final case class WrongArgumentCount(func: Func, expected: Int, actual: Int) extends SemanticError {
    def message = "Wrong number of arguments for function '" + func.name + "': expected " + expected + " but found " + actual
  }
  final case class NonCompilableNode(node: Node) extends SemanticError {
    def message = "The node " + node + " cannot be compiled"
  }
  final case class ExpectedLiteral(node: Node) extends SemanticError {
    def message = "Expected literal but found '" + node.sql + "'"
  }
  final case class AmbiguousReference(node: Node, relations: List[SqlRelation]) extends SemanticError {
    def message = "The expression '" + node.sql + "' is ambiguous and might refer to any of the tables " + relations.mkString(", ")
  }
  final case object CompiledTableMissing extends SemanticError {
    def message = "Expected the root table to be compiled but found nothing"
  }
  final case class CompiledSubtableMissing(name: String) extends SemanticError {
    def message = "Expected to find a compiled subtable with name \"" + name + "\""
  }
  final case class DateFormatError(func: Func, str: String, hint: Option[String]) extends SemanticError {
    def message = "Date/time string could not be parsed as " + func.name + ": " + str + hint.map(" (" + _ + ")").getOrElse("")
  }
}

trait SemanticAnalysis {
  import slamdata.engine.sql._
  import SemanticError._

  type Failure = NonEmptyList[SemanticError]

  private def fail[A](e: SemanticError) = Validation.failure[NonEmptyList[SemanticError], A](NonEmptyList(e))
  private def succeed[A](s: A) = Validation.success[NonEmptyList[SemanticError], A](s)

  def tree(root: Node): AnnotatedTree[Node, Unit] = AnnotatedTree.unit(root, n => n.children)

  /**
   * This analyzer looks for function invocations (including operators),
   * and binds them to their associated function definitions in the
   * provided library. If a function definition cannot be found,
   * produces an error with details on the failure.
   */
  def FunctionBind[A](library: Library) = {
    def findFunction(name: String) = {
      val lcase = name.toLowerCase

      library.functions.find(f => f.name.toLowerCase == lcase).map(f => Validation.success(Some(f))).getOrElse(
        fail(FunctionNotFound(name))
      )
    }

    Analysis.annotate[Node, A, Option[Func], Failure] {
      case (InvokeFunction(name, args)) => findFunction(name)

      case (Unop(expr, op)) => findFunction(op.name)

      case (Binop(left, right, op)) => findFunction(op.name)

      case _ => Validation.success(None)
    }
  }

  sealed trait Synthetic
  object Synthetic {
    final case object SortKey extends Synthetic
  }

  implicit val SyntheticRenderTree = RenderTree.fromToString[Synthetic]("Synthetic")

  /**
   * Inserts synthetic fields into the projections of each `select` stmt to hold
   * the values that will be used in sorting, and annotates each new projection
   * with Synthetic.SortKey. The compiler will generate a step to remove these
   * fields after the sort operation.
   */
  def TransformSelect[A]: Analysis[Node, A, Option[Synthetic], Failure] = {
    val prefix = "__sd__"

    def transform(node: Node): Node =
      node match {
        case sel @ Select(_, projections, _, _, _, Some(sql.OrderBy(keys)), _, _) => {
          def matches(key: Expr): PartialFunction[Proj, Expr] = key match {
            case Ident(keyName) => {
              case Proj(_, Some(alias))        if keyName == alias    => key
              case Proj(Ident(projName), None) if keyName == projName => key
              case Proj(Splice(_), _)                                 => key
            }
            case _ => {
              case Proj(expr2, Some(alias)) if key == expr2 => Ident(alias)
            }
          }

          // Note: order of the keys has to be preserved, so this complex fold seems
          // to be the best way.
          type Target = (List[Proj], List[(Expr, OrderType)], Int)

          val (projs2, keys2, _) = keys.foldRight[Target]((Nil, Nil, 0)) {
            case ((expr, orderType), (projs, keys, index)) =>
              projections.collectFirst(matches(expr)).fold {
                val name  = prefix + index.toString()
                val proj2 = Proj(expr, Some(name))
                val key2  = Ident(name) -> orderType
                (proj2 :: projs, key2 :: keys, index + 1)
              } (
                kExpr => (projs, (kExpr, orderType) :: keys, index))
          }

          sel.copy(projections = projections ++ projs2,
                   orderBy     = Some(sql.OrderBy(keys2)))
        }

        case _ => node
      }

    val ann = Analysis.annotate[Node, Unit, Option[Synthetic], Failure] { node =>
      node match {
        case Proj(_, Some(name)) if name.startsWith(prefix) =>
          Some(Synthetic.SortKey).success
        case _ => None.success
      }
    }

    tree1 => ann(tree(transform(tree1.root)))
  }

  case class TableScope(scope: Map[String, SqlRelation])

  implicit val ShowTableScope = new Show[TableScope] {
    override def show(v: TableScope) = Show[Map[String, Node]].show(v.scope)
  }

  /**
   * This analysis identifies all the named tables within scope at each node in
   * the tree. If two tables are given the same name within the same scope, then
   * because this leads to an ambiguity, an error is produced containing details
   * on the duplicate name.
   */
  def ScopeTables[A] = Analysis.readTree[Node, A, TableScope, Failure] { tree =>
    import Validation.{success, failure}

    Analysis.fork[Node, A, TableScope, Failure]((scopeOf, node) => {
      def parentScope(node: Node) = tree.parent(node).map(scopeOf).getOrElse(TableScope(Map()))

      node match {
        case Select(_, projections, relations, filter, groupBy, orderBy, limit, offset) =>
          val parentMap = parentScope(node).scope

          (relations.foldLeft[Validation[Failure, Map[String, SqlRelation]]](success(Map.empty[String, SqlRelation])) {
            case (v, relation) =>
              implicit val sg = Semigroup.firstSemigroup[SqlRelation]

              v +++ tree.subtree(relation).foldDown[Validation[Failure, Map[String, SqlRelation]]](success(Map.empty[String, SqlRelation])) {
                case (v, relation : SqlRelation) =>
                  v.fold(
                    failure,
                    acc => {
                      val name = relation match {
                        case TableRelationAST(name, aliasOpt) => Some(aliasOpt.getOrElse(name))
                        case ExprRelationAST(_, alias)        => Some(alias)
                        case JoinRelation(_, _, _, _)         => None
                        case CrossRelation(_, _)              => None
                      }

                      (name.map { name =>
                        (acc.get(name).map{ relation2 =>
                          fail(DuplicateRelationName(name, relation2))
                        }).getOrElse(success(acc + (name -> relation)))
                      }).getOrElse(success(acc))
                    }
                  )

                case (v, _) => v // We're only interested in relations
              }
          }).map(map => TableScope(parentMap ++ map))

        case _ => success(parentScope(node))
      }
    })
  }

  sealed trait Provenance {
    import Provenance._

    def & (that: Provenance): Provenance = Both(this, that)

    def | (that: Provenance): Provenance = Either(this, that)

    def simplify: Provenance = this match {
      case x : Either => anyOf(x.flatten.map(_.simplify).filterNot(_ == Empty))
      case x : Both => allOf(x.flatten.map(_.simplify).filterNot(_ == Empty))
      case _ => this
    }

    def namedRelations: Map[String, List[NamedRelation]] = Foldable[List].foldMap(relations)(_.namedRelations)

    def relations: List[SqlRelation] = this match {
      case Empty => Nil
      case Value => Nil
      case Relation(value) => value :: Nil
      case Either(v1, v2) => v1.relations ++ v2.relations
      case Both(v1, v2) => v1.relations ++ v2.relations
    }

    def flatten: Set[Provenance] = Set(this)

    override def equals(that: scala.Any): Boolean = (this, that) match {
      case (x, y) if (x.eq(y.asInstanceOf[AnyRef])) => true
      case (Relation(v1), Relation(v2)) => v1 == v2
      case (Either(_, _), that @ Either(_, _)) => this.simplify.flatten == that.simplify.flatten
      case (Both(_, _), that @ Both(_, _)) => this.simplify.flatten == that.simplify.flatten
      case (_, _) => false
    }

    override def hashCode = this match {
      case Either(_, _) => this.simplify.flatten.hashCode
      case Both(_, _) => this.simplify.flatten.hashCode
      case _ => super.hashCode
    }
  }
  trait ProvenanceInstances {
    implicit val ProvenanceRenderTree = new RenderTree[Provenance] { self =>
      import Provenance._

      override def render(v: Provenance) = {
        val ProvenanceNodeType = List("Provenance")

        def nest(l: RenderedTree, r: RenderedTree, sep: String) = (l, r) match {
          case (RenderedTree(_, ll, Nil), RenderedTree(_, rl, Nil)) =>
                    Terminal(ProvenanceNodeType, Some("(" + ll + " " + sep + " " + rl + ")"))
          case _ => NonTerminal(ProvenanceNodeType, Some(sep), l :: r :: Nil)
        }

        v match {
          case Empty               => Terminal(ProvenanceNodeType, Some("Empty"))
          case Value               => Terminal(ProvenanceNodeType, Some("Value"))
          case Relation(value)     => RenderTree[Node].render(value).copy(nodeType = ProvenanceNodeType)
          case Either(left, right) => nest(self.render(left), self.render(right), "|")
          case Both(left, right)   => nest(self.render(left), self.render(right), "&")
        }
      }
    }

    implicit val ProvenanceOrMonoid = new Monoid[Provenance] {
      import Provenance._

      def zero = Empty

      def append(v1: Provenance, v2: => Provenance) = (v1, v2) match {
        case (Empty, that) => that
        case (this0, Empty) => this0
        case _ => v1 | v2
      }
    }

    implicit val ProvenanceAndMonoid = new Monoid[Provenance] {
      import Provenance._

      def zero = Empty

      def append(v1: Provenance, v2: => Provenance) = (v1, v2) match {
        case (Empty, that) => that
        case (this0, Empty) => this0
        case _ => v1 & v2
      }
    }
  }
  object Provenance extends ProvenanceInstances {
    case object Empty extends Provenance
    case object Value extends Provenance
    case class Relation(value: SqlRelation) extends Provenance
    case class Either(left: Provenance, right: Provenance) extends Provenance {
      override def flatten: Set[Provenance] = {
        def flatten0(x: Provenance): Set[Provenance] = x match {
          case Either(left, right) => flatten0(left) ++ flatten0(right)
          case _ => Set(x)
        }
        flatten0(this)
      }
    }
    case class Both(left: Provenance, right: Provenance) extends Provenance {
      override def flatten: Set[Provenance] = {
        def flatten0(x: Provenance): Set[Provenance] = x match {
          case Both(left, right) => flatten0(left) ++ flatten0(right)
          case _ => Set(x)
        }
        flatten0(this)
      }
    }

    def allOf(xs: Iterable[Provenance]): Provenance = {
      import scalaz.std.iterable._

      xs.concatenate(ProvenanceAndMonoid)
    }

    def anyOf(xs: Iterable[Provenance]): Provenance = {
      import scalaz.std.iterable._

      xs.concatenate(ProvenanceOrMonoid)
    }
  }

  /**
   * This phase infers the provenance of every expression, issuing errors
   * if identifiers are used with unknown provenance. The phase requires
   * TableScope annotations on the tree.
   */
  def ProvenanceInfer = Analysis.readTree[Node, TableScope, Provenance, Failure] { tree =>
    Analysis.join[Node, TableScope, Provenance, Failure]((provOf, node) => {
      import Validation.{success, failure}

      def propagate(child: Node) = success(provOf(child))

      def NA: Validation[Nothing, Provenance] = success(Provenance.Empty)

      (node match {
        case Select(_, projections, relations, filter, groupBy, orderBy, limit, offset) =>
          success(Provenance.allOf(projections.map(provOf)))

        case Proj(expr, _)      => propagate(expr)
        case SetLiteral(exprs)  => success(Provenance.Value)
        case ArrayLiteral(exprs) => success(Provenance.Value)
          // FIXME: NA case
        case Splice(expr)       => expr.fold(NA)(x => success(provOf(x)))
        case v @ Vari(_)        => success(Provenance.Value)
        case Binop(left, right, op) =>
          success(provOf(left) & provOf(right))
        case Unop(expr, op) => success(provOf(expr))
        case ident @ Ident(name) =>
          val tableScope = tree.attr(node).scope

          (tableScope.get(name).map((Provenance.Relation.apply _) andThen success)).getOrElse {
            Provenance.anyOf(tableScope.values.map(Provenance.Relation.apply)) match {
              case Provenance.Empty => fail(NoTableDefined(ident))

              case x => success(x)
            }
          }

        case InvokeFunction(name, args) =>
          success(Provenance.allOf(args.map(provOf)))
        case Case(cond, expr) => propagate(expr)
        case Match(expr, cases, default) =>
          success(cases.map(provOf).concatenate(Provenance.ProvenanceAndMonoid))
        case Switch(cases, default) => success(cases.map(provOf).concatenate(Provenance.ProvenanceAndMonoid))

        case IntLiteral(value) => success(Provenance.Value)

        case FloatLiteral(value) => success(Provenance.Value)

        case StringLiteral(value) => success(Provenance.Value)

        case BoolLiteral(value) => success(Provenance.Value)

        case NullLiteral => success(Provenance.Value)

        case r @ TableRelationAST(_, _) => success(Provenance.Relation(r))

        case r @ ExprRelationAST(_, _) => success(Provenance.Relation(r))

        case r @ JoinRelation(_, _, _, _) => success(Provenance.Relation(r))

        case r @ CrossRelation(_, _) => success(Provenance.Relation(r))

        case GroupBy(keys, having) => success(Provenance.allOf(keys.map(provOf)))

        case OrderBy(keys) => success(Provenance.allOf(keys.map(_._1).toList.map(provOf)))

        case _ : BinaryOperator => NA

        case _ : UnaryOperator => NA
      }).map(_.simplify)
    })
  }

  sealed trait InferredType
  object InferredType {
    case class Specific(value: Type) extends InferredType
    case object Unknown extends InferredType

    implicit val ShowInferredType = new Show[InferredType] {
      override def show(v: InferredType) = v match {
        case Unknown => Cord("?")
        case Specific(v) => Show[Type].show(v)
      }
    }
  }

  /**
   * This phase works top-down to push out known types to terms with unknowable
   * types (such as columns and wildcards). The annotation is the type of the node,
   * which defaults to Type.Top in cases where it is not known.
   */
  def TypeInfer = {
    Analysis.readTree[Node, Option[Func], Map[Node, Type], Failure] { tree =>
      import Validation.{success}

      Analysis.fork[Node, Option[Func], Map[Node, Type], Failure]((mapOf, node) => {
        /**
         * Retrieves the inferred type of the current node being annotated.
         */
        def inferredType = for {
          parent   <- tree.parent(node)
          selfType <- mapOf(parent).get(node)
        } yield selfType

        /**
         * Propagates the inferred type of this node to its sole child node.
         */
        def propagate(child: Node) = propagateAll(child :: Nil)

        /**
         * Propagates the inferred type of this node to its identically-typed
         * children nodes.
         */
        def propagateAll(children: Seq[Node]) = success(inferredType.map(t => Map(children.map(_ -> t): _*)).getOrElse(Map()))

        def annotateFunction(args: List[Node]) =
          (tree.attr(node).map { func =>
            val typesV = inferredType.map(func.untype).getOrElse(success(func.domain))
            typesV map (types => (args zip types).toMap)
          }).getOrElse(fail(FunctionNotBound(node)))

        /**
         * Indicates no information content for the children of this node.
         */
        def NA = success(Map.empty[Node, Type])

        node match {
          case Select(_, projections, relations, filter, groupBy, orderBy, limit, offset) =>
            inferredType match {
              // TODO: If there's enough type information in the inferred type to do so, push it
              //       down to the projections.

              case _ => NA
            }

          case Proj(expr, _)     => propagate(expr)
          case SetLiteral(exprs) =>
            inferredType match {
              // Push the set type down to the children:
              case Some(Type.Set(tpe)) => success(exprs.map(_ -> tpe).toMap)

              case _ => NA
            }
          case ArrayLiteral(exprs) =>
            inferredType match {
              // Push the array type down to the children:
              case Some(Type.FlexArr(_, _, tpe)) => success(exprs.map(_ -> tpe).toMap)

              case _ => NA
            }
          case Splice(expr) => expr.fold(NA)(propagate(_))
          case v @ Vari(_) => NA
          case Binop(left, right, _) => annotateFunction(left :: right :: Nil)
          case Unop(expr, _) => annotateFunction(expr :: Nil)
          case Ident(_) => NA
          case InvokeFunction(_, args) => annotateFunction(args)
          case Case(_, expr) => propagate(expr)
          case Match(_, cases, default) => propagateAll(cases ++ default)
          case Switch(cases, default) => propagateAll(cases ++ default)
          case IntLiteral(_) => NA
          case FloatLiteral(_) => NA
          case StringLiteral(_) => NA
          case BoolLiteral(_) => NA
          case NullLiteral => NA
          case TableRelationAST(_, _) => NA
          case ExprRelationAST(expr, _) => propagate(expr)
          case JoinRelation(_, _, _, _) => NA
          case CrossRelation(_, _) => NA
          case GroupBy(_, _) => NA
          case OrderBy(_) => NA
          case _: BinaryOperator => NA
          case _: UnaryOperator  => NA
        }
      })
    } >>> Analysis.readTree[Node, Map[Node, Type], InferredType, Failure] { tree =>
      Analysis.fork[Node, Map[Node, Type], InferredType, Failure]((typeOf, node) => {
        // Read the inferred type of this node from the parent node's attribute:
        succeed((for {
          parent   <- tree.parent(node)
          selfType <- tree.attr(parent).get(node)
        } yield selfType).map(InferredType.Specific.apply).getOrElse(InferredType.Unknown))
      })
    }
  }

  /**
   * This phase works bottom-up to check the type of all expressions.
   * In the event of a type error, an error will be produced containing
   * details on the expected versus actual type.
   */
  def TypeCheck = {
    Analysis.readTree[Node, (Option[Func], InferredType), Type, Failure] { tree =>
      Analysis.join[Node, (Option[Func], InferredType), Type, Failure]((typeOf, node) => {
        def func(node: Node): ValidationNel[SemanticError, Func] = {
          tree.attr(node)._1.map(Validation.success).getOrElse(fail(FunctionNotBound(node)))
        }

        def inferType(default: Type): ValidationNel[SemanticError, Type] = succeed(tree.attr(node)._2 match {
          case InferredType.Unknown => default
          case InferredType.Specific(v) => v
        })

        def typecheckArgs(func: Func, actual: List[Type]): ValidationNel[SemanticError, Unit] = {
          val expected = func.domain

          if (expected.length != actual.length) {
            fail[Unit](WrongArgumentCount(func, expected.length, actual.length))
          } else {
            (expected.zip(actual).map {
              case (expected, actual) => Type.typecheck(expected, actual)
            }).sequenceU.map(κ(()))
          }
        }

        def typecheckFunc(args: List[Expr]) = {
          func(node).fold(
            Validation.failure,
            func => {
              val argTypes = args.map(typeOf)

              typecheckArgs(func, argTypes).fold(
                Validation.failure,
                κ(func.apply(argTypes)))
            })
        }

        def NA = succeed(Type.Bottom)

        def propagate(n: Node) = succeed(typeOf(n))

        node match {
          case s @ Select(_, projections, relations, filter, groupBy, orderBy, limit, offset) =>
            succeed(Type.Obj(s.namedProjections(None).map(t => (t._1, typeOf(t._2))).toMap, None))

          case Proj(expr, _)     => propagate(expr)
          case SetLiteral(exprs) => succeed(Type.Arr(exprs.map(typeOf)))  // FIXME: should be Type.Set(...)
          case ArrayLiteral(exprs) => succeed(Type.Arr(exprs.map(typeOf)))
          case Splice(_) => inferType(Type.Top)
          case v @ Vari(_) => inferType(Type.Top)
          case Binop(left, right, op) => typecheckFunc(left :: right :: Nil)
          case Unop(expr, op) => typecheckFunc(expr :: Nil)
          case Ident(name) => inferType(Type.Top)
          case InvokeFunction(name, args) => typecheckFunc(args.toList)
          case Case(cond, expr) => succeed(typeOf(expr))
          case Match(expr, cases, default) =>
            succeed((cases ++ default).map(typeOf).foldLeft[Type](Type.Top)(_ | _).lub)
          case Switch(cases, default) =>
            succeed((cases ++ default).map(typeOf).foldLeft[Type](Type.Top)(_ | _).lub)
          case IntLiteral(value) => succeed(Type.Const(Data.Int(value)))
          case FloatLiteral(value) => succeed(Type.Const(Data.Dec(value)))
          case StringLiteral(value) => succeed(Type.Const(Data.Str(value)))
          case BoolLiteral(value) => succeed(Type.Const(Data.Bool(value)))
          case NullLiteral => succeed(Type.Const(Data.Null))
          case TableRelationAST(_, _) => NA
          case ExprRelationAST(expr, _) => propagate(expr)
          case JoinRelation(_, _, _, _) => succeed(Type.Bool)
          case CrossRelation(left, right) => succeed(typeOf(left) & typeOf(right))
          case GroupBy(keys, having) =>
            // Not necessary but might be useful:
            succeed(Type.Arr(keys.map(typeOf)))
          case OrderBy(keys) => NA
          case _: BinaryOperator => NA
          case _: UnaryOperator  => NA
        }
      })
    }
  }

  type Annotations = (((Option[Synthetic], Provenance), Option[Func]), Type)

  val AllPhases: Analysis[Node, Unit, Annotations, Failure] =
    (TransformSelect[Unit].push(()) >>>
      ScopeTables.second >>>
      ProvenanceInfer.second).push(()) >>>
    FunctionBind[Unit](std.StdLib).second.dup2 >>>
    TypeInfer.second >>>
    TypeCheck.pop2
}
object SemanticAnalysis extends SemanticAnalysis


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package org.codemonkey.simplejavamail;
002
003/**
004 * Defines a set of restriction flags for email address validation. To remain completely true to RFC 2822, all flags should be set to
005 * <code>true</code>.
006 *
007 * @author Benny Bottema
008 * @see #EmailAddressValidationCriteria(boolean, boolean)
009 */
010public class EmailAddressValidationCriteria {
011
012        private final boolean allowDomainLiterals;
013        private final boolean allowQuotedIdentifiers;
014
015        /**
016         * Criteria which is most RFC 2822 compliant and allows all compiant address forms, including the more exotic ones.
017         *
018         * @see #EmailAddressValidationCriteria(boolean, boolean)
019         */
020        public static final EmailAddressValidationCriteria RFC_COMPLIANT = new EmailAddressValidationCriteria(true, true);
021
022        /**
023         * @param allowDomainLiterals <ul>
024         *            <li>This flag states whether domain literals are allowed in the email address, e.g.:
025         *            <p>
026         *            <tt>someone@[192.168.1.100]</tt> or <br>
027         *            <tt>john.doe@[23:33:A2:22:16:1F]</tt> or <br>
028         *            <tt>me@[my computer]</tt>
029         *            </p>
030         *            <p>
031         *            The RFC says these are valid email addresses, but most people don't like allowing them. If you don't want to allow them,
032         *            and only want to allow valid domain names (<a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>, x.y.z.com, etc),
033         *            change this constant to <tt>false</tt>.
034         *            <p>
035         *            Its default value is <tt>true</tt> to remain RFC 2822 compliant, but you should set it depending on what you need for your
036         *            application.</li>
037         *            </ul>
038         * @param allowQuotedIdentifiers <ul>
039         *            <li>This flag states whether quoted identifiers are allowed (using quotes and angle brackets around the raw address) are
040         *            allowed, e.g.:
041         *            <p>
042         *            <tt>"John Smith" &lt;john.smith@somewhere.com&gt;</tt>
043         *            <p>
044         *            The RFC says this is a valid mailbox. If you don't want to allow this, because for example, you only want users to enter
045         *            in a raw address (<tt>john.smith@somewhere.com</tt> - no quotes or angle brackets), then change this constant to
046         *            <tt>false</tt>.
047         *            <p>
048         *            Its default value is <tt>true</tt> to remain RFC 2822 compliant, but you should set it depending on what you need for your
049         *            application.</li>
050         *            </ul>
051         */
052        public EmailAddressValidationCriteria(boolean allowDomainLiterals, boolean allowQuotedIdentifiers) {
053                this.allowDomainLiterals = allowDomainLiterals;
054                this.allowQuotedIdentifiers = allowQuotedIdentifiers;
055        }
056
057        public final boolean isAllowDomainLiterals() {
058                return allowDomainLiterals;
059        }
060
061        public final boolean isAllowQuotedIdentifiers() {
062                return allowQuotedIdentifiers;
063        }
064}


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

namespace ScintillaNET
{
    /// <summary>
    /// A <see cref="Scintilla" /> document.
    /// </summary>
    /// <remarks>
    /// This is an opaque type, meaning it can be used by a <see cref="Scintilla" /> control but
    /// otherwise has no public members of its own.
    /// </remarks>
    public struct Document
    {
        internal IntPtr Value;

        /// <summary>
        /// A read-only field that represents an uninitialized document.
        /// </summary>
        public static readonly Document Empty;

        /// <summary>
        /// Returns a value indicating whether this instance is equal to a specified object.
        /// </summary>
        /// <param name="obj">An object to compare with this instance or null.</param>
        /// <returns>true if <paramref name="obj" /> is an instance of <see cref="Document" /> and equals the value of this instance; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            return (obj is IntPtr) && Value == ((Document)obj).Value;
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        /// <returns>A 32-bit signed integer hash code.</returns>
        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }

        /// <summary>
        /// Determines whether two specified instances of <see cref="Document" /> are equal.
        /// </summary>
        /// <param name="a">The first document to compare.</param>
        /// <param name="b">The second document to compare.</param>
        /// <returns>true if <paramref name="a" /> equals <paramref name="b" />; otherwise, false.</returns>
        public static bool operator ==(Document a, Document b)
        {
            return a.Value == b.Value;
        }

        /// <summary>
        /// Determines whether two specified instances of <see cref="Document" /> are not equal.
        /// </summary>
        /// <param name="a">The first document to compare.</param>
        /// <param name="b">The second document to compare.</param>
        /// <returns>true if <paramref name="a" /> does not equal <paramref name="b" />; otherwise, false.</returns>
        public static bool operator !=(Document a, Document b)
        {
            return a.Value != b.Value;
        }
    }
}


text:
#include "navmesh/CCNavMesh.h"
#if CC_USE_NAVMESH

#include "platform/CCFileUtils.h"
#include "renderer/CCRenderer.h"
#include "recast/Detour/DetourCommon.h"
#include "recast/DebugUtils/DetourDebugDraw.h"
#include <sstream>

NS_CC_BEGIN

#pragma pack(push,1)
struct TileCacheSetHeader
{
    int32_t magic;
    int32_t version;
    int32_t numTiles;
    dtNavMeshParams meshParams;
    dtTileCacheParams cacheParams;
};

struct TileCacheTileHeader
{
    dtCompressedTileRef tileRef;
    int32_t dataSize;
};
#pragma pack(pop)

static unsigned char* parseRow(unsigned char* buf, unsigned char* bufEnd, char* row, int len)
{
    bool start = true;
    bool done = false;
    int n = 0;
    while (!done && buf < bufEnd)
    {
        char c = *buf;
        buf++;
        // multirow
        switch (c)
        {
        case '\n':
            if (start) break;
            done = true;
            break;
        case '\r':
            break;
        case '\t':
        case ' ':
            if (start) break;
        default:
            start = false;
            row[n++] = c;
            if (n >= len - 1)
                done = true;
            break;
        }
    }
    row[n] = '\0';
    return buf;
}

static const int TILECACHESET_MAGIC = 'T' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'TSET';
static const int TILECACHESET_VERSION = 1;
static const int MAX_AGENTS = 128;

NavMesh* NavMesh::create(const std::string &navFilePath, const std::string &geomFilePath)
{
    auto ref = new (std::nothrow) NavMesh();
    if (ref && ref->initWithFilePath(navFilePath, geomFilePath))
    {
        ref->autorelease();
        return ref;
    }
    CC_SAFE_DELETE(ref);
    return nullptr;
}

NavMesh::NavMesh()
    : _navMesh(nullptr)
    , _navMeshQuery(nullptr)
    , _crowed(nullptr)
    , _tileCache(nullptr)
    , _allocator(nullptr)
    , _compressor(nullptr)
    , _meshProcess(nullptr)
    , _geomData(nullptr)
    , _isDebugDrawEnabled(false)
{

}

NavMesh::~NavMesh()
{
    dtFreeTileCache(_tileCache);
    dtFreeCrowd(_crowed);
    dtFreeNavMesh(_navMesh);
    dtFreeNavMeshQuery(_navMeshQuery);
    CC_SAFE_DELETE(_allocator);
    CC_SAFE_DELETE(_compressor);
    CC_SAFE_DELETE(_meshProcess);
    CC_SAFE_DELETE(_geomData);

    for (auto iter : _agentList){
        CC_SAFE_RELEASE(iter);
    }
    _agentList.clear();

    for (auto iter : _obstacleList){
        CC_SAFE_RELEASE(iter);
    }
    _obstacleList.clear();
}

bool NavMesh::initWithFilePath(const std::string &navFilePath, const std::string &geomFilePath)
{
    _navFilePath = navFilePath;
    _geomFilePath = geomFilePath;
    if (!read()) return false;
    return true;
}

bool NavMesh::read()
{
    if (!loadGeomFile()) return false;
    if (!loadNavMeshFile()) return false;

    return true;
}

bool NavMesh::loadNavMeshFile()
{
    auto data = FileUtils::getInstance()->getDataFromFile(_navFilePath);
    if (data.isNull()) return false;

    // Read header.
    unsigned int offset = 0;
    TileCacheSetHeader header = *((TileCacheSetHeader*)(data.getBytes() + offset));
    offset += sizeof(TileCacheSetHeader);
    if (header.magic != TILECACHESET_MAGIC)
    {
        return false;
    }
    if (header.version != TILECACHESET_VERSION)
    {
        return false;
    }

    _navMesh = dtAllocNavMesh();
    if (!_navMesh)
    {
        return false;
    }
    dtStatus status = _navMesh->init(&header.meshParams);
    if (dtStatusFailed(status))
    {
        return false;
    }

    _tileCache = dtAllocTileCache();
    if (!_tileCache)
    {
        return false;
    }

    _allocator = new (std::nothrow) LinearAllocator(32000);
    _compressor = new (std::nothrow) FastLZCompressor;
    _meshProcess = new (std::nothrow) MeshProcess(_geomData);
    status = _tileCache->init(&header.cacheParams, _allocator, _compressor, _meshProcess);

    if (dtStatusFailed(status))
    {
        return false;
    }

    // Read tiles.
    for (int i = 0; i < header.numTiles; ++i)
    {
        TileCacheTileHeader tileHeader = *((TileCacheTileHeader*)(data.getBytes() + offset));
        offset += sizeof(TileCacheTileHeader);
        if (!tileHeader.tileRef || !tileHeader.dataSize)
            break;

        unsigned char* tileData = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
        if (!tileData) break;
        memcpy(tileData, (data.getBytes() + offset), tileHeader.dataSize);
        offset += tileHeader.dataSize;

        dtCompressedTileRef tile = 0;
        _tileCache->addTile(tileData, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile);

        if (tile)
            _tileCache->buildNavMeshTile(tile, _navMesh);
    }

    //create crowed
    _crowed = dtAllocCrowd();
    _crowed->init(MAX_AGENTS, header.cacheParams.walkableRadius, _navMesh);

    //create NavMeshQuery
    _navMeshQuery = dtAllocNavMeshQuery();
    _navMeshQuery->init(_navMesh, 2048);

    _agentList.assign(MAX_AGENTS, nullptr);
    _obstacleList.assign(header.cacheParams.maxObstacles, nullptr);
    //duDebugDrawNavMesh(&_debugDraw, *_navMesh, DU_DRAWNAVMESH_OFFMESHCONS);
    return true;
}

bool NavMesh::loadGeomFile()
{
    unsigned char* buf = nullptr;
    auto data = FileUtils::getInstance()->getDataFromFile(_geomFilePath);
    if (data.isNull()) return false;
    buf = data.getBytes();
    _geomData = new (std::nothrow) GeomData;
    _geomData->offMeshConCount = 0;

    unsigned char* src = buf;
    unsigned char* srcEnd = buf + data.getSize();
    char row[512];
    while (src < srcEnd)
    {
        // Parse one row
        row[0] = '\0';
        src = parseRow(src, srcEnd, row, sizeof(row) / sizeof(char));
        if (row[0] == 'c')
        {
            // Off-mesh connection
            if (_geomData->offMeshConCount < GeomData::MAX_OFFMESH_CONNECTIONS)
            {
                float* v = &_geomData->offMeshConVerts[_geomData->offMeshConCount * 3 * 2];
                int bidir, area = 0, flags = 0;
                float rad;
                sscanf(row + 1, "%f %f %f  %f %f %f %f %d %d %d",
                    &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
                _geomData->offMeshConRads[_geomData->offMeshConCount] = rad;
                _geomData->offMeshConDirs[_geomData->offMeshConCount] = (unsigned char)bidir;
                _geomData->offMeshConAreas[_geomData->offMeshConCount] = (unsigned char)area;
                _geomData->offMeshConFlags[_geomData->offMeshConCount] = (unsigned short)flags;
                _geomData->offMeshConCount++;
            }
        }
    }

    return true;
}

void NavMesh::dtDraw()
{
    drawObstacles();
    _debugDraw.depthMask(false);
    duDebugDrawNavMeshWithClosedList(&_debugDraw, *_navMesh, *_navMeshQuery, DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST/* | DU_DRAWNAVMESH_COLOR_TILES*/);
    drawAgents();
    drawOffMeshConnections();
    _debugDraw.depthMask(true);
}

void cocos2d::NavMesh::drawOffMeshConnections()
{
    unsigned int conColor = duRGBA(192, 0, 128, 192);
    unsigned int baseColor = duRGBA(0, 0, 0, 64);
    _debugDraw.begin(DU_DRAW_LINES, 2.0f);
    for (int i = 0; i < _geomData->offMeshConCount; ++i)
    {
        float* v = &_geomData->offMeshConVerts[i * 3 * 2];

        _debugDraw.vertex(v[0], v[1], v[2], baseColor);
        _debugDraw.vertex(v[0], v[1] + 0.2f, v[2], baseColor);

        _debugDraw.vertex(v[3], v[4], v[5], baseColor);
        _debugDraw.vertex(v[3], v[4] + 0.2f, v[5], baseColor);

        duAppendCircle(&_debugDraw, v[0], v[1] + 0.1f, v[2], _geomData->offMeshConRads[i], baseColor);
        duAppendCircle(&_debugDraw, v[3], v[4] + 0.1f, v[5], _geomData->offMeshConRads[i], baseColor);

        if (/*hilight*/true)
        {
            duAppendArc(&_debugDraw, v[0], v[1], v[2], v[3], v[4], v[5], 0.25f,
                (_geomData->offMeshConDirs[i] & 1) ? 0.6f : 0.0f, 0.6f, conColor);
        }
    }
    _debugDraw.end();
}

void cocos2d::NavMesh::drawObstacles()
{
    // Draw obstacles
    for (auto iter : _obstacleList)
    {
        if (iter){
            const dtTileCacheObstacle* ob = _tileCache->getObstacleByRef(iter->_obstacleID);
            if (ob->state == DT_OBSTACLE_EMPTY) continue;
            float bmin[3], bmax[3];
            _tileCache->getObstacleBounds(ob, bmin, bmax);

            unsigned int col = 0;
            if (ob->state == DT_OBSTACLE_PROCESSING)
                col = duRGBA(255, 255, 0, 128);
            else if (ob->state == DT_OBSTACLE_PROCESSED)
                col = duRGBA(255, 192, 0, 192);
            else if (ob->state == DT_OBSTACLE_REMOVING)
                col = duRGBA(220, 0, 0, 128);

            duDebugDrawCylinder(&_debugDraw, bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2], col);
            duDebugDrawCylinderWire(&_debugDraw, bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2], duDarkenCol(col), 2);
        }
    }
}

void cocos2d::NavMesh::drawAgents()
{
    for (auto iter : _agentList)
    {
        if (iter){
            auto agent = _crowed->getAgent(iter->_agentID);
            float r = iter->getRadius();
            float h = iter->getHeight();

            unsigned int col = duRGBA(0, 0, 0, 32);
            duDebugDrawCircle(&_debugDraw, agent->npos[0], agent->npos[1], agent->npos[2], r, col, 2.0f);

            col = duRGBA(220, 220, 220, 128);
            if (agent->targetState == DT_CROWDAGENT_TARGET_REQUESTING || agent->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE)
                col = duLerpCol(col, duRGBA(128, 0, 255, 128), 32);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_PATH)
                col = duLerpCol(col, duRGBA(128, 0, 255, 128), 128);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_FAILED)
                col = duRGBA(255, 32, 16, 128);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
                col = duLerpCol(col, duRGBA(64, 255, 0, 128), 128);

            duDebugDrawCylinder(&_debugDraw, agent->npos[0] - r, agent->npos[1] + r*0.1f, agent->npos[2] - r,
                agent->npos[0] + r, agent->npos[1] + h, agent->npos[2] + r, col);

        }
    }

    // Velocity stuff.
    for (auto iter : _agentList)
    {
        if (iter){
            auto agent = _crowed->getAgent(iter->_agentID);

            const float radius = agent->params.radius;
            const float height = agent->params.height;
            const float* pos = agent->npos;
            const float* vel = agent->vel;
//            const float* dvel = agent->dvel;

            unsigned int col = duRGBA(220, 220, 220, 192);
            if (agent->targetState == DT_CROWDAGENT_TARGET_REQUESTING || agent->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE)
                col = duLerpCol(col, duRGBA(128, 0, 255, 192), 32);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_PATH)
                col = duLerpCol(col, duRGBA(128, 0, 255, 192), 128);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_FAILED)
                col = duRGBA(255, 32, 16, 192);
            else if (agent->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
                col = duLerpCol(col, duRGBA(64, 255, 0, 192), 128);

            duDebugDrawCircle(&_debugDraw, pos[0], pos[1] + height, pos[2], radius, col, 2.0f);

            //duDebugDrawArrow(&_debugDraw, pos[0], pos[1] + height, pos[2],
            //    pos[0] + dvel[0], pos[1] + height + dvel[1], pos[2] + dvel[2],
            //    0.0f, 0.4f, duRGBA(0, 192, 255, 192), 2.0f);

            duDebugDrawArrow(&_debugDraw, pos[0], pos[1] + height, pos[2],
                pos[0] + vel[0], pos[1] + height + vel[1], pos[2] + vel[2],
                0.0f, 0.4f, duRGBA(0, 0, 0, 160), 2.0f);
        }
    }
}

void NavMesh::removeNavMeshObstacle(NavMeshObstacle *obstacle)
{
    auto iter = std::find(_obstacleList.begin(), _obstacleList.end(), obstacle);
    if (iter != _obstacleList.end()){
        obstacle->removeFrom(_tileCache);
        obstacle->release();
        _obstacleList[iter - _obstacleList.begin()] = nullptr;
    }
}

void NavMesh::addNavMeshObstacle(NavMeshObstacle *obstacle)
{
    auto iter = std::find(_obstacleList.begin(), _obstacleList.end(), nullptr);
    if (iter != _obstacleList.end()){
        obstacle->addTo(_tileCache);
        obstacle->retain();
        _obstacleList[iter - _obstacleList.begin()] = obstacle;
    }
}

void NavMesh::removeNavMeshAgent(NavMeshAgent *agent)
{
    auto iter = std::find(_agentList.begin(), _agentList.end(), agent);
    if (iter != _agentList.end()){
        agent->removeFrom(_crowed);
        agent->setNavMeshQuery(nullptr);
        agent->release();
        _agentList[iter - _agentList.begin()] = nullptr;
    }
}

void NavMesh::addNavMeshAgent(NavMeshAgent *agent)
{
    auto iter = std::find(_agentList.begin(), _agentList.end(), nullptr);
    if (iter != _agentList.end()){
        agent->addTo(_crowed);
        agent->setNavMeshQuery(_navMeshQuery);
        agent->retain();
        _agentList[iter - _agentList.begin()] = agent;
    }
}

bool NavMesh::isDebugDrawEnabled() const
{
    return _isDebugDrawEnabled;
}

void NavMesh::setDebugDrawEnable(bool enable)
{
    _isDebugDrawEnabled = enable;
}

void NavMesh::debugDraw(Renderer* renderer)
{
    if (_isDebugDrawEnabled){
        _debugDraw.clear();
        dtDraw();
        _debugDraw.draw(renderer);
    }
}

void NavMesh::update(float dt)
{
    for (auto iter : _agentList){
        if (iter)
            iter->preUpdate(dt);
    }

    for (auto iter : _obstacleList){
        if (iter)
            iter->preUpdate(dt);
    }

    if (_crowed)
        _crowed->update(dt, nullptr);

    if (_tileCache)
        _tileCache->update(dt, _navMesh);

    for (auto iter : _agentList){
        if (iter)
            iter->postUpdate(dt);
    }

    for (auto iter : _obstacleList){
        if (iter)
            iter->postUpdate(dt);
    }
}

void cocos2d::NavMesh::findPath(const Vec3 &start, const Vec3 &end, std::vector<Vec3> &pathPoints)
{
    static const int MAX_POLYS = 256;
    static const int MAX_SMOOTH = 2048;
    float ext[3];
    ext[0] = 2; ext[1] = 4; ext[2] = 2;
    dtQueryFilter filter;
    dtPolyRef startRef, endRef;
    dtPolyRef polys[MAX_POLYS];
    int npolys = 0;
    _navMeshQuery->findNearestPoly(&start.x, ext, &filter, &startRef, 0);
    _navMeshQuery->findNearestPoly(&end.x, ext, &filter, &endRef, 0);
    _navMeshQuery->findPath(startRef, endRef, &start.x, &end.x, &filter, polys, &npolys, MAX_POLYS);

    if (npolys)
    {
        //// Iterate over the path to find smooth path on the detail mesh surface.
        //dtPolyRef polys[MAX_POLYS];
        //memcpy(polys, polys, sizeof(dtPolyRef)*npolys);
        //int npolys = npolys;

        float iterPos[3], targetPos[3];
        _navMeshQuery->closestPointOnPoly(startRef, &start.x, iterPos, 0);
        _navMeshQuery->closestPointOnPoly(polys[npolys - 1], &end.x, targetPos, 0);

        static const float STEP_SIZE = 0.5f;
        static const float SLOP = 0.01f;

        int nsmoothPath = 0;
        //dtVcopy(&m_smoothPath[m_nsmoothPath * 3], iterPos);
        //m_nsmoothPath++;

        pathPoints.push_back(Vec3(iterPos[0], iterPos[1], iterPos[2]));
        nsmoothPath++;

        // Move towards target a small advancement at a time until target reached or
        // when ran out of memory to store the path.
        while (npolys && nsmoothPath < MAX_SMOOTH)
        {
            // Find location to steer towards.
            float steerPos[3];
            unsigned char steerPosFlag;
            dtPolyRef steerPosRef;

            if (!getSteerTarget(_navMeshQuery, iterPos, targetPos, SLOP,
                polys, npolys, steerPos, steerPosFlag, steerPosRef))
                break;

            bool endOfPath = (steerPosFlag & DT_STRAIGHTPATH_END) ? true : false;
            bool offMeshConnection = (steerPosFlag & DT_STRAIGHTPATH_OFFMESH_CONNECTION) ? true : false;

            // Find movement delta.
            float delta[3], len;
            dtVsub(delta, steerPos, iterPos);
            len = dtMathSqrtf(dtVdot(delta, delta));
            // If the steer target is end of path or off-mesh link, do not move past the location.
            if ((endOfPath || offMeshConnection) && len < STEP_SIZE)
                len = 1;
            else
                len = STEP_SIZE / len;
            float moveTgt[3];
            dtVmad(moveTgt, iterPos, delta, len);

            // Move
            float result[3];
            dtPolyRef visited[16];
            int nvisited = 0;
            _navMeshQuery->moveAlongSurface(polys[0], iterPos, moveTgt, &filter,
                result, visited, &nvisited, 16);

            npolys = fixupCorridor(polys, npolys, MAX_POLYS, visited, nvisited);
            npolys = fixupShortcuts(polys, npolys, _navMeshQuery);

            float h = 0;
            _navMeshQuery->getPolyHeight(polys[0], result, &h);
            result[1] = h;
            dtVcopy(iterPos, result);

            // Handle end of path and off-mesh links when close enough.
            if (endOfPath && inRange(iterPos, steerPos, SLOP, 1.0f))
            {
                // Reached end of path.
                dtVcopy(iterPos, targetPos);
                if (nsmoothPath < MAX_SMOOTH)
                {
                    //dtVcopy(&m_smoothPath[m_nsmoothPath * 3], iterPos);
                    //m_nsmoothPath++;
                    pathPoints.push_back(Vec3(iterPos[0], iterPos[1], iterPos[2]));
                    nsmoothPath++;
                }
                break;
            }
            else if (offMeshConnection && inRange(iterPos, steerPos, SLOP, 1.0f))
            {
                // Reached off-mesh connection.
                float startPos[3], endPos[3];

                // Advance the path up to and over the off-mesh connection.
                dtPolyRef prevRef = 0, polyRef = polys[0];
                int npos = 0;
                while (npos < npolys && polyRef != steerPosRef)
                {
                    prevRef = polyRef;
                    polyRef = polys[npos];
                    npos++;
                }
                for (int i = npos; i < npolys; ++i)
                    polys[i - npos] = polys[i];
                npolys -= npos;

                // Handle the connection.
                dtStatus status = _navMesh->getOffMeshConnectionPolyEndPoints(prevRef, polyRef, startPos, endPos);
                if (dtStatusSucceed(status))
                {
                    if (nsmoothPath < MAX_SMOOTH)
                    {
                        //dtVcopy(&m_smoothPath[m_nsmoothPath * 3], startPos);
                        //m_nsmoothPath++;
                        pathPoints.push_back(Vec3(startPos[0], startPos[1], startPos[2]));
                        nsmoothPath++;
                        // Hack to make the dotted path not visible during off-mesh connection.
                        if (nsmoothPath & 1)
                        {
                            //dtVcopy(&m_smoothPath[m_nsmoothPath * 3], startPos);
                            //m_nsmoothPath++;
                            pathPoints.push_back(Vec3(startPos[0], startPos[1], startPos[2]));
                            nsmoothPath++;
                        }
                    }
                    // Move position at the other side of the off-mesh link.
                    dtVcopy(iterPos, endPos);
                    float eh = 0.0f;
                    _navMeshQuery->getPolyHeight(polys[0], iterPos, &eh);
                    iterPos[1] = eh;
                }
            }

            // Store results.
            if (nsmoothPath < MAX_SMOOTH)
            {
                //dtVcopy(&m_smoothPath[m_nsmoothPath * 3], iterPos);
                //m_nsmoothPath++;

                pathPoints.push_back(Vec3(iterPos[0], iterPos[1], iterPos[2]));
                nsmoothPath++;
            }
        }
    }
}

NS_CC_END

#endif //CC_USE_NAVMESH


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Avenida</tipo><logradouro>Gedalha</logradouro><bairro>Fundão</bairro><cidade>Recife</cidade><uf>PE</uf><cep>52130120</cep></feed>


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/cert/internal/trust_store_chrome.h"
#include "base/containers/span.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "net/cert/internal/cert_errors.h"
#include "net/cert/internal/parsed_certificate.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "third_party/boringssl/src/include/openssl/pool.h"

namespace net {

namespace {

#include "net/data/ssl/chrome_root_store/chrome-root-store-inc.cc"
}  // namespace

TrustStoreChrome::TrustStoreChrome()
    : TrustStoreChrome(kChromeRootCertList, /*certs_are_static=*/true) {}

TrustStoreChrome::TrustStoreChrome(base::span<const ChromeRootCertInfo> certs,
                                   bool certs_are_static) {
  // TODO(hchao, sleevi): Explore keeping a CRYPTO_BUFFER of just the DER
  // certificate and subject name. This would hopefully save memory compared
  // to keeping the full parsed representation in memory, especially when
  // there are multiple instances of TrustStoreChrome.
  for (const auto& cert_info : certs) {
    bssl::UniquePtr<CRYPTO_BUFFER> cert;
    if (certs_are_static) {
      // TODO(mattm,hchao): When the component updater is implemented, ensure
      // the static data crypto_buffers for the compiled-in roots are kept
      // alive, so that roots from the component updater data will de-dupe
      // against them.
      cert = x509_util::CreateCryptoBufferFromStaticDataUnsafe(
          cert_info.root_cert_der);
    } else {
      cert = x509_util::CreateCryptoBuffer(cert_info.root_cert_der);
    }
    CertErrors errors;
    auto parsed = ParsedCertificate::Create(
        std::move(cert), x509_util::DefaultParseCertificateOptions(), &errors);
    DCHECK(parsed);
    // TODO(hchao): Figure out how to fail gracefully when the Chrome Root Store
    // gets a bad component update.
    trust_store_.AddTrustAnchor(parsed);
  }
}

TrustStoreChrome::~TrustStoreChrome() = default;

void TrustStoreChrome::SyncGetIssuersOf(const ParsedCertificate* cert,
                                        ParsedCertificateList* issuers) {
  trust_store_.SyncGetIssuersOf(cert, issuers);
}

CertificateTrust TrustStoreChrome::GetTrust(
    const ParsedCertificate* cert,
    base::SupportsUserData* debug_data) const {
  return trust_store_.GetTrust(cert, debug_data);
}

bool TrustStoreChrome::Contains(const ParsedCertificate* cert) const {
  return trust_store_.Contains(cert);
}

// static
std::unique_ptr<TrustStoreChrome> TrustStoreChrome::CreateTrustStoreForTesting(
    base::span<const ChromeRootCertInfo> certs) {
  // Note: wrap_unique is used because the constructor is private.
  return base::WrapUnique(
      new TrustStoreChrome(certs, /*certs_are_static=*/false));
}

}  // namespace net


text:
#include<string>
#include<vector>
#include "CardDeck.h"
#include "Card.h"
#include "Players.h"
using namespace std;

namespace CardGames
{

/**

This class will handle the players hands and commands from the players.
This will contain a vector of cards for each player to play.

@author Wesley Howell
*/

//Constructors
Players::Players(void)
    : m_chips()
{
	//Create a new hand for the player
	hand = new vector<Card::Cards>();
}
//Copy Constructor
Players::Players(const Players& source)
{

	(*hand).clear();
	hand = source.hand;
    m_chips = source.m_chips;

}

//Destructor
Players::~Players(void)
{

	if( hand )
    {
        hand->clear();
        delete hand;
    }
}

//Overload Operators
Players& Players::operator=(const Players& source)
{
	if(&source == this)
		return *this;

    if( hand )
    {
        delete hand;
    }
    hand = source.hand;

    m_chips = source.m_chips;

	return *this;
}

//Accessors
vector<Card::Cards>& Players::getHand(void)
{
	return *hand;
}

Chips& Players::getChips()
{
    return m_chips;
}

//Mutator
void Players::addToHand(Card::Cards card)
{
	(*hand).push_back(card);
}

void Players::removeFromHand(int i)
{
	(*hand).erase((*hand).begin() + (i-1));
}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>model</title>
<meta name="date" content="2006-07-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

model

Classes

Card

PlayingCard


text:
package net.xaethos.sandbox.fragments;

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import rx.Observable;
import rx.Scheduler;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;

@RunWith(DataProviderRunner.class)
public class FormControllerTest {

    PrettyFormFragment.FormController formController;
    Scheduler testScheduler;

    PublishSubject<CharSequence> emailTextInput;
    PublishSubject<CharSequence> thingamajigTextInput;
    PublishSubject<CharSequence> fiddlesticksTextInput;

    @Before
    public void setUp() throws Exception {
        emailTextInput = PublishSubject.create();
        thingamajigTextInput = PublishSubject.create();
        fiddlesticksTextInput = PublishSubject.create();

        formController = new PrettyFormFragment.FormController(emailTextInput,
                thingamajigTextInput,
                fiddlesticksTextInput);
        testScheduler = Schedulers.immediate();
    }

    @Test
    @DataProvider(value = {",required",
            "a,invalid email",
            "foo@example,invalid email",
            "foo@example.com,null",
            "foo+alt@example.com,null"
    })
    public void emailInputError(String input, String error) throws Exception {
        Action1<CharSequence> onError = subscribeMockAction(formController.emailErrors());
        emailTextInput.onNext(input);
        verify(onError, only()).call(error);
    }

    @Test
    @DataProvider(value = {",null", "some text,null", "12345678901,max 10 characters"})
    public void thingamajigInputError(String input, String error) throws Exception {
        Action1<CharSequence> onError = subscribeMockAction(formController.thingamajigErrors());
        thingamajigTextInput.onNext(input);
        verify(onError, only()).call(error);
    }

    @Test
    @DataProvider(value = {",null",
            "13,null",
            "foo,invalid number",
            "5.1,invalid number",
            "-3,must be positive"
    })
    public void fiddlesticksInputError(String input, String error) throws Exception {
        Action1<CharSequence> onError = subscribeMockAction(formController.fiddlesticksErrors());
        fiddlesticksTextInput.onNext(input);
        verify(onError, only()).call(error);
    }

    @Test
    @DataProvider(value = {"a@b.c,foo,1,true",
            "a@b.c,,,true",
            ",foo,1,false",
            "a@b,foo,1,false",
            "a@b.c,foo bar baz,1,false",
            "a@b.c,foo,1.2,false",
            "a@b.c,foo,-1,false",
    })
    public void submitEnabledWhenAllValid(
            String email, String thingamajig, String fiddlesticks, boolean submitEnabled)
            throws Exception {
        Action1<Boolean> setEnabled = subscribeMockAction(formController.submitEnabledControl());
        emailTextInput.onNext(email);
        thingamajigTextInput.onNext(thingamajig);
        fiddlesticksTextInput.onNext(fiddlesticks);
        verify(setEnabled).call(submitEnabled);
    }

    @SuppressWarnings("unchecked")
    private <T> Action1<T> subscribeMockAction(Observable<T> observable) {
        Action1<T> mockAction = mock(Action1.class);
        observable.subscribeOn(testScheduler).observeOn(testScheduler).subscribe(mockAction);
        return mockAction;
    }

}


text:
package transform // import "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/internal/transform"

import (
	"errors"
	"fmt"
	"strings"

	mpb "go.opentelemetry.io/proto/otlp/metrics/v1"
)

var (
	errUnknownAggregation = errors.New("unknown aggregation")
	errUnknownTemporality = errors.New("unknown temporality")
)

type errMetric struct {
	m   *mpb.Metric
	err error
}

func (e errMetric) Unwrap() error {
	return e.err
}

func (e errMetric) Error() string {
	format := "invalid metric (name: %q, description: %q, unit: %q): %s"
	return fmt.Sprintf(format, e.m.Name, e.m.Description, e.m.Unit, e.err)
}

func (e errMetric) Is(target error) bool {
	return errors.Is(e.err, target)
}

// multiErr is used by the data-type transform functions to wrap multiple
// errors into a single return value. The error message will show all errors
// as a list and scope them by the datatype name that is returning them.
type multiErr struct {
	datatype string
	errs     []error
}

// errOrNil returns nil if e contains no errors, otherwise it returns e.
func (e *multiErr) errOrNil() error {
	if len(e.errs) == 0 {
		return nil
	}
	return e
}

// append adds err to e. If err is a multiErr, its errs are flattened into e.
func (e *multiErr) append(err error) {
	// Do not use errors.As here, this should only be flattened one layer. If
	// there is a *multiErr several steps down the chain, all the errors above
	// it will be discarded if errors.As is used instead.
	switch other := err.(type) {
	case *multiErr:
		// Flatten err errors into e.
		e.errs = append(e.errs, other.errs...)
	default:
		e.errs = append(e.errs, err)
	}
}

func (e *multiErr) Error() string {
	es := make([]string, len(e.errs))
	for i, err := range e.errs {
		es[i] = fmt.Sprintf("* %s", err)
	}

	format := "%d errors occurred transforming %s:\n\t%s"
	return fmt.Sprintf(format, len(es), e.datatype, strings.Join(es, "\n\t"))
}

func (e *multiErr) Unwrap() error {
	switch len(e.errs) {
	case 0:
		return nil
	case 1:
		return e.errs[0]
	}

	// Return a multiErr without the leading error.
	cp := &multiErr{
		datatype: e.datatype,
		errs:     make([]error, len(e.errs)-1),
	}
	copy(cp.errs, e.errs[1:])
	return cp
}

func (e *multiErr) Is(target error) bool {
	if len(e.errs) == 0 {
		return false
	}
	// Check if the first error is target.
	return errors.Is(e.errs[0], target)
}