text:
@import './sample-styles/vars.css';

/* Functional classes */
@import './sample-styles/colors.css';
@import './sample-styles/lists.css';
@import './sample-styles/size.css';
@import './sample-styles/text.css';
@import './sample-styles/forms.css';
@import './sample-styles/tooltip-colors.css';

/* Example styling */
html {
  box-sizing: border-box;
  -ms-overflow-style: scrollbar;
  -webkit-tap-highlight-color: transparent; }

*, *:before, *:after {
  box-sizing: inherit; }

html {
  font-size: 16px; }

body {
  background-color: #fff;
  color: #333;
  font-size: 1rem;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  line-height: 1.5; }

h1 {
  font-size: 2.5rem; }

h2 {
  font-size: 2rem; }

h3 {
  font-size: 1.75rem; }

h4 {
  font-size: 1.5rem; }

h5 {
  font-size: 1.25rem; }

h6 {
  font-size: 1rem; }

a {
  color: var(--color-brand-primary-500);
  text-decoration: none; }

  a:active, a:focus, a:hover {
    text-decoration: underline; }

code, kbd, pre, samp {
  font-family: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }

hr {
  border-bottom: 1px solid #f0f1f1;
  border-left: 0;
  border-right: 0;
  border-top: 0;
  margin: 1em 0; }

  .round {
    color: #fff;
    background: #555;
    padding: 1px 6px;
    border-radius: 50%;
    font-size: .7rem;
    cursor: pointer;
}


