text:
using System;
using NUnit.Framework;
using OctoFX.Core.Model;

namespace OctoFX.Tests.OctoFX.Core.Model
{
    [TestFixture]
    public class CurrencyTests
    {
        [Test]
        [TestCase("AUD", "AUD", "Australian Dollar")]
        [TestCase("EUR", "EUR", "Euro")]
        [TestCase("GBP", "GBP", "British Pound")]
        [TestCase("gbp", "GBP", "British Pound")]
        [TestCase("USD", "USD", "United States Dollar")]
        [TestCase("Usd", "USD", "United States Dollar")]
        public void ShouldFindByCurrencyCode(string find, string expectedIsoCode, string expectedDisplayName)
        {
            var found = Currency.FromIsoCode(find);
            Assert.That(found.IsoCurrencyCode, Is.EqualTo(expectedIsoCode));
            Assert.That(found.DisplayName, Is.EqualTo(expectedDisplayName));
        }

        [Test]
        [TestCase(null)]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase(" USD")]
        [TestCase("USD  ")]
        [TestCase("CAD")]
        public void ShouldThrowWhenUnsupported(string find)
        {
            Assert.Throws<NotSupportedException>(() => Currency.FromIsoCode(find));
        }

        [Test]
        public void ShouldBeEqual()
        {
            var a = Currency.Usd;
            var b = Currency.FromIsoCode("USD");
            Assert.That(a, Is.EqualTo(b));
            Assert.That(a == b, Is.True);
            Assert.That(a != b, Is.False);
            Assert.That(a.GetHashCode() == b.GetHashCode(), Is.True);
        }

        [Test]
        public void ShouldNotBeEqual()
        {
            var a = Currency.Usd;
            var b = Currency.FromIsoCode("GBP");
            Assert.That(a, Is.Not.EqualTo(b));
            Assert.That(a == b, Is.False);
            Assert.That(a != b, Is.True);
            Assert.That(a.GetHashCode() == b.GetHashCode(), Is.False);
        }

        [Test]
        public void CanConvert()
        {
            var currency = Currency.Usd;
            string s = currency;
            Currency currency2 = s;

            Assert.AreEqual(currency, currency2);
        }
    }
}


