text:
RSpec::Support.require_rspec_core "formatters/base_text_formatter"
RSpec::Support.require_rspec_core "formatters/html_printer"

module RSpec
  module Core
    module Formatters
      # @private
      class HtmlFormatter < BaseFormatter
        Formatters.register self, :start, :example_group_started, :start_dump,
                            :example_started, :example_passed, :example_failed,
                            :example_pending, :dump_summary

        def initialize(output)
          super(output)
          @failed_examples = []
          @example_group_number = 0
          @example_number = 0
          @header_red = nil
          @printer = HtmlPrinter.new(output)
        end

        def start(notification)
          super
          @printer.print_html_start
          @printer.flush
        end

        def example_group_started(notification)
          super
          @example_group_red = false
          @example_group_number += 1

          @printer.print_example_group_end unless example_group_number == 1
          @printer.print_example_group_start(example_group_number,
                                             notification.group.description,
                                             notification.group.parent_groups.size)
          @printer.flush
        end

        def start_dump(_notification)
          @printer.print_example_group_end
          @printer.flush
        end

        def example_started(_notification)
          @example_number += 1
        end

        def example_passed(passed)
          @printer.move_progress(percent_done)
          @printer.print_example_passed(passed.example.description, passed.example.execution_result.run_time)
          @printer.flush
        end

        def example_failed(failure)
          @failed_examples << failure.example
          unless @header_red
            @header_red = true
            @printer.make_header_red
          end

          unless @example_group_red
            @example_group_red = true
            @printer.make_example_group_header_red(example_group_number)
          end

          @printer.move_progress(percent_done)

          example = failure.example

          exception = failure.exception
          exception_details = if exception
                                {
                                  :message => failure.message_lines.join("\n"),
                                  :backtrace => failure.formatted_backtrace.join("\n")
                                }
                              end
          extra = extra_failure_content(failure)

          @printer.print_example_failed(
            example.execution_result.pending_fixed,
            example.description,
            example.execution_result.run_time,
            @failed_examples.size,
            exception_details,
            (extra == "") ? false : extra
          )
          @printer.flush
        end

        def example_pending(pending)
          example = pending.example

          @printer.make_header_yellow unless @header_red
          @printer.make_example_group_header_yellow(example_group_number) unless @example_group_red
          @printer.move_progress(percent_done)
          @printer.print_example_pending(example.description, example.execution_result.pending_message)
          @printer.flush
        end

        def dump_summary(summary)
          @printer.print_summary(
            summary.duration,
            summary.example_count,
            summary.failure_count,
            summary.pending_count
          )
          @printer.flush
        end

      private

        # If these methods are declared with attr_reader Ruby will issue a
        # warning because they are private.
        # rubocop:disable Style/TrivialAccessors

        # The number of the currently running example_group.
        def example_group_number
          @example_group_number
        end

        # The number of the currently running example (a global counter).
        def example_number
          @example_number
        end
        # rubocop:enable Style/TrivialAccessors

        def percent_done
          result = 100.0
          if @example_count > 0
            result = (((example_number).to_f / @example_count.to_f * 1000).to_i / 10.0).to_f
          end
          result
        end

        # Override this method if you wish to output extra HTML for a failed
        # spec. For example, you could output links to images or other files
        # produced during the specs.
        def extra_failure_content(failure)
          RSpec::Support.require_rspec_core "formatters/html_snippet_extractor"
          backtrace = (failure.exception.backtrace || []).map do |line|
            RSpec.configuration.backtrace_formatter.backtrace_line(line)
          end
          backtrace.compact!
          @snippet_extractor ||= HtmlSnippetExtractor.new
          "
#{@snippet_extractor.snippet(backtrace)}
"
        end
      end
    end
  end
end


text:
require 'spec_helper'

describe 'User edits a merge request', :js do
  include Select2Helper

  let(:project) { create(:project, :repository) }
  let(:merge_request) { create(:merge_request, source_project: project, target_project: project) }
  let(:user) { create(:user) }

  before do
    project.add_maintainer(user)
    sign_in(user)

    visit(edit_project_merge_request_path(project, merge_request))
  end

  it 'changes the target branch' do
    expect(page).to have_content('Target branch')

    select2('merge-test', from: '#merge_request_target_branch')
    click_button('Save changes')

    expect(page).to have_content("Request to merge #{merge_request.source_branch} into merge-test")
    expect(page).to have_content("changed target branch from #{merge_request.target_branch} to merge-test")
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CreateInvalidations < ActiveRecord::Migration[4.2]
  def change
    create_table :invalidations do |t|
      t.string   :summary, limit: 255, null: false
      t.string   :details, limit: 10000
      t.integer  :petition_id
      t.string   :name, limit: 255
      t.string   :postcode, limit: 255
      t.string   :ip_address, limit: 20
      t.string   :email, limit: 255
      t.datetime :created_after
      t.datetime :created_before
      t.string   :constituency_id, limit: 30
      t.string   :location_code, limit: 30
      t.integer  :matching_count, null: false, default: 0
      t.integer  :invalidated_count, null: false, default: 0
      t.datetime :enqueued_at, null: true
      t.datetime :started_at, null: true
      t.datetime :cancelled_at, null: true
      t.datetime :completed_at, null: true
      t.datetime :counted_at, null: true
      t.timestamps null: false
    end

    add_index :invalidations, :petition_id
    add_index :invalidations, :started_at
    add_index :invalidations, :completed_at
    add_index :invalidations, :cancelled_at
  end
end


text:
title: "5.1.0"
date:
draft: false
weight: 850
---