text:
* 2016-01-10 (**Version 3.0.5**)
 * Search now replaces characters that would be invalid for file names so that such records can be saved (fixes #18)
 * Fix search issue where duplicate record names for a table where not being saved. Can now save the sys_id in the file name via new config option: `ensureUniqueNames` (fixes #17)
 * Readme updates

* 2016-01-09 (**Version 3.0.4**)
 * Allow saving the sys_id and other meta data about a record (fixes #5). All communications with a record will now use the sys_id except the first which uses the defined property in the config folders list
 * Tables that are extended no longer save files from their descendants (fixes #20)

* 2015-12-19 (**Version 3.0.3**)
 * Fix search issue where sync data records were not being saved on slow machines (File I/O racing is bad)
 * Fix missing callback crash (fixes #14)

* 2015-11-23 (**Version 3.0.2**)
 * Support custom "ignoreFile" config option for file watcher (thanks to @dwightgunning)

* 2015-11-16 (**Version 3.0.1**)
 * Fix issue with search where 0 byte files (no proper record data) were causing issues

* 2015-11-06 (**Version 3.0** :mushroom:)
 * Fully enable search because I love being productive! (more details in readme)

* 2015-10-14 (**Version 2.4.10**)
 * Fix rare race condition with File I/O processes that sometimes caused changed files to be overwritten instead of uploaded

* 2015-10-14 (**Version 2.4.9**)
 * Fix osx-notifier issue where record names starting with symbols crashed the notification app on mac (fixes #9)
   * If your record is like "(Keyfile)" then the notifcation will show "_(Keyfile)".

* 2015-10-13 (**Version 2.4.8**)
 * Fix password encoding issue occuring when not specifying a config path (fixes #10)

* 2015-10-09 (**Version 2.4.7**)
 * Fix windows path issues and add upgrade warning
    * **UPGRADE NOTICE**: config files on all systems should now use *nix style paths. This means `"m:\\Desktop\\records"` is now invalid and should be replaced with `"m:/Dekstop/records"`

* 2015-09-01 (**Version 2.4.6**)
 * Added more default folder configs
 * Cleaned up readme
 * Prepared for search and search based auto-download support
 * Added support for flaky SSL setups (self-signed certificates etc.)
   * see `acceptBadSSL` usage in README

* 2015-08-23 (**Version 2.4.5**)
 * Fixed notification parameter bug causing issues for certain notifications

* 2015-08-23 (**Version 2.4.4**)
 * Added option to click notifications which then loads the record in the browser
 * Fixed minor issue where exporting current setup included default folder definitions (which are not needed)

* 2015-08-12 (**Version 2.4.3**)
 * Fixed bug for first run where the file watcher was not being started if preLoad or createAllFolders was true

* 2015-07-19 (**Version 2.4.2**)
 * Updated README and added video to demo FileSync in action

* 2015-05-20 (**Version 2.4.1**)
 * FIX issue where the `--config` option with a relative path did not work

* 2015-05-17 (**Version 2.4.0**)
 * Make README more logical and easier to follow (inc. TOC)
 * Support exporting the current list of downloaded records for quickstart and backup
   * Command Line Usage `/node-darwin src/app --export your-new-file.config.json`

* 2015-05-09 (**Version 2.3.0**)
 * Improved logging (timestamps and proper info/warn/error usage via winston)
 * Refactor, improve documentation and complete test support (testSyncConflict function)
 * Add support for [SASS CSS pre-comiler](http://sass-lang.com/) based development

* 2015-05-06 (**Version 2.2.4**)
 * FIX issue where config files existing on a custom path could not be updated for first-run scenarios.

* 2015-05-01 (**Version 2.2.3**)
 * FIX issue where incorrect file names created by user caused an endless record lookup loop

* 2015-04-13 (**Version 2.2.0**)
 * Isolate file and record based functions in own Class
 * Add tests for downloading and updating records
 * Simplify function calling and add more call backs (to support testing)

* 2015-04-13 (**Version 2.1.0**)
 * Rewrite pre-loading and re-syncing of files.
 * Clean up watching files system to be enabled and disabled at the right times and avoid file writes triggering watch changes

* 2015-04-06 (**Version 2.0.0 !**)
 * Add preLoad option to download files defined per root in "preLoad" object
 * Re-write documentation for app.config.json due to massive simplification and first-run setup
 * Fix redundant requests to instance for syncing
 * Add automatic folder creation option
   * Set ```createAllFolders: true``` in app.config.json

* 2015-04-04
 * Make folder definitions standard across all projects but allow users to override the defaults or extend them.
   * Set ```"ignoreDefaultFolders": true,``` if desired and specify own ```"folders": {...}``` for a custom setup

* 2015-04-03 (**major changes!** :mushroom:)
 * Allow specifying the location of the config file:
   * ```./node-darwin app/src --config=/computer/somefile.json```
 * Cleanup formatting
 * Add help option:
   * ```./node-darwin app/src --help```
 * Save sync data in JSON format so that we can make more use of it
   * WARNING: existing users will need to remove their current .sync dir and resync. When starting the app a warning will be output on the command line explaining what to do...
     * ```./node-darwin app/src --resync```
     * ```rm - Rf .sync``` (per site root dir)

* 2015-03-26
 * Upgraded node_modules (```npm update```) to latest version other than restify (which was throwing too many errors on current and future node versions node@0.10.37 and node@0.12.0 with restify@3.0.1. restify@2.6.0 is stable)
 * Add more connection error support

* 2015-03-23
 * Add basic test support to ensure setup is upgrade safe:
   * ```./node-darwin app/src --test```
 * Add jshint for cleaner scripting
 * Add module to parse command line args easily

* 2015-03-18
 * Fixed some trivial stuff regarding connection handling

* 2015-03-16
 * Added conflict management! Now it's impossible to overwrite server records that would result in data loss!

* 2015-03-14
 * Update readme and add road map. Encourage contribution!
 * Refactored code setup and allow config file to be outside of repo
 * Enable non 'https' instance connections
 * Added notification support (OS X)

* 2015-03-10
 * Added support for Eureka+ versions
 * Initial clone and file re-structure

redpajama_set_name: RedPajamaGithub


text:
<?php
use ANDS\VocabsRegistry\Model\Vocabulary;
?>
@extends('layout/vocab_layout')

@section('og-description')
  @if(is_object($vocab) && (!empty($vocab->getDescription())))
    <?php
    $clean_description = htmlspecialchars(substr(str_replace(
    array('"','[[',']]'), '', $vocab->getDescription()), 0, 200));
    ?>
  @endif
  @if(isset($clean_description))
    <meta ng-non-bindable property="og:description"
          content="{{ $clean_description }}" />
  @else
    <meta ng-non-bindable property="og:description"
          content="Find, access, and re-use vocabularies for research" />
  @endif
@stop
@section('script')
  var vocab_resolving_services =
  {{json_encode(get_config_item('vocab_resolving_services'))}};
  var subject_vocab_proxy =
  {{json_encode(get_config_item('subject_vocab_proxy'))}};
@stop
@section('content')

              @if($vocab)
                {{ htmlspecialchars($vocab->getTitle()) }}
              @else
                Add a new Vocabulary
              @endif

    @if($vocab)
      <input type="hidden" type="text" value="{{ $vocab->getId() }}"
             id="vocab_id"/>
      <input type="hidden" type="text" value="{{ $vocab->getSlug() }}"
             id="vocab_slug"/>
    @endif

            Loading PoolParty Projects... Please wait...

PoolParty Integration

                PoolParty Search
                <input type="text" class="form-control"
                       placeholder="PoolParty ID"
                       ng-model="project"
                       uib-typeahead="project as project.title for project in projects | filter:projectSearch($viewValue) | limitTo:8"
                       typeahead-min-length="1">

Search for a PoolParty
                  Project to pre-fill form

Title

[[ project.title ]]

PoolParty ID

[[ project.id ]]

              Use this PoolParty Project

 0">

[[ msg ]]

      <form name="form.cms" novalidate>

                @if(null != $this->user->affiliations())

                    Owner

                    <select name="owner" id="owner" required
                            class="form-control caret-for-select"
                            placeholder="vocab Owner"
                            ng-disabled="commitVocabOwner"
                            ng-options="owner.id as (owner.name + ' ('+owner.id+')') for owner in user_orgs_names"
                            ng-model="vocab.owner" ng-if="user_orgs.length>1"></select>
                    <select name="owner" id="owner" required
                            class="form-control" placeholder="vocab Owner"
                            ng-if="user_orgs.length==1 && !vocab.owner"
                            ng-model="vocab.owner"
                            ng-disabled="commitVocabOwner"
                            ng-options="owner.id as (owner.name + ' ('+owner.id+')') for owner in user_orgs_names"
                            ng-init="vocab.owner=user_orgs[0]"> </select>
                    <select name="owner" id="owner" required
                            class="form-control" placeholder="vocab Owner"
                            ng-options="owner.id as (owner.name + ' ('+owner.id+')') for owner in user_orgs_names"
                            ng-if="user_orgs.length==1 && vocab.owner.length > 0"
                            ng-disabled="commitVocabOwner"
                            ng-model="vocab.owner"></select>

To give editing rights to others in
                      your organisation, please select the appropriate
                      organisational Owner.

                  Continue
                @endif

          Populating Vocabulary... Please Wait...

                  Vocabulary Title

                  <input type="text" required class="form-control"
                         ng-model="vocab.title" name="title"
                         placeholder="Vocabulary Title">

Vocabulary Title is required.

                  Vocabulary Acronym

                  <input type="text" class="form-control"
                         ng-model="vocab.acronym" name="acronym"
                         placeholder="Vocabulary Acronym">

                  Vocabulary Description

                  <textarea ui-tinymce="tinymceOptions"
                            class="form-control edit-html" ng-model="vocab.description"
                            placeholder="Vocabulary Description" rows="10"
                            required name="description"></textarea>

Vocabulary Description is required.

                  Vocabulary Licence

                  <select name="" id="" class="form-control caret-for-select"
                          placeholder="vocab Licence"
                          ng-options="lic for lic in licence"
                          ng-model="vocab.licence"><option value="">No selection</option></select>

                  Vocabulary Creation Date

                    <input type="text" id="creation_date" class="form-control"
                           required name="creation_date"
                           placeholder="Vocabulary Creation Date (supported formats: YYYY-MM-DD, YYYY-MM, YYYY)"
                           ng-model="vocab.creation_date"
                           uib-datepicker-popup="yyyy-MM-dd"
                           alt-input-formats="['yyyy-MM', 'yyyy']"
                           is-open="opened" on-open-focus="false"
                           ng-focus="opened = true">

                      <button type="button" class="btn btn-default"
                              ng-click="opened = !opened"></button>

Vocabulary Creation Date is required.
                    Supported formats: YYYY-MM-DD, YYYY-MM, YYYY.

                  Revision Cycle

                  <input type="text" class="form-control"
                         ng-model="vocab.revision_cycle"
                         placeholder="Revision Cycle">

                  Note

                  <textarea ui-tinymce="tinymceOptions"
                            class="form-control" ng-model="vocab.note"
                            placeholder="Notes" rows="10"></textarea>

Top Concepts

                  <input type="text" class="form-control" placeholder="New Top Concept" ng-model="vocab.top_concept[$index]">

                    <button class="btn btn-primary btn-primary-warning btn-non-rounded" type="button"
                            ng-click="list_remove('top_concept', $index)" title="Remove this top concept"></button>

                <button class="btn btn-primary" type="button" ng-click="addtolist('top_concept')"> Add Top Concept</button>

Languages

                  <language-selection ng-if="vocab.owner" ng-model="vocab.language[0]" tag="[[ vocab.language[0] ]]">
                  </language-selection>

 1">
                  <language-selection ng-if="vocab.owner" ng-change="changeValue($index)" ng-model="vocab.language[$index]" tag="[[ vocab.language[$index] ]]">
                  </language-selection>

                    <button class="btn btn-primary btn-primary-warning btn-non-rounded" type="button"
                            ng-click="list_remove('language', $index); setLanguageErrors(undefined)" title="Remove this language"></button>

[[ error ]]

                <button class="btn btn-primary" type="button" ng-click="addtolist('language'); setLanguageErrors(undefined)"> Add Language</button>

At least one language must be provided.

Subjects

Subject Source	 Subject Label

                  <tr ng-repeat="subject in vocab.subjects track by $index"
                      subject-directive
                      id="[['subject_'+$index]]"
                      index="$index"
                      subject_type="vocab.subjects[$index].subject_source"
                      subject_label="vocab.subjects[$index].subject_label"
                      subject_iri="vocab.subjects[$index].subject_iri"
                      subject_notation="vocab.subjects[$index].subject_notation"
                      on-close="list_remove('subjects', $index)"
                  >

                <button id="add_subject_button" class="btn btn-primary" type="button" ng-click="addtolist('subjects')"> Add Subject</button>

At least one subject drawn from the
                    "ANZSRC Field of Research" vocabulary must be provided.
                    Select a value from the Subject Source dropdown and select
                    a Subject Label.

PoolParty Project Info

PoolParty Project ID

[[ vocab.poolparty_id ]]

Versions

Title	Status

                      [[ version.title ]]
                      [[ version.status ]]

                 Add a version

Related

Title	 Type

                      [[ related.title ]]
                      [[ related.type ]]

                      [[ related.title ]]
                      internal

                  <button class="btn btn-primary" type="button"
                          ng-click="relatedmodal('add', 'publisher')"> Add a publisher</button>
                  <button type="button" class="btn btn-primary dropdown-toggle"
                          data-toggle="dropdown" aria-expanded="false"></button>

Related Internal Vocabulary

Related External Vocabulary

Related Party

Related Service

At least one publisher must be provided.

                Save
                  to draft

                Publish

                Deprecate

[[ error_message ]]

There are validation errors in the form.

 0">

[[ msg ]]

                  [[ error ]]

                Exit
                Exit Without Saving

                 Saving...

      </form>

@stop
@section('emacs_local_variables')

@stop


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . './libraries/REST_Controller.php';

use Illuminate\Support\Facades\DB;

class Certificado extends REST_Controller
{
    protected $_insert_id;

    protected $proprietario;

    function __construct()
    {
        parent::__construct();
        $this->load->helper('message_error');

        error_reporting(E_ERROR);

        date_default_timezone_set('America/Sao_Paulo');
        header('Content-Type: application/json');
    }

    /**
     * @return array
     */

    function emitidas_get()
    {

        try {

            $certificados = Certificados::with('proposta.cotacao','custos')->whereIn('status_id', [1,30])->get();
            $retorno = [];
            $assitencia = [];

            if (!$certificados->isEmpty()) {
                foreach ($certificados as $certificado) {

                    $dados = [
                        "tipo_arquivo" => 2,
                        "numero_certificado" => str_pad($certificado->id, 20, 0, STR_PAD_LEFT),
                        "ano" => $certificado->proposta->veiculo->veicano,
                        "combustivel" => $certificado->proposta->veiculo->combustivel->sigla,
                        "numero_capitalizacao" => NULL,
                        "numero_serie_sorteio" => NULL,
                        "chassi" => $certificado->proposta->veiculo->veicchassi,
                        "renavam" => $certificado->proposta->veiculo->veicrenavam,
                        "placa" => $certificado->proposta->veiculo->veicplaca,
                        "marca" => $certificado->proposta->veiculo->fipe->marca,
                        "modelo" => $certificado->proposta->veiculo->fipe->modelo,
                        "cod_fipe" => $certificado->proposta->veiculo->fipe->codefipe,
                        "cor" => $certificado->proposta->veiculo->veicor,
                        "valor" => $certificado->proposta->veiculo->fipe
                            ->anovalor()
                            ->where('ano', $certificado->proposta->veiculo->veicano)
                            ->where('idcombustivel', $certificado->proposta->veiculo->veictipocombus)
                            ->first()->valor,
                        "zero_km" => ($certificado->proposta->veiculo->veicautozero ? 'Y' : 'N'),
                        "dono_veiculo" => ($certificado->proposta->veiculo->propcpfcnpj != $certificado->proposta->veiculo->clicpfcnpj ? 'N' : 'Y'),
                        "nome" => $certificado->proposta->cotacao->segurado->clinomerazao,
                        "cpf_cnpj" => $certificado->proposta->cotacao->segurado->clicpfcnpj,
                        "cep" => $certificado->proposta->cotacao->segurado->clicep,
                        "endereco" => $certificado->proposta->cotacao->segurado->clinmend,
                        "numero" => $certificado->proposta->cotacao->segurado->clinumero,
                        "complemento" => ($certificado->proposta->cotacao->segurado->cliendcomplet) == null ? 'Nao informado' : $certificado->proposta->cotacao->segurado->cliendcomplet,
                        "bairro" => ($certificado->proposta->cotacao->segurado->bairro) == null ? 'Nao informado': $certificado->proposta->cotacao->segurado->bairro,
                        "estado" => $certificado->proposta->cotacao->segurado->clicduf,
                        "cidade" => $certificado->proposta->cotacao->segurado->clinmcidade,
                        "data_nascimento" => date('Y-m-d', strtotime($certificado->proposta->cotacao->segurado->clidtnasc)),
                        "estado_civil" => $certificado->proposta->cotacao->segurado->estadocivil->sigla,
                        "valor_mensal_seguro" => $certificado->custo_mensal->sum('custo_mensal'),

                        "categoria" => $certificado->proposta->veiculo->tipo->codigo,
                        "data_venda" => $certificado->dt_inicio_virgencia,
                    ];
                    foreach ($certificado->custos as $custo) {
                        $cobert = $custo->seguradora_produto()->where('idseguradora', 3)->first();
                        $dados['coberturas'][] = [
                            'CodigoCobertura' => $cobert->id_produto_seguradora,
                            'Premio' => $custo->custo_mensal,
                        ];
                        $assitencia[] = (int)$cobert->id_produto_seguradora;
                    }

                    $assitencias = [
                        "possui_assistencia" => (in_array(1004, $assitencia) ? 'S' : 'N'),
                        "assistencia_reparo_vidro" => (in_array(1000, $assitencia) ? 'S' : 'N'),
                        "assistencia_reparo_parachoque" => (in_array(1001, $assitencia) ? 'S' : 'N'),
                        "assistencia_reparo_pintura" => (in_array(1002, $assitencia) ? 'S' : 'N'),
                        "assistencia_residencial" => (in_array(1003, $assitencia) ? 'S' : 'N'),
                        "assistencia_pt_colisao" => (in_array(238, $assitencia) ? 'S' : 'N'),
                    ];

                    $retorno['retorno'][] = array_merge($dados, $assitencias);
                }

                $movimento = MovimentoCertificado::create([
                    'datas_enviadas' => json_encode($retorno),
                    'dt_envio' => date('Y-m-d H:i:s'),
                    'status_id' => 26,
                    'tipo_envio' => 'emitidos'
                ]);
                Certificados::where('status_id', 1)->update(['status_id' => 30]);

                $retorno = array_merge([
                    'status' => '000 - sucesso',
                    'cdretorno' => '000',
                ], $retorno);
                $retorno['id_lote'] = $movimento->id;

                $this->response($retorno);
            } else {
                $this->response([
                    'status' => '000 - sucesso',
                    'cdretorno' => '000',
                    'retorno' => 'Não há certificados emitidos tente novamente mais tarde!!!'
                ]);
            }

        } catch (Exception $e) {

            $this->response([
                'status' => '405 - erro',
                'cdretorno' => '405',
                'retorno' => 'Ocorreu um erro interno, tente novamente mais tarde se caso o erro pesistir contate o suporte do sistema'
            ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);

        }

    }

    function emitidasRetorno_post()
    {

        $datas = $this->post();

        $movimento = MovimentoCertificado::find($datas['id_lote']);

        if (!$movimento) {
            return $this->response([
                'status' => '404 - Error',
                'cdretorno' => '404',
                'retorno' => 'Número de lote invalido'], REST_Controller::HTTP_BAD_REQUEST);
        } else {

            $movimento->dt_retorno = date('Y-m-d H:i:s');
            $movimento->datas_recebidas = json_encode($datas);
            $movimento->status_id = 27;
            $movimento->save();

            $certificados_enviados = json_decode($movimento->datas_enviadas);

            $aceitos = [];
            $nao_aceitos = [];
            $nao_retorno = [];

            foreach ($datas['retorno'] as $key => $data_retorno) {
                if ($data_retorno['status'] == 1) {
                    $nao_aceitos[] = (int)$data_retorno['numero_certificado'];
                }
            }

            foreach ($certificados_enviados->retorno as $certificado) {

                if (in_array(str_pad((int)$certificado->numero_certificado, 20, 0, STR_PAD_LEFT), array_column($datas['retorno'], 'numero_certificado'))) {
                    $aceitos[] = (int)$certificado->numero_certificado;
                } else {
                    $nao_retorno[] = (int)$certificado->numero_certificado;
                }

            }

            Certificados::whereIn('id', $aceitos)->update(['status_id'=> 31]);
            Certificados::whereIn('id', $nao_aceitos)->update(['status_id'=> 32]);
            Certificados::whereIn('id', $nao_retorno)->update(['status_id'=> 33]);

            $this->response([
                'status' => '000 - sucesso',
                'cdretorno' => '000',
                'retorno' => (count($nao_retorno) >= 1 ? 'Operação realizada com sucesso! Porém alguns dos certificados enviados não teve retorno, checar o parâmentro retnornado "nao_reternou" ' : 'Operação realizada com sucesso'),
                'nao_retornou' => $nao_retorno]);
        }

    }

    public function cancelados_get()
    {

        try {

            $certificados = Certificados::with('apolice.cancelamento.motivo')->where('status_id', 40)->get();
            $retorno = [];

            if (!$certificados->isEmpty()) {
                foreach ($certificados as $certificado) {

                    $retorno['retorno'][] = [
                        "tipo_arquivo" => 4,
                        "numero_certificado" => str_pad($certificado->id, 20, 0, STR_PAD_LEFT),
                        "cpf_cnpj" => $certificado->proposta->cotacao->segurado->clicpfcnpj,
                        "data_cancelamento" => date('Y-m-d', strtotime($certificado->apolice->cancelamento->created_at)),
                        "tipo_cancelamento" => $certificado->apolice->cancelamento->motivo->tipo,
                        "motivo_cancelamento" => $certificado->apolice->cancelamento->motivo->cod_motivo,
                    ];
                }

                $movimento = MovimentoCertificado::create([
                    'datas_enviadas' => json_encode($retorno),
                    'dt_envio' => date('Y-m-d H:i:s'),
                    'status_id' => 26,
                    'tipo_envio' => 'cancelados'
                ]);

                Certificados::where('status_id', 29)->update(['status_id' => 30]);
                $retorno = array_merge([
                    'status' => '000 - sucesso',
                    'cdretorno' => '000',
                ], $retorno);
                $retorno['id_lote'] = $movimento->id;

                $this->response($retorno);
            } else {
                $this->response([
                    'status' => '000 - sucesso',
                    'cdretorno' => '000',
                    'retorno' => 'Não há certificados emitidos tente novamente mais tarde!!!'
                ]);
            }

        } catch (Exception $e) {

            $this->response([
                'status' => '405 - erro',
                'cdretorno' => '405',
                'retorno' => 'Ocorreu um erro interno, tente novamente mais tarde se caso o erro pesistir contate o suporte do sistema',
                'exception' => $e
            ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);

        }

    }

    public function canceladosRetorno_post()
    {

        $datas = $this->post();

        $movimento = MovimentoCertificado::find($datas['id_lote']);

        if (!$movimento) {
            return $this->response([
                'status' => '404 - Error',
                'cdretorno' => '404',
                'retorno' => 'Número de lote invalido'], REST_Controller::HTTP_BAD_REQUEST);
        } else {
            $movimento->dt_retorno = date('Y-m-d H:i:s');
            $movimento->datas_recebidas = json_encode($datas);
            $movimento->status_id = 27;
            $movimento->save();

            $certificados_enviados = json_decode($movimento->datas_enviadas);

            $aceitos = [];
            $nao_aceitos = [];
            $nao_retorno = [];

            foreach ($datas['retorno'] as $key => $data_retorno) {
                if ($data_retorno['status'] == 1) {
                    $nao_aceitos[] = (int)$data_retorno['numero_certificado'];
                }
            }

            foreach ($certificados_enviados->retorno as $certificado) {

                if (in_array(str_pad((int)$certificado->numero_certificado, 20, 0, STR_PAD_LEFT), array_column($datas['retorno'], 'numero_certificado'))) {
                    $aceitos[] = (int)$certificado->numero_certificado;
                } else {
                    $nao_retorno[] = (int) $certificado->numero_certificado;
                }

            }

            Certificados::whereIn('id', $aceitos)->update(['status_id'=> 42]);
            Certificados::whereIn('id', $nao_aceitos)->update(['status_id'=> 43]);
            Certificados::whereIn('id', $nao_retorno)->update(['status_id'=> 44]);

            $this->response([
                'status' => '000 - sucesso',
                'cdretorno' => '000',
                'retorno' => (count($nao_retorno) >= 1 ? 'Operação realizada com sucesso! Porém alguns dos certificados enviados não teve retorno, checar o parâmentro retnornado "nao_reternou" ' : 'Operação realizada com sucesso'),
                'nao_retornou' => $nao_retorno]);
        }
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Stud. Mycol. 5: 61 (1973)

#### Original name
Phyllostictina hymenaeae Bat. & A.F. Vital

### Remarks
null


text:
extern "C" void STDMETHODCALLTYPE start_runtime_thunk_stub();

#include <pshpack1.h>
//=================================================================================
class bootstrap_thunk
{
private:
    std::uint32_t m_token;

    struct {
        BYTE            m_call;         //0xe8
        UINT32          m_thunkFcn;     //bootstrapper function
    } m_code;

    pal::dll_t       m_dll;            // pal::dll_t of this module
    std::uintptr_t       *m_slot;             // VTable slot for this thunk

public:
    // Get thunk from the return address that the call instruction would have pushed
    static bootstrap_thunk *get_thunk_from_cookie(std::uintptr_t cookie);

    // Get thunk from the return address that the call instruction would have pushed
    static bootstrap_thunk *get_thunk_from_entrypoint(std::uintptr_t entryAddr);

    // Initializes the thunk to point to pThunkInitFcn that will load the
    // runtime and perform the real thunk initialization.
    void initialize(std::uintptr_t pThunkInitFcn,
                    pal::dll_t dll,
                    std::uint32_t token,
                    std::uintptr_t *pSlot);

    // Returns the slot address of the vtable entry for this thunk
    std::uintptr_t *get_slot_address();

    // Returns the pal::dll_t for this thunk's module
    pal::dll_t get_dll_handle();

    // Returns the token of this thunk
    std::uint32_t get_token();

    std::uintptr_t get_entrypoint();
};
#include <poppack.h>

#endif


text:
require 'arelastic/sorts/sort'
require 'arelastic/sorts/field'
require 'arelastic/sorts/geo_distance'


text:
package org.wso2.carbon.identity.recovery.endpoint.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.identity.recovery.endpoint.dto.PropertyDTO;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;

import javax.validation.constraints.NotNull;

@ApiModel(description = "")
public class CodeValidationRequestDTO  {

  private String code = null;

  private String step = null;

  private List<PropertyDTO> properties = new ArrayList<PropertyDTO>();

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("code")
  public String getCode() {
    return code;
  }
  public void setCode(String code) {
    this.code = code;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("step")
  public String getStep() {
    return step;
  }
  public void setStep(String step) {
    this.step = step;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("properties")
  public List<PropertyDTO> getProperties() {
    return properties;
  }
  public void setProperties(List<PropertyDTO> properties) {
    this.properties = properties;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class CodeValidationRequestDTO {\n");

    sb.append("  code: ").append(code).append("\n");
    sb.append("  step: ").append(step).append("\n");
    sb.append("  properties: ").append(properties).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
def smallest_integer(list_of_nums)
  minimum = list_of_nums[0]
  list_of_nums.each do |x|
    if x < minimum
       minimum = x
    end
  end
  p minimum
end


text:
using namespace SDKTemplate;

using namespace Platform;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Interop;

GlyphConverter::GlyphConverter()
{
}

Object ^ GlyphConverter::Convert(Object ^value, TypeName targetType, Object ^parameter, String ^language)
{
    IBox<Boolean>^ isExpanded = dynamic_cast<IBox<Boolean>^>(value);
    if (isExpanded != nullptr && isExpanded->Value)
    {
        return ExpandedGlyph;
    }
    else
    {
        return CollapsedGlyph;
    }
}

Object ^ GlyphConverter::ConvertBack(Object ^value, TypeName targetType, Object ^parameter, String ^language)
{
    throw ref new NotImplementedException();
}


text:
package mo_string

import "github.com/watermint/toolbox/essentials/log/esl"

type SelectString interface {
	String
	Options() []string
	SetOptions(selected string, opts ...string)
	SetSelect(selected string)
	IsValid() bool
}

func NewSelect() SelectString {
	return &selectString{
		opts:     []string{},
		selected: "",
	}
}

type selectString struct {
	opts     []string
	selected string
}

func (z *selectString) Value() string {
	return z.selected
}

func (z *selectString) Options() []string {
	return z.opts
}

func (z *selectString) SetOptions(selected string, opts ...string) {
	z.opts = opts
	z.SetSelect(selected)
}

func (z *selectString) SetSelect(selected string) {
	z.selected = selected
	if !z.IsValid() {
		l := esl.Default()
		l.Debug("The value `selected` is not in `opts`",
			esl.String("selected", selected),
			esl.Strings("opts", z.opts))
	}
}

func (z *selectString) IsValid() bool {
	for _, s := range z.opts {
		if s == z.selected {
			return true
		}
	}
	return false
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
  >

<hibernate-mapping>
  <class name="org.hisp.dhis.programstagefilter.ProgramStageInstanceFilter" table="programstageinstancefilter">

    <cache usage="read-write" />

    <id name="id" column="programstageinstancefilterid">
      <generator class="native" />
    </id>

    <property name="uid" column="uid" unique="true" length="11" not-null="true" />
    <property name="created" type="timestamp" not-null="true" />
    <property name="lastUpdated" type="timestamp" not-null="true"/>
    <many-to-one name="lastUpdatedBy" class="org.hisp.dhis.user.User" column="lastupdatedby" foreign-key="fk_lastupdateby_userid" />

    <property name="name" column="name" not-null="true" length="230" />

    <property name="description" />

    <property name="program" column="program" length="11" not-null="true" />

    <property name="programStage" column="programstage" length="11" />

    <property name="eventQueryCriteria" column="eventquerycriteria" type="jbEventQueryCriteria" />

    <many-to-one name="createdBy" class="org.hisp.dhis.user.User" column="userid" foreign-key="fk_programstageinstancefilter_userid" />

    <!-- Sharing -->
    <property name="sharing" type="jsbObjectSharing"/>

    <property name="translations" type="jblTranslations"/>

  </class>

</hibernate-mapping>


text:
package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
    /*Escribe un programa que pida un valor numérico y muestre su valor absoluto.

                El programa no terminará hasta que el usuario escriba el valor 0.*/

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int numero = 0;
        int total = 0;

        for (int i = 0; i < 10; i++) {

            System.out.print("Introduce un numero: ");
            numero = Integer.parseInt(br.readLine());
            total = total + numero;
        }
        System.out.println("El Total es : " + total);
    }

}


text:
import sys
import os
import subprocess
import shutil
import fix_rocks_network
import setup_for_centos7
import json

pxelinux_kernels_dir='/tftpboot/pxelinux/';
centos6_templates_dir='./centos6_ks'
centos6_dir='/export/rocks/install/centos6/';
centos6_ks_scripts_dir=centos6_dir;
rocks_customize_nodes_dir='/export/rocks/install/site-profiles/6.1.1/nodes/'

def setup_for_centos6(params):
  shutil.rmtree(centos6_dir, ignore_errors=True);
  try:
    os.remove(centos6_dir);
  except Exception:
    pass
  os.makedirs(centos6_ks_scripts_dir, 0755);
  #PXE boot changes
  setup_for_centos7.fix_pxe_bug();
  #ssh public key
  shutil.rmtree(centos6_ks_scripts_dir+'/ssh_public_keys', ignore_errors=True);
  try:
    os.remove(centos6_ks_scripts_dir+'/ssh_public_keys');
  except Exception:
    pass
  if('ssh_public_keys_file' in params):
    shutil.copy(params['ssh_public_keys_file'], centos6_ks_scripts_dir+'/ssh_public_keys');
  #Copy extend-compute.xml
  shutil.copy(centos6_templates_dir+'/extend-compute.xml', rocks_customize_nodes_dir+'/extend-compute.xml');
  #Copy other files in the directory
  status = subprocess.call('rsync -a --exclude=extend-compute.xml '+centos6_templates_dir+'/ '+centos6_ks_scripts_dir+'/', shell=True);
  if(status != 0):
    sys.stderr.write('ERROR: could not copy pre/post install scripts\n');
    raise Exception('Could not copy pre/post install scripts');
  #Get root password
  root_passwd='$6$CdGXnN6zABQ0Pc/7$lsUtU27wSxwpGNrLQq00Mzpwb27ujgkV5Trq8wlZrqOmrmFuX6q5X0hebNKKs5DSk8.fU3o.b6Z0ISOfNnpTl.';
  sys.stderr.write('Enter the root password to be set for your cluster by kickstart\n');
  pid = subprocess.Popen('grub-crypt --sha-512', shell=True, stdout=subprocess.PIPE);
  stdout_str = pid.communicate()[0];
  if(pid.returncode == 0):
    root_passwd = stdout_str.strip();
  else:
    sys.stderr.write('ERROR: could not obtain root password, using a random string. Re-run the program to set your root passwd\n');
    raise Exception('Could not obtain root password - exiting');
  cmd = 'sed -i -e \'/rootpw/c\\\n    <rootpw>--iscrypted '+root_passwd+'</rootpw>\' '+rocks_customize_nodes_dir+'/extend-compute.xml';
  status = subprocess.call(cmd, shell=True);
  if(status != 0):
    sys.stderr.write('ERROR: could not obtain root password, using a random string. Re-run the program to set your root passwd\n');
    raise Exception('Could not obtain root password - exiting');
  if('timezone' in params):
    cmd = 'sed -i -e \'/timezone/c\\\n    <timezone>'+params['timezone']+'</timezone>\' '+rocks_customize_nodes_dir+'/extend-compute.xml';
    status = subprocess.call(cmd, shell=True);
    if(status != 0):
      sys.stderr.write('ERROR: could not setup timezone in kickstart file\n');
      raise Exception('Could not setup timezone in kickstart file');
  if('proxy_host' in params and 'proxy_port' in params):
    cmd = 'sed -i -e \'/post_install/c\\\n    bash -x ./centos6/post_install.sh '+params['proxy_host']+' '+params['proxy_port']+'\' '+rocks_customize_nodes_dir+'/extend-compute.xml';
    status = subprocess.call(cmd, shell=True);
    if(status != 0):
      sys.stderr.write('ERROR: could not setup proxy args for post-install\n');
      raise Exception('Could not setup proxy args for post-install');
  status = subprocess.call('cd /export/rocks/install && rocks create distro', shell=True);
  if(status != 0):
    sys.stderr.write('ERROR: could not build rocks distro\n');
    raise Exception('Could not build rocks distro');

if __name__ == "__main__":
  params = {};
  if(len(sys.argv) >= 2):
    with open(sys.argv[1], 'rb') as data_file:
      params = json.load(data_file);
  directory = os.path.dirname(sys.argv[0]);
  if(directory and directory != ''):
    os.chdir(directory);
  setup_for_centos6(params);


text:
package com.hlgranite.warehousescanner;

import java.util.Date;

/**
 * Created by yeang-shing.then on 9/24/13.
 */
public class Shipment {
    private Barcode barcode;
    public Barcode getBarcode() {
        return this.barcode;
    }

    private Date date;
    public Date getDate() {
        return this.date;
    }

    private int quantity;
    public int getQuantity() {
        return this.quantity;
    }

    public Shipment(Barcode barcode, int quantity) {
        //Log.i("INFO", "new Shipment: " + barcode.toString() + " with "+quantity+"pcs");
        this.barcode = barcode;
        // todo: this.date = date;
        this.quantity = quantity;
    }

}


text:
package client

import (
	"github.com/keybase/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
)

func platformSpecificCtlCommands(cl *libcmdline.CommandLine, g *libkb.GlobalContext) []cli.Command {
	return nil
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("app", "0015_app_manifest_url"),
    ]

    operations = [
        migrations.AlterField(
            model_name="appextension",
            name="mount",
            field=models.CharField(
                choices=[
                    ("customer_overview_create", "customer_overview_create"),
                    (
                        "customer_overview_more_actions",
                        "customer_overview_more_actions",
                    ),
                    ("customer_details_more_actions", "customer_details_more_actions"),
                    ("product_overview_create", "product_overview_create"),
                    ("product_overview_more_actions", "product_overview_more_actions"),
                    ("product_details_more_actions", "product_details_more_actions"),
                    ("navigation_catalog", "navigation_catalog"),
                    ("navigation_orders", "navigation_orders"),
                    ("navigation_customers", "navigation_customers"),
                    ("navigation_discounts", "navigation_discounts"),
                    ("navigation_translations", "navigation_translations"),
                    ("navigation_pages", "navigation_pages"),
                    ("order_details_more_actions", "order_details_more_actions"),
                    ("order_overview_create", "order_overview_create"),
                    ("order_overview_more_actions", "order_overview_more_actions"),
                ],
                max_length=256,
            ),
        ),
    ]


text:
package visitors

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/linuxboot/fiano/pkg/log"
	"github.com/linuxboot/fiano/pkg/uefi"
)

var (
	// FV examples
	sampleFV []byte // Sample FV from OVMF
)

func init() {
	var err error
	sampleFV, err = ioutil.ReadFile("../../integration/roms/ovmfSECFV.fv")
	if err != nil {
		log.Fatalf("%v", err)
	}
}

var (
	// File headers
	// Hardcoded checksums for testing :(
	// I don't know how to do it better without rewriting or calling code under test.
	emptyPadHeader = append(uefi.FFGUID[:],
		[]byte{8, uefi.EmptyBodyChecksum, byte(uefi.FVFileTypePad), 0, uefi.FileHeaderMinLength, 0x00, 0x00, 0xF8}...) // Empty pad file header with no data
	goodFreeFormHeader = append(uefi.FFGUID[:],
		[]byte{202, uefi.EmptyBodyChecksum, byte(uefi.FVFileTypeFreeForm), 0, uefi.FileHeaderMinLength, 0x00, 0x00, 0xF8}...) // Empty freeform file header with no data
	nvarStoreHeader = append(uefi.NVAR[:],
		[]byte{182, uefi.EmptyBodyChecksum, byte(uefi.FVFileTypeRaw), 0, uefi.FileHeaderMinLength, 0x00, 0x00, 0xF8}...) // Empty NVAR file header with no data
)

var (
	// File examples
	emptyPadFile     = emptyPadHeader // Empty pad file with no data
	badFreeFormFile  []byte           // File with bad checksum. Should construct fine, but not validate
	goodFreeFormFile []byte           // Good file
	nvarStoreFile    []byte           // File containing an NVarStore
)

func init() {
	goodFreeFormFile = append(goodFreeFormHeader, linuxSec...)
	goodFreeFormFile = append(goodFreeFormFile, smallSec...)
	goodFreeFormFile = append(goodFreeFormFile, []byte{0, 0}...) // Alignment
	goodFreeFormFile = append(goodFreeFormFile, tinySec...)
	goodFreeFormFile[20] = byte(uefi.FileHeaderMinLength + len(tinySec) + 2 + len(linuxSec) + len(smallSec))

	badFreeFormFile = make([]byte, len(goodFreeFormFile))
	copy(badFreeFormFile, goodFreeFormFile)
	badFreeFormFile[16] = 0 // Zero out checksum

	nvarStoreFile = append(nvarStoreHeader, nvarEntryHeader...)
	nvarStoreFile = append(nvarStoreFile, byte(0))
	nvarStoreFile = append(nvarStoreFile, []byte("Test")...)
	nvarStoreFile = append(nvarStoreFile, byte(0))
	nvarStoreFile = append(nvarStoreFile, uefi.FFGUID[:]...)
	nvarStoreFile[20] = byte(uefi.FileHeaderMinLength + len(nvarEntryHeader) + 6 + len(uefi.FFGUID))

}

var (
	// NVAR examples
	nvarEntryHeader = []byte{0x4E, 0x56, 0x41, 0x52, 16, 0, 0xFF, 0xFF, 0xFF, byte(uefi.NVarEntryValid | uefi.NVarEntryASCIIName)}
)

var (
	// Section examples
	tinySec  = []byte{4, 0, 0, byte(uefi.SectionTypeRaw)}                               // Section header with no data
	smallSec = append([]byte{22, 0, 0, byte(uefi.SectionTypeRaw)}, make([]byte, 18)...) // 20 byte Section
	linuxSec = []byte{0x10, 0x00, 0x00, 0x15, 0x4c, 0x00, 0x69, 0x00,
		0x6e, 0x00, 0x75, 0x00, 0x78, 0x00, 0x00, 0x00} // Linux UI section
)

func TestExtractAssembleFile(t *testing.T) {
	var tests = []struct {
		name    string
		origBuf []byte
		newBuf  []byte
	}{
		{"emptyPadFile", emptyPadFile, emptyPadFile},
		{"badFreeFormFile", badFreeFormFile, goodFreeFormFile},
		{"goodFreeFormFile", goodFreeFormFile, goodFreeFormFile},
		{"nvarStoreFile", nvarStoreFile, nvarStoreFile},
	}
	// Set erasepolarity to FF
	uefi.Attributes.ErasePolarity = 0xFF
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			tmpDir, err := ioutil.TempDir("", "section-test")

			if err != nil {
				t.Fatalf("could not create temp dir: %v", err)
			}
			defer os.RemoveAll(tmpDir)

			f, err := uefi.NewFile(test.origBuf)
			if err != nil {
				t.Fatalf("Unable to parse file object %v, got %v", test.origBuf, err.Error())
			}
			var fIndex uint64
			if err = f.Apply(&Extract{BasePath: tmpDir, DirPath: ".", Index: &fIndex}); err != nil {
				t.Fatalf("Unable to extract file %v, got %v", test.origBuf, err.Error())
			}
			if err = f.Apply(&ParseDir{BasePath: tmpDir}); err != nil {
				t.Fatalf("Unable to parse files %v, got %v", test.origBuf, err.Error())
			}
			if err = f.Apply(&Assemble{}); err != nil {
				t.Fatalf("Unable to reassemble file %v, got %v", test.origBuf, err.Error())
			}
			nb := f.Buf()
			if len(test.newBuf) != len(nb) {
				t.Fatalf("Binary sizes differ!\n Expected: %v\n Assembled: %v\n", len(test.newBuf), len(nb))
			}
			for i := range test.newBuf {
				if test.newBuf[i] != nb[i] {
					t.Fatalf("Binaries differ at %v!\n Expected: %v\n Assembled: %v\n", i, test.newBuf[i], nb[i])
				}
			}
		})
	}
}

func TestExtractAssembleFV(t *testing.T) {
	var tests = []struct {
		name    string
		origBuf []byte
		newBuf  []byte
	}{
		{"sampleFV", sampleFV, sampleFV},
	}
	// Set erasepolarity to FF
	uefi.Attributes.ErasePolarity = 0xFF
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			tmpDir, err := ioutil.TempDir("", "section-test")

			if err != nil {
				t.Fatalf("could not create temp dir: %v", err)
			}
			defer os.RemoveAll(tmpDir)

			fv, err := uefi.NewFirmwareVolume(test.origBuf, 0, false)
			if err != nil {
				t.Fatalf("Unable to parse file object %v, got %v", test.origBuf, err.Error())
			}
			var fIndex uint64
			if err = fv.Apply(&Extract{BasePath: tmpDir, DirPath: ".", Index: &fIndex}); err != nil {
				t.Fatalf("Unable to extract file %v, got %v", test.origBuf, err.Error())
			}
			if err = fv.Apply(&ParseDir{BasePath: tmpDir}); err != nil {
				t.Fatalf("Unable to parse files %v, got %v", test.origBuf, err.Error())
			}
			if err = fv.Apply(&Assemble{}); err != nil {
				t.Fatalf("Unable to reassemble file %v, got %v", test.origBuf, err.Error())
			}
			nb := fv.Buf()
			if len(test.newBuf) != len(nb) {
				t.Fatalf("Binary sizes differ!\n Expected: %v\n Assembled: %v\n", len(test.newBuf), len(nb))
			}
			for i := range test.newBuf {
				if test.newBuf[i] != nb[i] {
					t.Fatalf("Binaries differ at %v!\n Expected: %v\n Assembled: %v\n", i, test.newBuf[i], nb[i])
				}
			}
		})
	}
}

func TestExtractAssembleSection(t *testing.T) {
	var tests = []struct {
		name      string
		buf       []byte
		fileOrder int
	}{
		{"tinySec", tinySec, 0},
		{"tinySec", tinySec, 1},
		{"smallSec", smallSec, 0},
		{"smallSec", smallSec, 1},
		{"linuxSec", linuxSec, 0},
		{"linuxSec", linuxSec, 1},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			tmpDir, err := ioutil.TempDir("", "section-test")

			if err != nil {
				t.Fatalf("could not create temp dir: %v", err)
			}
			defer os.RemoveAll(tmpDir)

			s, err := uefi.NewSection(test.buf, test.fileOrder)
			if err != nil {
				t.Fatalf("Unable to parse section object %v, got %v", test.buf, err.Error())
			}
			var fIndex uint64
			if err = s.Apply(&Extract{BasePath: tmpDir, DirPath: ".", Index: &fIndex}); err != nil {
				t.Fatalf("Unable to extract section %v, got %v", test.buf, err.Error())
			}
			if err = s.Apply(&ParseDir{BasePath: tmpDir}); err != nil {
				t.Fatalf("Unable to parse files %v, got %v", test.buf, err.Error())
			}
			if err = s.Apply(&Assemble{}); err != nil {
				t.Fatalf("Unable to reassemble file %v, got %v", test.buf, err.Error())
			}
			nb := s.Buf()
			if len(test.buf) != len(nb) {
				t.Fatalf("Binary sizes differ!\n Expected: %v\n Assembled: %v\n", len(test.buf), len(nb))
			}
			for i := range test.buf {
				if test.buf[i] != nb[i] {
					t.Fatalf("Binaries differ at %v!\n Expected: %v\n Assembled: %v\n", i, test.buf[i], nb[i])
				}
			}
		})
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>wei.mark</groupId>
  <artifactId>standout</artifactId>
  <version>1.0</version>
  <versioning>
    <versions>
      <version>1.0</version>
    </versions>
    <lastUpdated>20140319042134</lastUpdated>
  </versioning>
</metadata>


text:
/**
 * Example showing how to upload a file using PUT.
 */
var Curl = require( '../lib/Curl' ),
    path = require( 'path' ),
    fs   = require( 'fs' ),
    crypto = require( 'crypto' );

var curl = new Curl(),
    url = 'httpbin.org/put',
    fileSize = 10 * 1024, //1KB
    fileName = path.resolve( __dirname, 'upload.test' ),
    fd = -1;

//write random bytes to a file, this will be our upload file.
fs.writeFileSync( fileName, crypto.randomBytes( fileSize ) );

console.log( 'File: ', fs.readFileSync( fileName, 'base64' ) );

fs.open( fileName, 'r+', function( err, fd ) {

    //enabling VERBOSE mode so we can get more details on what is going on.
    curl.setOpt( Curl.option.VERBOSE, 1 );
    //set UPLOAD to a truthy value to enable PUT upload.
    curl.setOpt( Curl.option.UPLOAD, 1 );
    //pass the file descriptor to the READDATA option
    // passing one invalid value here will cause an aborted by callback error.
    curl.setOpt( Curl.option.READDATA, fd );

    curl.setOpt( Curl.option.URL, url );

    curl.on( 'end', function( statusCode, body ) {

        console.log( body );

        //remember to always close the file descriptor!
        fs.closeSync( fd );

        fs.unlinkSync( fileName );

        //the same for the curl instance, always close it when you don't need it anymore.
        this.close();
    });

    curl.on( 'error', function( err ) {

        console.log( err );

        fs.closeSync( fd );
        fs.unlinkSync( fileName );
        this.close();
    });

    curl.perform();
});


text:
/* */
(function(process) {
  var PropertyOptimizer = require("../../properties/optimizer");
  var CleanUp = require("./clean-up");
  var extractProperties = require("../../properties/extractor");
  var canReorder = require("../../properties/reorderable").canReorder;
  var canReorderSingle = require("../../properties/reorderable").canReorderSingle;
  function AdvancedOptimizer(options, context) {
    this.options = options;
    this.minificationsMade = [];
    this.propertyOptimizer = new PropertyOptimizer(this.options, context);
  }
  function changeBodyOf(token, newBody) {
    token.body = newBody.tokenized;
    token.metadata.body = newBody.list.join(';');
    token.metadata.bodiesList = newBody.list;
  }
  function changeSelectorOf(token, newSelectors) {
    token.value = newSelectors.tokenized;
    token.metadata.selector = newSelectors.list.join(',');
    token.metadata.selectorsList = newSelectors.list;
  }
  function unsafeSelector(value) {
    return /\.|\*| :/.test(value);
  }
  function naturalSorter(a, b) {
    return a > b;
  }
  AdvancedOptimizer.prototype.isSpecial = function(selector) {
    return this.options.compatibility.selectors.special.test(selector);
  };
  AdvancedOptimizer.prototype.removeDuplicates = function(tokens) {
    var matched = {};
    var forRemoval = [];
    for (var i = 0,
        l = tokens.length; i < l; i++) {
      var token = tokens[i];
      if (token.kind != 'selector')
        continue;
      var id = token.metadata.body + '@' + token.metadata.selector;
      var alreadyMatched = matched[id];
      if (alreadyMatched) {
        forRemoval.push(alreadyMatched[0]);
        alreadyMatched.unshift(i);
      } else {
        matched[id] = [i];
      }
    }
    forRemoval = forRemoval.sort(function(a, b) {
      return a > b ? 1 : -1;
    });
    for (var j = 0,
        n = forRemoval.length; j < n; j++) {
      tokens.splice(forRemoval[j] - j, 1);
    }
    this.minificationsMade.unshift(forRemoval.length > 0);
  };
  AdvancedOptimizer.prototype.mergeAdjacent = function(tokens) {
    var forRemoval = [];
    var lastToken = {
      selector: null,
      body: null
    };
    var adjacentSpace = this.options.compatibility.selectors.adjacentSpace;
    for (var i = 0,
        l = tokens.length; i < l; i++) {
      var token = tokens[i];
      if (token.kind != 'selector') {
        lastToken = {
          selector: null,
          body: null
        };
        continue;
      }
      if (lastToken.kind == 'selector' && token.metadata.selector == lastToken.metadata.selector) {
        var joinAt = [lastToken.body.length];
        changeBodyOf(lastToken, this.propertyOptimizer.process(token.value, lastToken.body.concat(token.body), joinAt, true));
        forRemoval.push(i);
      } else if (lastToken.body && token.metadata.body == lastToken.metadata.body && !this.isSpecial(token.metadata.selector) && !this.isSpecial(lastToken.metadata.selector)) {
        changeSelectorOf(lastToken, CleanUp.selectors(lastToken.value.concat(token.value), false, adjacentSpace));
        forRemoval.push(i);
      } else {
        lastToken = token;
      }
    }
    for (var j = 0,
        m = forRemoval.length; j < m; j++) {
      tokens.splice(forRemoval[j] - j, 1);
    }
    this.minificationsMade.unshift(forRemoval.length > 0);
  };
  AdvancedOptimizer.prototype.reduceNonAdjacent = function(tokens) {
    var candidates = {};
    var repeated = [];
    for (var i = tokens.length - 1; i >= 0; i--) {
      var token = tokens[i];
      if (token.kind != 'selector')
        continue;
      var isComplexAndNotSpecial = token.value.length > 1 && !this.isSpecial(token.metadata.selector);
      var selectors = isComplexAndNotSpecial ? [token.metadata.selector].concat(token.metadata.selectorsList) : [token.metadata.selector];
      for (var j = 0,
          m = selectors.length; j < m; j++) {
        var selector = selectors[j];
        if (!candidates[selector])
          candidates[selector] = [];
        else
          repeated.push(selector);
        candidates[selector].push({
          where: i,
          list: token.metadata.selectorsList,
          isPartial: isComplexAndNotSpecial && j > 0,
          isComplex: isComplexAndNotSpecial && j === 0
        });
      }
    }
    var reducedInSimple = this.reduceSimpleNonAdjacentCases(tokens, repeated, candidates);
    var reducedInComplex = this.reduceComplexNonAdjacentCases(tokens, candidates);
    this.minificationsMade.unshift(reducedInSimple || reducedInComplex);
  };
  AdvancedOptimizer.prototype.reduceSimpleNonAdjacentCases = function(tokens, repeated, candidates) {
    var reduced = false;
    function filterOut(idx, bodies) {
      return data[idx].isPartial && bodies.length === 0;
    }
    function reduceBody(token, newBody, processedCount, tokenIdx) {
      if (!data[processedCount - tokenIdx - 1].isPartial) {
        changeBodyOf(token, newBody);
        reduced = true;
      }
    }
    for (var i = 0,
        l = repeated.length; i < l; i++) {
      var selector = repeated[i];
      var data = candidates[selector];
      this.reduceSelector(tokens, selector, data, {
        filterOut: filterOut,
        callback: reduceBody
      });
    }
    return reduced;
  };
  AdvancedOptimizer.prototype.reduceComplexNonAdjacentCases = function(tokens, candidates) {
    var reduced = false;
    var localContext = {};
    function filterOut(idx) {
      return localContext.data[idx].where < localContext.intoPosition;
    }
    function collectReducedBodies(token, newBody, processedCount, tokenIdx) {
      if (tokenIdx === 0)
        localContext.reducedBodies.push(newBody);
    }
    allSelectors: for (var complexSelector in candidates) {
      var into = candidates[complexSelector];
      if (!into[0].isComplex)
        continue;
      var intoPosition = into[into.length - 1].where;
      var intoToken = tokens[intoPosition];
      var reducedBodies = [];
      var selectors = this.isSpecial(complexSelector) ? [complexSelector] : into[0].list;
      localContext.intoPosition = intoPosition;
      localContext.reducedBodies = reducedBodies;
      for (var j = 0,
          m = selectors.length; j < m; j++) {
        var selector = selectors[j];
        var data = candidates[selector];
        if (data.length < 2)
          continue allSelectors;
        localContext.data = data;
        this.reduceSelector(tokens, selector, data, {
          filterOut: filterOut,
          callback: collectReducedBodies
        });
        if (reducedBodies[reducedBodies.length - 1].list.join(';') != reducedBodies[0].list.join(';'))
          continue allSelectors;
      }
      intoToken.body = reducedBodies[0].tokenized;
      reduced = true;
    }
    return reduced;
  };
  AdvancedOptimizer.prototype.reduceSelector = function(tokens, selector, data, options) {
    var bodies = [];
    var bodiesAsList = [];
    var joinsAt = [];
    var processedTokens = [];
    for (var j = data.length - 1,
        m = 0; j >= 0; j--) {
      if (options.filterOut(j, bodies))
        continue;
      var where = data[j].where;
      var token = tokens[where];
      bodies = bodies.concat(token.body);
      bodiesAsList.push(token.metadata.bodiesList);
      processedTokens.push(where);
    }
    for (j = 0, m = bodiesAsList.length; j < m; j++) {
      if (bodiesAsList[j].length > 0)
        joinsAt.push((joinsAt[j - 1] || 0) + bodiesAsList[j].length);
    }
    var optimizedBody = this.propertyOptimizer.process(selector, bodies, joinsAt, false);
    var processedCount = processedTokens.length;
    var propertyIdx = optimizedBody.tokenized.length - 1;
    var tokenIdx = processedCount - 1;
    while (tokenIdx >= 0) {
      if ((tokenIdx === 0 || (optimizedBody.tokenized[propertyIdx] && bodiesAsList[tokenIdx].indexOf(optimizedBody.tokenized[propertyIdx].value) > -1)) && propertyIdx > -1) {
        propertyIdx--;
        continue;
      }
      var newBody = {
        list: optimizedBody.list.splice(propertyIdx + 1),
        tokenized: optimizedBody.tokenized.splice(propertyIdx + 1)
      };
      options.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx);
      tokenIdx--;
    }
  };
  AdvancedOptimizer.prototype.mergeNonAdjacentBySelector = function(tokens) {
    var allSelectors = {};
    var repeatedSelectors = [];
    var i;
    for (i = tokens.length - 1; i >= 0; i--) {
      if (tokens[i].kind != 'selector')
        continue;
      if (tokens[i].body.length === 0)
        continue;
      var selector = tokens[i].metadata.selector;
      allSelectors[selector] = [i].concat(allSelectors[selector] || []);
      if (allSelectors[selector].length == 2)
        repeatedSelectors.push(selector);
    }
    for (i = repeatedSelectors.length - 1; i >= 0; i--) {
      var positions = allSelectors[repeatedSelectors[i]];
      selectorIterator: for (var j = positions.length - 1; j > 0; j--) {
        var positionOne = positions[j - 1];
        var tokenOne = tokens[positionOne];
        var positionTwo = positions[j];
        var tokenTwo = tokens[positionTwo];
        directionIterator: for (var direction = 1; direction >= -1; direction -= 2) {
          var topToBottom = direction == 1;
          var from = topToBottom ? positionOne + 1 : positionTwo - 1;
          var to = topToBottom ? positionTwo : positionOne;
          var delta = topToBottom ? 1 : -1;
          var moved = topToBottom ? tokenOne : tokenTwo;
          var target = topToBottom ? tokenTwo : tokenOne;
          var movedProperties = extractProperties(moved);
          while (from != to) {
            var traversedProperties = extractProperties(tokens[from]);
            from += delta;
            var reorderable = topToBottom ? canReorder(movedProperties, traversedProperties) : canReorder(traversedProperties, movedProperties);
            if (!reorderable && !topToBottom)
              continue selectorIterator;
            if (!reorderable && topToBottom)
              continue directionIterator;
          }
          var joinAt = topToBottom ? [target.body.length] : [moved.body.length];
          var joinedBodies = topToBottom ? moved.body.concat(target.body) : target.body.concat(moved.body);
          var newBody = this.propertyOptimizer.process(target.value, joinedBodies, joinAt, true);
          changeBodyOf(target, newBody);
          changeBodyOf(moved, {
            tokenized: [],
            list: []
          });
        }
      }
    }
  };
  AdvancedOptimizer.prototype.mergeNonAdjacentByBody = function(tokens) {
    var candidates = {};
    var adjacentSpace = this.options.compatibility.selectors.adjacentSpace;
    for (var i = tokens.length - 1; i >= 0; i--) {
      var token = tokens[i];
      if (token.kind != 'selector')
        continue;
      if (token.body.length > 0 && unsafeSelector(token.metadata.selector))
        candidates = {};
      var oldToken = candidates[token.metadata.body];
      if (oldToken && !this.isSpecial(token.metadata.selector) && !this.isSpecial(oldToken.metadata.selector)) {
        changeSelectorOf(token, CleanUp.selectors(oldToken.value.concat(token.value), false, adjacentSpace));
        changeBodyOf(oldToken, {
          tokenized: [],
          list: []
        });
        candidates[token.metadata.body] = null;
      }
      candidates[token.metadata.body] = token;
    }
  };
  AdvancedOptimizer.prototype.restructure = function(tokens) {
    var movableTokens = {};
    var movedProperties = [];
    var multiPropertyMoveCache = {};
    var movedToBeDropped = [];
    var self = this;
    var maxCombinationsLevel = 2;
    var ID_JOIN_CHARACTER = '%';
    function sendToMultiPropertyMoveCache(position, movedProperty, allFits) {
      for (var i = allFits.length - 1; i >= 0; i--) {
        var fit = allFits[i][0];
        var id = addToCache(movedProperty, fit);
        if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) {
          removeAllMatchingFromCache(id);
          break;
        }
      }
    }
    function addToCache(movedProperty, fit) {
      var id = cacheId(fit);
      multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || [];
      multiPropertyMoveCache[id].push([movedProperty, fit]);
      return id;
    }
    function removeAllMatchingFromCache(matchId) {
      var matchSelectors = matchId.split(ID_JOIN_CHARACTER);
      var forRemoval = [];
      var i;
      for (var id in multiPropertyMoveCache) {
        var selectors = id.split(ID_JOIN_CHARACTER);
        for (i = selectors.length - 1; i >= 0; i--) {
          if (matchSelectors.indexOf(selectors[i]) > -1) {
            forRemoval.push(id);
            break;
          }
        }
      }
      for (i = forRemoval.length - 1; i >= 0; i--) {
        delete multiPropertyMoveCache[forRemoval[i]];
      }
    }
    function cacheId(cachedTokens) {
      var id = [];
      for (var i = 0,
          l = cachedTokens.length; i < l; i++) {
        id.push(cachedTokens[i].metadata.selector);
      }
      return id.join(ID_JOIN_CHARACTER);
    }
    function tokensToMerge(sourceTokens) {
      var uniqueTokensWithBody = [];
      var mergeableTokens = [];
      for (var i = sourceTokens.length - 1; i >= 0; i--) {
        if (self.isSpecial(sourceTokens[i].metadata.selector))
          continue;
        mergeableTokens.unshift(sourceTokens[i]);
        if (sourceTokens[i].body.length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1)
          uniqueTokensWithBody.push(sourceTokens[i]);
      }
      return uniqueTokensWithBody.length > 1 ? mergeableTokens : [];
    }
    function shortenIfPossible(position, movedProperty) {
      var name = movedProperty[0];
      var value = movedProperty[1];
      var key = movedProperty[3];
      var valueSize = name.length + value.length + 1;
      var allSelectors = [];
      var qualifiedTokens = [];
      var mergeableTokens = tokensToMerge(movableTokens[key]);
      if (mergeableTokens.length < 2)
        return ;
      var allFits = findAllFits(mergeableTokens, valueSize, 1);
      var bestFit = allFits[0];
      if (bestFit[1] > 0)
        return sendToMultiPropertyMoveCache(position, movedProperty, allFits);
      for (var i = bestFit[0].length - 1; i >= 0; i--) {
        allSelectors = bestFit[0][i].value.concat(allSelectors);
        qualifiedTokens.unshift(bestFit[0][i]);
      }
      allSelectors = CleanUp.selectorDuplicates(allSelectors);
      dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens);
    }
    function fitSorter(fit1, fit2) {
      return fit1[1] > fit2[1];
    }
    function findAllFits(mergeableTokens, propertySize, propertiesCount) {
      var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1);
      return combinations.sort(fitSorter);
    }
    function allCombinations(tokensVariant, propertySize, propertiesCount, level) {
      var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]];
      if (tokensVariant.length > 2 && level > 0) {
        for (var i = tokensVariant.length - 1; i >= 0; i--) {
          var subVariant = Array.prototype.slice.call(tokensVariant, 0);
          subVariant.splice(i, 1);
          differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1));
        }
      }
      return differenceVariants;
    }
    function sizeDifference(tokensVariant, propertySize, propertiesCount) {
      var allSelectorsSize = 0;
      for (var i = tokensVariant.length - 1; i >= 0; i--) {
        allSelectorsSize += tokensVariant[i].body.length > propertiesCount ? tokensVariant[i].metadata.selector.length : -1;
      }
      return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
    }
    function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) {
      var bodyMetadata = {};
      var i,
          j,
          k,
          m;
      for (i = mergeableTokens.length - 1; i >= 0; i--) {
        var mergeableToken = mergeableTokens[i];
        for (j = mergeableToken.body.length - 1; j >= 0; j--) {
          for (k = 0, m = properties.length; k < m; k++) {
            var property = properties[k];
            if (mergeableToken.body[j].value === property[3]) {
              bodyMetadata[property[3]] = mergeableToken.body[j].metadata;
              mergeableToken.body.splice(j, 1);
              mergeableToken.metadata.bodiesList.splice(j, 1);
              mergeableToken.metadata.body = mergeableToken.metadata.bodiesList.join(';');
              break;
            }
          }
        }
      }
      var newToken = {
        kind: 'selector',
        metadata: {}
      };
      var allBodies = {
        tokenized: [],
        list: []
      };
      for (i = properties.length - 1; i >= 0; i--) {
        allBodies.tokenized.push({value: properties[i][3]});
        allBodies.list.push(properties[i][3]);
      }
      changeSelectorOf(newToken, allSelectors);
      changeBodyOf(newToken, allBodies);
      for (i = properties.length - 1; i >= 0; i--) {
        newToken.body[i].metadata = bodyMetadata[properties[i][3]];
      }
      tokens.splice(position, 0, newToken);
    }
    function dropPropertiesAt(position, movedProperty) {
      var key = movedProperty[3];
      if (movableTokens[key] && movableTokens[key].length > 1)
        shortenIfPossible(position, movedProperty);
    }
    function processMultiPropertyMove(position, propertiesAndMergableTokens) {
      var valueSize = 0;
      var properties = [];
      var property;
      for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) {
        property = propertiesAndMergableTokens[i][0];
        var fullValue = property[3];
        valueSize += fullValue.length + (i > 0 ? 1 : 0);
        properties.push(property);
      }
      var mergeableTokens = propertiesAndMergableTokens[0][1];
      var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
      if (bestFit[1] > 0)
        return false;
      var allSelectors = [];
      var qualifiedTokens = [];
      for (i = bestFit[0].length - 1; i >= 0; i--) {
        allSelectors = bestFit[0][i].value.concat(allSelectors);
        qualifiedTokens.unshift(bestFit[0][i]);
      }
      allSelectors = CleanUp.selectorDuplicates(allSelectors);
      dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens);
      for (i = properties.length - 1; i >= 0; i--) {
        property = properties[i];
        var index = movedProperties.indexOf(property);
        delete movableTokens[property[3]];
        if (index > -1 && movedToBeDropped.indexOf(index) == -1)
          movedToBeDropped.push(index);
      }
      return true;
    }
    for (var i = tokens.length - 1; i >= 0; i--) {
      var token = tokens[i];
      var isSelector;
      var j,
          k,
          m;
      if (token.kind == 'selector') {
        isSelector = true;
      } else if (token.kind == 'block' && !token.isFlatBlock) {
        isSelector = false;
      } else {
        continue;
      }
      var movedCount = movedProperties.length;
      var properties = extractProperties(token);
      movedToBeDropped = [];
      var unmovableInCurrentToken = [];
      for (j = properties.length - 1; j >= 0; j--) {
        for (k = j - 1; k >= 0; k--) {
          if (!canReorderSingle(properties[j], properties[k])) {
            unmovableInCurrentToken.push(j);
            break;
          }
        }
      }
      for (j = 0, m = properties.length; j < m; j++) {
        var property = properties[j];
        var movedSameProperty = false;
        for (k = 0; k < movedCount; k++) {
          var movedProperty = movedProperties[k];
          if (movedToBeDropped.indexOf(k) == -1 && !canReorderSingle(property, movedProperty)) {
            dropPropertiesAt(i + 1, movedProperty);
            movedToBeDropped.push(k);
            delete movableTokens[movedProperty[3]];
          }
          if (!movedSameProperty)
            movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1];
        }
        if (!isSelector || unmovableInCurrentToken.indexOf(j) > -1)
          continue;
        var key = property[3];
        movableTokens[key] = movableTokens[key] || [];
        movableTokens[key].push(token);
        if (!movedSameProperty)
          movedProperties.push(property);
      }
      movedToBeDropped = movedToBeDropped.sort(naturalSorter);
      for (j = 0, m = movedToBeDropped.length; j < m; j++) {
        movedProperties.splice(movedToBeDropped[j] - j, 1);
      }
    }
    var position = tokens[0] && tokens[0].kind == 'at-rule' && tokens[0].value.indexOf('@charset') === 0 ? 1 : 0;
    for (; position < tokens.length - 1; position++) {
      var isImportRule = tokens[position].kind === 'at-rule' && tokens[position].value.indexOf('@import') === 0;
      var isEscapedCommentSpecial = tokens[position].kind === 'text' && tokens[position].value.indexOf('__ESCAPED_COMMENT_SPECIAL') === 0;
      if (!(isImportRule || isEscapedCommentSpecial))
        break;
    }
    for (i = 0; i < movedProperties.length; i++) {
      dropPropertiesAt(position, movedProperties[i]);
    }
  };
  AdvancedOptimizer.prototype.mergeMediaQueries = function(tokens) {
    var candidates = {};
    var reduced = [];
    for (var i = tokens.length - 1; i >= 0; i--) {
      var token = tokens[i];
      if (token.kind != 'block' || token.isFlatBlock === true)
        continue;
      var candidate = candidates[token.value];
      if (!candidate) {
        candidate = [];
        candidates[token.value] = candidate;
      }
      candidate.push(i);
    }
    for (var name in candidates) {
      var positions = candidates[name];
      positionLoop: for (var j = positions.length - 1; j > 0; j--) {
        var source = tokens[positions[j]];
        var target = tokens[positions[j - 1]];
        var movedProperties = extractProperties(source);
        for (var k = positions[j] + 1; k < positions[j - 1]; k++) {
          var traversedProperties = extractProperties(tokens[k]);
          if (!canReorder(movedProperties, traversedProperties))
            continue positionLoop;
        }
        target.body = source.body.concat(target.body);
        source.body = [];
        reduced.push(target);
      }
    }
    return reduced;
  };
  function optimizeProperties(tokens, propertyOptimizer) {
    for (var i = 0,
        l = tokens.length; i < l; i++) {
      var token = tokens[i];
      if (token.kind == 'selector') {
        changeBodyOf(token, propertyOptimizer.process(token.value, token.body, false, true));
      } else if (token.kind == 'block') {
        optimizeProperties(token.body, propertyOptimizer);
      }
    }
  }
  AdvancedOptimizer.prototype.optimize = function(tokens) {
    var self = this;
    function _optimize(tokens, withRestructuring) {
      tokens.forEach(function(token) {
        if (token.kind == 'block') {
          var isKeyframes = /@(-moz-|-o-|-webkit-)?keyframes/.test(token.value);
          _optimize(token.body, !isKeyframes);
        }
      });
      optimizeProperties(tokens, self.propertyOptimizer);
      self.removeDuplicates(tokens);
      self.mergeAdjacent(tokens);
      self.reduceNonAdjacent(tokens);
      self.mergeNonAdjacentBySelector(tokens);
      self.mergeNonAdjacentByBody(tokens);
      if (self.options.restructuring && withRestructuring) {
        self.restructure(tokens);
        self.mergeAdjacent(tokens);
      }
      if (self.options.mediaMerging) {
        var reduced = self.mergeMediaQueries(tokens);
        for (var i = reduced.length - 1; i >= 0; i--) {
          _optimize(reduced[i].body);
        }
      }
    }
    _optimize(tokens, true);
  };
  module.exports = AdvancedOptimizer;
})(require("process"));