text:
`loopback-connector-mysql` is the MySQL connector module for [loopback-datasource-juggler](http://docs.strongloop.com/loopback-datasource-juggler/).

## Installation

````sh
npm install loopback-connector-mysql --save
````

## Usage

To use it you need `loopback-datasource-juggler`.

1. Setup dependencies in `package.json`:

    ```json
    {
      ...
      "dependencies": {
        "loopback-datasource-juggler": "latest",
        "loopback-connector-mysql": "latest"
      },
      ...
    }
    ```

2. Use:

    ```javascript
        var DataSource = require('loopback-datasource-juggler').DataSource;
        var dataSource = new DataSource('mysql', {
            host: 'localhost',
            port: 3306,
            database: 'mydb',
            username: 'myuser',
            password: 'mypass'
        });
    ```
    You can optionally pass a few additional parameters supported by [`node-mysql`](https://github.com/felixge/node-mysql),
    most particularly `password` and `collation`. `Collation` currently defaults
    to `utf8_general_ci`. The `collation` value will also be used to derive the
    connection charset.

## Data type mappings

`loopback-connector-mysql` uses the following rules to map between JSON types and MySQL data types.

### JSON to MySQL types

- String/JSON: VARCHAR
- Text: TEXT
- Number: INT
- Date: DATETIME
- BOOLEAN: TINYINT(1)
- Point/GeoPoint: POINT
- Enum: ENUM

### MySQL to JSON types

- CHAR: String
- CHAR(1): Boolean
- VARCHAR/TINYTEXT/MEDIUMTEXT/LONGTEXT/TEXT/ENUM/SET: String
- TINYBLOB/MEDIUMBLOB/LONGBLOB/BLOB/BINARY/VARBINARY/BIT: Binary
- TINYINT/SMALLINT/INT/MEDIUMINT/YEAR/FLOAT/DOUBLE/NUMERIC/DECIMAL: Number
- DATE/TIMESTAMP/DATETIME: Date

## Using the `dataType` field/column option with MySQL

`loopback-connector-mysql` allows mapping of LoopBack model properties to MYSQL columns using the 'mysql' property of the
 property definition. For example,

    "locationId":{
        "type":"String",
        "required":true,
        "length":20,
        "mysql":
        {
            "columnName":"LOCATION_ID",
            "dataType":"VARCHAR2",
            "dataLength":20,
            "nullable":"N"
        }
    }

`loopback-connector-mysql` also supports using the `dataType` column/property attribute to specify what MySQL column
type is used for many loopback-datasource-juggler types.

The following type-dataType combinations are supported:
- Number
  - integer
    - tinyint
    - smallint
    - mediumint
    - int
    - bigint

     Use the `limit` option to alter the display width.

     Example:
      `{ count : { type: Number, dataType: 'smallInt' }}`

  - floating point types
    - float
    - double

     Use the `precision` and `scale` options to specify custom precision. Default is (16,8).

     Example:
      `{ average : { type: Number, dataType: 'float', precision: 20, scale: 4 }}`

  - fixed-point exact value types
    - decimal
    - numeric

     Use the `precision` and `scale` options to specify custom precision. Default is (9,2).

     These aren't likely to function as true fixed-point.

     Example:
      `{ stdDev : { type: Number, dataType: 'decimal', precision: 12, scale: 8 }}`

- String / DataSource.Text / DataSource.JSON
  - varchar
  - char
  - text
  - mediumtext
  - tinytext
  - longtext

  Example:
   `{ userName : { type: String, dataType: 'char', limit: 24 }}`

  Example:
   `{ biography : { type: String, dataType: 'longtext' }}`

- Date
  - datetime
  - timestamp

  Example:
   `{ startTime : { type: Date, dataType: 'timestamp' }}`

* Enum
  Enums are special.
  Create an Enum using Enum factory:

```javascript
    var MOOD = dataSource.EnumFactory('glad', 'sad', 'mad');
    MOOD.SAD;    // 'sad'
    MOOD(2);     // 'sad'
    MOOD('SAD'); // 'sad'
    MOOD('sad'); // 'sad'
```

  - `{ mood: { type: MOOD }}`
  - `{ choice: { type: dataSource.EnumFactory('yes', 'no', 'maybe'), null: false }}`

## Discovering Models

MySQL data sources allow you to discover model definition information from existing mysql databases. See the following APIs:

 - [dataSource.discoverModelDefinitions([owner], fn)](https://github.com/strongloop/loopback#datasourcediscovermodeldefinitionsusername-fn)
 - [dataSource.discoverSchema([owner], name, fn)](https://github.com/strongloop/loopback#datasourcediscoverschemaowner-name-fn)

### Asynchronous APIs for discovery

* MySQL.prototype.discoverModelDefinitions = function (options, cb)
  - options:
    - all: {Boolean} To include tables/views from all schemas/owners
    - owner/schema: {String} The schema/owner name
    - views: {Boolean} To include views
  - cb:
    - Get a list of table/view names, for example:

        {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' }
        {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }
        {type: 'view', name: 'INVENTORY_VIEW', owner: 'STRONGLOOP' }

* MySQL.prototype.discoverModelProperties = function (table, options, cb)
  - table: {String} The name of a table or view
  - options:
    - owner/schema: {String} The schema/owner name
  - cb:
    - Get a list of model property definitions, for example:

          { owner: 'STRONGLOOP',
            tableName: 'PRODUCT',
            columnName: 'ID',
            dataType: 'VARCHAR2',
            dataLength: 20,
            nullable: 'N',
            type: 'String' }
          { owner: 'STRONGLOOP',
            tableName: 'PRODUCT',
            columnName: 'NAME',
            dataType: 'VARCHAR2',
            dataLength: 64,
            nullable: 'Y',
            type: 'String' }

* MySQL.prototype.discoverPrimaryKeys= function(table, options, cb)
  - table: {String} The name of a table or view
  - options:
    - owner/schema: {String} The schema/owner name
  - cb:
    - Get a list of primary key definitions, for example:

        { owner: 'STRONGLOOP',
          tableName: 'INVENTORY',
          columnName: 'PRODUCT_ID',
          keySeq: 1,
          pkName: 'ID_PK' }
        { owner: 'STRONGLOOP',
          tableName: 'INVENTORY',
          columnName: 'LOCATION_ID',
          keySeq: 2,
          pkName: 'ID_PK' }

* MySQL.prototype.discoverForeignKeys= function(table, options, cb)
  - table: {String} The name of a table or view
  - options:
    - owner/schema: {String} The schema/owner name
  - cb:
    - Get a list of foreign key definitions, for example:

        { fkOwner: 'STRONGLOOP',
          fkName: 'PRODUCT_FK',
          fkTableName: 'INVENTORY',
          fkColumnName: 'PRODUCT_ID',
          keySeq: 1,
          pkOwner: 'STRONGLOOP',
          pkName: 'PRODUCT_PK',
          pkTableName: 'PRODUCT',
          pkColumnName: 'ID' }

* MySQL.prototype.discoverExportedForeignKeys= function(table, options, cb)

  - table: {String} The name of a table or view
  - options:
    - owner/schema: {String} The schema/owner name
  - cb:
    - Get a list of foreign key definitions that reference the primary key of the given table, for example:

        { fkName: 'PRODUCT_FK',
          fkOwner: 'STRONGLOOP',
          fkTableName: 'INVENTORY',
          fkColumnName: 'PRODUCT_ID',
          keySeq: 1,
          pkName: 'PRODUCT_PK',
          pkOwner: 'STRONGLOOP',
          pkTableName: 'PRODUCT',
          pkColumnName: 'ID' }

### Discover/build/try the models

#### Build a LDL schema by discovery

Data sources backed by the MySQL connector can discover LDL models from the database using the `discoverSchema` API. For
example,

    dataSource.discoverSchema('INVENTORY', {owner: 'STRONGLOOP'}, function (err, schema) {
        ...
    }

Here is the sample result. Please note there are 'mysql' properties in addition to the regular LDL model options and
properties. The 'mysql' objects contain the MySQL specific mappings.

    {
      "name":"Inventory",
      "options":{
        "idInjection":false,
        "mysql":{
          "schema":"STRONGLOOP",
          "table":"INVENTORY"
        }
      },
      "properties":{
        "productId":{
          "type":"String",
          "required":false,
          "length":60,
          "precision":null,
          "scale":null,
          "id":1,
          "mysql":{
            "columnName":"PRODUCT_ID",
            "dataType":"varchar",
            "dataLength":60,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"NO"
          }
        },
        "locationId":{
          "type":"String",
          "required":false,
          "length":60,
          "precision":null,
          "scale":null,
          "id":2,
          "mysql":{
            "columnName":"LOCATION_ID",
            "dataType":"varchar",
            "dataLength":60,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"NO"
          }
        },
        "available":{
          "type":"Number",
          "required":false,
          "length":null,
          "precision":10,
          "scale":0,
          "mysql":{
            "columnName":"AVAILABLE",
            "dataType":"int",
            "dataLength":null,
            "dataPrecision":10,
            "dataScale":0,
            "nullable":"YES"
          }
        },
        "total":{
          "type":"Number",
          "required":false,
          "length":null,
          "precision":10,
          "scale":0,
          "mysql":{
            "columnName":"TOTAL",
            "dataType":"int",
            "dataLength":null,
            "dataPrecision":10,
            "dataScale":0,
            "nullable":"YES"
          }
        }
      }
    }

We can also discover and build model classes in one shot. The following example uses `discoverAndBuildModels` to discover,
build and try the models:

    dataSource.discoverAndBuildModels('INVENTORY', { owner: 'STRONGLOOP', visited: {}, associations: true},
         function (err, models) {
            // Show records from the models
            for(var m in models) {
                models[m].all(show);
            };

            // Find one record for inventory
            models.Inventory.findOne({}, function(err, inv) {
                console.log("\nInventory: ", inv);
                // Follow the foreign key to navigate to the product
                inv.product(function(err, prod) {
                    console.log("\nProduct: ", prod);
                    console.log("\n ------------- ");
                });
        });
    }

redpajama_set_name: RedPajamaGithub


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

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

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

    /**
     *

     * List of summaries of edge deployment plans.
     *

     */
    private java.util.List<EdgeDeploymentPlanSummary> edgeDeploymentPlanSummaries;
    /**
     *

     * The token to use when calling the next page of results.
     *

     */
    private String nextToken;

    /**
     *

     * List of summaries of edge deployment plans.
     *

     *
     * @return List of summaries of edge deployment plans.
     */

    public java.util.List<EdgeDeploymentPlanSummary> getEdgeDeploymentPlanSummaries() {
        return edgeDeploymentPlanSummaries;
    }

    /**
     *

     * List of summaries of edge deployment plans.
     *

     *
     * @param edgeDeploymentPlanSummaries
     *        List of summaries of edge deployment plans.
     */

    public void setEdgeDeploymentPlanSummaries(java.util.Collection<EdgeDeploymentPlanSummary> edgeDeploymentPlanSummaries) {
        if (edgeDeploymentPlanSummaries == null) {
            this.edgeDeploymentPlanSummaries = null;
            return;
        }

        this.edgeDeploymentPlanSummaries = new java.util.ArrayList<EdgeDeploymentPlanSummary>(edgeDeploymentPlanSummaries);
    }

    /**
     *

     * List of summaries of edge deployment plans.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setEdgeDeploymentPlanSummaries(java.util.Collection)} or
     * {@link #withEdgeDeploymentPlanSummaries(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param edgeDeploymentPlanSummaries
     *        List of summaries of edge deployment plans.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEdgeDeploymentPlansResult withEdgeDeploymentPlanSummaries(EdgeDeploymentPlanSummary... edgeDeploymentPlanSummaries) {
        if (this.edgeDeploymentPlanSummaries == null) {
            setEdgeDeploymentPlanSummaries(new java.util.ArrayList<EdgeDeploymentPlanSummary>(edgeDeploymentPlanSummaries.length));
        }
        for (EdgeDeploymentPlanSummary ele : edgeDeploymentPlanSummaries) {
            this.edgeDeploymentPlanSummaries.add(ele);
        }
        return this;
    }

    /**
     *

     * List of summaries of edge deployment plans.
     *

     *
     * @param edgeDeploymentPlanSummaries
     *        List of summaries of edge deployment plans.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEdgeDeploymentPlansResult withEdgeDeploymentPlanSummaries(java.util.Collection<EdgeDeploymentPlanSummary> edgeDeploymentPlanSummaries) {
        setEdgeDeploymentPlanSummaries(edgeDeploymentPlanSummaries);
        return this;
    }

    /**
     *

     * The token to use when calling the next page of results.
     *

     *
     * @param nextToken
     *        The token to use when calling the next page of results.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token to use when calling the next page of results.
     *

     *
     * @return The token to use when calling the next page of results.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token to use when calling the next page of results.
     *

     *
     * @param nextToken
     *        The token to use when calling the next page of results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEdgeDeploymentPlansResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEdgeDeploymentPlanSummaries() != null)
            sb.append("EdgeDeploymentPlanSummaries: ").append(getEdgeDeploymentPlanSummaries()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ListEdgeDeploymentPlansResult == false)
            return false;
        ListEdgeDeploymentPlansResult other = (ListEdgeDeploymentPlansResult) obj;
        if (other.getEdgeDeploymentPlanSummaries() == null ^ this.getEdgeDeploymentPlanSummaries() == null)
            return false;
        if (other.getEdgeDeploymentPlanSummaries() != null && other.getEdgeDeploymentPlanSummaries().equals(this.getEdgeDeploymentPlanSummaries()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getEdgeDeploymentPlanSummaries() == null) ? 0 : getEdgeDeploymentPlanSummaries().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListEdgeDeploymentPlansResult clone() {
        try {
            return (ListEdgeDeploymentPlansResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

=cut

package Bio::EnsEMBL::Production::Pipeline::Search::DumpGenomeJson;

use strict;
use warnings;

use base qw/Bio::EnsEMBL::Production::Pipeline::Search::BaseDumpJson/;

use Bio::EnsEMBL::Utils::Exception qw(throw);
use Bio::EnsEMBL::Registry;

use JSON;
use File::Path qw(make_path);
use Bio::EnsEMBL::Production::Search::GenomeFetcher;
use Bio::EnsEMBL::Production::Search::GeneFetcher;
use Bio::EnsEMBL::Production::Search::SequenceFetcher;
use Bio::EnsEMBL::Production::Search::MarkerFetcher;
use Bio::EnsEMBL::Production::Search::LRGFetcher;
use Bio::EnsEMBL::Production::Search::IdFetcher;
use Bio::EnsEMBL::Production::Pipeline::Common::SpeciesFactory qw(has_variation);

use Log::Log4perl qw/:easy/;

sub dump {
    my ($self, $species) = @_;
    if ($species !~ /Ancestral sequences/) {
        my $compara = $self->param('compara');
        if (!defined $compara) {
            $compara = $self->division();
            if (!defined $compara || $compara eq '') {
                $compara = 'multi';
            }
        }
        if (defined $compara) {
            $self->{logger}->info("Using compara $compara");
        }
        # dump the genome file
        $self->{logger}->info("Dumping genome for " . $species);
        my $genome_file = $self->dump_genome($species, $compara);
        $self->{logger}->info("Completed dumping " . $species);

        # figure out output
        $self->dataflow_output_id({
            species     => $species,
            type        => 'core',
            genome_file => $genome_file },
            2);

        $self->dataflow_output_id({
            species     => $species,
            type        => 'otherfeatures',
            genome_file => $genome_file },
            7)
            if (Bio::EnsEMBL::Registry->get_DBAdaptor($species, 'otherfeatures')
            );

        $self->dataflow_output_id({
            species     => $species,
            type        => 'variation',
            genome_file => $genome_file },
            4)
            if ($self->has_variation($species));

        $self->dataflow_output_id({
            species     => $species,
            type        => 'funcgen',
            genome_file => $genome_file },
            6)
            if (Bio::EnsEMBL::Registry->get_DBAdaptor($species, 'funcgen'))
        ;

    } ## end if ( $species !~ /Ancestral sequences/)
    return;
} ## end sub dump

sub dump_genome {
    my ($self, $species, $compara) = @_;
    my $genome;
    if ($compara && $compara ne 'multi') {
        $genome =
            Bio::EnsEMBL::Production::Search::GenomeFetcher->new(-EG => 1)
                ->fetch_genome($species);
    }
    else {
        $genome = Bio::EnsEMBL::Production::Search::GenomeFetcher->new()
            ->fetch_genome($species);
    }
    return $self->write_json($species, 'genome', $genome);
}

1;


text:
<?php

return [
#BUSCADOR
	'searcher' => 'Pesquisar aqui...',

#MENU
    'index' => 'Index',
    'item' => 'Item',
    'contact' => 'Contacto',
	'customer' => 'Clientes',
	'portofolio' => 'Portfolio',
	'service' => 'Serviços',
	'about'=>'About',
	'primetitle'=>'Portugues incredibly beautiful and fully responsive.',
	'primecontent'=>'Portugues, consectetur adipiscing elit. Fusce elementum, nulla vel pellentesque consequat, ante nulla hendrerit arcu, ac tincidunt mauris lacus sed leo. vamus suscipit molestie vestibulum.',

	'empresa' => 'Companhia',
	'filosofia-da-empresa' => 'Filosofia da Empresa',
	'onde-estamos' => 'Onde estamos',
	'fale-connosco' => 'Fale com a gente',
	'trabalhe-connosco' => 'Trabalhe connosco',

#SLIDER
	'slider-text1' => '"As nossas áreas de actuação são, estudos projectos, consultoria e fiscalização.',
	'slider-text2' => 'Temos as competências e experiências necessárias para garantir um trabalho de',
	'slider-text3' => 'excelência. Possuímos especialidades da arquitectura e engenharia. Quadros técnicos',
	'slider-text4' => 'Com o domínio das diferentes especialidades da arquitectura e engenharia."',

	'slider1-text1' => '"visualizamos as ideias dos nossos clientes e traduzimo-las em projectos personalizados."',

	'slider2-text1' => '"nossas equipas multidisciplinares são experientes e especializadas nas diferentes',
	'slider2-text2' => 'competências técnicas da arquitectura e engenharia dimensionadas e organizadas de',
	'slider2-text3' => 'acordo com as características do serviço a prestar e dos requisitos do cliente"',

#CONTENIDO
	'home-dir-title' => 'Inicio',
	'last-project' => 'Últimas Projectos',
	'who-we-are' => 'Quem Somos',
	'who-we-are-text1' => 'A ITEM É UMA EMPRESA DE DIREITO ANGOLANO, COM SEDE EM LUANDA E FILIAL EM MALANJE.
		   	FOI CONCEBIDA COM O OBJECTIVO DE PRESTAR SERVIÇOS DE ARQUITECTURA E DE ENGENHARIA.',
	'read-more' => 'Leia Mais',
	'values' => 'Valores',
	'values-excellence' => 'EXCELÊNCIA',
	'values-text1' => 'Perseguimos incansávelmente, a excelência em tudo o que fazemos, todos os dias.',
	'values-people' => 'PESSOAS',
	'values-text2' => 'Trabalhamos em um ambiente que promove a inclusão, mudanças, novas ideias, respeito pelo indivíduo e oportunidades iguais de sucesso para todos.',
	'values-ssma' => 'SSMA',
	'values-text3' => 'Trabalhamos com segurança de maneira a proteger e promover a saúde e o bem-estar das pessoas e do meio ambiente.',
	'values-integrity' => 'INTEGRIDADE',
	'values-responsibility' => 'RESPONSABILIDADE',
	'values-client' => 'CLIENTE',
	'values-text4' => 'O Alicerce da ITEM é a integridade dos seus funcionários. Somos abertos, francos e confiáveis no relacionamento com clientes, fornecedores, colegas, accionistas e comunidades onde actuamos.',
	'values-text5' => 'Somos responsáveis – individualmente e em equipas – por nossos comportamentos, nossas acções e nossos resultados.',
	'values-text6' => 'É uma pessoa que nos trás os desejos e necessidades. É nossa obrigação lidar com ele de maneira lucrativa para ele e para nós.',
	'what-we-do' => 'O QUE FAZEMOS',
	'view-more' => 'Leia Mais',
	'what-we-do-title1' => 'ESTUDOS E PROJECTOS',
	'what-we-do-title2' => 'CONSULTORIA',
	'what-we-do-title3' => 'FISCALIZAÇÃO',
	'what-we-do-text1' => 'Visualizamos as ideias dos nossos Clientes e traduzimo-las em projectos personalizados.',
	'what-we-do-text2' => 'A ITEM oferece serviços de Vistória Técnica de Projectos e Obras.',
	'what-we-do-text3' => 'Esta é uma actividade essencial na área da construção para cumprir e verificar as directrizes dos projectos.',

#FOOTER
	'newsletter-title' => 'Boletim de Notícias',
	'newsletter-description' => 'Digite seu e-mail e assine nosso boletim informativo.',
	'newsletter-email' => 'Correio Eletrônico',
	'newsletter-button' => 'Subscrever',
	'contact-title' => 'Contacto',
	'contact-field-one' => 'Endereço: Condomínio Mirantes do Talatona Casa D20 – Talatona | Luanda – Angola
',
	'contact-field-two' => 'Telefone: +244 222 019 224
',
	'contact-field-tree' => 'Email: atendimento@itemao.com
',
	'social-tittle' => 'Redes Sociales',
	'copyrigh' => '© Copyright 2017 Item Engineering. Todos os direitos reservados.',

	#REGISTRO EMAIL
	'mss-reg-email' => 'Sucesso! Seu e-mail foi registrado com sucesso.',
	'mss-alert1-email' => 'Atenção! O endereço de e-mail não é válido.',
	'mss-alert2-email' => 'Atenção! Seu e-mail já foi registrado.',

];


text:
---
layout: post
title: max points on a line
cagegory: leetcode
---

{{ page.title }}

  This problem looks so hard.But, it seems that I have seen this some where before. Two monthes before, when we take part in the ACM campus of BUPT, There was a problem looks like this.It was asking that Is there an three points on a same line?

How to resolve these two questions?

These two problems looks different. But actually they are almost same qusetions. While one is asking you to figure out the existance, the other one is asking you to figure out the maxnum.

Solve the easy one first

Obviously, the existance one question is easy. Two points could determine a line, and we just need to find out is there a line appears two or more times. Hashtable is quite suit for this problems. And this problem is resolved.

Harder one seems no longer harder

Come back to this question, it could be resolved by hashtables too. And we need to enumerate each point. For this point put the lines formed with other point into a hashtable, and get the maxnum.

someting mistake I have made

There are duplicate points.

Do not forget add the point itself.

If two line have the same one point, only the k(y=kx+b) is the important thing.

The max of double in CPP is 1.79769e+308

At the begining, I save every points in the hashtable, this is really suck.

code of CPP

{% highlight cpp linenos %}
/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        int n = points.size();
        if ( n == 0 ) {
            return 0;
        }
        map < double , int > kMap;
        kMap.clear();
        int result = 0;
        int same = 0;
        for ( int i = 0; i < n; i++ ) {
            same = 0;
            int count = 0;
            kMap.clear();
            for ( int j = 0; j < n; j++ ) {
                if ( samePoint(points[i],points[j]) ) {
                    same++;
                    continue;
                }
                double k = getK(points[i],points[j]);
                kMap[k] += 1;
                count = max(count,kMap[k]);
            }
            result = max(result,count+same);
        }
        return result;
    }

    bool samePoint( Point p1, Point p2 ) {
        return p1.x == p2.x && p1.y == p2.y;
    }

    double getK( Point p1, Point p2 ) {
        double x = p1.x-p2.x;
        double y = p1.y-p2.y;
        if ( x == 0 ) {
            return 1.79769e+308;
        }
        return y/x;
    }
};
{% endhighlight %}


text:
package com.culabs.unicomportal.dao;

import com.culabs.unicomportal.model.db.DBVolumes;

public interface DBVolumesMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int insert(DBVolumes record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int insertSelective(DBVolumes record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    DBVolumes selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int updateByPrimaryKeySelective(DBVolumes record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int updateByPrimaryKeyWithBLOBs(DBVolumes record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table volumes
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int updateByPrimaryKey(DBVolumes record);
}


text:
DEFAULT_ANYENV_ROOT = '/usr/local/anyenv'.freeze

def run(attributes, username = ENV['USER'])
  init(username)

  clone_anyenv
  clone_anyenv_update

  directory "#{@root_path}/envs"

  install_envs(attributes)
end

private

def scheme
  @scheme ||= node[:anyenv][:scheme] || 'git'
end

def init(username)
  @username = username
  @root_path = ENV['ANYENV_ROOT'] || DEFAULT_ANYENV_ROOT
end

def anyenv_init_with(command)
  <<-"EOS".gsub("\n", ' ')
    export ANYENV_ROOT=#{@root_path};
    export PATH=#{@root_path}/bin:${PATH};
    eval "$(anyenv init -)";
    #{command}
  EOS
end

def clone_repository(install_path, repo_path)
  git install_path do
    user @username if @username
    repository repo_path if repo_path
    not_if "test -d #{install_path}"
  end
end

def clone_anyenv
  repo_path = "#{scheme}://github.com/riywo/anyenv.git"
  clone_repository(@root_path, repo_path)
end

def clone_anyenv_update
  install_path = "#{@root_path}/plugins/anyenv-update"
  repo_path = "#{scheme}://github.com/znz/anyenv-update.git"
  clone_repository(install_path, repo_path)
end

def install_envs(attributes)
  attributes[:install_versions].each do |envs|
    envs.each do |env, vers|
      install_env(env)

      vers.each do |ver|
        install_env_version(env, ver)
      end

      global_version(env, vers.first)
    end
  end
end

def install_env(envname)
  exec = anyenv_init_with <<-EOS
    yes | anyenv install #{envname}
  EOS
  is_exec = anyenv_init_with "type #{envname}"

  execute "install #{envname}" do
    user @username if @username
    command exec
    not_if is_exec
  end
end

def install_env_version(envname, version)
  exec = anyenv_init_with <<-EOS
    yes | #{envname} install #{version}
  EOS
  is_exec = anyenv_init_with "#{envname} versions | grep #{version}"

  execute "#{envname} install #{version}" do
    user @username if @username
    command exec
    not_if is_exec
  end
end

def global_version(envname, version)
  exec = anyenv_init_with <<-EOS
    #{envname} global;
    #{version}; #{envname} rehash;
  EOS
  is_exec = anyenv_init_with "#{envname} versions | grep #{version}"

  execute "#{envname} global #{version}" do
    user @username if @username
    command exec
    not_if is_exec
  end
end


text:
recurrent-title: "Conversation cafe"
recurrent-description: "Drop in and improve your English speaking and listening skills with the help of native and fluent English speakers. £1 including a coffee or tea and a biscuit."
recurrent-day: Fridays
recurrent-times: 1000-1200
recurrent-location: ipswich-county-library
recurrent-location-display-name: Ipswich County Library
recurrent-location-display-url: /branches/ipswich-county-library/
recurrent-category: language-courses
---


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

import java.io.Serializable;
import java.util.List;

import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.context.Context;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

/**
 * @author martin.grofcik
 */
public class ConvertProcessVariable implements JavaDelegate, Serializable {

    @Override
    public void execute(DelegateExecution execution) {
            List<String> list  = (List<String>) execution.getVariable("listVariable");
            ObjectMapper mapper = Context.getProcessEngineConfiguration().getObjectMapper();
            ArrayNode jsonArray = mapper.createArrayNode();
            list.forEach(listItem ->  jsonArray.add(listItem));
            execution.setVariable("listVariable", jsonArray);
    }
}


text:
<!DOCTYPE html>
<title>Flex minimum height with intrinsic min-height specified</title>
<link rel="author" title="dgrogan@chromium.org" href="mailto:dgrogan@chromium.org" />
<link rel="help" href="https://drafts.csswg.org/css-flexbox/#min-size-auto" />
<link rel="help" href="https://drafts.csswg.org/css-sizing-3/#valdef-width-min-content" />
<link rel="match" href="../reference/ref-filled-green-100px-square-only.html" />
<link rel="bookmark" href="https://crbug.com/1088223">
<meta name="assert" content="Flex uses automatic minimum sizes when item specifies min-height:intrinsic, because that is treated as auto.">

Test passes if there is a filled green square.


text:
<?php
namespace NGS\Client;

/**
 * Request object used by {@see NGS\Client\RestHttp}
 */
class HttpRequest
{
    private $uri;
    private $curl;
    private $method;
    private $options;
    private $responseInfo;
    private $responseHeaders;

    public function __construct($uri, $method = null, $body = null, $headers = null, $options = null)
    {
        $this->uri = $uri;
        $this->curl = curl_init($uri);

        $this->options = array(
            CURLOPT_RETURNTRANSFER  => true,
            CURLINFO_HEADER_OUT     => true,
        );

        if (is_array($options)) {
            $this->options += $options;
        }

        $this->method = $method;

        if($method !== null)
            $this->method($method);
        if($body !== null)
            $this->body($body);
        if($headers !== null)
            $this->headers($headers);
    }

    public function headers($headers)
    {
        if(!isset($this->options[CURLOPT_HTTPHEADER]))
            $this->options[CURLOPT_HTTPHEADER] = array();

        if(is_array($headers)) {
            foreach($headers as $key => $value)
                $this->options[CURLOPT_HTTPHEADER][] = $value;
        }
        else if(is_string($headers)) {
            $this->options[CURLOPT_HTTPHEADER][] = $headers;
        }
        return $this;
    }

    public function method($method)
    {
        $method = strtoupper($method);
        if ($method === 'POST') {
            $this->options[CURLOPT_POST] = true;
        } else {
            $this->options[CURLOPT_CUSTOMREQUEST] = $method;
        }
        return $this;
    }

    public function body($body)
    {
        $this->options[CURLOPT_POSTFIELDS] = $body;
    }

    public function send()
    {
        curl_setopt_array($this->curl, $this->options);

        $response = curl_exec($this->curl);
        $this->responseInfo = curl_getinfo($this->curl);

        return $response;
    }

    public function getResponseInfo()
    {
        return $this->responseInfo;
    }

    public function getResponseHeaders()
    {
        return $this->getResponseInfo();
    }

    public function getResponseCode()
    {
        return isset($this->responseInfo['http_code']) ? $this->responseInfo['http_code'] : null;
    }

    public function getResponseContentType()
    {
        return isset($this->responseInfo['content_type']) ? $this->responseInfo['content_type'] : null;
    }

    public function getError()
    {
        $error = curl_error($this->curl);
        return $error ? $error : null;
    }

    public function __toString()
    {
        $headers = isset($this->options[CURLOPT_HTTPHEADER]) ? $this->options[CURLOPT_HTTPHEADER] : array();
        $body = isset($this->options[CURLOPT_POSTFIELDS]) ? $this->options[CURLOPT_POSTFIELDS] : '';
        return strtoupper($this->method).' '.$this->uri."\n"
            .implode("\n", $headers)."\n"
            .$body;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/markpovlsen/Documents/iotivity/android/examples/provisioningclient/src/main/res/values/dimens.xml -->
    <eat-comment/>
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <!-- From: file:/home/markpovlsen/Documents/iotivity/android/examples/provisioningclient/src/main/res/values/strings.xml -->
    <eat-comment/>
    <string name="action_settings">Settings</string>
    <string name="app_name">Provisioning Client</string>
    <string name="hello_world">Hello world!</string>
    <!-- From: file:/home/markpovlsen/Documents/iotivity/android/examples/provisioningclient/src/main/res/values/styles.xml -->
    <eat-comment/>
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>
</resources>


text:
package nl.knaw.huygens.timbuctoo.model.properties;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.control.Try;
import nl.knaw.huygens.timbuctoo.model.properties.converters.Converter;
import nl.knaw.huygens.timbuctoo.model.properties.converters.HasOptions;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.Optional;

public class LocalProperty extends ReadableProperty {
  private static final Logger LOG = LoggerFactory.getLogger(ReadableProperty.class);
  public static final String DATABASE_PROPERTY_NAME = "dbName";
  public static final String OPTIONS_PROPERTY_NAME = "options";

  private final String propName;
  private final Converter converter;

  public LocalProperty(String propName, Converter converter) {
    super(() -> __.<Object, String>values(propName).map(prop -> Try.of(() -> converter.tinkerpopToJson(prop.get()))),
      () -> __.values(propName).map(prop -> Try.of(prop::get)));
    this.propName = propName;
    this.converter = converter;
  }

  public String getDatabasePropertyName() {
    return propName;
  }

  public Optional<Collection<String>> getOptions() {
    if (converter instanceof HasOptions) {
      return Optional.of(((HasOptions) converter).getOptions());
    } else {
      return Optional.empty();
    }
  }

  public Optional<Collection<String>> getParts() {
    if (converter instanceof HasParts) {
      return Optional.of(((HasParts) converter).getParts());
    } else {
      return Optional.empty();
    }
  }

  public void setJson(Vertex vertex, JsonNode value) throws IOException {
    if (value == null) {
      vertex.property(propName).remove();
    } else {
      vertex.property(propName, converter.jsonToTinkerpop(value));
    }
  }

  public void setValue(Vertex vertex, Object value) throws IOException {
    converter.validate(value);
    if (value == null) {
      vertex.property(propName).remove();
    } else {
      vertex.property(propName, value);
    }
  }

  @Override
  public String getTypeId() {
    return converter.getGuiTypeId();
  }

  @Override
  public String getUniqueTypeId() {
    return converter.getUniqueTypeIdentifier();
  }

  @Override
  public Vertex save(Graph graph, String clientPropertyName) {
    Vertex propertyVertex = super.save(graph, clientPropertyName);

    propertyVertex.property(DATABASE_PROPERTY_NAME, propName);

    if (converter instanceof HasOptions) {
      try {
        propertyVertex.property(OPTIONS_PROPERTY_NAME,
          new ObjectMapper().writeValueAsString(((HasOptions) converter).getOptions()));
      } catch (JsonProcessingException e) {
        LOG.error("Failed to write options to database for property {}", propName);
      }
    }
    return propertyVertex;
  }
}


text:
package com.polidea.rxandroidble.internal.operations;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;

import com.polidea.rxandroidble.RxBleConnection;
import com.polidea.rxandroidble.internal.RxBleRadioOperation;
import com.polidea.rxandroidble.internal.connection.RxBleGattCallback;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

import static rx.Observable.just;

public class RxBleRadioOperationDisconnect extends RxBleRadioOperation<Void> {

    private static final int TIMEOUT_DISCONNECT = 10;
    private final RxBleGattCallback rxBleGattCallback;
    private final AtomicReference<BluetoothGatt> bluetoothGattAtomicReference;
    private final BluetoothManager bluetoothManager;

    public RxBleRadioOperationDisconnect(RxBleGattCallback rxBleGattCallback, AtomicReference<BluetoothGatt> bluetoothGattAtomicReference,
                                         BluetoothManager bluetoothManager) {
        this.rxBleGattCallback = rxBleGattCallback;
        this.bluetoothGattAtomicReference = bluetoothGattAtomicReference;
        this.bluetoothManager = bluetoothManager;
    }

    @Override
    public void run() {
        //noinspection Convert2MethodRef
        just(bluetoothGattAtomicReference.get())
                .filter(bluetoothGatt -> bluetoothGatt != null)
                .flatMap(bluetoothGatt -> isDisconnected(bluetoothGatt) ? just(bluetoothGatt) : disconnect(bluetoothGatt))
                .doOnTerminate(() -> releaseRadio())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        bluetoothGatt -> bluetoothGatt.close(),
                        throwable -> onError(throwable),
                        () -> onCompleted()
                );
    }

    private boolean isDisconnected(BluetoothGatt bluetoothGatt) {
        return bluetoothManager.getConnectionState(bluetoothGatt.getDevice(), BluetoothProfile.GATT) == BluetoothProfile.STATE_DISCONNECTED;
    }

    /**
     * TODO: [DS] 09.02.2016 This operation makes the radio to block until disconnection - maybe it would be better if it would not?
     * What would happen then if a consecutive call to BluetoothDevice.connectGatt() would be made? What BluetoothGatt would be returned?
     * 1. A completely fresh BluetoothGatt - would work with the current flow
     * 2. The same BluetoothGatt - in this situation we should probably cancel the pending BluetoothGatt.close() call
     */
    private Observable<BluetoothGatt> disconnect(BluetoothGatt bluetoothGatt) {
        return Observable.create(subscriber -> {
            //noinspection Convert2MethodRef
            rxBleGattCallback
                    .getOnConnectionStateChange()
                            // It should never happen because if connection was never acquired then it will complete earlier.
                            // Just in case timeout here.
                    .timeout(TIMEOUT_DISCONNECT, TimeUnit.SECONDS, just(RxBleConnection.RxBleConnectionState.DISCONNECTED))
                    .filter(rxBleConnectionState -> rxBleConnectionState == RxBleConnection.RxBleConnectionState.DISCONNECTED)
                    .take(1)
                    .map(rxBleConnectionState -> bluetoothGatt)
                    .subscribe(subscriber);

            bluetoothGatt.disconnect();
        });
    }
}


text:
import { URL } from "./http";
import { Headers } from "./headers";

export class InvalidHost extends Error {
}

export class Host {
    url: URL;
    headers: Headers;

    constructor (url: URL, headers?: Headers) {
        this.url = url;

        // Validate that the URL looks vaguely sane as an absolute URL.
        // This helps protect everything downstream.
        const regex = /^(https?):\/\/(.+)$/;
        if (!url.match(regex)) {
            throw new InvalidHost(
                `can't create Host with malformed URL: ${url}`,
            );
        }
        this.headers = headers || new Headers();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boletín de la Soc. Ciencias de Córdoba 29(2-3): 122 (1926)

#### Original name
Marasmius coprophilus Speg.

### Remarks
null


text:
package dao

import (
	"go-common/app/job/main/identify/conf"
	"go-common/library/cache/memcache"
	xsql "go-common/library/database/sql"
)

// Dao dao
type Dao struct {
	c      *conf.Config
	authDB *xsql.DB
	authMC *memcache.Pool
}

// New init mysql db
func New(c *conf.Config) (dao *Dao) {
	dao = &Dao{
		c:      c,
		authDB: xsql.NewMySQL(c.AuthDB),
		authMC: memcache.NewPool(c.AuthMC),
	}
	return
}

// Close close the resource.
func (d *Dao) Close() {
	d.authDB.Close()
}


text:
<?php
class general_controller extends Controller
{
    protected function is_logined()
    {
        if(isset($_SESSION['USER']['USER_ID'])) return $_SESSION['USER']['USER_ID'];
        die(json_encode(array('status' => 'unlogined', 'msg' => '您还未登陆或登录超时')));
    }
}


text:
<?php

namespace Klarna\Rest\Tests\Component\OrderManagement;

use GuzzleHttp\Message\Response;
use GuzzleHttp\Stream\Stream;
use Klarna\Rest\OrderManagement\Capture;
use Klarna\Rest\OrderManagement\Order;
use Klarna\Rest\Tests\Component\ResourceTestCase;
use Klarna\Rest\Transport\Connector;

/**
 * Component test cases for the order resource.
 */
class OrderTest extends ResourceTestCase
{
    /**
     * Make sure that the request sent and retrieved data is correct when fetching
     * the order.
     *
     * @return void
     */
    public function testFetch()
    {
        $json = <<<JSON
{
    "order_id": "0002",
    "updated": "from json",
    "captures": [
        {
            "capture_id": "1002",
            "test": "data"
        }
    ]
}
JSON;

        $this->mock->addResponse(
            new Response(
                200,
                ['Content-Type' => 'application/json'],
                Stream::factory($json)
            )
        );

        $order = new Order($this->connector, '0002');
        $order['updated'] = 'not from json';

        $order->fetch();

        $this->assertEquals('from json', $order['updated']);
        $this->assertEquals('0002', $order->getId());

        $request = $this->history->getLastRequest();
        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals('/ordermanagement/v1/orders/0002', $request->getPath());

        $this->assertAuthorization($request);

        $capture = $order['captures'][0];
        $this->assertInstanceOf('Klarna\Rest\OrderManagement\Capture', $capture);
        $this->assertEquals($capture->getId(), $capture['capture_id']);
        $this->assertEquals('1002', $capture->getId());
        $this->assertEquals('data', $capture['test']);
    }

    /**
     * Make sure that the request sent is correct when acknowledging an order.
     *
     * @return void
     */
    public function testAcknowledge()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->acknowledge();

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/acknowledge',
            $request->getPath()
        );

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when cancelling an order.
     *
     * @return void
     */
    public function testCancel()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->cancel();

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/cancel',
            $request->getPath()
        );

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when extending authorization time.
     *
     * @return void
     */
    public function testExtendAuthorizationTime()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->extendAuthorizationTime();

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/extend-authorization-time',
            $request->getPath()
        );

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when releasing remaining
     * authorization.
     *
     * @return void
     */
    public function testReleaseRemainingAuthorization()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->releaseRemainingAuthorization();

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/release-remaining-authorization',
            $request->getPath()
        );

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when updating authorization.
     *
     * @return void
     */
    public function testUpdateAuthorization()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->updateAuthorization(['data' => 'sent in']);

        $request = $this->history->getLastRequest();
        $this->assertEquals('PATCH', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/authorization',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"sent in"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when updating merchant references.
     *
     * @return void
     */
    public function testUpdateMerchantReferences()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->updateMerchantReferences(['data' => 'sent in']);

        $request = $this->history->getLastRequest();
        $this->assertEquals('PATCH', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/merchant-references',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"sent in"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when updating customer details.
     *
     * @return void
     */
    public function testUpdateCustomerDetails()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->updateCustomerDetails(['data' => 'sent in']);

        $request = $this->history->getLastRequest();
        $this->assertEquals('PATCH', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/customer-details',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"sent in"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when performing a refund.
     *
     * @return void
     */
    public function testRefund()
    {
        $this->mock->addResponse(new Response(204));

        $order = new Order($this->connector, '0002');
        $order->refund(['data' => 'sent in']);

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/refunds',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"sent in"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct when performing a refund.
     *
     * @return void
     */
    public function testRefund201()
    {
        $this->mock->addResponse(new Response(201));

        $order = new Order($this->connector, '0002');
        $order->refund(['data' => 'sent in']);

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/refunds',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"sent in"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent is correct and that the location is updated
     * when creating an order.
     *
     * @return void
     */
    public function testCreateCapture()
    {
        $this->mock->addResponse(
            new Response(201, ['Location' => 'http://somewhere/a-path'])
        );

        $order = new Order($this->connector, '0002');
        $capture = $order->createCapture(['data' => 'goes here']);

        $this->assertInstanceOf('Klarna\Rest\OrderManagement\Capture', $capture);
        $this->assertEquals('http://somewhere/a-path', $capture->getLocation());

        $request = $this->history->getLastRequest();
        $this->assertEquals('POST', $request->getMethod());
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/captures',
            $request->getPath()
        );

        $this->assertEquals('application/json', $request->getHeader('Content-Type'));
        $this->assertEquals('{"data":"goes here"}', strval($request->getBody()));

        $this->assertAuthorization($request);
    }

    /**
     * Make sure that the request sent and retrieved data is correct when fetching
     * a capture.
     *
     * @return void
     */
    public function testFetchCapture()
    {
        $json = <<<JSON
{
    "capture_id": "1002",
    "updated": "from json"
}
JSON;

        $this->mock->addResponse(
            new Response(
                200,
                ['Content-Type' => 'application/json'],
                Stream::factory($json)
            )
        );

        $order = new Order($this->connector, '0002');

        $capture = $order->fetchCapture('1002');
        $this->assertInstanceOf('Klarna\Rest\OrderManagement\Capture', $capture);
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/captures/1002',
            $capture->getLocation()
        );

        $this->assertEquals('from json', $capture['updated']);
        $this->assertEquals('1002', $capture->getId());
        $this->assertEquals($capture->getId(), $capture['capture_id']);
    }

    /**
     * Make sure that the request sent and retrieved data is correct when fetching
     * a capture that exists in the captures list.
     *
     * @return void
     */
    public function testFetchCaptureExisting()
    {
        $json = <<<JSON
{
    "capture_id": "1002",
    "updated": "from json"
}
JSON;

        $this->mock->addResponse(
            new Response(
                200,
                ['Content-Type' => 'application/json'],
                Stream::factory($json)
            )
        );

        $order = new Order($this->connector, '0002');

        $capture = new Capture($this->connector, $order->getLocation(), '1002');
        $capture['capture_id'] = '1002';
        $capture['updated'] = 'not from json';

        $order['captures'][] = $capture;

        $capture = $order->fetchCapture('1002');
        $this->assertInstanceOf('Klarna\Rest\OrderManagement\Capture', $capture);
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/captures/1002',
            $capture->getLocation()
        );

        $this->assertEquals('from json', $capture['updated']);
        $this->assertEquals('1002', $capture->getId());
        $this->assertEquals($capture->getId(), $capture['capture_id']);
    }

    /**
     * Make sure that the request sent and retrieved data is correct when fetching
     * a capture that is not already in the captures list.
     *
     * @return void
     */
    public function testFetchCaptureNew()
    {
        $json = <<<JSON
{
    "capture_id": "1003",
    "updated": "from json"
}
JSON;

        $this->mock->addResponse(
            new Response(
                200,
                ['Content-Type' => 'application/json'],
                Stream::factory($json)
            )
        );

        $order = new Order($this->connector, '0002');

        $capture = new Capture($this->connector, $order->getLocation(), '1002');
        $capture['capture_id'] = '1002';
        $capture['updated'] = 'not from json';

        $order['captures'][] = $capture;

        $capture = $order->fetchCapture('1003');
        $this->assertInstanceOf('Klarna\Rest\OrderManagement\Capture', $capture);
        $this->assertEquals(
            '/ordermanagement/v1/orders/0002/captures/1003',
            $capture->getLocation()
        );

        $this->assertEquals('from json', $capture['updated']);
        $this->assertEquals('1003', $capture->getId());
        $this->assertEquals($capture->getId(), $capture['capture_id']);
    }
}


text:
<?php

namespace SabreForRainLoop\DAV\Exception;

class BadRequest extends \SabreForRainLoop\DAV\Exception {

    /**
     * Returns the HTTP statuscode for this exception
     *
     * @return int
     */
    public function getHTTPCode() {

        return 400;

    }

}


text:
#!/bin/bash

typeset __abspath=$(cd ${0%/*} && echo $PWD/${0##*/})
typeset __shelldir=`dirname "${__abspath}"`
typeset __testdir=`dirname "${__shelldir}"`
typeset __tmp=`mktemp /tmp/avn-test.XXXXXX`
typeset __written=""
export HOME="${__testdir}/fixtures"

# start in a known location
cd "${__testdir}/fixtures/home"

function _avn() {
  echo avn called >> ${__tmp}
}

source "${__shelldir}/helpers.sh"
source "${__testdir}/../bin/avn.sh"

# test that _avn isn't invoked when .node-version file isn't there
cd "${__testdir}/fixtures/none"
__written=`echo $(cat ${__tmp})`

assertEqual `pwd` "${__testdir}/fixtures/none" || exit 1
assertEqual "" "${__written}" || exit 1

rm ${__tmp}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 16(1): 20 (1924)

#### Original name
Russula subtilis Burl.

### Remarks
null


text:
package org.corundummc.biomes.overworld.arboreal.forest;

import org.corundummc.biomes.interfaces.instances.MutatedBiome;
import org.corundummc.biomes.interfaces.types.MutatedBiomeType;
import org.corundummc.world.Location;

import org.corundummc.biomes.overworld.arboreal.forest.ForestBiome.ForestBiomeType;
import org.corundummc.biomes.overworld.arboreal.forest.ForestedBiome.ForestedBiomeType;

import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.BiomeGenMutated;

public class FlowerForestBiome extends ForestedBiome<FlowerForestBiome, BiomeGenMutated, FlowerForestBiome.FlowerForestBiomeType> implements MutatedBiome<ForestBiomeType> {
    protected FlowerForestBiome(Location location) {
        super(location);
    }

    /** This class represents one single {@link BiomeType}; classes like this are used instead of
     * simple instances of their parent types because of the self-parameterization <tt>S</tt>. */
    static class FlowerForestBiomeType extends ForestedBiomeType<FlowerForestBiomeType, BiomeGenMutated, FlowerForestBiome> implements MutatedBiomeType<ForestBiomeType> {
        public static final FlowerForestBiomeType TYPE = new FlowerForestBiomeType();

        private FlowerForestBiomeType() {
            super((BiomeGenMutated) BiomeGenBase.getBiome(132));
        }

        @Override
        public FlowerForestBiome fromLocation(Location location) {
            return new FlowerForestBiome(location);
        }

        @Override
        public ForestBiomeType getBase() {
            return ForestBiomeType.TYPE;
        }
    }

    @Override
    public ForestBiomeType getBaseType() {
        return getType().getBase();
    }

    @Override
    public FlowerForestBiomeType getType() {
        return FlowerForestBiomeType.TYPE;
    }
}


text:
"""This module contains base classes for DREST."""

from dynamic_rest.utils import model_from_definition

class DynamicSerializerBase(object):

    """Base class for all DREST serializers."""
    pass

def resettable_cached_property(func):
    """Decorator to add cached computed properties to an object.
    Similar to Django's `cached_property` decorator, except stores
    all the data under a single well-known key so that it can easily
    be blown away.
    """

    def wrapper(self):
        if not hasattr(self, '_resettable_cached_properties'):
            self._resettable_cached_properties = {}
        if func.__name__ not in self._resettable_cached_properties:
            self._resettable_cached_properties[func.__name__] = func(self)
        return self._resettable_cached_properties[func.__name__]

    # Returns a property whose getter is the 'wrapper' function
    return property(wrapper)

def cacheable_object(cls):
    """Decorator to add a reset() method that clears data cached by
    the @resettable_cached_property decorator. Technically this could
    be a mixin...
    """

    def reset(self):
        if hasattr(self, '_resettable_cached_properties'):
            self._resettable_cached_properties = {}

    cls.reset = reset
    return cls

@cacheable_object
class CacheableFieldMixin(object):
    """Overide Field.root and Field.context to make fields/serializers
    cacheable and reusable. The DRF version uses @cached_property which
    doesn't have a public API for resetting. This version uses normal
    object variables with and adds a `reset()` API.
    """

    @resettable_cached_property
    def root(self):
        root = self
        while root.parent is not None:
            root = root.parent
        return root

    @resettable_cached_property
    def context(self):
        return getattr(self.root, '_context', {})

class GetModelMixin(object):
    """
    Mixin to retrieve model hashid

    Implementation from
    https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
    """

    def __init__(self, *args, **kwargs):
        self.model = kwargs.pop('model', None)
        super(GetModelMixin, self).__init__(*args, **kwargs)

    def get_model(self):
        """
        Return the model to generate the HashId for.

        By default, this will equal the model defined within the Meta of the
        ModelSerializer, but can be redefined either during initialisation
        of the Field, or by providing a get_<field_name>_model method on the
        parent serializer.

        The Meta can either explicitly define a model, or provide a
        dot-delimited string path to it.
        """
        if self.model is None:
            custom_fn_name = 'get_{0}_model'.format(self.field_name)

            if hasattr(self.parent, custom_fn_name):
                return getattr(self.parent, custom_fn_name)()
            else:
                try:
                    return self.parent.Meta.model
                except AttributeError:
                    raise AssertionError(
                        'No "model" value passed to field "{0}"'.format(
                            type(self).__name__
                        )
                    )
        elif isinstance(self.model, str):
            return model_from_definition(self.model)
        else:
            return self.model


text:
| [home](README.md) | [boolean logic](boolean_logic.md) | [integer arithmetic](integer_arithmetic.md) | [channeling constraints](channeling.md) | [scheduling](scheduling.md) | [Using the CP-SAT solver](solver.md) | [Model manipulation](model.md) | [Python API](https://google.github.io/or-tools/python/ortools/sat/python/cp_model.html) |
| ----------------- | --------------------------------- | ------------------------------------------- | --------------------------------------- | --------------------------- | ------------------------------------ | ------------------------------ | -------------------------------- |

# Channeling constraints

https://developers.google.com/optimization/

<!--ts-->
* [Channeling constraints](#channeling-constraints)
   * [If-Then-Else expressions](#if-then-else-expressions)
      * [Python code](#python-code)
      * [C++ code](#c-code)
      * [Java code](#java-code)
      * [C# code](#c-code-1)
   * [A bin-packing problem](#a-bin-packing-problem)
      * [Python code](#python-code-1)
      * [C++ code](#c-code-2)
      * [Java code](#java-code-1)
      * [C# code](#c-code-3)

<!--te-->

A *channeling constraint* links variables inside a model. They're used when you
want to express a complicated relationship between variables, such as "if this
variable satisfies a condition, force another variable to a particular value".

Channeling is usually implemented using *half-reified* linear constraints: one
constraint implies another (a → b), but not necessarily the other way
around (a ← b).

## If-Then-Else expressions

Let's say you want to implement the following: "If *x* is less than 5, set *y*
to 0. Otherwise, set *y* to 10-*x*". You can do this creating an intermediate
boolean variable *b* that is true if *x* is greater than or equal to 5, and
false otherwise:

*b* implies *y* == 10 - *x*

not(*b*) implies *y* == 0

These are implemented using the `OnlyEnforceIf` method as shown below.

### Python code

```python
"""Link integer constraints together."""

from ortools.sat.python import cp_model

class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
  """Print intermediate solutions."""

  def __init__(self, variables):
    cp_model.CpSolverSolutionCallback.__init__(self)
    self.__variables = variables
    self.__solution_count = 0

  def on_solution_callback(self):
    self.__solution_count += 1
    for v in self.__variables:
      print('%s=%i' % (v, self.Value(v)), end=' ')
    print()

  def solution_count(self):
    return self.__solution_count

def ChannelingSampleSat():
  """Demonstrates how to link integer constraints together."""

  # Create the CP-SAT model.
  model = cp_model.CpModel()

  # Declare our two primary variables.
  x = model.NewIntVar(0, 10, 'x')
  y = model.NewIntVar(0, 10, 'y')

  # Declare our intermediate boolean variable.
  b = model.NewBoolVar('b')

  # Implement b == (x >= 5).
  model.Add(x >= 5).OnlyEnforceIf(b)
  model.Add(x < 5).OnlyEnforceIf(b.Not())

  # Create our two half-reified constraints.
  # First, b implies (y == 10 - x).
  model.Add(y == 10 - x).OnlyEnforceIf(b)
  # Second, not(b) implies y == 0.
  model.Add(y == 0).OnlyEnforceIf(b.Not())

  # Search for x values in increasing order.
  model.AddDecisionStrategy([x], cp_model.CHOOSE_FIRST,
                            cp_model.SELECT_MIN_VALUE)

  # Create a solver and solve with a fixed search.
  solver = cp_model.CpSolver()

  # Force the solver to follow the decision strategy exactly.
  solver.parameters.search_branching = cp_model.FIXED_SEARCH
  # Enumerate all solutions.
  solver.parameters.enumerate_all_solutions = True

  # Search and print out all solutions.
  solution_printer = VarArraySolutionPrinter([x, y, b])
  solver.Solve(model, solution_printer)

ChannelingSampleSat()
```

### C++ code

```cpp
#include <stdlib.h>

#include "ortools/base/logging.h"
#include "absl/types/span.h"
#include "ortools/sat/cp_model.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_solver.h"
#include "ortools/sat/model.h"
#include "ortools/sat/sat_parameters.pb.h"

namespace operations_research {
namespace sat {

void ChannelingSampleSat() {
  // Create the CP-SAT model.
  CpModelBuilder cp_model;

  // Declare our two primary variables.
  const IntVar x = cp_model.NewIntVar({0, 10});
  const IntVar y = cp_model.NewIntVar({0, 10});

  // Declare our intermediate boolean variable.
  const BoolVar b = cp_model.NewBoolVar();

  // Implement b == (x >= 5).
  cp_model.AddGreaterOrEqual(x, 5).OnlyEnforceIf(b);
  cp_model.AddLessThan(x, 5).OnlyEnforceIf(Not(b));

  // Create our two half-reified constraints.
  // First, b implies (y == 10 - x).
  cp_model.AddEquality(x + y, 10).OnlyEnforceIf(b);
  // Second, not(b) implies y == 0.
  cp_model.AddEquality(y, 0).OnlyEnforceIf(Not(b));

  // Search for x values in increasing order.
  cp_model.AddDecisionStrategy({x}, DecisionStrategyProto::CHOOSE_FIRST,
                               DecisionStrategyProto::SELECT_MIN_VALUE);

  // Create a solver and solve with a fixed search.
  Model model;
  SatParameters parameters;
  parameters.set_search_branching(SatParameters::FIXED_SEARCH);
  parameters.set_enumerate_all_solutions(true);
  model.Add(NewSatParameters(parameters));
  model.Add(NewFeasibleSolutionObserver([&](const CpSolverResponse& r) {
    LOG(INFO) << "x=" << SolutionIntegerValue(r, x)
              << " y=" << SolutionIntegerValue(r, y)
              << " b=" << SolutionBooleanValue(r, b);
  }));
  SolveCpModel(cp_model.Build(), &model);
}

}  // namespace sat
}  // namespace operations_research

int main() {
  operations_research::sat::ChannelingSampleSat();

  return EXIT_SUCCESS;
}
```

### Java code

```java
package com.google.ortools.sat.samples;

import com.google.ortools.Loader;
import com.google.ortools.sat.DecisionStrategyProto;
import com.google.ortools.sat.SatParameters;
import com.google.ortools.sat.BoolVar;
import com.google.ortools.sat.CpModel;
import com.google.ortools.sat.CpSolver;
import com.google.ortools.sat.CpSolverSolutionCallback;
import com.google.ortools.sat.IntVar;
import com.google.ortools.sat.LinearExpr;

/** Link integer constraints together. */
public class ChannelingSampleSat {
  public static void main(String[] args) throws Exception {
    Loader.loadNativeLibraries();
    // Create the CP-SAT model.
    CpModel model = new CpModel();

    // Declare our two primary variables.
    IntVar[] vars = new IntVar[] {model.newIntVar(0, 10, "x"), model.newIntVar(0, 10, "y")};

    // Declare our intermediate boolean variable.
    BoolVar b = model.newBoolVar("b");

    // Implement b == (x >= 5).
    model.addGreaterOrEqual(vars[0], 5).onlyEnforceIf(b);
    model.addLessOrEqual(vars[0], 4).onlyEnforceIf(b.not());

    // Create our two half-reified constraints.
    // First, b implies (y == 10 - x).
    model.addEquality(LinearExpr.sum(vars), 10).onlyEnforceIf(b);
    // Second, not(b) implies y == 0.
    model.addEquality(vars[1], 0).onlyEnforceIf(b.not());

    // Search for x values in increasing order.
    model.addDecisionStrategy(
        new IntVar[] {vars[0]},
        DecisionStrategyProto.VariableSelectionStrategy.CHOOSE_FIRST,
        DecisionStrategyProto.DomainReductionStrategy.SELECT_MIN_VALUE);

    // Create the solver.
    CpSolver solver = new CpSolver();

    // Force the solver to follow the decision strategy exactly.
    solver.getParameters().setSearchBranching(SatParameters.SearchBranching.FIXED_SEARCH);
    // Tell the solver to enumerate all solutions.
    solver.getParameters().setEnumerateAllSolutions(true);

    // Solve the problem with the printer callback.
    solver.solve(
        model,
        new CpSolverSolutionCallback() {
          public CpSolverSolutionCallback init(IntVar[] variables) {
            variableArray = variables;
            return this;
          }

          @Override
          public void onSolutionCallback() {
            for (IntVar v : variableArray) {
              System.out.printf("%s=%d ", v.getName(), value(v));
            }
            System.out.println();
          }

          private IntVar[] variableArray;
        }.init(new IntVar[] {vars[0], vars[1], b}));
  }
}
```

### C\# code

```cs
using System;
using Google.OrTools.Sat;
using Google.OrTools.Util;

public class VarArraySolutionPrinter : CpSolverSolutionCallback
{
    public VarArraySolutionPrinter(IntVar[] variables)
    {
        variables_ = variables;
    }

    public override void OnSolutionCallback()
    {
        {
            foreach (IntVar v in variables_)
            {
                Console.Write(String.Format("{0}={1} ", v.ToString(), Value(v)));
            }
            Console.WriteLine();
        }
    }

    private IntVar[] variables_;
}

public class ChannelingSampleSat
{
    static void Main()
    {
        // Create the CP-SAT model.
        CpModel model = new CpModel();

        // Declare our two primary variables.
        IntVar x = model.NewIntVar(0, 10, "x");
        IntVar y = model.NewIntVar(0, 10, "y");

        // Declare our intermediate boolean variable.
        BoolVar b = model.NewBoolVar("b");

        // Implement b == (x >= 5).
        model.Add(x >= 5).OnlyEnforceIf(b);
        model.Add(x < 5).OnlyEnforceIf(b.Not());

        // Create our two half-reified constraints.
        // First, b implies (y == 10 - x).
        model.Add(y == 10 - x).OnlyEnforceIf(b);
        // Second, not(b) implies y == 0.
        model.Add(y == 0).OnlyEnforceIf(b.Not());

        // Search for x values in increasing order.
        model.AddDecisionStrategy(new IntVar[] { x }, DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst,
                                  DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue);

        // Create the solver.
        CpSolver solver = new CpSolver();

        // Force solver to follow the decision strategy exactly.
        // Tell the solver to search for all solutions.
        solver.StringParameters = "search_branching:FIXED_SEARCH, enumerate_all_solutions:true";

        VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, b });
        solver.Solve(model, cb);
    }
}
```

This displays the following:

```
x=0 y=0 b=0
x=1 y=0 b=0
x=2 y=0 b=0
x=3 y=0 b=0
x=4 y=0 b=0
x=5 y=5 b=1
x=6 y=4 b=1
x=7 y=3 b=1
x=8 y=2 b=1
x=9 y=1 b=1
x=10 y=0 b=1
```

## A bin-packing problem

As another example of a channeling constraint, consider a bin packing problem in
which one part of the model computes the load of each bin, while another
maximizes the number of bins under a given threshold. To implement this, you can
*channel* the load of each bin into a set of boolean variables, each indicating
whether it's under the threshold.

To make this more concrete, let's say you have 10 bins of capacity 100, and
items to pack into the bins. You would like to maximize the number of bins that
can accept one emergency load of size 20.

To do this, you need to maximize the number of bins that have a load less
than 80.  In the code below, channeling is used to link the *load* and *slack*
variables together:

### Python code

```python
"""Solves a binpacking problem using the CP-SAT solver."""

from ortools.sat.python import cp_model

def BinpackingProblemSat():
  """Solves a bin-packing problem using the CP-SAT solver."""
  # Data.
  bin_capacity = 100
  slack_capacity = 20
  num_bins = 5
  all_bins = range(num_bins)

  items = [(20, 6), (15, 6), (30, 4), (45, 3)]
  num_items = len(items)
  all_items = range(num_items)

  # Model.
  model = cp_model.CpModel()

  # Main variables.
  x = {}
  for i in all_items:
    num_copies = items[i][1]
    for b in all_bins:
      x[(i, b)] = model.NewIntVar(0, num_copies, 'x_%i_%i' % (i, b))

  # Load variables.
  load = [model.NewIntVar(0, bin_capacity, 'load_%i' % b) for b in all_bins]

  # Slack variables.
  slacks = [model.NewBoolVar('slack_%i' % b) for b in all_bins]

  # Links load and x.
  for b in all_bins:
    model.Add(load[b] == sum(x[(i, b)] * items[i][0] for i in all_items))

  # Place all items.
  for i in all_items:
    model.Add(sum(x[(i, b)] for b in all_bins) == items[i][1])

  # Links load and slack through an equivalence relation.
  safe_capacity = bin_capacity - slack_capacity
  for b in all_bins:
    # slack[b] => load[b] <= safe_capacity.
    model.Add(load[b] <= safe_capacity).OnlyEnforceIf(slacks[b])
    # not(slack[b]) => load[b] > safe_capacity.
    model.Add(load[b] > safe_capacity).OnlyEnforceIf(slacks[b].Not())

  # Maximize sum of slacks.
  model.Maximize(sum(slacks))

  # Solves and prints out the solution.
  solver = cp_model.CpSolver()
  status = solver.Solve(model)
  print('Solve status: %s' % solver.StatusName(status))
  if status == cp_model.OPTIMAL:
    print('Optimal objective value: %i' % solver.ObjectiveValue())
  print('Statistics')
  print('  - conflicts : %i' % solver.NumConflicts())
  print('  - branches  : %i' % solver.NumBranches())
  print('  - wall time : %f s' % solver.WallTime())

BinpackingProblemSat()
```

### C++ code

```cpp
#include <stdlib.h>

#include <vector>

#include "ortools/base/logging.h"
#include "ortools/sat/cp_model.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_solver.h"

namespace operations_research {
namespace sat {

void BinpackingProblemSat() {
  // Data.
  const int kBinCapacity = 100;
  const int kSlackCapacity = 20;
  const int kNumBins = 5;

  const std::vector<std::vector<int>> items = {
      {20, 6}, {15, 6}, {30, 4}, {45, 3}};
  const int num_items = items.size();

  // Model.
  CpModelBuilder cp_model;

  // Main variables.
  std::vector<std::vector<IntVar>> x(num_items);
  for (int i = 0; i < num_items; ++i) {
    const int num_copies = items[i][1];
    for (int b = 0; b < kNumBins; ++b) {
      x[i].push_back(cp_model.NewIntVar({0, num_copies}));
    }
  }

  // Load variables.
  std::vector<IntVar> load(kNumBins);
  for (int b = 0; b < kNumBins; ++b) {
    load[b] = cp_model.NewIntVar({0, kBinCapacity});
  }

  // Slack variables.
  std::vector<BoolVar> slacks(kNumBins);
  for (int b = 0; b < kNumBins; ++b) {
    slacks[b] = cp_model.NewBoolVar();
  }

  // Links load and x.
  for (int b = 0; b < kNumBins; ++b) {
    LinearExpr expr;
    for (int i = 0; i < num_items; ++i) {
      expr += x[i][b] * items[i][0];
    }
    cp_model.AddEquality(expr, load[b]);
  }

  // Place all items.
  for (int i = 0; i < num_items; ++i) {
    cp_model.AddEquality(LinearExpr::Sum(x[i]), items[i][1]);
  }

  // Links load and slack through an equivalence relation.
  const int safe_capacity = kBinCapacity - kSlackCapacity;
  for (int b = 0; b < kNumBins; ++b) {
    // slack[b] => load[b] <= safe_capacity.
    cp_model.AddLessOrEqual(load[b], safe_capacity).OnlyEnforceIf(slacks[b]);
    // not(slack[b]) => load[b] > safe_capacity.
    cp_model.AddGreaterThan(load[b], safe_capacity)
        .OnlyEnforceIf(Not(slacks[b]));
  }

  // Maximize sum of slacks.
  cp_model.Maximize(LinearExpr::Sum(slacks));

  // Solving part.
  const CpSolverResponse response = Solve(cp_model.Build());
  LOG(INFO) << CpSolverResponseStats(response);
}

}  // namespace sat
}  // namespace operations_research

int main() {
  operations_research::sat::BinpackingProblemSat();

  return EXIT_SUCCESS;
}
```

### Java code

```java
package com.google.ortools.sat.samples;

import com.google.ortools.Loader;
import com.google.ortools.sat.CpSolverStatus;
import com.google.ortools.sat.CpModel;
import com.google.ortools.sat.CpSolver;
import com.google.ortools.sat.IntVar;
import com.google.ortools.sat.LinearExpr;
import com.google.ortools.sat.LinearExprBuilder;
import com.google.ortools.sat.Literal;

/** Solves a bin packing problem with the CP-SAT solver. */
public class BinPackingProblemSat {
  public static void main(String[] args) throws Exception {
    Loader.loadNativeLibraries();
    // Data.
    int binCapacity = 100;
    int slackCapacity = 20;
    int numBins = 5;

    int[][] items = new int[][] {{20, 6}, {15, 6}, {30, 4}, {45, 3}};
    int numItems = items.length;

    // Model.
    CpModel model = new CpModel();

    // Main variables.
    IntVar[][] x = new IntVar[numItems][numBins];
    for (int i = 0; i < numItems; ++i) {
      int numCopies = items[i][1];
      for (int b = 0; b < numBins; ++b) {
        x[i][b] = model.newIntVar(0, numCopies, "x_" + i + "_" + b);
      }
    }

    // Load variables.
    IntVar[] load = new IntVar[numBins];
    for (int b = 0; b < numBins; ++b) {
      load[b] = model.newIntVar(0, binCapacity, "load_" + b);
    }

    // Slack variables.
    Literal[] slacks = new Literal[numBins];
    for (int b = 0; b < numBins; ++b) {
      slacks[b] = model.newBoolVar("slack_" + b);
    }

    // Links load and x.
    for (int b = 0; b < numBins; ++b) {
      LinearExprBuilder expr = LinearExpr.newBuilder();
      for (int i = 0; i < numItems; ++i) {
        expr.addTerm(x[i][b], items[i][0]);
      }
      model.addEquality(expr, load[b]);
    }

    // Place all items.
    for (int i = 0; i < numItems; ++i) {
      LinearExprBuilder expr = LinearExpr.newBuilder();
      for (int b = 0; b < numBins; ++b) {
        expr.add(x[i][b]);
      }
      model.addEquality(expr, items[i][1]);
    }

    // Links load and slack.
    int safeCapacity = binCapacity - slackCapacity;
    for (int b = 0; b < numBins; ++b) {
      //  slack[b] => load[b] <= safeCapacity.
      model.addLessOrEqual(load[b], safeCapacity).onlyEnforceIf(slacks[b]);
      // not(slack[b]) => load[b] > safeCapacity.
      model.addGreaterOrEqual(load[b], safeCapacity + 1).onlyEnforceIf(slacks[b].not());
    }

    // Maximize sum of slacks.
    model.maximize(LinearExpr.sum(slacks));

    // Solves and prints out the solution.
    CpSolver solver = new CpSolver();
    CpSolverStatus status = solver.solve(model);
    System.out.println("Solve status: " + status);
    if (status == CpSolverStatus.OPTIMAL) {
      System.out.printf("Optimal objective value: %f%n", solver.objectiveValue());
      for (int b = 0; b < numBins; ++b) {
        System.out.printf("load_%d = %d%n", b, solver.value(load[b]));
        for (int i = 0; i < numItems; ++i) {
          System.out.printf("  item_%d_%d = %d%n", i, b, solver.value(x[i][b]));
        }
      }
    }
    System.out.println("Statistics");
    System.out.println("  - conflicts : " + solver.numConflicts());
    System.out.println("  - branches  : " + solver.numBranches());
    System.out.println("  - wall time : " + solver.wallTime() + " s");
  }
}
```

### C\# code

```cs
using System;
using Google.OrTools.Sat;

public class BinPackingProblemSat
{
    static void Main()
    {
        // Data.
        int bin_capacity = 100;
        int slack_capacity = 20;
        int num_bins = 5;

        int[,] items = new int[,] { { 20, 6 }, { 15, 6 }, { 30, 4 }, { 45, 3 } };
        int num_items = items.GetLength(0);

        // Model.
        CpModel model = new CpModel();

        // Main variables.
        IntVar[,] x = new IntVar[num_items, num_bins];
        for (int i = 0; i < num_items; ++i)
        {
            int num_copies = items[i, 1];
            for (int b = 0; b < num_bins; ++b)
            {
                x[i, b] = model.NewIntVar(0, num_copies, String.Format("x_{0}_{1}", i, b));
            }
        }

        // Load variables.
        IntVar[] load = new IntVar[num_bins];
        for (int b = 0; b < num_bins; ++b)
        {
            load[b] = model.NewIntVar(0, bin_capacity, String.Format("load_{0}", b));
        }

        // Slack variables.
        BoolVar[] slacks = new BoolVar[num_bins];
        for (int b = 0; b < num_bins; ++b)
        {
            slacks[b] = model.NewBoolVar(String.Format("slack_{0}", b));
        }

        // Links load and x.
        int[] sizes = new int[num_items];
        for (int i = 0; i < num_items; ++i)
        {
            sizes[i] = items[i, 0];
        }
        for (int b = 0; b < num_bins; ++b)
        {
            IntVar[] tmp = new IntVar[num_items];
            for (int i = 0; i < num_items; ++i)
            {
                tmp[i] = x[i, b];
            }
            model.Add(load[b] == LinearExpr.WeightedSum(tmp, sizes));
        }

        // Place all items.
        for (int i = 0; i < num_items; ++i)
        {
            IntVar[] tmp = new IntVar[num_bins];
            for (int b = 0; b < num_bins; ++b)
            {
                tmp[b] = x[i, b];
            }
            model.Add(LinearExpr.Sum(tmp) == items[i, 1]);
        }

        // Links load and slack.
        int safe_capacity = bin_capacity - slack_capacity;
        for (int b = 0; b < num_bins; ++b)
        {
            //  slack[b] => load[b] <= safe_capacity.
            model.Add(load[b] <= safe_capacity).OnlyEnforceIf(slacks[b]);
            // not(slack[b]) => load[b] > safe_capacity.
            model.Add(load[b] > safe_capacity).OnlyEnforceIf(slacks[b].Not());
        }

        // Maximize sum of slacks.
        model.Maximize(LinearExpr.Sum(slacks));

        // Solves and prints out the solution.
        CpSolver solver = new CpSolver();
        CpSolverStatus status = solver.Solve(model);
        Console.WriteLine(String.Format("Solve status: {0}", status));
        if (status == CpSolverStatus.Optimal)
        {
            Console.WriteLine(String.Format("Optimal objective value: {0}", solver.ObjectiveValue));
            for (int b = 0; b < num_bins; ++b)
            {
                Console.WriteLine(String.Format("load_{0} = {1}", b, solver.Value(load[b])));
                for (int i = 0; i < num_items; ++i)
                {
                    Console.WriteLine(string.Format("  item_{0}_{1} = {2}", i, b, solver.Value(x[i, b])));
                }
            }
        }
        Console.WriteLine("Statistics");
        Console.WriteLine(String.Format("  - conflicts : {0}", solver.NumConflicts()));
        Console.WriteLine(String.Format("  - branches  : {0}", solver.NumBranches()));
        Console.WriteLine(String.Format("  - wall time : {0} s", solver.WallTime()));
    }
}
```


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\Models\DDC3899;

use Doctrine\Common\Collections\Collection;

/**
 * @Entity
 * @Table(name="dc3899_users")
 */
class DDC3899User
{
    /**
     * @var int
     * @Id
     * @Column(type="integer")
     */
    public $id;

    /**
     * @psalm-var Collection<int, DDC3899Contract>
     * @OneToMany(targetEntity="DDC3899Contract", mappedBy="user")
     */
    public $contracts;
}


text:
<?php
/*===================================
=            Navigation             =
===================================*/
/**
 * Cleaner walker for wp_nav_menu()
 *
 * class required_walker
 * Custom output to enable the the ZURB Navigation style.
 * Courtesy of Kriesi.at. http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output
 * From required+ Foundation http://themes.required.ch
 *
 * And Swalkinshaw https://github.com/swalkinshaw
 *
 * Walker_Nav_Menu (WordPress default) example output:
 *
Home

 *
Sample Page</l
 *
 * reverie_walker as above example output:
 *
Home

 *
Sample Page

 *
 */
class reverie_walker extends Walker_Nav_Menu {
	/**
	 * Specify the item type to allow different walkers
	 * @var array
	 */
	var $nav_bar = '';
	function __construct( $nav_args = '' ) {
		$defaults = array(
			'item_type' => 'li',
			'in_top_bar' => false,
			'menu_type' => 'main-menu' //enable menu differenciation, used in preg_replace classes[] below
		);
		$this->nav_bar = apply_filters( 'req_nav_args', wp_parse_args( $nav_args, $defaults ) );
	}
	function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
        $id_field = $this->db_fields['id'];
        if ( is_object( $args[0] ) ) {
            $args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
        }
        return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
	function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
		global $wp_query;
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
		$class_names = $value = '';
		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
		$classes[] = 'menu-item-' . $item->ID;
    // Additionnal Class cleanup, as found in Roots_Nav_Walker - Roots Theme lib/nav.php
    // see http://roots.io/ and https://github.com/roots/roots
    $slug = sanitize_title($item->title);
    $classes = preg_replace('/(current(-menu-|[-_]page[-_])(item|parent|ancestor))/', '', $classes);
    $classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes);
    $menu_type = $this->nav_bar['menu_type'];
    $classes[] = 'menu-item menu-item-' . $menu_type . ' menu-item-' . $slug;

    $classes = array_unique($classes);
		// Check for flyout
		$flyout_toggle = '';
                $toggle_sub_menu = '';
		if ( $args->has_children && $this->nav_bar['item_type'] == 'li' ) {
			if ( $depth == 0 && $this->nav_bar['in_top_bar'] == false ) {
				$classes[] = 'has-flyout';
                                $toggle_sub_menu = 'data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"';
                                $toggle_sub_menu_class = "class=\"dropdown-toggle\" ";
				//$flyout_toggle = '';
                                $toggle_li_class = 'dropdown';
                                $toggle_arrow = '';
			} else if ( $this->nav_bar['in_top_bar'] == true ) {
				$classes[] = 'has-dropdown';
				$flyout_toggle = '';
			}
		}
		$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
		$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . ' ' . $toggle_li_class. '"' : '';
		if ( $depth > 0 ) {
			$output .= $indent . '
ID . '"' . $value . $class_names .'>';
		} else {
			$output .= $indent . ( $this->nav_bar['in_top_bar'] == true ? '

' : '' ) . '<' . $this->nav_bar['item_type'] . ' id="menu-item-'. $item->ID . '"' . $value . $class_names .' >';
		}
		$attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
		$attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
		$attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
                $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
                $attributes .= $toggle_sub_menu_class;
                $attributes .= $toggle_sub_menu;
		$item_output  = $args->before;
		$item_output .= '';
		$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after .$toggle_arrow;
		$item_output .= '';
		$item_output .= $flyout_toggle; // Add possible flyout toggle
		$item_output .= $args->after;
		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}
	function end_el( &$output, $item, $depth = 0, $args = array() ) {
		if ( $depth > 0 ) {
			$output .= "
\n";
		} else {
			$output .= "</" . $this->nav_bar['item_type'] . ">\n";
		}
	}
	function start_lvl( &$output, $depth = 0, $args = array() ) {
		if ( $depth == 0 && $this->nav_bar['item_type'] == 'li' ) {
			$indent = str_repeat("\t", 1);
    		$output .= $this->nav_bar['in_top_bar'] == true ? "\n$indent
\n" : "\n$indent
\n";
    	} else {
			$indent = str_repeat("\t", $depth);
    		$output .= $this->nav_bar['in_top_bar'] == true ? "\n$indent
\n" : "\n$indent
\n";
		}
  	}
}


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

	<title>SHTOOLS - Localized spectral analysis</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../css/sh.css">
	<link rel="icon" type="image/vnd.microsoft.icon" href="../../images/favicon.ico">

				HOME
				DOWNLOAD
				DOCUMENTATION
				FAQ

>  Home > Documentation > Python > Localized Spectral Analysis

SHMTDebias

Invert for the global power spectrum given a multitaper spectrum estimate formed with spherical cap localization windows.

Usage

mtdebias, lmid = pyshtools.SHMTDebias (mtspectra, tapers, nl, [lmax, lwin, k, taper_wt])

Returns

mtdebias : float, dimension (2, n)

The global power spectrum (column 1) and uncertainty (column 2). The midpoints of the n spherical harmonic bins are given in lmid.

lmid : float, dimension (n)

The midpoints of the spherical harmonic bins for which the global power spectrum is constant.

Parameters

mtspectra : float, dimension (2, lmaxin+1)

The localized multitaper spectrum estimate and uncertainty, obtained from a routine such as SHMultitaperCSE or SHMultitaperSE.

tapers : float, dimension (lwinin+1, kin)

An array of the K windowing functions, arranged in columns, obtained from a call to SHReturnTapers.

nl : integer

The global power spectrum is assumed to be constant within bins of spherical harmonic wdith nl. In addition, the global power spectrum will be assumed to be constant beyond lmax.

lmax : optional, integer, default = lmaxin

The spherical harmonic bandwidth of the localized multitaper spectrum estimates.

lwin : optional, integer, default = lwinin

The spherical harmonic bandwidth of the windowing functions in the array tapers.

k : optional, integer, default = kin

The number of tapers utilized in the multitaper spectral analysis.

taper_wt : optional, float, dimension (kin)

The weights used in calculating the multitaper spectral estimates. Optimal values of the weights (for a known global power spectrum) can be obtained from the routine SHMTVarOpt.

Description

SHMTDebias will invert for the global power spectrum given a localized multitaper spectrum estimate formed from spherical cap localization windows. This linear inverse problem is inherently underdetermined, and in order to achive a unique solution it is assumed that the global spectrum is constant in bins of width nl, and that the global power spectrum is constant for degrees greater than lmax. In practice nl should be increased until the global power spectrum is everywhere positive (negative values would be unphysical) and the variances are reasonable. Further details can be found in Wieczorek and Simons (2007).

This set of linear equations is solved using the method of singular value decomposition as outlined in Press et al. (1992, pp. 670-672). Each value of the multitaper spectrum estimate mtspectra[0,:], as well as the corresponding rows of the transformation matrix, is divided by the uncertainties of the estimate mtspectra[1,:]. The solution and uncertainty are given by eqs 15.4.17 and 15.4.19 of Press et al. (1992, p. 671), respectively.

If taper_wt is not specified, the weights will all be assumed to be equal to 1/K.

References

Press, W.H., S.A. Teukolsky, W.T. Vetterling, and B.P. Flannery, Numerical Recipes in FORTRAN: The Art of Scientific Computing, 2nd ed., Cambridge Univ. Press, Cambridge, UK, 1992.

Wieczorek, M. A. and F. J. Simons, Minimum-variance multitaper spectral estimation on the sphere, J. Fourier Anal. Appl., 13, 665-692, doi:10.1007/s00041-006-6904-1, 2007.

See also

shmultitaperse, shmultitapercse, shreturntapers, shmtvaropt, shmtcouplingmatrix

>  Home > Documentation > Python > Localized Spectral Analysis

			Institut de Physique du Globe de Paris
			University of Sorbonne Paris Cité
			© 2015 Mark Wieczorek


text:
MercadosVerticales
==================

Mercados Verticales Gestion