Crunchy Data announces the release of [Crunchy Postgres for Kubernetes](https://www.crunchydata.com/products/crunchy-postgresql-for-kubernetes/) 5.1.0.

Crunchy Postgres for Kubernetes is powered by [PGO](https://github.com/CrunchyData/postgres-operator), the open source [Postgres Operator](https://github.com/CrunchyData/postgres-operator) from [Crunchy Data](https://www.crunchydata.com). [PGO](https://github.com/CrunchyData/postgres-operator) is released in conjunction with the [Crunchy Container Suite](https://github.com/CrunchyData/container-suite).

Crunchy Postgres for Kubernetes 5.1.0 includes the following software versions upgrades:

- [Patroni](https://patroni.readthedocs.io/) is now at version 2.1.3.
- [pgAdmin 4](https://www.pgadmin.org/) is now at version 4.30
- [pgBackRest](https://pgbackrest.org/) is updated to version 2.38.
- The [pgAudit](https://github.com/pgaudit/pgaudit) extension is now at version 1.6.2 (PG 14), 1.5.2 (PG 13), 1.4.3 (PG 12), 1.3.4 (PG 11) & 1.2.4 (PG 10).
- The [pgnodemx](https://github.com/CrunchyData/pgnodemx) extension is now at version 1.3.0.
- The [TimescaleDB](https://github.com/timescale/timescaledb) extension is now at version 2.6.0.

Read more about how you can [get started]({{< relref "quickstart/_index.md" >}}) with Crunchy Postgres for Kubernetes. We recommend [forking the Postgres Operator examples](https://github.com/CrunchyData/postgres-operator-examples/fork) repo.

## Major Features

### pgAdmin 4 Integration

PGO v5.1 reintroduces the pgAdmin 4 integration from [PGO v4](https://access.crunchydata.com/documentation/postgres-operator/4.7.5/architecture/pgadmin4/). v5.1 adds the [`spec.userInterace.pgAdmin`]({{< relref "references/crd.md" >}}#postgresclusterspecuserinterfacepgadmin) section to the `PostgresCluster` custom resource to enable pgAdmin 4 integration for a Postgres cluster. Any users defined in `spec.users` are are synced with pgAdmin 4, allowing for a seamless management experience.

Please see the [pgAdmin 4 section](https://access.crunchydata.com/documentation/postgres-operator/v5/architecture/pgadmin4/) of the PGO documentation for more information about this integration.

### Removal of SSH Requirement for Local Backups

Previous versions of PGO relied on the use of `ssh` to take backups and store archive files on Kubernetes-managed storage. PGO v5.1 now uses mTLS to securely transfer and manage these files.

The upgrade to pgBackRest TLS is seamless and transparent if using related image environment variables with your PGO Deployment (please see the [PostgresCluster CRD reference](https://access.crunchydata.com/documentation/postgres-operator/v5/references/crd/) for more information).  This is because PGO will automatically handle updating all image tags across all existing PostgresCluster's following the upgrade to v5.1, seamlessly rolling out any new images as required for proper pgBackRest TLS functionality.

If you are not using related image environment variables, and are instead explicitly defining images via the `image` fields in your PostgresCluster spec, then an additional step is required in order to ensure a seamless upgrade.  Specifically, all `postgrescluster.spec.image` and `postgrescluster.spec.backups.pgbackrest.image` fields must first be updated to specify images containing pgBackRest 2.38.  Therefore, prior to upgrading, please update all `postgrescluster.spec.image` and `postgrescluster.spec.backups.pgbackrest.image` fields to the latest versions of the `crunchy-postgres` and `crunchy-pgbackrest` containers available per the [Components and Compatibility guide](https://access.crunchydata.com/documentation/postgres-operator/v5/references/components/) (please note that the `crunchy-postgres` container should be updated to the latest version available for the major version of PostgreSQL currently being utilized within a cluster).

In the event that PGO is upgraded to v5.1 _before_ updating your image tags, simply update any `image` fields in your PostgresCluster spec as soon as possible following the upgrade.

## Features

- Set [Pod Disruption Budgets]({{< relref "architecture/high-availability.md" >}}#pod-disruption-budgets) (PDBs) for both Postgres and PgBouncer instances.
- Postgres configuration changes requiring a database restart are now automatically rolled out to all instances in the cluster.
- Do not recreate instance Pods for changes that only require a Postgres restart. These types of changes are now applied more quickly.
- Support for [manual switchovers or failovers]({{< relref "tutorial/administrative-tasks.md">}}#changing-the-primary).
- Rotate PgBouncer TLS certificates without downtime.
- Add support for using Active Directory for securely authenticating with PostgreSQL using the GSSAPI.
- Support for using [AWS IAM roles with S3]({{< relref "tutorial/backups.md" >}}#using-an-aws-integrated-identity-provider-and-role) with backups when PGO is deployed in EKS.
- The characters used for password generation can now be controlled using the `postgrescluster.spec.users.password.type` parameter. Choices are `AlphaNumeric` and `ASCII`; defaults to `ASCII`.
- Introduction for automatically checking for updates for PGO and Postgres components. If an update is discovered, it is included in the PGO logs.

## Changes

- As a result of [a fix in PgBouncer v1.16](https://github.com/libusual/libusual/commit/ab960074cb7a), PGO no longer sets verbosity settings in the PgBouncer configuration to catch missing `%include` directives.  Users can increase verbosity in their own configuration files to maintain the previous behavior.
- The Postgres `archive_timeout` setting now defaults to 60 seconds (`60s`), which matches the behavior from PGO v4. If you do not require for WAL files to be generated once a minute (e.g. generally idle system where a window of data-loss is acceptable or a development system), you can set this to `0`:

```yaml
spec:
  patroni:
    dynamicConfiguration:
      postgresql:
        parameters:
          archive_timeout: 0
```
- All Pods now have `enableServiceLinks` set to `false` in order to ensure injected environment variables do not conflict with the various applications running within.

## Fixes

- The names of CronJobs created for scheduled backups are shortened to `<cluster name>-<repo#>-<backup type>` to allow for longer PostgresCluster names.


text:
namespace Boring32::Strings
{
	std::string ConvertWStringToString(const std::wstring& wstr);
	std::wstring ConvertStringToWString(const std::string& str);
	std::vector<std::wstring> TokeniseString(const std::wstring& stringToTokenise, const std::wstring& delimiter);
	std::wstring Replace(std::wstring source, const std::wstring& from, const std::wstring& to);
}


text:
import java.util.*;
import java.io.*;

public class A337 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int m = Integer.parseInt(s[1]);
        s = br.readLine().split(" ");
        int a[] = new int[m];
        for(int i = 0;i<m;i++) a[i] = Integer.parseInt(s[i]);
        Arrays.sort(a);
        int best = Integer.MAX_VALUE;
        for(int i = 0;i<=m-n;i++){
            best = Math.min(best,(a[i+n-1]-a[i]));
        }
        System.out.println(best);

    }
}


text:
copyright:
  years: 2016

---

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

# Introdução a cadeias de ferramentas
{: #toolchains-setup}

Última atualização: 28 de abril de 2016
{: .last-updated}

É possível criar uma cadeia de ferramentas de duas maneiras: usar um modelo para
criar uma cadeia de ferramentas ou incluir uma cadeia de ferramentas em um
app. Dependendo do modelo ou cadeia de
ferramentas que usar, a cadeia de ferramentas poderá incluir um
repositório
(repo) GitHub que é preenchido com o código de início do app e um pipeline de entrega pré-configurado. Ao
enviar por push as mudanças no repo GitHub da cadeia de
ferramentas, o pipeline de entrega automaticamente constrói e implementa o app no {{site.data.keyword.Bluemix}}.
{: shortdesc}

**Importante**: este recurso é experimental. As cadeias de ferramentas podem não ser estáveis e podem mudar de
formas que não sejam compatíveis com versões anteriores. Elas não são recomendadas para uso em ambientes de produção. Para usar cadeias de ferramentas,
deve-se fazer uma
[solicitação
para acesso](https://new-console.ng.bluemix.net/devops?cm_mmc=IBMBluemixGarageMethod-_-MethodSite-_-10-19-15::12-31-18-_-toolchains-welcome-page){: new_window} única. As cadeias de ferramentas estão disponíveis
somente na região de Dallas.

##Criando uma cadeia de ferramentas com base em um modelo
{: #creating_a_toolchain_from_a_template}

Após sua solicitação de acesso a cadeias de ferramentas ser aprovada, será possível usar um modelo como um ponto de início para criar uma
cadeia de ferramentas que inclua um conjunto específico de integrações de ferramenta.

1. No painel DevOps, na guia **Cadeias de ferramentas**, clique em **Criar uma cadeia de ferramentas** para
criar sua primeira cadeia de ferramentas. Se você já tiver uma cadeia de ferramentas, clique no botão (+) para criar outra cadeia de ferramentas.
1. Clique em um modelo da cadeia de ferramentas. Por exemplo, para usar uma
amostra de armazenamento on-line para criar a cadeia de ferramentas, clique em
**Cadeia de ferramentas nativas da nuvem para microsserviços**.
1. Na página de criação da cadeia de ferramentas, revise o diagrama da cadeia de ferramentas que estiver prestes a criar. O diagrama
mostrará cada integração de ferramenta em sua fase de ciclo de vida na cadeia de ferramentas. O diagrama na imagem a seguir é um exemplo. Ao criar
uma cadeia de ferramentas, o diagrama mostrará cada integração de ferramenta que é parte da cadeia de ferramentas.
![Diagrama da cadeia de ferramentas](images/toolchain_diagram.png)

1. Revise as informações padrão para as configurações da cadeia de ferramentas. O nome da cadeia de ferramentas as identifica em
{{site.data.keyword.Bluemix}}. Se você já tiver uma cadeia de ferramentas com esse nome ou se desejar usar um nome diferente, mude o nome
da cadeia de ferramentas.
1. Se você desejar criar a cadeia de ferramentas antes de configurar as
integrações de ferramentas, clique em **CRIAR** e confirme que deseja
criar a cadeia sem as integrações. Continue na seção
[Criando uma cadeia de ferramentas](#creating_a_toolchain) que descreve
as etapas executadas automaticamente para configurar sua cadeia de ferramentas.
1. Se você desejar configurar integrações de ferramentas antes de criar a cadeia
de ferramentas, na seção Integrações configuráveis, selecione cada integração de
ferramenta que deseja configurar. Para
obter informações sobre configurar integrações de ferramentas, consulte [Configurando integrações de ferramenta](../toolchains/toolchains_integrations.html){: new_window}.

##Criando uma cadeia de ferramentas com base em um aplicativo
{: #creating_a_toolchain_from_an_app}

Após sua solicitação de acesso a cadeias de ferramentas ser aprovada, será possível criar uma cadeia de ferramentas do seu app. A cadeia de
ferramentas pode suportar desenvolvimento, implementação e monitoramento contínuos e mais, e é associada ao seu app. Cada app pode ser
associado a uma cadeia de ferramentas. Ao enviar por push mudanças no
repo GitHub da cadeia de ferramentas, o pipeline automaticamente
constrói e implementa o app.

1. Em sua página Visão geral, no ladrilho Entrega contínua, clique em **Incluir cadeia de ferramentas**. Como
alternativa, no Bluemix Classic Experience, clique em **INCLUIR GIT**. Seu app é configurado para entrega contínua a partir
de um novo repo GitHub que é preenchido com o código de início do
iniciador.
1. Na página de criação da cadeia de ferramentas, revise o diagrama da cadeia de ferramentas que estiver prestes a criar. O diagrama
mostrará cada integração de ferramenta em sua fase de ciclo de vida na cadeia de ferramentas.
1. Revise as informações padrão para as configurações da cadeia de ferramentas. O nome da cadeia de ferramentas as identifica em
{{site.data.keyword.Bluemix}}. Se você já tiver uma cadeia de ferramentas com esse nome ou se desejar usar um nome diferente, mude o nome
da cadeia de ferramentas.
1. Na seção Integrações configuráveis, selecione cada integração de ferramenta que deseja configurar para sua cadeia de ferramentas. Para
obter informações sobre configurar integrações de ferramentas, consulte [Configurando integrações de ferramenta](../toolchains/toolchains_integrations.html){: new_window}.

## Configurando uma cadeia de ferramentas
{: #setting_up_a_toolchain}

Se você não tiver criado ainda a cadeia de ferramentas, clique em **CRIAR**. Várias etapas são executadas automaticamente para configurar sua cadeia de ferramentas:

 * A cadeia de ferramentas é criada.
 * Se você tiver configurado a integração de ferramenta Pipeline de entrega, os pipelines serão acionados.
 * Se você tiver configurado a integração de ferramenta Sauce Labs, a integração Sauce Labs será configurada para incluir tarefas nos
pipelines e executar testes.
 * Se você tiver configurado a integração de ferramenta PagerDuty, a integração PagerDuty será configurada para enviar notificações
ao canal configurado no Slack. Essas notificações indicam quando ocorre um problema.
 * Se você tiver configurado a integração de ferramenta Slack, a integração Slack será configurada para enviar notificações ao canal
configurado no Slack. Essas notificações indicam o progresso da implementação; por exemplo, `Conectado com projeto XYZ`,
`Pipeline configurado` e `Estágio 'construção' iniciado`.
 * Se você tiver configurado a integração de ferramenta
GitHub, o repo GitHub de amostra é clonado na conta do GitHub.

##Visualizando uma cadeia de ferramentas
{: #viewing_a_toolchain}

Após a configuração da cadeia de ferramentas e de todas as integrações de
ferramentas, a página Integrações de ferramentas é aberta.

1. Revise a página para ver uma representação visual da cadeia de ferramentas para seu app.
1. Para acessar uma integração de ferramenta que esteja em sua cadeia de ferramentas, clique no ladrilho da ferramenta.

 **Dica**: se você tiver mais de um
repo
GitHub, poderá ter diversos ladrilhos para a mesma integração de ferramenta
porque cada repo precisa de seu próprio pipeline.


text:
package org.knowm.xchange.gdax;

import static org.fest.assertions.api.Assertions.assertThat;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.junit.Test;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.gdax.dto.marketdata.GDAXProductStats;
import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker;
import org.knowm.xchange.gdax.dto.trade.GDAXFill;

import com.fasterxml.jackson.databind.ObjectMapper;

import si.mazi.rescu.serialization.jackson.DefaultJacksonObjectMapperFactory;
import si.mazi.rescu.serialization.jackson.JacksonObjectMapperFactory;

/**
 * Created by Yingzhe on 4/8/2015.
 */
public class GDAXAdaptersTest {

  @Test
  public void parseDateTest() {
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03Z").getTime()).isEqualTo(1493737803000L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.1Z").getTime()).isEqualTo(1493737803100L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.12Z").getTime()).isEqualTo(1493737803120L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.123Z").getTime()).isEqualTo(1493737803123L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.1234567Z").getTime()).isEqualTo(1493737803123L);

    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03").getTime()).isEqualTo(1493737803000L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.1").getTime()).isEqualTo(1493737803100L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.12").getTime()).isEqualTo(1493737803120L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.123").getTime()).isEqualTo(1493737803123L);
    assertThat(GDAXAdapters.parseDate("2017-05-02T15:10:03.123456").getTime()).isEqualTo(1493737803123L);

    assertThat(GDAXAdapters.parseDate("2017-06-21T04:52:01.996Z").getTime()).isEqualTo(1498020721996L);
  }

  @Test
  public void testTickerAdapter() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = GDAXAdaptersTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");
    InputStream is2 = GDAXAdaptersTest.class.getResourceAsStream("/marketdata/example-stats-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    GDAXProductTicker coinbaseExTicker = mapper.readValue(is, GDAXProductTicker.class);
    GDAXProductStats coinbaseExStats = mapper.readValue(is2, GDAXProductStats.class);

    Ticker ticker = GDAXAdapters.adaptTicker(coinbaseExTicker, coinbaseExStats, CurrencyPair.BTC_USD);

    assertThat(ticker.getLast().toString()).isEqualTo("246.28000000");
    assertThat(ticker.getBid().toString()).isEqualTo("637");
    assertThat(ticker.getAsk().toString()).isEqualTo("637.11");
    assertThat(ticker.getHigh().toString()).isEqualTo("255.47000000");
    assertThat(ticker.getLow().toString()).isEqualTo("244.29000000");
    assertThat(ticker.getVolume()).isEqualTo(new BigDecimal("4661.70407704"));
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(ticker.getTimestamp());
    assertThat(dateString).isEqualTo("2015-04-08 20:49:06");
  }

  @Test
  public void testTradeHistoryAdapter() throws IOException {
    JacksonObjectMapperFactory factory = new DefaultJacksonObjectMapperFactory();
    ObjectMapper mapper = factory.createObjectMapper();

    InputStream is = getClass().getResourceAsStream("/trade/example-fills.json");
    GDAXFill[] fills = mapper.readValue(is, GDAXFill[].class);

    UserTrades trades = GDAXAdapters.adaptTradeHistory(fills);

    assertThat(trades.getUserTrades()).hasSize(1);

    UserTrade trade = trades.getUserTrades().get(0);

    assertThat(trade.getId()).isEqualTo("470768");
    assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.ETH_BTC);
    assertThat(trade.getPrice()).isEqualTo("0.05915000");
    assertThat(trade.getTradableAmount()).isEqualTo("0.01000000");
    assertThat(trade.getOrderId()).isEqualTo("b4b3bbb1-e0e3-4532-9413-23123448ce35");
    assertThat(trade.getTimestamp().getTime()).isEqualTo(1493623910243L);
    assertThat(trade.getFeeAmount()).isEqualTo("0.0000017745000000");
    assertThat(trade.getType()).isEqualTo(OrderType.BID);
  }
}


text:
/**
 * @file integrator.h
 *
 * A resettable integrator
 *
 * @author Lorenz Meier <lorenz@px4.io>
 */

#pragma once

#include <mathlib/mathlib.h>

class Integrator
{
public:
	Integrator(uint64_t auto_reset_interval = 4000 /* 250 Hz */, bool coning_compensation = false);
	virtual ~Integrator();

	/**
	 * Put an item into the integral.
	 *
	 * @param timestamp	Timestamp of the current value
	 * @param val		Item to put
	 * @param integral	Current integral in case the integrator did reset, else the value will not be modified
	 * @return		true if putting the item triggered an integral reset
	 *			and the integral should be published
	 */
	bool			put(uint64_t timestamp, math::Vector<3> &val, math::Vector<3> &integral, uint64_t &integral_dt);

	/**
	 * Get the current integral value
	 *
	 * @return		the integral since the last auto-reset
	 */
	math::Vector<3>		get() { return _integral_auto; }

	/**
	 * Read from the integral
	 *
	 * @param auto_reset	Reset the integral to zero on read
	 * @return		the integral since the last read-reset
	 */
	math::Vector<3>		read(bool auto_reset);

	/**
	 * Get current integral start time
	 */
	uint64_t		current_integral_start() { return _last_auto; }

private:
	uint64_t _auto_reset_interval;		/**< the interval after which the content will be published and the integrator reset */
	uint64_t _last_integration;			/**< timestamp of the last integration step */
	uint64_t _last_auto;				/**< last auto-announcement of integral value */
	math::Vector<3> _integral_auto;			/**< the integrated value which auto-resets after _auto_reset_interval */
	math::Vector<3> _integral_read;			/**< the integrated value since the last read */
	math::Vector<3> _last_val;			/**< previously integrated last value */
	math::Vector<3> _last_delta;			/**< last local delta */
	void (*_auto_callback)(uint64_t, math::Vector<3>);	/**< the function callback for auto-reset */
	bool _coning_comp_on;				/**< coning compensation */

	/* we don't want this class to be copied */
	Integrator(const Integrator &);
	Integrator operator=(const Integrator &);
};


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Fondant</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="/bower_components/highlightjs/styles/default.css" />
    <link rel="stylesheet" href="/bower_components/normalize-css/normalize.css" />

    <link rel="stylesheet" href="/styles/fondant.css">

    <link rel="stylesheet" href="/styles/stylus.css">

Fondant

Getting Started

CSS

Download


text:
"""Constants for the AVM FRITZ!SmartHome integration."""
from __future__ import annotations

import logging
from typing import Final

ATTR_STATE_BATTERY_LOW: Final = "battery_low"
ATTR_STATE_DEVICE_LOCKED: Final = "device_locked"
ATTR_STATE_HOLIDAY_MODE: Final = "holiday_mode"
ATTR_STATE_LOCKED: Final = "locked"
ATTR_STATE_SUMMER_MODE: Final = "summer_mode"
ATTR_STATE_WINDOW_OPEN: Final = "window_open"

ATTR_TEMPERATURE_UNIT: Final = "temperature_unit"

ATTR_TOTAL_CONSUMPTION: Final = "total_consumption"
ATTR_TOTAL_CONSUMPTION_UNIT: Final = "total_consumption_unit"

CONF_CONNECTIONS: Final = "connections"
CONF_COORDINATOR: Final = "coordinator"

DEFAULT_HOST: Final = "fritz.box"
DEFAULT_USERNAME: Final = "admin"

DOMAIN: Final = "fritzbox"

LOGGER: Final[logging.Logger] = logging.getLogger(__package__)

PLATFORMS: Final[list[str]] = ["binary_sensor", "climate", "switch", "sensor"]


text:
package com.consol.citrus.docker.command;

import java.util.stream.Stream;

import com.consol.citrus.context.TestContext;
import com.consol.citrus.docker.actions.DockerExecuteAction;
import com.consol.citrus.docker.client.DockerClient;
import com.consol.citrus.docker.message.DockerMessageHeaders;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Volume;
import org.springframework.util.StringUtils;

/**
 * @author Christoph Deppisch
 * @since 2.4
 */
public class ContainerCreate extends AbstractDockerCommand<CreateContainerResponse> {

    public static final String DELIMITER = ";";

    /**
     * Default constructor initializing the command name.
     */
    public ContainerCreate() {
        super("docker:container:create");
    }

    @Override
    public void execute(DockerClient dockerClient, TestContext context) {
        CreateContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().createContainerCmd(getImageId(context));

        if (hasParameter("name")) {
            command.withName(getParameter("name", context));
        }

        if (hasParameter("attach-stderr")) {
            command.withAttachStderr(Boolean.valueOf(getParameter("attach-stderr", context)));
        }

        if (hasParameter("attach-stdin")) {
            command.withAttachStdin(Boolean.valueOf(getParameter("attach-stdin", context)));
        }

        if (hasParameter("attach-stdout")) {
            command.withAttachStdout(Boolean.valueOf(getParameter("attach-stdout", context)));
        }

        if (hasParameter("capability-add")) {
            if (getParameters().get("capability-add") instanceof Capability[]) {
                command.withCapAdd((Capability[]) getParameters().get("capability-add"));
            } else {
                command.withCapAdd(getCapabilities("capability-add", context));
            }
        }

        if (hasParameter("capability-drop")) {
            if (getParameters().get("capability-drop") instanceof Capability[]) {
                command.withCapAdd((Capability[]) getParameters().get("capability-drop"));
            } else {
                command.withCapDrop(getCapabilities("capability-drop", context));
            }
        }

        if (hasParameter("domain-name")) {
            command.withDomainName(getParameter("domain-name", context));
        }

        if (hasParameter("cmd")) {
            if (getParameters().get("cmd") instanceof Capability[]) {
                command.withCmd((String[]) getParameters().get("cmd"));
            } else {
                command.withCmd(StringUtils.delimitedListToStringArray(getParameter("cmd", context), DELIMITER));
            }
        }

        if (hasParameter("env")) {
            if (getParameters().get("env") instanceof Capability[]) {
                command.withEnv((String[]) getParameters().get("env"));
            } else {
                command.withEnv(StringUtils.delimitedListToStringArray(getParameter("env", context), DELIMITER));
            }
        }

        if (hasParameter("entrypoint")) {
            command.withEntrypoint(getParameter("entrypoint", context));
        }

        if (hasParameter("hostname")) {
            command.withHostName(getParameter("hostname", context));
        }

        if (hasParameter("port-specs")) {
            if (getParameters().get("port-specs") instanceof Capability[]) {
                command.withPortSpecs((String[]) getParameters().get("port-specs"));
            } else {
                command.withPortSpecs(StringUtils.delimitedListToStringArray(getParameter("port-specs", context), DELIMITER));
            }
        }

        ExposedPort[] exposedPorts = {};
        if (hasParameter("exposed-ports")) {
            if (getParameters().get("exposed-ports") instanceof ExposedPort[]) {
                exposedPorts = (ExposedPort[]) getParameters().get("exposed-ports");
            } else {
                exposedPorts = getExposedPorts(getParameter("exposed-ports", context), context);
            }
            command.withExposedPorts(exposedPorts);
        }

        if (hasParameter("port-bindings")) {
            if (getParameters().get("port-bindings") instanceof Ports) {
                command.withPortBindings((Ports) getParameters().get("port-bindings"));
            } if (getParameters().get("port-bindings") instanceof PortBinding[]) {
                command.withPortBindings((PortBinding[]) getParameters().get("port-bindings"));
            } else {
                command.withPortBindings(getPortBindings(getParameter("port-bindings", context), exposedPorts, context));
            }
        } else if (exposedPorts.length > 0) {
            command.withPortBindings(getPortBindings("", exposedPorts, context));
        }

        if (hasParameter("volumes")) {
            if (getParameters().get("volumes") instanceof ExposedPort[]) {
                command.withVolumes((Volume[]) getParameters().get("volumes"));
            } else {
                command.withVolumes(getVolumes(context));
            }
        }

        if (hasParameter("working-dir")) {
            command.withWorkingDir(getParameter("working-dir", context));
        }

        CreateContainerResponse response = command.exec();
        context.setVariable(DockerMessageHeaders.CONTAINER_ID, response.getId());
        setCommandResult(response);

        if (!hasParameter("name")) {
            InspectContainerCmd inspect = dockerClient.getEndpointConfiguration().getDockerClient().inspectContainerCmd(response.getId());
            InspectContainerResponse inspectResponse = inspect.exec();
            context.setVariable(DockerMessageHeaders.CONTAINER_NAME, inspectResponse.getName().substring(1));
        }
    }

    /**
     * Gets the volume specs from comma delimited string.
     * @return
     */
    private Volume[] getVolumes(TestContext context) {
        String[] volumes = StringUtils.commaDelimitedListToStringArray(getParameter("volumes", context));
        Volume[] volumeSpecs = new Volume[volumes.length];

        for (int i = 0; i < volumes.length; i++) {
            volumeSpecs[i] = new Volume(volumes[i]);
        }

        return volumeSpecs;
    }

    /**
     * Gets the capabilities added.
     * @return
     */
    private Capability[] getCapabilities(String addDrop, TestContext context) {
        String[] capabilities = StringUtils.commaDelimitedListToStringArray(getParameter(addDrop, context));
        Capability[] capAdd = new Capability[capabilities.length];

        for (int i = 0; i < capabilities.length; i++) {
            capAdd[i] = Capability.valueOf(capabilities[i]);
        }

        return capAdd;
    }

    /**
     * Construct set of exposed ports from comma delimited list of ports.
     * @param portSpecs
     * @param context
     * @return
     */
    private ExposedPort[] getExposedPorts(String portSpecs, TestContext context) {
        String[] ports = StringUtils.commaDelimitedListToStringArray(portSpecs);
        ExposedPort[] exposedPorts = new ExposedPort[ports.length];

        for (int i = 0; i < ports.length; i++) {
            String portSpec = context.replaceDynamicContentInString(ports[i]);

            if (portSpec.startsWith("udp:")) {
                exposedPorts[i] = ExposedPort.udp(Integer.valueOf(portSpec.substring("udp:".length())));
            } else if (portSpec.startsWith("tcp:")) {
                exposedPorts[i] = ExposedPort.tcp(Integer.valueOf(portSpec.substring("tcp:".length())));
            } else {
                exposedPorts[i] = ExposedPort.tcp(Integer.valueOf(portSpec));
            }
        }

        return exposedPorts;
    }

    /**
     * Construct set of port bindings from comma delimited list of ports.
     * @param portSpecs
     * @param exposedPorts
     * @param context
     * @return
     */
    private Ports getPortBindings(String portSpecs, ExposedPort[] exposedPorts, TestContext context) {
        String[] ports = StringUtils.commaDelimitedListToStringArray(portSpecs);
        Ports portsBindings = new Ports();

        for (String portSpec : ports) {
            String[] binding = context.replaceDynamicContentInString(portSpec).split(":");
            if (binding.length == 2) {
                Integer hostPort = Integer.valueOf(binding[0]);
                Integer port = Integer.valueOf(binding[1]);

                portsBindings.bind(Stream.of(exposedPorts).filter(exposed -> port.equals(exposed.getPort())).findAny().orElse(ExposedPort.tcp(port)), Ports.Binding.bindPort(hostPort));
            }
        }

        Stream.of(exposedPorts).filter(exposed -> !portsBindings.getBindings().keySet().contains(exposed)).forEach(exposed -> portsBindings.bind(exposed, Ports.Binding.empty()));

        return portsBindings;
    }

    /**
     * Sets the image id parameter.
     * @param id
     * @return
     */
    public ContainerCreate image(String id) {
        getParameters().put(IMAGE_ID, id);
        return this;
    }

    /**
     * Sets the image name parameter.
     * @param name
     * @return
     */
    public ContainerCreate name(String name) {
        getParameters().put("name", name);
        return this;
    }

    /**
     * Sets the attach-stderr parameter.
     * @param attachStderr
     * @return
     */
    public ContainerCreate attachStdErr(Boolean attachStderr) {
        getParameters().put("attach-stderr", attachStderr);
        return this;
    }

    /**
     * Sets the attach-stdin parameter.
     * @param attachStdin
     * @return
     */
    public ContainerCreate attachStdIn(Boolean attachStdin) {
        getParameters().put("attach-stdin", attachStdin);
        return this;
    }

    /**
     * Sets the attach-stdout parameter.
     * @param attachStdout
     * @return
     */
    public ContainerCreate attachStdOut(Boolean attachStdout) {
        getParameters().put("attach-stdout", attachStdout);
        return this;
    }

    /**
     * Adds capabilities as command parameter.
     * @param capabilities
     * @return
     */
    public ContainerCreate addCapability(Capability ... capabilities) {
        getParameters().put("capability-add", capabilities);
        return this;
    }

    /**
     * Drops capabilities as command parameter.
     * @param capabilities
     * @return
     */
    public ContainerCreate dropCapability(Capability ... capabilities) {
        getParameters().put("capability-drop", capabilities);
        return this;
    }

    /**
     * Sets the domain-name parameter.
     * @param domainName
     * @return
     */
    public ContainerCreate domainName(String domainName) {
        getParameters().put("domain-name", domainName);
        return this;
    }

    /**
     * Adds commands as command parameter.
     * @param commands
     * @return
     */
    public ContainerCreate cmd(String ... commands) {
        getParameters().put("cmd", commands);
        return this;
    }

    /**
     * Adds environment variables as command parameter.
     * @param envVars
     * @return
     */
    public ContainerCreate env(String ... envVars) {
        getParameters().put("env", envVars);
        return this;
    }

    /**
     * Sets the entrypoint parameter.
     * @param entrypoint
     * @return
     */
    public ContainerCreate entryPoint(String entrypoint) {
        getParameters().put("entrypoint", entrypoint);
        return this;
    }

    /**
     * Sets the hostname parameter.
     * @param hostname
     * @return
     */
    public ContainerCreate hostName(String hostname) {
        getParameters().put("hostname", hostname);
        return this;
    }

    /**
     * Adds port-specs variables as command parameter.
     * @param portSpecs
     * @return
     */
    public ContainerCreate portSpecs(String ... portSpecs) {
        getParameters().put("port-specs", portSpecs);
        return this;
    }

    /**
     * Adds exposed-ports variables as command parameter.
     * @param exposedPorts
     * @return
     */
    public ContainerCreate exposedPorts(ExposedPort ... exposedPorts) {
        getParameters().put("exposed-ports", exposedPorts);
        return this;
    }

    /**
     * Adds explicit port bindings as command parameter.
     * @param portBindings
     * @return
     */
    public ContainerCreate portBindings(Ports ... portBindings) {
        getParameters().put("port-bindings", portBindings);
        return this;
    }

    /**
     * Adds explicit port bindings as command parameter.
     * @param portBindings
     * @return
     */
    public ContainerCreate portBindings(PortBinding ... portBindings) {
        getParameters().put("port-bindings", portBindings);
        return this;
    }

    /**
     * Adds volumes variables as command parameter.
     * @param volumes
     * @return
     */
    public ContainerCreate volumes(Volume ... volumes) {
        getParameters().put("volumes", volumes);
        return this;
    }

    /**
     * Sets the working-dir parameter.
     * @param workingDir
     * @return
     */
    public ContainerCreate workingDir(String workingDir) {
        getParameters().put("working-dir", workingDir);
        return this;
    }

    /**
     * Command builder.
     */
    public static final class Builder extends AbstractDockerCommandBuilder<CreateContainerResponse, ContainerCreate, Builder> {

        public Builder(DockerExecuteAction.Builder parent) {
            super(parent, new ContainerCreate());
        }

        /**
         * Sets the image id parameter.
         * @param id
         * @return
         */
        public Builder image(String id) {
            command.image(id);
            return this;
        }

        /**
         * Sets the image name parameter.
         * @param name
         * @return
         */
        public Builder name(String name) {
            command.name(name);
            return this;
        }

        /**
         * Sets the attach-stderr parameter.
         * @param attachStderr
         * @return
         */
        public Builder attachStdErr(Boolean attachStderr) {
            command.attachStdErr(attachStderr);
            return this;
        }

        /**
         * Sets the attach-stdin parameter.
         * @param attachStdin
         * @return
         */
        public Builder attachStdIn(Boolean attachStdin) {
            command.attachStdIn(attachStdin);
            return this;
        }

        /**
         * Sets the attach-stdout parameter.
         * @param attachStdout
         * @return
         */
        public Builder attachStdOut(Boolean attachStdout) {
            command.attachStdOut(attachStdout);
            return this;
        }

        /**
         * Adds capabilities as command parameter.
         * @param capabilities
         * @return
         */
        public Builder addCapability(Capability ... capabilities) {
            command.addCapability(capabilities);
            return this;
        }

        /**
         * Drops capabilities as command parameter.
         * @param capabilities
         * @return
         */
        public Builder dropCapability(Capability ... capabilities) {
            command.dropCapability(capabilities);
            return this;
        }

        /**
         * Sets the domain-name parameter.
         * @param domainName
         * @return
         */
        public Builder domainName(String domainName) {
            command.domainName(domainName);
            return this;
        }

        /**
         * Adds commands as command parameter.
         * @param commands
         * @return
         */
        public Builder cmd(String ... commands) {
            command.cmd(commands);
            return this;
        }

        /**
         * Adds environment variables as command parameter.
         * @param envVars
         * @return
         */
        public Builder env(String ... envVars) {
            command.env(envVars);
            return this;
        }

        /**
         * Sets the entrypoint parameter.
         * @param entrypoint
         * @return
         */
        public Builder entryPoint(String entrypoint) {
            command.entryPoint(entrypoint);
            return this;
        }

        /**
         * Sets the hostname parameter.
         * @param hostname
         * @return
         */
        public Builder hostName(String hostname) {
            command.hostName(hostname);
            return this;
        }

        /**
         * Adds port-specs variables as command parameter.
         * @param portSpecs
         * @return
         */
        public Builder portSpecs(String ... portSpecs) {
            command.portSpecs(portSpecs);
            return this;
        }

        /**
         * Adds exposed-ports variables as command parameter.
         * @param exposedPorts
         * @return
         */
        public Builder exposedPorts(ExposedPort ... exposedPorts) {
            command.exposedPorts(exposedPorts);
            return this;
        }

        /**
         * Adds explicit port bindings as command parameter.
         * @param portBindings
         * @return
         */
        public Builder portBindings(Ports ... portBindings) {
            command.portBindings(portBindings);
            return this;
        }

        /**
         * Adds explicit port bindings as command parameter.
         * @param portBindings
         * @return
         */
        public Builder portBindings(PortBinding ... portBindings) {
            command.portBindings(portBindings);
            return this;
        }

        /**
         * Adds volumes variables as command parameter.
         * @param volumes
         * @return
         */
        public Builder volumes(Volume ... volumes) {
            command.volumes(volumes);
            return this;
        }

        /**
         * Sets the working-dir parameter.
         * @param workingDir
         * @return
         */
        public Builder workingDir(String workingDir) {
            command.workingDir(workingDir);
            return this;
        }
    }
}


text:
package tray.display;

import java.util.ArrayList;

import tray.display.IMessageDisplay.MessageType;
import util.logger.ILogger;

import monitor.MonitorInfo;
import monitor.build.BuildMeta;
import monitor.build.IBuild.BuildStatus;

public class NotificationManager implements INotificationManager {

	private ILogger logger;
	private IMessageDisplay display;
	private MonitorInfo data;

	public NotificationManager(ILogger logger, IMessageDisplay display) {
		this.display = display;
	}

	@Override
	public void updateStatus(MonitorInfo data, boolean force) {
		ArrayList<String> rawMessages = getStatusMessages(new MonitorInfo(), data);
		if(this.data == null){
			// initial update
			if(data.getBuilds().size() > 0){
				displayStatusMessage(rawMessages, getMessageType(data));
			}else{
				displayEmptyMessage();
			}
		}else{
			// while running
			ArrayList<String> messages = getStatusMessages(this.data, data);
			if(messages.size() > 0){
				displayStatusMessage(messages, getMessageType(data));
			}else if(force){
				if(data.getBuilds().size() > 0){
					displayStatusMessage(rawMessages, getMessageType(data));
				}else{
					displayEmptyMessage();
				}
				force = false;
			}
		}
		this.data = data;
	}

	private void displayStatusMessage(ArrayList<String> messages, MessageType type) {
		StringBuilder message = new StringBuilder();
		for(int i=0; i< messages.size(); i++){
			message.append(messages.get(i));
			if(i < messages.size()-1){
				message.append((display.supportNewline() ? "\n" : ", "));
			}
		}
		display.displayMessage(message.toString(), type);
	}

	private void displayEmptyMessage() {
		display.displayMessage("Add some builds !", MessageType.WARNING);
	}

	private MessageType getMessageType(MonitorInfo data) {
		return data.getStatus() == BuildStatus.OK ? MessageType.INFO : MessageType.ERROR;
	}

	private ArrayList<String> getStatusMessages(MonitorInfo oldData, MonitorInfo newData) {
		ArrayList<String> messages = new ArrayList<String>();
		StatusAnalyzer analyzer = new StatusAnalyzer(oldData, newData);
		for(StatusAnalyzer.StatusChange change : analyzer.getChanges()){
			try{
				BuildMeta meta = new BuildMeta(change.identifier);
				if(display.supportNewline()){
					String identifier = meta.name+"@"+meta.server;
					if(change.oldStatus != null){
						messages.add(identifier+" ("+change.oldStatus+" >> "+change.newStatus+")");
					}else{
						messages.add(identifier+" ("+change.newStatus+")");
					}
				}else{
					messages.add(meta.name+"->"+change.newStatus);
				}
			}catch(Exception e){
				logger.error(e);
			}
		}
		return messages;
	}
}


text:
<!DOCTYPE html >

          <title>spark - it.agilelab.bigdata.spark</title>
          <meta name="description" content="spark - it.agilelab.bigdata.spark" />
          <meta name="keywords" content="spark it.agilelab.bigdata.spark" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

it.agilelab.bigdata

spark

        package

        spark

<input id="mbrsel-input" type="text" accesskey="/" />

            Visibility

Public

All

Value Members

        package

        search

Core functionality of Spark Search resides here.

Core functionality of Spark Search resides here.

it.agilelab.bigdata.spark.search.SearchableRDD and its implementations are the main classes which provide
user-facing funcitonality.

There are three implementations available: it.agilelab.bigdata.spark.search.impl.BroadcastIndexLuceneRDD,
it.agilelab.bigdata.spark.search.impl.PartitionsIndexLuceneRDD and
it.agilelab.bigdata.spark.search.impl.DistributedIndexLuceneRDD.

Ungrouped


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.bridge.service.core.s3;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.cloud.bridge.service.exception.PermissionDeniedException;
import com.cloud.bridge.util.IpAddressRange;

public class S3PolicyIPAddressCondition extends S3PolicyCondition {
    protected final static Logger logger = Logger.getLogger(S3PolicyIPAddressCondition.class);

	private Map<ConditionKeys,IpAddressRange[]> keys = new HashMap<ConditionKeys,IpAddressRange[]>();

	public S3PolicyIPAddressCondition() {
	}

	/**
	 * Return a set holding all the condition keys kept in this object.
	 * @return Set<String>
	 */
	public Set<ConditionKeys> getAllKeys() {
		return keys.keySet();
	}

	/**
	 * After calling getAllKeys(), pass in each key from that result to get
	 * the key's associated list of values.
	 * @param key
	 * @return String[]
	 */
	public IpAddressRange[] getKeyValues(ConditionKeys key) {
		return keys.get(key);
	}

	/**
	 * Convert the key's values into the type depending on the what the condition expects.
	 * @throws ParseException
	 * @throws IOException
	 */
	public void setKey(ConditionKeys key, String[] values) throws ParseException, Exception
	{
		IpAddressRange[] addresses = new IpAddressRange[ values.length ];

		for( int i=0; i < values.length; i++ )
	        addresses[i] = IpAddressRange.parseRange( values[i] );

	    keys.put(key, addresses);
	}

	public boolean isTrue(S3PolicyContext context, String SID) throws Exception
	{
		// -> improperly defined condition evaluates to false
		Set<ConditionKeys> keySet = getAllKeys();
		if (null == keySet) return false;
		Iterator<ConditionKeys> itr = keySet.iterator();
		if (!itr.hasNext()) return false;

		// -> returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
		//    For HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.
		IpAddressRange toCompareWith = IpAddressRange.parseRange( context.getRemoveAddr());
		if (null == toCompareWith) return false;

		// -> all keys in a condition are ANDed together (one false one terminates the entire condition)
		while( itr.hasNext())
		{
			ConditionKeys keyName = itr.next();
			IpAddressRange[] valueList = getKeyValues( keyName );
			boolean keyResult = false;

			// -> stop when we hit the first true key value (i.e., key values are 'OR'ed together)
            for( int i=0; i < valueList.length && !keyResult; i++ )
            {
            	switch( condition ) {
        		case IpAddress:
        			 if (valueList[i].contains( toCompareWith )) keyResult = true;
       			     break;
        		case NotIpAddres:
       			     if (!valueList[i].contains( toCompareWith )) keyResult = true;
       			     break;
		        default:
			         return false;
            	}
    			logger.info( "S3PolicyIPAddressCondition eval - SID: " + SID + ", " + condition + ", key: " + keyName + ", valuePassedIn: " + toCompareWith.toString() + ", valueInRule: " + valueList[i].toString() + ", result: " + keyResult );
            }

            // -> if all key values are false, false then that key is false and then the entire condition is then false
            if (!keyResult) return false;
		}

		return true;
	}

	public void verify() throws PermissionDeniedException
	{
		if (0 == keys.size())
   	       throw new PermissionDeniedException( "S3 Bucket Policy IpAddress Condition needs at least one key-value pairs" );
	}

	public String toString()
	{
		StringBuffer value = new StringBuffer();
		Set<ConditionKeys> keySet = getAllKeys();
		if (null == keySet) return "";
		Iterator<ConditionKeys> itr = keySet.iterator();

		value.append( condition + " (an IP address condition): \n" );
		while( itr.hasNext()) {
			ConditionKeys keyName = itr.next();
			value.append( keyName );
			value.append( ": \n" );
			IpAddressRange[] valueList = getKeyValues( keyName );
			for( int i=0; i < valueList.length; i++ ) {
				if (0 < i) value.append( "\n" );
				value.append( valueList[i].toString());
			}
			value.append( "\n\n" );
		}

		return value.toString();
	}
}


text:
namespace net {

// ProofSourceChromium implements the QUIC ProofSource interface.
// TODO(rtenneti): implement details of this class.
class NET_EXPORT_PRIVATE ProofSourceChromium : public ProofSource {
 public:
  ProofSourceChromium();
  ~ProofSourceChromium() override;

  // Initializes this object based on the certificate chain in |cert_path|,
  // and the PKCS#8 RSA private key in |key_path|. Signed certificate
  // timestamp may be loaded from |sct_path| if it is non-empty.
  bool Initialize(const base::FilePath& cert_path,
                  const base::FilePath& key_path,
                  const base::FilePath& sct_path);

  // ProofSource interface
  bool GetProof(const IPAddressNumber& server_ip,
                const std::string& hostname,
                const std::string& server_config,
                bool ecdsa_ok,
                const std::vector<std::string>** out_certs,
                std::string* out_signature,
                std::string* out_leaf_cert_sct) override;

 private:
  scoped_ptr<crypto::RSAPrivateKey> private_key_;
  std::vector<std::string> certificates_;
  std::string signed_certificate_timestamp_;

  DISALLOW_COPY_AND_ASSIGN(ProofSourceChromium);
};

}  // namespace net

#endif  // NET_QUIC_CRYPTO_PROOF_SOURCE_CHROMIUM_H_


text: algorithm progress for practice


text:
using System;
using System.IO;
using System.Threading;
using CrossPlatformAdapter;

using Guards;

using MetroLog.Internal;

namespace MetroLog
{
    public static class LogManagerFactory
    {
        private static readonly ILogConfigurator configurator = PlatformAdapter.Current.Resolve<ILogConfigurator>();
        private static readonly Lazy<ILogManager> lazyLogManager;
        private static LoggingConfiguration defaultConfig = configurator.CreateDefaultSettings();

        static LogManagerFactory()
        {
            lazyLogManager = new Lazy<ILogManager>(() => CreateLogManager(), LazyThreadSafetyMode.ExecutionAndPublication);
        }

        public static LoggingConfiguration CreateLibraryDefaultSettings()
        {
            return configurator.CreateDefaultSettings();
        }

        public static LoggingConfiguration CreateLibrarySettings(Stream configFileStream)
        {
            return configurator.CreateFromXml(configFileStream);
        }

        public static ILogManager CreateLogManager(LoggingConfiguration config = null)
        {
            var cfg = config ?? DefaultConfiguration;
            cfg.Freeze();

            ILogManager manager;
            var logManagerCreator = PlatformAdapter.Current.TryResolve<ILogManagerCreator>();
            if (logManagerCreator != null)
            {
                manager = logManagerCreator.Create(cfg);
            }
            else
            {
                manager = new LogManagerBase(cfg);
            }

            configurator.OnLogManagerCreated(manager);

            return manager;
        }

        public static LoggingConfiguration DefaultConfiguration
        {
            get
            {
                return defaultConfig;
            }
            set
            {
                Guard.ArgumentNotNull(() => value);
                if (lazyLogManager.IsValueCreated)
                {
                    throw new InvalidOperationException("Must set DefaultConfiguration before any calls to DefaultLogManager");
                }

                defaultConfig = value;
            }
        }

        public static ILogManager DefaultLogManager
        {
            get
            {
                return lazyLogManager.Value;
            }
        }
    }
}


text:
This is my collection of helpers for the ACME editor.
Mostly copy and paste from other sources (according
licenses to be found in the respective subfolders).


text:
function [peakRow, peakCol] = psfFindPeak(input)
% Find row/col corresponding to max of two dimensional PSF input.
%
% Syntax:
%   [peakRow, peakCol] = psfFindPeak(input)
%
% Description:
%    Find row/col corresponding to max of two dimensional PSF input.
%
%    This method works reasonably when there is more than one maximum in
%    the input, in that it returns the coordinates of one of the maxima.
%    No thought is investing in figuring out which one if there are
%    multiple locations with the identical maximal value -- it's just
%    whatever the max() routine picks.
%
% Inputs:
%    input   - Two-dimensional PSF input
%
% Outputs:
%    peakRow - Corresponding row to PSF Max
%    peakCol - Corresponding column to PSF Max
%
% Optional key/value pairs:
%    None.
%

% History:
%    12/22/09  dhb  Encapsulate this as a function with improved method.
%    11/10/17  jnm  Comments & formatting
%    01/11/18  jnm  Formatting update to match Wiki

% Examples:
%{
    [pR pC] = psfFindPeak([0 1 10 1; 1 2 5 1; 1 1 1 4])
%}

[m, n] = size(input);
[~, ind] = max(input(:));
[peakRow, peakCol] = ind2sub([m, n], ind);
if (input(peakRow, peakCol) ~= max(input(:)))
    error('Value at max location is not input maximum. Hmmm.');
end

end


text:
if (NOT nanomsg_NAME)

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)

include (ExternalProject)
include (ExternalSource)
include (BuildSupport)

external_source (nanomsg
    0.4
    nanomsg-0.4-beta.tar.gz
    374dca0a9c0ca1403f2a920400acc33e
    http://download.nanomsg.org)

message ("Installing ${nanomsg_NAME} into FlyEM build area: ${BUILDEM_DIR} ...")
if (${APPLE})
    message ("nanomsg install: Detected Apple platform.")
	set (LIBFILE "dylib")
elseif (${UNIX})
    message ("nanomsg install: Detected UNIX-like platform.")
	set (LIBFILE "so")
# set (COMPILE_FLAGS "-lrt")
elseif (${WINDOWS})
    message (FATAL_ERROR "Detected Windows platform.  No nanomsg setup for it yet!")
endif ()

ExternalProject_Add(${nanomsg_NAME}
    PREFIX            ${BUILDEM_DIR}
    URL               ${nanomsg_URL}
    URL_MD5           ${nanomsg_MD5}
    UPDATE_COMMAND    ""
    PATCH_COMMAND     ""
    CONFIGURE_COMMAND ./configure
        --prefix=${BUILDEM_DIR}
        --enable-shared
        --enable-static
        LDFLAGS=${BUILDEM_LDFLAGS}
        CPPFLAGS=-I${BUILDEM_DIR}/include
    BUILD_COMMAND     ${BUILDEM_ENV_STRING} $(MAKE)
    BUILD_IN_SOURCE   1
    INSTALL_COMMAND   ${BUILDEM_ENV_STRING} $(MAKE) install

# BUILD_COMMAND     ${BUILDEM_ENV_STRING} $(MAKE) ${COMPILE_FLAGS}
#    INSTALL_COMMAND   ${CMAKE_COMMAND} -E copy
#        ${nanomsg_SRC_DIR}/libnanomsg.${LIBFILE}.${nanomsg_RELEASE} ${BUILDEM_LIB_DIR}/libnanomsg.${LIBFILE}
)

set_target_properties(${nanomsg_NAME} PROPERTIES EXCLUDE_FROM_ALL ON)

set (nanomsg_STATIC_LIBRARIES ${BUILDEM_LIB_DIR}/libnanomsg.a)

endif (NOT nanomsg_NAME)


text:
import styled from 'styled-components'

import type { TTestable } from '@/spec'

import Img from '@/Img'
import css, { theme } from '@/utils/css'

export const Wrapper = styled.div.attrs(({ testid }: TTestable) => ({
  'data-test-id': testid,
}))<TTestable>``

export const Label = styled.div`
  ${css.flex('align-center')};
`
export const Icon = styled(Img)`
  ${css.size(14)};
  fill: ${theme('thread.articleDigest')};
`
export const Text = styled.div`
  font-size: 12px;
  color: ${theme('thread.articleDigest')};
  margin-right: 5px;
`


text:
package io.minetweak.inventory;

/**
 * Represents an inventory in the game.
 *
 * @author Logan Gorence
 */
public interface IInventory {

    /**
     * Get the amount of slots in this inventory.
     * @return Amount of slots in the inventory
     */
    int getSlotCount();

    /**
     * Get an IItemStack for a specified slot.
     * @param slot Slot index
     * @return Slot's item(s)
     */
    IItemStack getSlot(int slot);

}


text:
$(function () {
/*
    function sidebar_resize() {
        var width = $('.col-sm-3').width();
        var padding_left = parseFloat($('#sidebar').css('padding-left').replace('px', ''));
        var padding_right = parseFloat($('#sidebar').css('padding-right').replace('px', ''));
        width -=  padding_left + padding_right;
        $('#sidebar').width(width);
    };

    $(window).scroll(function () {
        var y = $(window).scrollTop();
        if (y > 0) {
            $("#main-navbar").addClass('shadowed');
        } else {
            $("#main-navbar").removeClass('shadowed');
        }
    });

    $(window).resize(function () {
        sidebar_resize();
    });
    var navbar_height = parseFloat($('#main-navbar').css('height'), 10) * 1.38;
    $('#sidebar').affix({
        offset: { top: $('#sidebar').offset().top - navbar_height }
    });

    sidebar_resize();
*/
    if (window.location.hash) {
        var pos = $(window.location.hash).offset().top - navbar_height;
        window.setTimeout(function () {
            $('html, body').animate({ scrollTop: pos }, 100);
        }, 50);
    }

    // initialize fancy tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // resizer for large codeblocks
    $('div.code').add('pre.notranslate').each(function () {
        if (this.clientHeight < this.scrollHeight) {
            $(this).after('<button class="codeblock_resizer btn btn-default btn-sm">Expand</button>')
                .css('height', '300px').css('max-height', 'none')
                .data('original_height', this.clientHeight);
        }
    });

    $('[data-trigger="manual"]').hover(function () {
        var placement;
        if ($('body').width() < 753) {
            placement = 'bottom';
        } else {
            placement = 'left';
        }
        $(this).data('bs.tooltip').options.placement = placement;
        $(this).tooltip('show');
    }, function() {
        $(this).tooltip('hide');
    });

    if (navigator.appName.toLowerCase() == 'konqueror') return;
    $('.codeblock_resizer').click(function () {
        $codeblock = $(this).prev();
        if (!$codeblock.hasClass('codeblock_expanded')) {
            $codeblock.addClass('codeblock_expanded');
            $codeblock.animate({
                'height': $codeblock[0].scrollHeight
            }, 500);
            $(this).text('Collapse');
        } else {
            $codeblock.removeClass('codeblock_expanded');
            $codeblock.animate({
                'height': $codeblock.data('original_height')
            }, 500);
            $(this).text('Expand');
        }
    });
});


text:
import PusherLink from "../PusherLink"
import { parse } from "graphql"
import Pusher from "pusher-js"
import { Operation } from "@apollo/client/core"
import pako from 'pako'

type MockChannel = {
  bind: (action: string, handler: Function) => void,
}

describe("PusherLink", () => {
  var channelName = "abcd-efgh"
  var log: any[]
  var pusher: any
  var options: any
  var link: any
  var query: any
  var operation: Operation

  beforeEach(() => {
    log = []
    pusher = {
      _channels: {},
      trigger: function(channel: string, event: string, data: any) {
        var handlers = this._channels[channel]
        if (handlers) {
          handlers.forEach(function(handler: [string, Function]) {
            if (handler[0] == event) {
              handler[1](data)
            }
          })
        }
      },
      subscribe: function(channel: string): MockChannel {
        log.push(["subscribe", channel])
        var handlers = this._channels[channel]
        if (!handlers) {
          handlers = this._channels[channel] = []
        }

        return {
          bind: (action: string, handler: Function): void => {
            handlers.push([action, handler])
          }
        }
      },
      unsubscribe: (channel: string): void => {
        log.push(["unsubscribe", channel])
      },
    }

    options = {
      pusher: (pusher as unknown) as Pusher
    }
    link = new PusherLink(options)

    query = parse("subscription { foo { bar } }")

    operation = ({
      query: query,
      variables: { a: 1 },
      operationId: "operationId",
      operationName: "operationName",
      getContext: () => {
        return {
          response: {
            headers: {
              get: (headerName: string) => {
                if (headerName == "X-Subscription-ID") {
                  return channelName
                } else {
                  throw "Unsupported header name: " + headerName
                }
              }
            }
          }
        }
      }
    } as unknown) as Operation
  })

  it("forwards errors to error handlers", () => {
    let passedErrorHandler: Function = () => {}

    var observable = link.request(operation, function(_operation: Operation): any {
      return {
        subscribe: (options: { next: Function, error: Function, complete: Function }): void => {
          passedErrorHandler = options.error
          {}
        }
      }
    })

    let errorHandlerWasCalled = false
    function createdErrorHandler(_err: Error) {
      errorHandlerWasCalled = true
    }

    observable.subscribe(function(result: any) {
      log.push(["received", result])
    }, createdErrorHandler)

    if (passedErrorHandler) {
      passedErrorHandler(new Error)
    }

    expect(errorHandlerWasCalled).toBe(true)
  })

  it("doesn't call the link request's `complete` handler because otherwise Apollo would clean up subscriptions", () => {
    let passedComplete: Function = () => {}

    var observable = link.request(operation, function(_operation: Operation): any {
      return {
        subscribe: (options: { next: Function, error: Function, complete: Function }): void => {
          passedComplete = options.complete
          {}
        }
      }
    })

    observable.subscribe(function(result: any) {
      log.push(["received", result])
    }, null, function() { log.push(["completed"])})

    expect(log).toEqual([])
    expect(passedComplete).toBeUndefined()
  })

  it("delegates to pusher", () => {
    var requestFinished: Function = () => {}

    var observable = link.request(operation, function(_operation: Operation): any {
      return {
        subscribe: (options: { next: Function }): void => {
          requestFinished = options.next
        }
      }
    })

    // unpack the underlying subscription
    observable.subscribe(function(result: any) {
      log.push(["received", result])
    })

    // Pretend the HTTP link finished
    requestFinished({})

    pusher.trigger(channelName, "update", {
      result: {
        data: "data 1"
      },
      more: true
    })

    pusher.trigger(channelName, "update", {
      result: {
        data: "data 2"
      },
      more: false
    })

    expect(log).toEqual([
      ["subscribe", "abcd-efgh"],
      ["received", { data: "data 1" }],
      ["received", { data: "data 2" }],
      ["unsubscribe", "abcd-efgh"]
    ])
  })

  it("delegates a manual unsubscribe to pusher", () => {
    var requestFinished: Function = () => {}

    var observable = link.request(operation, function(_operation: Operation): any {
      return {
        subscribe: (options: { next: Function }): void => {
          requestFinished = options.next
        }
      }
    })

    // unpack the underlying subscription
    var subscription = observable.subscribe(function(result: any) {
      log.push(["received", result])
    })

    // Pretend the HTTP link finished
    requestFinished({})

    pusher.trigger(channelName, "update", {
      result: {
        data: "data 1"
      },
      more: true
    })

    subscription.unsubscribe()

    expect(log).toEqual([
      ["subscribe", "abcd-efgh"],
      ["received", { data: "data 1" }],
      ["unsubscribe", "abcd-efgh"]
    ])
  })

  it("throws an error when no `decompress:` is configured", () => {
    const link = new PusherLink({
      pusher: new Pusher("123"),
    })

    const observer = {
      next: (_result: object) => {},
      complete: () => {},
    }

    const payload = {
      more: true,
      compressed_result: "abcdef",
    }

    expect(() => {
      link._onUpdate("abc", observer, payload)
    }).toThrow("Received compressed_result but PusherLink wasn't configured with `decompress: (result: string) => any`. Add this configuration.")
  })

  it("decompresses compressed_result", () => {
    const link = new PusherLink({
      pusher: new Pusher("123"),
      decompress: (compressed) => {
        const buff = Buffer.from(compressed, 'base64');
        return JSON.parse(pako.inflate(buff, { to: 'string' }));
       },
    })

    const results: Array<object | string> = []

    const observer = {
      next: (result: object) => { results.push(result) },
      complete: () => { results.push("complete") },
    }

    const compressedData = pako.deflate(JSON.stringify({ a: 1, b: 2}))
    // Browsers have `TextEncoder` for this
    const compressedStr = Buffer.from(compressedData).toString("base64")
    const payload = {
      more: true,
      compressed_result: compressedStr,
    }

    // Send a dummy payload and then terminate the subscription
    link._onUpdate("abc", observer, payload)
    link._onUpdate("abc", observer, { more: false })
    expect(results).toEqual([{a: 1, b: 2}, "complete"])
  })
})


text:
![ReactJS](/lib/images/react-components.png)

experimental repo for ReactJS with Fluxxor

Open three terminal tabs (db, server, client)

```sh
npm install
chmod +x launcher.sh
mongod
node server.js
./launcher.sh
```

## License
[MIT License](https://raw.githubusercontent.com/mjw56/react-components/master/LICENSE)


text:
package org.effectivejava.examples.chapter05.item28;

public class EmptyStackException extends RuntimeException {
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('profiles', '0008_auto_20150801_1847'),
        ('Forum', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='musicianpost',
            options={'ordering': ['-score', '-timestamp']},
        ),
        migrations.AlterModelOptions(
            name='musicianresponse',
            options={'ordering': ['-score', '-timestamp']},
        ),
        migrations.AlterModelOptions(
            name='nonmusicianpost',
            options={'ordering': ['-score', '-timestamp']},
        ),
        migrations.AlterModelOptions(
            name='nonmusicianresponse',
            options={'ordering': ['-score', '-timestamp']},
        ),
        migrations.AddField(
            model_name='musicianpost',
            name='location',
            field=models.ForeignKey(to='profiles.Location', default=''),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='nonmusicianpost',
            name='location',
            field=models.ForeignKey(to='profiles.Location', default=''),
            preserve_default=False,
        ),
    ]


text:
require 'spec_helper'
module Alf
  module Sql
    describe Builder, "order_by_clause" do

      let(:ordering){ Ordering.new([[:name, :asc], [:city, :desc]]) }

      context 'without desaliaser' do
        subject{ builder.order_by_clause(ordering) }

        let(:expected){
          [:order_by_clause,
            [:order_by_term, [:column_name, 'name'], 'asc'],
            [:order_by_term, [:column_name, 'city'], 'desc'] ]
        }

        it{ should eq(expected) }
      end

      context 'with a desaliaser' do
        let(:desaliaser){
          ->(a){
            if a == "name"
              [:qualified_name, [:range_var_name, "t1"], [:column_name, a]]
            else
              nil
            end
          }
        }

        subject{ builder.order_by_clause(ordering, &desaliaser) }

        let(:expected){
          [:order_by_clause,
            [:order_by_term, [:qualified_name, [:range_var_name, "t1"], [:column_name, 'name']], 'asc'],
            [:order_by_term, [:column_name, 'city'], 'desc'] ]
        }

        it{ should eq(expected) }
      end

    end
  end
end


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

public class Attack : MonoBehaviour
{
    public Entity parent;
    public float minDamage = 0.0f, maxDamage = 0.0f;
    public float cooldown = 0.5f;
    public float animTime = 0.25f;
    public float timeSinceUse = 0.0f;
    public float powerAttackDamageModifier = 2.0f;
    public float powerAttackCooldownModifier = 2.0f;
    public float powerAttackSpeedModifier = 2.0f;
    protected bool isPowerAttack = false;
    public AttackType attackType = AttackType.NOTSET;
    // Damage type
    // Debuffs
    // Etc.

	public enum AttackType
	{
		MELEE,
		RANGED,
		MAGIC,
		OTHER,
		BUNNY,
		NOTSET
	}

    public virtual void Update()
    {
        timeSinceUse += Time.deltaTime;
    }
    public virtual void Use(int attackMode, Vector2 pos, Vector2 aim)
    {
    }

    public void TryToUse(int attackMode, Vector2 pos, Vector2 aim)
    {
        if (timeSinceUse >= (isPowerAttack ? cooldown * powerAttackCooldownModifier : cooldown))
        {
            timeSinceUse = 0.0f;
            GetComponent<AudioSource>().Play();
            Use(attackMode, pos, aim);
        }
    }

    public virtual void UpdateAttackMove()
    {

    }

    public virtual float getDamageMultiplier()
	{
		return 1F;
	}

    public virtual void AttackMoveEnded()
    {

    }
}


text:
import logging
from pyvisdk.exceptions import InvalidArgumentError

########################################
# Automatically generated, do not edit.
########################################

log = logging.getLogger(__name__)

def VmfsDatastoreMultipleExtentOption(vim, *args, **kwargs):
    '''Datastore addition policy to use multiple extents on the disk for a VMFS
    datastore. Multiple extents implies that more than one disk partition will be
    created on the disk for creating or increasing the capacity of a VMFS
    datastore. Multiple extents are needed when unpartitioned space is fragmented
    in the existing partition layout of the disk.'''

    obj = vim.client.factory.create('ns0:VmfsDatastoreMultipleExtentOption')

    # do some validation checking...
    if (len(args) + len(kwargs)) < 2:
        raise IndexError('Expected at least 3 arguments got: %d' % len(args))

    required = [ 'vmfsExtent', 'layout' ]
    optional = [ 'partitionFormatChange', 'dynamicProperty', 'dynamicType' ]

    for name, arg in zip(required+optional, args):
        setattr(obj, name, arg)

    for name, value in kwargs.items():
        if name in required + optional:
            setattr(obj, name, value)
        else:
            raise InvalidArgumentError("Invalid argument: %s.  Expected one of %s" % (name, ", ".join(required + optional)))

    return obj


text:
require 'womanizer'

describe Womanizer do
  let(:text) { 'Kleine Kinder können keine kleinen Kirschkerne knacken' }
  let(:encoded) { subject.encode(text) }
  let(:words) { encoded.split }
  it 'encodes every letter into a case variation' do
    words.should have(text.bytes.length).items
    words.each do |w|
      w.should match(/\Amorewom[ae]n\z/i)
    end
  end

  it 'decodes' do
    recoded = subject.decode( encoded )
    recoded.should == text
  end

  it 'is ruby' do
    subject.define!
    foo = 23
    res = ok moREwoMAn moREwOMAN moREwOMAN
    res.should == 23
  end
end


text:
spin = {}
require 'iguanaServer'

-- Helper functions
local function makeUrl(Config)
   local Protocol = Config.https and 'https://' or 'http://'
   return Protocol .. Config.host .. ':' .. Config.port
end

local function getIguana(Config)
   return iguanaServer.connect{
      url = makeUrl(Config),
      username = Config.user,
      password = Config.pass
   }
end

local function checkChannelName(Name)
   local Start, Finish = string.find(Name, spin.conf.params.sandbox_name .. ' %x+')
   return Start == 1 and Finish == 61
end

local function makeZip(Sandbox, Main, Project, Samples, Shared, Other)
   local DirNames = {Sandbox.channel.from_http.guid:nodeValue(), 'other', 'shared'}

   local Tree = {
      [Sandbox.channel.from_http.guid:nodeValue()] = {
         ['main.lua'] = Main,
         ['project.prj'] = Project,
         ['samples.json'] = Samples
      },
      ['other'] = Other or {},
      ['shared'] = Shared or {}
   }
   return filter.base64.enc(filter.zip.deflate(Tree))
end
-- End helpers

-- Returns a "Translator" object. Only called by a Node object.
local function getTranslator(ChannelGuid, Iggy, Sandbox, Node)

   local Translator = {}

   local function checkSelfParam(self)
      if self ~= Translator then
         error("Try calling the function using colon syntax (e.g. Translator:funcName()).", 3)
      end
   end

   ------------------------
   -- PUBLIC TRANSLATOR API
   ------------------------
   function Translator:baseUrl()
      checkSelfParam(self)
      trace(iguana.webInfo())
      trace(Sandbox)

      -- This line is waiting for web port to be available in channel API.
      -- Fallbacks are (a) hard-coding in config, and (b) hoping remote port is the same as local one.
      local TargetPort = self:node():httpPort() or iguana.webInfo().https_channel_server.port
      return self:node():protocol() .. self:node():host() .. ':' .. TargetPort .. '/' .. Sandbox.channel.from_http.mapper_url_path .. '/'
   end

   function Translator:cGuid()
      checkSelfParam(self)
      return Sandbox.channel.guid:nodeValue()
   end

   function Translator:tGuid()
      checkSelfParam(self)
      return Sandbox.channel.from_http.guid:nodeValue()
   end

   function Translator:node()
      checkSelfParam(self)
      return Node
   end

   function Translator:start()
      checkSelfParam(self)
      Iggy:startChannel{guid = self:cGuid(), live=true}
      if (Iggy:pollChannelStatus{guid = self:cGuid(), channel_status='on'}) then
         return self
      end
      error("Could not start sandbox channel '" .. Sandbox.channel.name:nodeValue())
   end

   function Translator:stop()
      checkSelfParam(self)
      Iggy:stopChannel{guid = self:cGuid(), live=true}
      if (Iggy:pollChannelStatus{guid = self:cGuid(), channel_status='off'}) then
         return self
      end
      error("Could not stop sandbox channel '" .. Sandbox.channel.name:nodeValue())
   end

   function Translator:reset()
      checkSelfParam(self)
      return self:stop():start()
   end

   function Translator:overload(ZipTree)
      checkSelfParam(self)
      local Success, Failure = pcall(function()
            return self:reset()
         end)
      local Url = Translator:baseUrl() .. 'overload'
      local Result, Code = net.http.post{url = Url, body=json.serialize{data=ZipTree, compact=true}, live=true}
      trace(Result)
      if Code == 200 then
         return self
      end
      error("Overload failed.")
   end

   function Translator:run(DataSet, Options)
      checkSelfParam(self)
      local Options = Options or {}
      local Url = Translator:baseUrl() .. 'go'
      local Result, Code = net.http.post{url = Url, body=json.serialize{data={DataSet = DataSet, Options = Options}, compact=true}, live=true}
      trace (Result)
      if Code ~= 200 then
         error{error = Result, code = Code}
      end
      --Echoes back the request by default (if no action specified in request url)
      return json.parse{data=Result}
   end

   function Translator:quit()
      checkSelfParam(self)
      self:stop()
      Iggy:removeChannel{guid = self:cGuid()}
      return true
   end
   ------------------------
   ------------------------

   return Translator
end

---------------------------------------
local function getNode(Config)
   local Iggy = getIguana(Config)

   -- Private functions
   local function getParamsHttps(Num)
      local Conf = Iggy:getDefaultConfig{
         source = iguanaServer.FROM_HTTPS,
         destination = iguanaServer.TO_CHANNEL
      }
      Conf.channel.name = spin.conf.params.sandbox_name .. ' ' .. Num
      Conf.channel.from_http.mapper_url_path = spin.conf.params.sandbox_uri .. "_" .. Num
      return Conf
   end

   local function setupTranslator(Sandbox)
      local Project = json.serialize{data = {
            Name = Sandbox.channel.name:nodeValue(),
            LuaDependencies = {},
            OtherDependencies = {}
         }
      }
      local Samples = json.serialize{data={}}

      local TranslatorName = Sandbox.channel.from_http.guid:nodeValue()
      local CleanedTranslatorName = TranslatorName:gsub('-', "_")
      local MyMain = spin.conf.defaults.main:gsub('PLACEHOLDER', CleanedTranslatorName )

      -- Note: Project and Samples below are not currently used, but can be, if we should ever
      -- want to launch a sandbox translator preloaded with dependencies or sample data.
      local ReadyToGo = makeZip(Sandbox, MyMain, Project, Samples)
      Iggy:importProject{guid=Sandbox.channel.from_http.guid:nodeValue(), project=ReadyToGo, live=true}
      return
   end

   local function findSandbox(Guid)
      local Success, Result = pcall(function()
            return Iggy:getChannelConfig{guid = Guid}
         end)
      return Success and Result or nil
   end

   local function findAnySandbox()
      local Conf = Iggy:listChannels()
      for i = 1, Conf:child("IguanaStatus"):childCount("Channel")  do
         local Channel = Conf.IguanaStatus:child("Channel", i)
         local Start, Finish = string.find(Channel.Name:nodeValue(), spin.conf.params.sandbox_name .. ' %x+')
         if (Start == 1 and Finish == 61) then
            return Iggy:getChannelConfig{guid = Channel.Guid:nodeValue()}
         end
      end
      return nil
   end

   local function makeSandbox()
      local Success, Result = pcall(function()
            math.randomseed(os.ts.time())
            local Num = math.random(9999999)
            local NewChannel = Iggy:addChannel{config = getParamsHttps(Num), live = true}
            trace(NewChannel)
            NewChannel.channel.name = NewChannel.channel.name:nodeValue():gsub(Num, NewChannel.channel.guid:nodeValue())
            NewChannel.channel.from_http.mapper_url_path = NewChannel.channel.from_http.mapper_url_path:nodeValue():gsub(Num, NewChannel.channel.guid:nodeValue())
            Iggy:updateChannel{config=NewChannel, live = true}
            setupTranslator(NewChannel)
            local Guid = NewChannel.channel.from_http.guid:nodeValue()
            local CommitResult = Iggy:saveProjectMilestone{guid = Guid, comment = "Remotely created by Spinner", live = true}
            Iggy:bumpProject{guid = Guid, commit_id = CommitResult.commit_id, live = true}
            return NewChannel
         end)
      if Success then
         return Result
      end
      error(Result)
   end

   local function findOrMakeSandbox(Guid)
      local Existing = nil
      if Guid then
         Existing = findSandbox(Guid)
         if not Existing then
            error("Could not find sandbox channel " .. Guid)
         end
      else
         Existing = findAnySandbox()
      end
      if Existing then
         return Existing
      end
      return makeSandbox()
   end

   local function clearSandboxes()
      -- uncomment the next line to avoid accidental clearouts
         if true then return true end
      local Conf = Iggy:listChannels()

      -- first look by GUID
      for i = 1, Conf:child("IguanaStatus"):childCount("Channel") do
         local Channel = Conf.IguanaStatus:child("Channel", i)
         -- trace(spin.conf.params.sandbox_name)
         if (checkChannelName(Channel.Name:nodeValue())) then
            Iggy:stopChannel{guid=Channel.Guid:nodeValue(), live=true}
            if (Iggy:pollChannelStatus{guid=Channel.Guid:nodeValue(), channel_status='off'}) then
               Iggy:removeChannel{guid=Channel.Guid:nodeValue(), live=true}
            end
         end
      end

      -- then clean up any with integer names
      for i = 1, Conf:child("IguanaStatus"):childCount("Channel") do
         local Channel = Conf.IguanaStatus:child("Channel", i)
         -- trace(spin.conf.params.sandbox_name)
         local Start, Finish = string.find(Channel.Name:nodeValue(), spin.conf.params.sandbox_name .. ' %d+')
         if Start then
            Iggy:stopChannel{guid=Channel.Guid:nodeValue(), live=true}
            if (Iggy:pollChannelStatus{guid=Channel.Guid:nodeValue(), channel_status='off'}) then
               Iggy:removeChannel{guid=Channel.Guid:nodeValue(), live=true}
            end
         end
      end
      return true
   end
   -- End private functions

   local Node = {}
   local function checkSelfParam(self)
      if self ~= Node then
         error("Try calling the function using colon syntax (e.g. Node:funcName()).", 3)
      end
   end

   ------------------
   -- PUBLIC NODE API
   ------------------
   function Node:protocol()
      return Config.https and 'https://' or 'http://'
   end

   function Node:host()
      checkSelfParam(self)
      return Config.host
   end

   function Node:port()
      checkSelfParam(self)
      return Config.port
   end

   -- REMOVE THIS ONCE CHANNEL CONFIG CAN SUPPLY WEB PORT
   function Node:httpPort()
      checkSelfParam(self)
      return Config.http_port
   end
   -----------

   function Node:url()
      checkSelfParam(self)
      return makeUrl(Config)
   end

   function Node:getTranslator(ChannelGuid)
      checkSelfParam(self)
      local Sandbox = findOrMakeSandbox(ChannelGuid)
      return getTranslator(ChannelGuid, Iggy, Sandbox, self)
   end

   function Node:getTranslators()
      checkSelfParam(self)
      local Translators = {}
      local Conf = Iggy:listChannels()
      for i = 1, Conf:child("IguanaStatus"):childCount("Channel") do
         local Channel = Conf.IguanaStatus:child("Channel", i)
         -- trace(spin.conf.params.sandbox_name)
         if (checkChannelName(Channel.Name:nodeValue())) then
            table.insert(Translators, self:getTranslator(Channel.Guid))
         end
      end
      return Translators
   end

   function Node:reset()
      checkSelfParam(self)
      clearSandboxes()
      return self
   end
   ------------------
   ------------------

   return Node
end

----------------------
function spin.getSpinner(Config)
   local Landscape = Config
   if Landscape['local'] then
      Landscape['local']['host'] = Landscape['local']['host'] or iguana.webInfo().ip
      Landscape['local']['port'] = Landscape['local']['port'] or iguana.webInfo().web_config.port
      Landscape['local']['https'] = Landscape['local']['https'] or iguana.webInfo().web_config.use_https
   end

   local function pickNode()
      -- Expand this to choose the least-busy node
      return 'local'
   end

   local Spinner = {}
   local function checkSelfParam(self)
      if self ~= Spinner then
         error("Try calling the function using colon syntax (e.g. Spinner:funcName()).", 3)
      end
   end

   ---------------------
   -- PUBLIC SPINNER API
   ---------------------
   function Spinner:getNode(Name)
      checkSelfParam(self)
      local Target = Name or pickNode()
      return getNode(Landscape[Target])
   end

   function Spinner:getNodes()
      checkSelfParam(self)
      local Nodes = {}
      for Name, Conf in pairs(Landscape) do
         Nodes[Name] = self:getNode(Name)
      end
      return Nodes
   end

   function Spinner:getTranslator()
      checkSelfParam(self)
      local Node = self:getNode()
      return Node:getTranslator()
   end
   ---------------------
   ---------------------

   return Spinner
end

-- These two are not in current use, but might be useful in the coming days.
function spin.makeProject(Sandbox, Vars)
   local Project = {
      Name = Sandbox.channel.name:nodeValue(),
      LuaDependencies = Vars.shared or {},
      OtherDependencies = Vars.other or {}
   }
   return json.serialize{data=Project}
end

function spin.checkSandbox(Status, Guid)
   for i = 1, Status:child("IguanaStatus"):childCount("Channel") do
      local Channel = Status.IguanaStatus:child("Channel", i)
      if Channel.Guid:nodeValue() == Guid then
         return Channel.Status:nodeValue()
      end
   end
   error("Sandbox channel was not found")
end

spin.conf = {}
spin.conf.params = {
   sandbox_name = 'SANDBOX CHANNEL DO NOT TOUCH',
   sandbox_uri = 'sandbox_do_not_touch'
}

spin.conf.defaults = {
   main = [==[
function main(Data)
   loadUrls_PLACEHOLDER()
   print(Data)
   local Stack = nil

   originalRespond_PLACEHOLDER = net.http.respond
   originalPush_PLACEHOLDER = queue.push

   local Success, ErrMsg = xpcall(
      function()
         originalRespond_PLACEHOLDER(serveRequest_PLACEHOLDER(Data))
      end,
      function()
         Stack = debug.traceback()
         originalRespond_PLACEHOLDER(serveError_PLACEHOLDER("Internal error", 500, Stack, Data))
      end)
end

function catch_PLACEHOLDER(Args)
   return Args
end

function loadUrls_PLACEHOLDER()
   Root = '/sandbox_do_not_touch_PLACEHOLDER'
   Actions = {
      ['overload'] = overload_PLACEHOLDER,
      ['go'] = go_PLACEHOLDER
   }
end

function serveRequest_PLACEHOLDER(Data)
   local Params = net.http.parseRequest{data = Data}
   local LastSlash = string.find(Params.location, "/[^/]*$")
   local Command = Params.location:sub(LastSlash + 1)
   if Actions[Command] then
      local Result = Actions[Command](Params)
      if Result.error and Result.code then
         return {body=json.serialize{data=Result}, code = Result.code, entity_type = 'text/json'}
      end
      local BodyData = json.serialize{data=Result}
      print(BodyData)
      return {body=BodyData, entity_type="text/json"}
   end

   --The default behaviour of a "fake" translator is simply to echo back the request
   return {body=Data, entity_type="text/plain"}
end

function serveError_PLACEHOLDER(String, Code, Stack, Data)
   local Body = {error = String}
   if Stack then
      Body.stack = Stack
   end
   if Request then
      Body.data = Data
   end
   -- Only log internal errors
   if Code > 499 then
      local ErrId = queue.push{data = Data}
      iguana.logError(Stack .. '\n' .. Data, ErrId)
   end
   local BodyData = json.serialize{data=Body}
   print(BodyData)
   return {code = Code, body = BodyData, entity_type = 'text/json'}
end

function overload_PLACEHOLDER(Params)
   local ZipTree = json.parse{data=Params.body}
   trace(ZipTree)
   require = function(Module)
      newRequire_PLACEHOLDER(Module, ZipTree)
   end
   updateVmds_PLACEHOLDER(ZipTree)

   local LuaText = ZipTree['main.lua']
   LuaText = LuaText:gsub('function main', 'function simulatedMain_PLACEHOLDER')
   local ReadyToRun = loadstring(LuaText)
   local Success, Result = pcall(ReadyToRun)
   if not Success then
      error("Error in code to be overloaded: " .. Result)
   end
   return {status = 'THAT TOTALLY WORKED'}
end

function go_PLACEHOLDER(Params)
   if not simulatedMain_PLACEHOLDER then
      return {error = 'This translator must be overridden before it can be run.', code = 403}
   end

   local Payload = json.parse{data=Params.body}
   local DataSet = Payload.DataSet
   local Options = Payload.Options

   -- This table will return messages for regressions and tests for unit testing
   local Results = {['tests'] = {}, ['messages'] = {}}

   -- Return nil on queue.push for the first time simulatedMain is run (i.e.
   -- without data for unit testing)
   queue.push = function() return nil end
   if #DataSet > 0 then
      Results.tests = simulatedMain_PLACEHOLDER(DataSet[1])
   else
      Results.tests = simulatedMain_PLACEHOLDER()
   end

   local doThisInstead = function(Args)
      table.insert(Results.messages, catch_PLACEHOLDER(Args))
   end

   net.http.respond = doThisInstead
   queue.push = doThisInstead

   for i = 1, #DataSet do
      simulatedMain_PLACEHOLDER(DataSet[i])
      if Options.OneForOne then
         if #Results.messages < i then
            doThisInstead({data=''})
         end
      end
   end

   net.http.respond = originalRespond_PLACEHOLDER
   queue.push = originalPush_PLACEHOLDER

   return Results
end

function getNode_PLACEHOLDER(ProjectTree, Pieces)
   local Node = ProjectTree
   for i = 1, #Pieces do
      trace(Pieces[i])
      Node = Node[Pieces[i]]
	   if Node == nil then
         -- Required file is a shard file, not local
         Node = getNode_PLACEHOLDER(ProjectTree.shared, Pieces)
         break
      end
   end
   return Node
end

function newRequire_PLACEHOLDER(ModName, ZipTree)
   local Pieces = ModName:split_PLACEHOLDER('%.')
   Pieces[#Pieces] = Pieces[#Pieces] .. '.lua'
   local Node = getNode_PLACEHOLDER(ZipTree, Pieces)
   local LuaText = loadstring(Node)
   local Success, Result = pcall(LuaText)
   if not Success then
      error("Error in code to be overloaded: " .. Result)
   end
   return Result
end

function findVmd_PLACEHOLDER(Node, Path)
   local Pieces = Path:split_PLACEHOLDER('/')
   for i = 1, #Pieces do
      trace(Pieces[i])
      Node = Node[Pieces[i]]
   end
   return Node
end

function updateVmds_PLACEHOLDER(ZipTree)
   local LegacyFunctionNames = {
      'chm.fromXml',
      'chm.parse',
      'chm.transform',
      'chm.toXml',
      'db.tables',
      'hl7.message',
      'hl7.parse',
      'x12.message',
      'x12.parse',
   }
   for i = 1, #LegacyFunctionNames do
      local Parts = LegacyFunctionNames[i]:split_PLACEHOLDER('%.')
      local Original = _G[Parts[1]][Parts[2]]
      _G[Parts[1]][Parts[2]] = function(Table)
         Table.vmd_definition = findVmd_PLACEHOLDER(ZipTree.other, Table.vmd)
         return Original(Table)
      end
   end
end

function string.split_PLACEHOLDER(s, d)
   local t = {}
   local i = 0
   local f
   local match = '(.-)' .. d .. '()'
   if string.find(s, d) == nil then
      return {s}
   end
   for sub, j in string.gfind(s, match) do
      i = i + 1
      t[i] = sub
      f = j
   end
   if i~= 0 then
      t[i+1]=string.sub(s,f)
   end
   return t
end

   ]==]
}

spin.conf.filterwrap = [[
function main(Data)
   local Revised = chm.transform{vmd = 'EDreports_PeerNET_Test.vmd', data = Data}
   queue.push(Revised)
end
]]

spin.conf.scratch = os.fs.abspath("~") .. '/sandbox_tmp'

return spin


text:
import { BaseGestureConfig, ContinousBaseGesture } from './gesture';
import {
  ForceTouchGestureConfig,
  ForceTouchGestureHandlerEventPayload,
} from '../ForceTouchGestureHandler';

export class ForceTouchGesture extends ContinousBaseGesture<ForceTouchGestureHandlerEventPayload> {
  public config: BaseGestureConfig & ForceTouchGestureConfig = {};

  constructor() {
    super();

    this.handlerName = 'ForceTouchGestureHandler';
  }

  minForce(force: number) {
    this.config.minForce = force;
    return this;
  }

  maxForce(force: number) {
    this.config.maxForce = force;
    return this;
  }

  feedbackOnActivation(value: boolean) {
    this.config.feedbackOnActivation = value;
    return this;
  }
}

export type ForceTouchGestureType = InstanceType<typeof ForceTouchGesture>;