text:
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/iotsitewise/IoTSiteWiseRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/iotsitewise/model/AssetModelProperty.h>
#include <aws/iotsitewise/model/AssetModelHierarchy.h>
#include <aws/iotsitewise/model/AssetModelCompositeModel.h>
#include <utility>
#include <aws/core/utils/UUID.h>

namespace Aws
{
namespace IoTSiteWise
{
namespace Model
{

  /**
   */
  class AWS_IOTSITEWISE_API UpdateAssetModelRequest : public IoTSiteWiseRequest
  {
  public:
    UpdateAssetModelRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateAssetModel"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ID of the asset model to update.

     */
    inline const Aws::String& GetAssetModelId() const{ return m_assetModelId; }

    /**
     *
The ID of the asset model to update.

     */
    inline bool AssetModelIdHasBeenSet() const { return m_assetModelIdHasBeenSet; }

    /**
     *
The ID of the asset model to update.

     */
    inline void SetAssetModelId(const Aws::String& value) { m_assetModelIdHasBeenSet = true; m_assetModelId = value; }

    /**
     *
The ID of the asset model to update.

     */
    inline void SetAssetModelId(Aws::String&& value) { m_assetModelIdHasBeenSet = true; m_assetModelId = std::move(value); }

    /**
     *
The ID of the asset model to update.

     */
    inline void SetAssetModelId(const char* value) { m_assetModelIdHasBeenSet = true; m_assetModelId.assign(value); }

    /**
     *
The ID of the asset model to update.

     */
    inline UpdateAssetModelRequest& WithAssetModelId(const Aws::String& value) { SetAssetModelId(value); return *this;}

    /**
     *
The ID of the asset model to update.

     */
    inline UpdateAssetModelRequest& WithAssetModelId(Aws::String&& value) { SetAssetModelId(std::move(value)); return *this;}

    /**
     *
The ID of the asset model to update.

     */
    inline UpdateAssetModelRequest& WithAssetModelId(const char* value) { SetAssetModelId(value); return *this;}

    /**
     *
A unique, friendly name for the asset model.

     */
    inline const Aws::String& GetAssetModelName() const{ return m_assetModelName; }

    /**
     *
A unique, friendly name for the asset model.

     */
    inline bool AssetModelNameHasBeenSet() const { return m_assetModelNameHasBeenSet; }

    /**
     *
A unique, friendly name for the asset model.

     */
    inline void SetAssetModelName(const Aws::String& value) { m_assetModelNameHasBeenSet = true; m_assetModelName = value; }

    /**
     *
A unique, friendly name for the asset model.

     */
    inline void SetAssetModelName(Aws::String&& value) { m_assetModelNameHasBeenSet = true; m_assetModelName = std::move(value); }

    /**
     *
A unique, friendly name for the asset model.

     */
    inline void SetAssetModelName(const char* value) { m_assetModelNameHasBeenSet = true; m_assetModelName.assign(value); }

    /**
     *
A unique, friendly name for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelName(const Aws::String& value) { SetAssetModelName(value); return *this;}

    /**
     *
A unique, friendly name for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelName(Aws::String&& value) { SetAssetModelName(std::move(value)); return *this;}

    /**
     *
A unique, friendly name for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelName(const char* value) { SetAssetModelName(value); return *this;}

    /**
     *
A description for the asset model.

     */
    inline const Aws::String& GetAssetModelDescription() const{ return m_assetModelDescription; }

    /**
     *
A description for the asset model.

     */
    inline bool AssetModelDescriptionHasBeenSet() const { return m_assetModelDescriptionHasBeenSet; }

    /**
     *
A description for the asset model.

     */
    inline void SetAssetModelDescription(const Aws::String& value) { m_assetModelDescriptionHasBeenSet = true; m_assetModelDescription = value; }

    /**
     *
A description for the asset model.

     */
    inline void SetAssetModelDescription(Aws::String&& value) { m_assetModelDescriptionHasBeenSet = true; m_assetModelDescription = std::move(value); }

    /**
     *
A description for the asset model.

     */
    inline void SetAssetModelDescription(const char* value) { m_assetModelDescriptionHasBeenSet = true; m_assetModelDescription.assign(value); }

    /**
     *
A description for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelDescription(const Aws::String& value) { SetAssetModelDescription(value); return *this;}

    /**
     *
A description for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelDescription(Aws::String&& value) { SetAssetModelDescription(std::move(value)); return *this;}

    /**
     *
A description for the asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelDescription(const char* value) { SetAssetModelDescription(value); return *this;}

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline const Aws::Vector<AssetModelProperty>& GetAssetModelProperties() const{ return m_assetModelProperties; }

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline bool AssetModelPropertiesHasBeenSet() const { return m_assetModelPropertiesHasBeenSet; }

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline void SetAssetModelProperties(const Aws::Vector<AssetModelProperty>& value) { m_assetModelPropertiesHasBeenSet = true; m_assetModelProperties = value; }

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline void SetAssetModelProperties(Aws::Vector<AssetModelProperty>&& value) { m_assetModelPropertiesHasBeenSet = true; m_assetModelProperties = std::move(value); }

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& WithAssetModelProperties(const Aws::Vector<AssetModelProperty>& value) { SetAssetModelProperties(value); return *this;}

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& WithAssetModelProperties(Aws::Vector<AssetModelProperty>&& value) { SetAssetModelProperties(std::move(value)); return *this;}

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& AddAssetModelProperties(const AssetModelProperty& value) { m_assetModelPropertiesHasBeenSet = true; m_assetModelProperties.push_back(value); return *this; }

    /**
     *
The updated property definitions of the asset model. For more information,
     * see Asset
     * properties in the IoT SiteWise User Guide.

You can specify up
     * to 200 properties per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& AddAssetModelProperties(AssetModelProperty&& value) { m_assetModelPropertiesHasBeenSet = true; m_assetModelProperties.push_back(std::move(value)); return *this; }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline const Aws::Vector<AssetModelHierarchy>& GetAssetModelHierarchies() const{ return m_assetModelHierarchies; }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline bool AssetModelHierarchiesHasBeenSet() const { return m_assetModelHierarchiesHasBeenSet; }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline void SetAssetModelHierarchies(const Aws::Vector<AssetModelHierarchy>& value) { m_assetModelHierarchiesHasBeenSet = true; m_assetModelHierarchies = value; }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline void SetAssetModelHierarchies(Aws::Vector<AssetModelHierarchy>&& value) { m_assetModelHierarchiesHasBeenSet = true; m_assetModelHierarchies = std::move(value); }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& WithAssetModelHierarchies(const Aws::Vector<AssetModelHierarchy>& value) { SetAssetModelHierarchies(value); return *this;}

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& WithAssetModelHierarchies(Aws::Vector<AssetModelHierarchy>&& value) { SetAssetModelHierarchies(std::move(value)); return *this;}

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& AddAssetModelHierarchies(const AssetModelHierarchy& value) { m_assetModelHierarchiesHasBeenSet = true; m_assetModelHierarchies.push_back(value); return *this; }

    /**
     *
The updated hierarchy definitions of the asset model. Each hierarchy
     * specifies an asset model whose assets can be children of any other assets
     * created from this asset model. For more information, see Asset
     * hierarchies in the IoT SiteWise User Guide.

You can specify up
     * to 10 hierarchies per asset model. For more information, see Quotas
     * in the IoT SiteWise User Guide.

     */
    inline UpdateAssetModelRequest& AddAssetModelHierarchies(AssetModelHierarchy&& value) { m_assetModelHierarchiesHasBeenSet = true; m_assetModelHierarchies.push_back(std::move(value)); return *this; }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline const Aws::Vector<AssetModelCompositeModel>& GetAssetModelCompositeModels() const{ return m_assetModelCompositeModels; }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline bool AssetModelCompositeModelsHasBeenSet() const { return m_assetModelCompositeModelsHasBeenSet; }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline void SetAssetModelCompositeModels(const Aws::Vector<AssetModelCompositeModel>& value) { m_assetModelCompositeModelsHasBeenSet = true; m_assetModelCompositeModels = value; }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline void SetAssetModelCompositeModels(Aws::Vector<AssetModelCompositeModel>&& value) { m_assetModelCompositeModelsHasBeenSet = true; m_assetModelCompositeModels = std::move(value); }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelCompositeModels(const Aws::Vector<AssetModelCompositeModel>& value) { SetAssetModelCompositeModels(value); return *this;}

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline UpdateAssetModelRequest& WithAssetModelCompositeModels(Aws::Vector<AssetModelCompositeModel>&& value) { SetAssetModelCompositeModels(std::move(value)); return *this;}

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline UpdateAssetModelRequest& AddAssetModelCompositeModels(const AssetModelCompositeModel& value) { m_assetModelCompositeModelsHasBeenSet = true; m_assetModelCompositeModels.push_back(value); return *this; }

    /**
     *
The composite asset models that are part of this asset model. Composite asset
     * models are asset models that contain specific properties. Each composite model
     * has a type that defines the properties that the composite model supports. Use
     * composite asset models to define alarms on this asset model.

     */
    inline UpdateAssetModelRequest& AddAssetModelCompositeModels(AssetModelCompositeModel&& value) { m_assetModelCompositeModelsHasBeenSet = true; m_assetModelCompositeModels.push_back(std::move(value)); return *this; }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline const Aws::String& GetClientToken() const{ return m_clientToken; }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline UpdateAssetModelRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline UpdateAssetModelRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}

    /**
     *
A unique case-sensitive identifier that you can provide to ensure the
     * idempotency of the request. Don't reuse this client token if a new idempotent
     * request is required.

     */
    inline UpdateAssetModelRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}

  private:

    Aws::String m_assetModelId;
    bool m_assetModelIdHasBeenSet;

    Aws::String m_assetModelName;
    bool m_assetModelNameHasBeenSet;

    Aws::String m_assetModelDescription;
    bool m_assetModelDescriptionHasBeenSet;

    Aws::Vector<AssetModelProperty> m_assetModelProperties;
    bool m_assetModelPropertiesHasBeenSet;

    Aws::Vector<AssetModelHierarchy> m_assetModelHierarchies;
    bool m_assetModelHierarchiesHasBeenSet;

    Aws::Vector<AssetModelCompositeModel> m_assetModelCompositeModels;
    bool m_assetModelCompositeModelsHasBeenSet;

    Aws::String m_clientToken;
    bool m_clientTokenHasBeenSet;
  };

} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws


text:
import ColumnChooser from './ColumnChooser.component';

export default ColumnChooser;