text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

    <property name="now" value="now()" dbms="mysql,h2"/>
    <property name="now" value="current_timestamp" dbms="postgresql"/>
    <property name="now" value="sysdate" dbms="oracle"/>

    <property name="autoIncrement" value="true" dbms="mysql,h2,postgresql,oracle"/>

    <property name="floatType" value="float4" dbms="postgresql, h2"/>
    <property name="floatType" value="float" dbms="mysql, oracle"/>

    <!--
        Added the entity Weight.
    -->
    <changeSet id="20160207193130" author="jhipster">
        <createTable tableName="weight">
            <column name="id" type="bigint" autoIncrement="${autoIncrement}">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="date_time" type="timestamp">
                <constraints nullable="false" />
            </column>

            <column name="systolic" type="integer">
                <constraints nullable="false" />
            </column>

            <column name="diastolic" type="integer">
                <constraints nullable="false" />
            </column>

            <column name="user_id" type="bigint"/>
            <!-- jhipster-needle-liquibase-add-column - Jhipster will add columns here, do not remove-->
        </createTable>
        <dropDefaultValue tableName="weight" columnName="date_time" columnDataType="datetime"/>

        <addForeignKeyConstraint baseColumnNames="user_id"
                                 baseTableName="weight"
                                 constraintName="fk_weight_user_id"
                                 referencedColumnNames="id"
                                 referencedTableName="jhi_user"/>

    </changeSet>
</databaseChangeLog>


text:
@class TableViewItem;

// Consumer protocol for Safe Browsing Privacy setting.
@protocol PrivacySafeBrowsingConsumer <ChromeTableViewConsumer>

// Reload cells for items. Does nothing if the model is not loaded yet.
- (void)reloadCellsForItems;

// Initializes item array for `safeBrowsingItems`.
- (void)setSafeBrowsingItems:(NSArray<TableViewItem*>*)safeBrowsingItems;

// Tells consumer if enterprise is enabled based on pref values in model.
- (void)setEnterpriseEnabled:(BOOL)enterpriseEnabled;

// Select `item`.
- (void)selectItem:(TableViewItem*)item;

// Shows enterprise pop up when info button is pressed in enterprise mode.
- (void)showEnterprisePopUp:(UIButton*)buttonView;

@end

#endif  // IOS_CHROME_BROWSER_UI_SETTINGS_PRIVACY_PRIVACY_SAFE_BROWSING_CONSUMER_H_

redpajama_set_name: RedPajamaGithub


text:
<!-- This file was autogenerated via cilium cmdref, do not edit manually-->

## cilium endpoint labels

Manage label configuration of endpoint

```
cilium endpoint labels [flags]
```

### Options

```
  -a, --add strings      Add/enable labels
  -d, --delete strings   Delete/disable labels
  -h, --help             help for labels
```

### Options inherited from parent commands

```
      --config string   config file (default is $HOME/.cilium.yaml)
  -D, --debug           Enable debug messages
  -H, --host string     URI to server-side API
```

### SEE ALSO

* [cilium endpoint](../cilium_endpoint)	 - Manage endpoints


text:
<?php

namespace Spatie\Backup\BackupHandlers\Database;

use Exception;
use Spatie\Backup\Console;

class DatabaseBuilder
{
    protected $database;
    protected $console;

    public function __construct()
    {
        $this->console = new Console();
    }

    public function getDatabase(array $realConfig)
    {
        try {
            $this->buildMySQL($realConfig);
        } catch (Exception $e) {
            throw new \Exception('Whoops, '.$e->getMessage());
        }

        return $this->database;
    }

    protected function buildMySQL(array $config)
    {
        $port = isset($config['port']) ? $config['port'] : 3306;

        $socket = isset($config['unix_socket']) ? $config['unix_socket'] : '';

        $this->database = new Databases\MySQLDatabase(
            $this->console,
            $config['database'],
            $config['username'],
            $config['password'],
            $this->determineHost($config),
            $port,
            $socket
        );
    }

    /**
     * Determine the host from the given config.
     *
     * @param array $config
     *
     * @return string
     *
     * @throws Exception
     */
    public function determineHost(array $config)
    {
        if (isset($config['host'])) {
            return $config['host'];
        }

        if (isset($config['read']['host'])) {
            return $config['read']['host'];
        }

        throw new Exception('could not determine host from config');
    }
}


text:
package weka.classifiers.bayes.net;

import weka.core.FastVector;
import weka.core.SerializedObject;
import weka.estimators.Estimator;

// Referenced classes of package weka.classifiers.bayes.net:
//            EditableBayesNet

class m_CPT extends m_CPT {

    static final long serialVersionUID = 1L;
    FastVector m_children;
    int m_nParent;
    Estimator m_CPT[][];
    final EditableBayesNet this$0;

    public void undo() {
        try {
            for (int i = 0; i < m_children.size(); i++) {
                int j = ((Integer)m_children.elementAt(i)).intValue();
                deleteArc(m_nParent, j);
                SerializedObject serializedobject = new SerializedObject(m_CPT[i]);
                m_Distributions[j] = (Estimator[])(Estimator[])serializedobject.getObject();
            }

        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public void redo() {
        try {
            for (int i = 0; i < m_children.size(); i++) {
                int j = ((Integer)m_children.elementAt(i)).intValue();
                addArc(m_nParent, j);
            }

        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    (int i, int j) {
        this$0 = EditableBayesNet.this;
        super(EditableBayesNet.this);
        try {
            m_nParent = i;
            m_children = new FastVector();
            m_children.addElement(Integer.valueOf(j));
            SerializedObject serializedobject = new SerializedObject(m_Distributions[j]);
            m_CPT = new Estimator[1][];
            m_CPT[0] = (Estimator[])(Estimator[])serializedobject.getObject();
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    m_CPT(int i, FastVector fastvector) {
        this$0 = EditableBayesNet.this;
        super(EditableBayesNet.this);
        try {
            m_nParent = i;
            m_children = new FastVector();
            m_CPT = new Estimator[fastvector.size()][];
            for (int j = 0; j < fastvector.size(); j++) {
                int k = ((Integer)fastvector.elementAt(j)).intValue();
                m_children.addElement(Integer.valueOf(k));
                SerializedObject serializedobject = new SerializedObject(m_Distributions[k]);
                m_CPT[j] = (Estimator[])(Estimator[])serializedobject.getObject();
            }

        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}


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

  angular
    .module('minotaur')
    .directive('ngMixitup', ngMixitup);

  /** @ngInject */
  function ngMixitup($timeout) {
    var directive = {
      restrict: 'EA',
      link: function(scope, element, attrs){
        /* eslint-disable */
        var options;
        if (attrs.ngMixitup) {
          options = scope.$eval(attrs.ngMixitup);
        }
        $timeout(function(){
          var mixer = mixitup(element, options);
        },600);
        /* eslint-enable */
      }
    };

    return directive;

  }

})();


text:
<readable><title>2245914678_1f82fc3d80</title><content>
A girl with dyed red hair wearing striped clothing talking on a cellphone .
A girl with read dreadlocks is talking on the phone .
a red haired girl with a black and white striped shirt talking on a cellphone
A woman with bright red hair and striped clothing talks on a phone .
A woman with red hair and a black striped shirt talking on the phone .
</content></readable>


text:
<?php

namespace Ticki\Core\Strategy;

use Ticki\Core\Model\Board;
use Ticki\Core\Model\Cell;

/**
 * Interface StrategyInterface
 * @package Ticki\Core\Strategy
 */
interface StrategyInterface
{
    /**
     * Add one cell on board using some strategy
     *
     * @param Board $board
     * @param $type
     *
     * @return Cell
     */
    public function getCell(Board $board, $type);

    /**
     * Get name
     *
     * @return string
     */
    public function name();
}


text:
class BDRM

  include Uni_Mind::Arch

  def hello_appster
    "Hello, Appster."
  end

end # === class BDRM


text: A Java AIS decoding library


text:
Wersja demonstracyjna: [Cookie Alert | Demo](https://xmentor.github.io/cookie_alert)

# Instalacja
* Pobierz pliki [Cookie Alert](https://github.com/xmentor/cookie_alert/archive/master.zip)

* Plik `cookie-alert.min.css` zalinkuj w sekcji head:
    ```
    <head>
        // some code
        <link rel="stylesheet" href="scieżka_dostępu/cookie-alert.min.css">
        // some code
    </head>
    ```
* Plik `cookie-alert.min.js` podepnij w sekcji body, tuż przed zamknięciem tego znacznika:

    ```
    <body>
        // some code
        <script src="scieżka_dostępu/cookie-alert.min.js"></script>
    </body>
    ```

# Ustawienia
* Ustawienia są opcjonalne
* Ustawienia dodajemy pod podpiętym skryptem `cookie-alert.min.js`:

    ```
    <script>
        cookie_alert.init({
            color: 'rgba(155,115,151,.7)', //domyślnie '#000'
            text_color: '#fff',            //domyślnie '#fff'
            position: 'bottom',            //domyślnie 'bottom'
            text: 'Niniejsza strona krzysta z plików cookies, korzystając ze strony wyrażasz zgodę na używanie cookies, zgodnie z ustawieniami przeglądarki!',   //domyślnie
            info_cookie: 'http://wszystkoociasteczkach.pl/' //domyślnie
        });
    </script>
    ```

# Licencja
[Licencja MIT](https://github.com/xmentor/cookie_alert/blob/master/LICENSE)


text:
package com.opengamma.sdk.margin;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;

import org.joda.beans.ser.JodaBeanSer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.opengamma.sdk.common.ServiceInvoker;
import com.opengamma.sdk.common.auth.Credentials;

import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy;

/**
 * Test.
 */
public class MarginClientTest {

  private static final Credentials CREDENTIALS = Credentials.ofApiKey("user", "password");
  private static final LocalDate VAL_DATE = LocalDate.of(2017, 6, 1);
  private static final MarginCalcRequest REQUEST = MarginCalcRequest.builder()
      .calculationTypes(MarginCalcType.MARGIN)
      .valuationDate(VAL_DATE)
      .reportingCurrency("GBP")
      .build();

  private static final String RESPONSE_LIST_CCPS = JodaBeanSer.PRETTY.simpleJsonWriter()
      .write(CcpsResult.of(Arrays.asList("LCH", "RUBBISH")));

  private static final String RESPONSE_GET_CCP_INFO = JodaBeanSer.PRETTY.simpleJsonWriter()
      .write(CcpInfo.of(
          Collections.singletonList(VAL_DATE),
          "GBP",
          Collections.singletonList("GBP"),
          Collections.singletonList("GBP"),
          new HashSet<>(Arrays.asList(MarginCalcType.PORTFOLIO_SUMMARY, MarginCalcType.MARGIN)),
          new HashSet<>(Arrays.asList(MarginCalcMode.SPOT))));

  private static final String RESPONSE_CALC_POST = "";
  private static final String RESPONSE_CALC_GET_PENDING = JodaBeanSer.PRETTY.simpleJsonWriter().write(
      MarginCalcResult.of(
          MarginCalcResultStatus.PENDING,
          set(MarginCalcType.MARGIN),
          MarginCalcMode.SPOT,
          VAL_DATE,
          "GBP",
          "GBP",
          true,
          Collections.emptyList(),
          null,
          null,
          null,
          Collections.emptyList()));
  private static final String RESPONSE_CALC_GET_COMPLETE = JodaBeanSer.PRETTY.simpleJsonWriter().write(
      MarginCalcResult.of(
          MarginCalcResultStatus.COMPLETED,
          set(MarginCalcType.MARGIN),
          MarginCalcMode.SPOT,
          VAL_DATE,
          "GBP",
          "GBP",
          true,
          Collections.singletonList(PortfolioItemSummary.of("1", "SWAP", "MySwap")),
          MarginSummary.of(125d, Collections.emptyList(), MarginBreakdown.of(125d, 125d, 0, 0)),
          null,
          null,
          Collections.emptyList()));
  private static final String RESPONSE_CALC_WHATIF_GET_COMPLETE = JodaBeanSer.PRETTY.simpleJsonWriter().write(
      MarginCalcResult.of(
          MarginCalcResultStatus.COMPLETED,
          set(MarginCalcType.MARGIN),
          MarginCalcMode.SPOT,
          VAL_DATE,
          "GBP",
          "GBP",
          true,
          Collections.singletonList(PortfolioItemSummary.of("1", "SWAP", "MySwap")),
          MarginSummary.of(260d, Collections.emptyList(), MarginBreakdown.of(260d, 260d, 0, 0)),
          null,
          null,
          Collections.emptyList()));
  private static final String RESPONSE_DELETE = "";
  private static final String RESPONSE_ERROR = JodaBeanSer.PRETTY.simpleJsonWriter().write(
      ErrorMessage.of(500, "Error", "Error"));

  private MockWebServer server;

  //-------------------------------------------------------------------------
  @BeforeEach
  public void setUp() throws IOException {
    server = new MockWebServer();
    server.start();
  }

  @AfterEach
  public void tearDown() throws IOException {
    server.shutdown();
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_listCcps() {
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/json")
        .setBody(RESPONSE_LIST_CCPS));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    CcpsResult ccps = client.listCcps();
    assertThat(ccps.getCcpNames()).hasSize(2);
    assertThat(ccps.getCcpNames().get(0)).isEqualTo(Ccp.LCH.name());
    assertThat(ccps.getCcpNames().get(1)).isEqualTo("RUBBISH");
    assertThat(ccps.isCcpAvailable(Ccp.LCH)).isTrue();
    assertThat(ccps.isCcpAvailable(Ccp.CME)).isFalse();
  }

  @Test
  public void test_getCcpInfo() {
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/json")
        .setBody(RESPONSE_GET_CCP_INFO));

    //call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    LocalDate expectedValuationDate = LocalDate.of(2017, 6, 1);
    String expectedCurrency = "GBP";

    CcpInfo ccpInfo = client.getCcpInfo(Ccp.LCH);
    assertThat(ccpInfo.getCalculationCurrencies()).isEqualTo(Collections.singletonList(expectedCurrency));
    assertThat(ccpInfo.getReportingCurrencies()).isEqualTo(Collections.singletonList(expectedCurrency));
    assertThat(ccpInfo.getDefaultCurrency()).isEqualTo(expectedCurrency);
    assertThat(ccpInfo.getValuationDates()).isEqualTo(Collections.singletonList(expectedValuationDate));
    assertThat(ccpInfo.getLatestValuationDate()).isEqualTo(expectedValuationDate);
  }

  @Test
  public void test_listCcps_fail() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(500)
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_ERROR));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> client.listCcps());
  }

  //-------------------------------------------------------------------------
  @Test
  @SuppressWarnings("deprecation")
  public void test_calculate() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_PENDING));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_COMPLETE));
    server.enqueue(new MockResponse()
        .setBody(RESPONSE_DELETE));

    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    MarginCalcResult result = client.calculate(Ccp.LCH, REQUEST);
    assertThat(result.getStatus()).isEqualTo(MarginCalcResultStatus.COMPLETED);
    assertThat(result.getType()).isEqualTo(MarginCalcRequestType.STANDARD);
    assertThat(result.getCalculationTypes()).isEqualTo(set(MarginCalcType.MARGIN));
    assertThat(result.getValuationDate()).isEqualTo(VAL_DATE);
  }

  @Test
  public void test_calculate_with_retries_failing() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));

    ServiceInvoker invoker = createInvoker(1, 1);
    MarginClient client = MarginClient.of(invoker);
    assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> client.listCcps());
    assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> client.getCcpInfo(Ccp.LCH));
    assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> client.calculate(Ccp.LCH, REQUEST));
  }

  @Test
  @SuppressWarnings("deprecation")
  public void test_calculate_with_retries_succeeding() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_PENDING));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_COMPLETE));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse()
        .setBody(RESPONSE_DELETE));

    ServiceInvoker invoker = createInvoker(1, 3);
    MarginClient client = MarginClient.of(invoker);

    MarginCalcResult result = client.calculate(Ccp.LCH, REQUEST);
    assertThat(result.getStatus()).isEqualTo(MarginCalcResultStatus.COMPLETED);
    assertThat(result.getType()).isEqualTo(MarginCalcRequestType.STANDARD);
    assertThat(result.getCalculationTypes()).isEqualTo(set(MarginCalcType.MARGIN));
    assertThat(result.getValuationDate()).isEqualTo(VAL_DATE);
  }

  // This method handles two concurrent HTTP requests, thus defines the MockWebServer in a different way.
  // For any what-if scenario request, the sequence of HTTP requests should look like this:
  // * POST - /margin/v1/ccps/lch/calculations - base portfolios
  // * POST - /margin/v1/ccps/lch/calculations - delta portfolios
  // * (for each portfolio) GET - /margin/v1/ccps/lch/calculations/[calcID] - until the status is COMPLETED.
  // * (for each portfolio) DELETE - /margin/v1/ccps/lch/calculations/[calcID]
  @Test
  @SuppressWarnings("deprecation")
  public void test_calculate_whatif() throws Exception {
    Dispatcher webServerDispatcher = new Dispatcher() {
      private boolean firstRequestSubmitted;
      private boolean firstCalcRequested;
      private boolean secondCalcRequested;

      @Override
      public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
        String requestPath = request.getPath();
        if (request.getMethod().equals("POST") && requestPath.equals("/margin/v3/ccps/lch/calculations")) {
          if (!firstRequestSubmitted) {
            firstRequestSubmitted = true;
            return new MockResponse()
                .setResponseCode(202)
                .setHeader("Location", server.url("/ccps/lch/calculations/789"))
                .setBody(RESPONSE_CALC_POST);
          } else {
            return new MockResponse()
                .setResponseCode(202)
                .setHeader("Location", server.url("/ccps/lch/calculations/790"))
                .setBody(RESPONSE_CALC_POST);
          }
        } else if (request.getMethod().equals("GET") && requestPath.equals("/margin/v3/ccps/lch/calculations/789")) {
          if (!firstCalcRequested) {
            firstCalcRequested = true;
            return new MockResponse()
                .setHeader("Content-Type", "application/json")
                .setBody(RESPONSE_CALC_GET_PENDING);
          } else {
            return new MockResponse()
                .setHeader("Content-Type", "application/json")
                .setBody(RESPONSE_CALC_GET_COMPLETE);
          }
        } else if (request.getMethod().equals("GET") && requestPath.equals("/margin/v3/ccps/lch/calculations/790")) {
          if (!secondCalcRequested) {
            secondCalcRequested = true;
            return new MockResponse()
                .setHeader("Content-Type", "application/json")
                .setBody(RESPONSE_CALC_GET_PENDING);
          } else {
            return new MockResponse()
                .setHeader("Content-Type", "application/json")
                .setBody(RESPONSE_CALC_WHATIF_GET_COMPLETE);
          }
        } else if (request.getMethod().equals("DELETE")) {
          return new MockResponse()
              .setBody(RESPONSE_DELETE);
        } else {

          return new MockResponse().setResponseCode(404);
        }
      }
    };
    server.setDispatcher(webServerDispatcher);

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    PortfolioDataFile lchPortfolioFile = PortfolioDataFile.of(Paths.get(
        "src/test/resources/lch-trades.txt"));
    MarginCalcRequest.of(VAL_DATE, "GBP", Collections.singletonList(lchPortfolioFile));

    MarginWhatIfCalcResult result = client.calculateWhatIf(Ccp.LCH, REQUEST, Collections.singletonList(lchPortfolioFile)); //Using the same portfolio for delta as well
    assertThat(result.getStatus()).isEqualTo(MarginCalcResultStatus.COMPLETED);
    assertThat(result.getType()).isEqualTo(MarginCalcRequestType.STANDARD);
    assertThat(result.getCalculationTypes()).isEqualTo(set(MarginCalcType.MARGIN));
    assertThat(result.getValuationDate()).isEqualTo(VAL_DATE);

    assertThat(result.getBaseSummary().getMargin()).isEqualTo(125.0); //Hard coded result, not relevant for portfolio
    assertThat(result.getCombinedSummary().getMargin()).isEqualTo(260.0); //Hard coded result, not relevant for portfolio
    assertThat(result.getDeltaSummary().getMargin()).isEqualTo(135.0);
  }

  @Test
  public void test_calculate_postFail() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(500)
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_ERROR));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> client.calculate(Ccp.LCH, REQUEST));
  }

  @Test
  public void test_calculate_getFail() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse()
        .setResponseCode(500)
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_ERROR));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> client.calculate(Ccp.LCH, REQUEST));
  }

  @Test
  public void test_calculate_deleteFail() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_COMPLETE));
    server.enqueue(new MockResponse()
        .setResponseCode(500)
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_ERROR));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    // succeeds - delete failure ignored
    client.calculate(Ccp.LCH, REQUEST);
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_delete_fail() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(500)
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_ERROR));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> client.deleteCalculation(Ccp.LCH, "789"));
  }

  //-------------------------------------------------------------------------
  @Test
  @SuppressWarnings("deprecation")
  public void test_calculateAsync() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_PENDING));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_COMPLETE));
    server.enqueue(new MockResponse()
        .setBody(RESPONSE_DELETE));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    CompletableFuture<MarginCalcResult> future = client.calculateAsync(Ccp.LCH, REQUEST);
    MarginCalcResult result = future.join();
    assertThat(result.getStatus()).isEqualTo(MarginCalcResultStatus.COMPLETED);
    assertThat(result.getType()).isEqualTo(MarginCalcRequestType.STANDARD);
    assertThat(result.getCalculationTypes()).isEqualTo(set(MarginCalcType.MARGIN));
    assertThat(result.getValuationDate()).isEqualTo(VAL_DATE);
  }

  @Test
  public void test_calculateAsync_createError() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(500));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    CompletableFuture<MarginCalcResult> future = client.calculateAsync(Ccp.LCH, REQUEST);
    assertThatExceptionOfType(CompletionException.class).isThrownBy(() -> future.join());
    assertThat(server.getRequestCount()).isEqualTo(1);
  }

  @Test
  public void test_calculateAsync_pollingError() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(202)
        .setHeader("Location", server.url("/ccps/lch/calculations/789"))
        .setBody(RESPONSE_CALC_POST));
    server.enqueue(new MockResponse()
        .setHeader("Content-Type", "application/xml")
        .setBody(RESPONSE_CALC_GET_PENDING));
    server.enqueue(new MockResponse()
        .setResponseCode(500));
    server.enqueue(new MockResponse()
        .setBody(RESPONSE_DELETE));

    // call server
    ServiceInvoker invoker = createInvoker();
    MarginClient client = MarginClient.of(invoker);

    CompletableFuture<MarginCalcResult> future = client.calculateAsync(Ccp.LCH, REQUEST);
    assertThatExceptionOfType(CompletionException.class).isThrownBy(() -> future.join());
    assertThat(server.getRequestCount()).isEqualTo(4);
  }

  private ServiceInvoker createInvoker() {
    return ServiceInvoker.builder(CREDENTIALS)
        .serviceUrl(server.url("/"))
        .authClientFactory(inv -> new TestingAuthClient())
        .build();
  }

  private ServiceInvoker createInvoker(int timeoutInSeconds, int retries) {
    return ServiceInvoker.builder(CREDENTIALS)
        .serviceUrl(server.url("/"))
        .authClientFactory(inv -> new TestingAuthClient())
        .httpClient(new OkHttpClient().newBuilder()
            .connectTimeout(timeoutInSeconds, TimeUnit.SECONDS)
            .readTimeout(timeoutInSeconds, TimeUnit.SECONDS)
            .writeTimeout(timeoutInSeconds, TimeUnit.SECONDS)
            .build())
        .retries(retries)
        .build();
  }

  @SafeVarargs
  private static final <T> Set<T> set(T... array) {
    return new HashSet<>(Arrays.asList(array));
  }

}


text:
package com.github.mvv.sawoko

sealed trait SignalGuard[S[_]] extends NotNull

final class InSignal[S[_], A](private val sig: S[A]) {
  override def hashCode = sig.hashCode
  override def equals(that: Any) = that match {
    case that: AnyRef if that.getClass == getClass =>
      sig == that.asInstanceOf[InSignal[S, _]].sig
    case _ =>
      false
  }
  def signal(implicit guard: SignalGuard[S]) = sig
}
object InSignal {
  def apply[S[_], A](signal: S[A]) = new InSignal[S, A](signal)
  implicit def signalToInSignal[S[_], A](signal: S[A]) =
    new InSignal[S, A](signal)
}
final class OutSignal[S[_], A](private val sig: S[A]) {
  override def hashCode = sig.hashCode
  override def equals(that: Any) = that match {
    case that: AnyRef if that.getClass == getClass =>
      sig == that.asInstanceOf[OutSignal[S, _]].sig
    case _ =>
      false
  }
  def signal(implicit guard: SignalGuard[S]) = sig
}
object OutSignal {
  def apply[S[_], A](signal: S[A]) = new OutSignal[S, A](signal)
  implicit def signalToOutSignal[S[_], A](signal: S[A]) =
    new OutSignal[S, A](signal)
}

trait CreateSignalAsyncExecutor[S[_]] extends AsyncExecutor {
  def registerCreateSignal[A](
        pid: Pid, callback: SimpleCallback[S[A]]): Option[SimpleResult[S[A]]]
}

final class CreateSignalOp[S[_], A]
            extends AsyncOp[CreateSignalAsyncExecutor[S], S[A]] {
  def register(ep: EP, callback: Callback) =
    ep.executor.registerCreateSignal(ep.pid, callback)
}

trait AwaitSignalWaitCap[S[_]] extends WaitCap

final case class AwaitSignal[S[_], A](in: InSignal[S, A]) extends WaitOp {
  type Cap = AwaitSignalWaitCap[S]
  type Result = A
}

trait EmitSignalAsyncExecutor[S[_]] extends AsyncExecutor {
  protected implicit val signalGuard = new SignalGuard[S] {}
  def registerEmitSignal[A](
        pid: Pid, out: S[A], value: A,
        callback: SimpleCallback[Boolean]): Option[SimpleResult[Boolean]]
}

final case class EmitSignalOp[S[_], A](out: OutSignal[S, A], value: A)
                 extends AsyncOp[EmitSignalAsyncExecutor[S], Boolean] {
  private implicit val signalGuard = new SignalGuard[S] {}
  def register(ep: EP, callback: Callback) =
    ep.executor.registerEmitSignal(ep.pid, out.signal, value, callback)
}

trait SignalOps[S[_]] {
  import AsyncOps._
  import WaitOps._

  @inline
  def createSignal[A] =
    exec(new CreateSignalOp[S, A])
  @inline
  def awaitSignal[S[_], A](in: InSignal[S, A]) =
    waitOne(AwaitSignal(in))
  @inline
  def awaitSignal[S[_], A](in: InSignal[S, A], timeout: Timeout) =
    waitOne(AwaitSignal(in), timeout)
  @inline
  def emitSignal[S[_], A](out: OutSignal[S, A], value: A) =
    exec(EmitSignalOp(out, value))
  @inline
  def emitSignal[S[_]](out: OutSignal[S, Unit]) =
    exec(EmitSignalOp(out, ()))
}


text:
import { ComponentFactoryResolver, Injectable, ApplicationRef, NgZone } from '@angular/core';
import { DomPortalHost } from '../portal/dom-portal-host';
import { OverlayRef } from './overlay-ref';
import { OverlayContainer } from './overlay-container';
var Overlay = (function () {
    function Overlay(_overlayContainer, _componentFactoryResolver, _appRef, _ngZone) {
        this._overlayContainer = _overlayContainer;
        this._componentFactoryResolver = _componentFactoryResolver;
        this._appRef = _appRef;
        this._ngZone = _ngZone;
        this._paneElements = {};
    }
    Overlay.prototype.create = function (positionClass, overlayContainer) {
        return this._createOverlayRef(this.getPaneElement(positionClass, overlayContainer));
    };
    Overlay.prototype.getPaneElement = function (positionClass, overlayContainer) {
        if (!this._paneElements[positionClass]) {
            this._paneElements[positionClass] = this._createPaneElement(positionClass, overlayContainer);
        }
        return this._paneElements[positionClass];
    };
    Overlay.prototype._createPaneElement = function (positionClass, overlayContainer) {
        var pane = document.createElement('div');
        pane.id = 'toast-container';
        pane.classList.add(positionClass);
        if (!overlayContainer) {
            this._overlayContainer.getContainerElement().appendChild(pane);
        }
        else {
            overlayContainer.getContainerElement().appendChild(pane);
        }
        return pane;
    };
    Overlay.prototype._createPortalHost = function (pane) {
        return new DomPortalHost(pane, this._componentFactoryResolver, this._appRef);
    };
    Overlay.prototype._createOverlayRef = function (pane) {
        return new OverlayRef(this._createPortalHost(pane), pane, this._ngZone);
    };
    return Overlay;
}());
export { Overlay };
Overlay.decorators = [
    { type: Injectable },
];
Overlay.ctorParameters = function () { return [
    { type: OverlayContainer, },
    { type: ComponentFactoryResolver, },
    { type: ApplicationRef, },
    { type: NgZone, },
]; };
export var OVERLAY_PROVIDERS = [
    Overlay,
    OverlayContainer,
];
//# sourceMappingURL=overlay.js.map


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CloudFront.Model
{
    /// <summary>
    /// Container for the parameters to the ListStreamingDistributions operation.
    /// <para> List streaming distributions. </para>
    /// </summary>
    /// <seealso cref="Amazon.CloudFront.AmazonCloudFront.ListStreamingDistributions"/>
    public class ListStreamingDistributionsRequest : AmazonWebServiceRequest
    {
        private string marker;
        private string maxItems;

        /// <summary>
        /// Use this when paginating results to indicate where to begin in your list of streaming distributions. The results include distributions in
        /// the list that occur after the marker. To get the next page of results, set the Marker to the value of the NextMarker from the current page's
        /// response (which is also the ID of the last distribution on that page).
        ///
        /// </summary>
        public string Marker
        {
            get { return this.marker; }
            set { this.marker = value; }
        }

        /// <summary>
        /// Sets the Marker property
        /// </summary>
        /// <param name="marker">The value to set for the Marker property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ListStreamingDistributionsRequest WithMarker(string marker)
        {
            this.marker = marker;
            return this;
        }

        // Check to see if Marker property is set
        internal bool IsSetMarker()
        {
            return this.marker != null;
        }

        /// <summary>
        /// The maximum number of streaming distributions you want in the response body.
        ///
        /// </summary>
        public string MaxItems
        {
            get { return this.maxItems; }
            set { this.maxItems = value; }
        }

        /// <summary>
        /// Sets the MaxItems property
        /// </summary>
        /// <param name="maxItems">The value to set for the MaxItems property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ListStreamingDistributionsRequest WithMaxItems(string maxItems)
        {
            this.maxItems = maxItems;
            return this;
        }

        // Check to see if MaxItems property is set
        internal bool IsSetMaxItems()
        {
            return this.maxItems != null;
        }
    }
}


text:
require "cases/helper"
require "active_record/tasks/database_tasks"
require "models/author"

module ActiveRecord
  module DatabaseTasksSetupper
    def setup
      @mysql_tasks, @postgresql_tasks, @sqlite_tasks = Array.new(
        3,
        Class.new do
          def create; end
          def drop; end
          def purge; end
          def charset; end
          def collation; end
          def structure_dump(*); end
          def structure_load(*); end
        end.new
      )

      $stdout, @original_stdout = StringIO.new, $stdout
      $stderr, @original_stderr = StringIO.new, $stderr
    end

    def teardown
      $stdout, $stderr = @original_stdout, @original_stderr
    end

    def with_stubbed_new
      ActiveRecord::Tasks::MySQLDatabaseTasks.stub(:new, @mysql_tasks) do
        ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stub(:new, @postgresql_tasks) do
          ActiveRecord::Tasks::SQLiteDatabaseTasks.stub(:new, @sqlite_tasks) do
            yield
          end
        end
      end
    end
  end

  ADAPTERS_TASKS = {
    mysql2:     :mysql_tasks,
    postgresql: :postgresql_tasks,
    sqlite3:    :sqlite_tasks
  }

  class DatabaseTasksUtilsTask < ActiveRecord::TestCase
    def test_raises_an_error_when_called_with_protected_environment
      protected_environments = ActiveRecord::Base.protected_environments
      current_env            = ActiveRecord::Base.connection.migration_context.current_environment

      InternalMetadata[:environment] = current_env

      assert_called_on_instance_of(
        ActiveRecord::MigrationContext,
        :current_version,
        times: 6,
        returns: 1
      ) do
        assert_not_includes protected_environments, current_env
        # Assert no error
        ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!

        ActiveRecord::Base.protected_environments = [current_env]

        assert_raise(ActiveRecord::ProtectedEnvironmentError) do
          ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!
        end
      end
    ensure
      ActiveRecord::Base.protected_environments = protected_environments
    end

    def test_raises_an_error_when_called_with_protected_environment_which_name_is_a_symbol
      protected_environments = ActiveRecord::Base.protected_environments
      current_env            = ActiveRecord::Base.connection.migration_context.current_environment

      InternalMetadata[:environment] = current_env

      assert_called_on_instance_of(
        ActiveRecord::MigrationContext,
        :current_version,
        times: 6,
        returns: 1
      ) do
        assert_not_includes protected_environments, current_env
        # Assert no error
        ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!

        ActiveRecord::Base.protected_environments = [current_env.to_sym]
        assert_raise(ActiveRecord::ProtectedEnvironmentError) do
          ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!
        end
      end
    ensure
      ActiveRecord::Base.protected_environments = protected_environments
    end

    def test_raises_an_error_if_no_migrations_have_been_made
      ActiveRecord::InternalMetadata.stub(:table_exists?, false) do
        assert_called_on_instance_of(
          ActiveRecord::MigrationContext,
          :current_version,
          returns: 1
        ) do
          assert_raise(ActiveRecord::NoEnvironmentInSchemaError) do
            ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!
          end
        end
      end
    end
  end

  class DatabaseTasksRegisterTask < ActiveRecord::TestCase
    def test_register_task
      klazz = Class.new do
        def initialize(*arguments); end
        def structure_dump(filename); end
      end
      instance = klazz.new

      klazz.stub(:new, instance) do
        assert_called_with(instance, :structure_dump, ["awesome-file.sql", nil]) do
          ActiveRecord::Tasks::DatabaseTasks.register_task(/foo/, klazz)
          ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => :foo }, "awesome-file.sql")
        end
      end
    end

    def test_unregistered_task
      assert_raise(ActiveRecord::Tasks::DatabaseNotSupported) do
        ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => :bar }, "awesome-file.sql")
      end
    end
  end

  class DatabaseTasksCreateTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_create") do
        with_stubbed_new do
          assert_called(eval("@#{v}"), :create) do
            ActiveRecord::Tasks::DatabaseTasks.create "adapter" => k
          end
        end
      end
    end
  end

  class DatabaseTasksDumpSchemaCacheTest < ActiveRecord::TestCase
    def test_dump_schema_cache
      path = "/tmp/my_schema_cache.yml"
      ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, path)
      assert File.file?(path)
    ensure
      ActiveRecord::Base.clear_cache!
      FileUtils.rm_rf(path)
    end
  end

  class DatabaseTasksCreateAllTest < ActiveRecord::TestCase
    def setup
      @configurations = { "development" => { "database" => "my-db" } }

      $stdout, @original_stdout = StringIO.new, $stdout
      $stderr, @original_stderr = StringIO.new, $stderr
    end

    def teardown
      $stdout, $stderr = @original_stdout, @original_stderr
    end

    def test_ignores_configurations_without_databases
      @configurations["development"]["database"] = nil

      with_stubbed_configurations_establish_connection do
        assert_not_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end

    def test_ignores_remote_databases
      @configurations["development"]["host"] = "my.server.tld"

      with_stubbed_configurations_establish_connection do
        assert_not_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end

    def test_warning_for_remote_databases
      @configurations["development"]["host"] = "my.server.tld"

      with_stubbed_configurations_establish_connection do
        ActiveRecord::Tasks::DatabaseTasks.create_all

        assert_match "This task only modifies local databases. my-db is on a remote host.",
          $stderr.string
      end
    end

    def test_creates_configurations_with_local_ip
      @configurations["development"]["host"] = "127.0.0.1"

      with_stubbed_configurations_establish_connection do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end

    def test_creates_configurations_with_local_host
      @configurations["development"]["host"] = "localhost"

      with_stubbed_configurations_establish_connection do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end

    def test_creates_configurations_with_blank_hosts
      @configurations["development"]["host"] = nil

      with_stubbed_configurations_establish_connection do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end

    private
      def with_stubbed_configurations_establish_connection
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        # To refrain from connecting to a newly created empty DB in
        # sqlite3_mem tests
        ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do
          yield
        end
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksCreateCurrentTest < ActiveRecord::TestCase
    def setup
      @configurations = {
        "development" => { "database" => "dev-db" },
        "test"        => { "database" => "test-db" },
        "production"  => { "url" => "abstract://prod-db-host/prod-db" }
      }
    end

    def test_creates_current_environment_database
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          ["database" => "test-db"],
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end

    def test_creates_current_environment_database_with_url
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          ["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"],
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("production")
          )
        end
      end
    end

    def test_creates_test_and_development_databases_when_env_was_not_specified
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["database" => "dev-db"],
            ["database" => "test-db"]
          ],
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    def test_creates_test_and_development_databases_when_rails_env_is_development
      old_env = ENV["RAILS_ENV"]
      ENV["RAILS_ENV"] = "development"

      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["database" => "dev-db"],
            ["database" => "test-db"]
          ],
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    ensure
      ENV["RAILS_ENV"] = old_env
    end

    def test_establishes_connection_for_the_given_environments
      ActiveRecord::Tasks::DatabaseTasks.stub(:create, nil) do
        assert_called_with(ActiveRecord::Base, :establish_connection, [:development]) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    private
      def with_stubbed_configurations_establish_connection
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do
          yield
        end
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksCreateCurrentThreeTierTest < ActiveRecord::TestCase
    def setup
      @configurations = {
        "development" => { "primary" => { "database" => "dev-db" }, "secondary" => { "database" => "secondary-dev-db" } },
        "test" => { "primary" => { "database" => "test-db" }, "secondary" => { "database" => "secondary-test-db" } },
        "production" => { "primary" => { "url" => "abstract://prod-db-host/prod-db" }, "secondary" => { "url" => "abstract://secondary-prod-db-host/secondary-prod-db" } }
      }
    end

    def test_creates_current_environment_database
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end

    def test_creates_current_environment_database_with_url
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"],
            ["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("production")
          )
        end
      end
    end

    def test_creates_test_and_development_databases_when_env_was_not_specified
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"],
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    def test_creates_test_and_development_databases_when_rails_env_is_development
      old_env = ENV["RAILS_ENV"]
      ENV["RAILS_ENV"] = "development"

      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"],
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    ensure
      ENV["RAILS_ENV"] = old_env
    end

    def test_establishes_connection_for_the_given_environments_config
      ActiveRecord::Tasks::DatabaseTasks.stub(:create, nil) do
        assert_called_with(
          ActiveRecord::Base,
          :establish_connection,
          [:development]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    private
      def with_stubbed_configurations_establish_connection
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do
          yield
        end
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksDropTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_drop") do
        with_stubbed_new do
          assert_called(eval("@#{v}"), :drop) do
            ActiveRecord::Tasks::DatabaseTasks.drop "adapter" => k
          end
        end
      end
    end
  end

  class DatabaseTasksDropAllTest < ActiveRecord::TestCase
    def setup
      @configurations = { development: { "database" => "my-db" } }

      $stdout, @original_stdout = StringIO.new, $stdout
      $stderr, @original_stderr = StringIO.new, $stderr
    end

    def teardown
      $stdout, $stderr = @original_stdout, @original_stderr
    end

    def test_ignores_configurations_without_databases
      @configurations[:development]["database"] = nil

      with_stubbed_configurations do
        assert_not_called(ActiveRecord::Tasks::DatabaseTasks, :drop) do
          ActiveRecord::Tasks::DatabaseTasks.drop_all
        end
      end
    end

    def test_ignores_remote_databases
      @configurations[:development]["host"] = "my.server.tld"

      with_stubbed_configurations do
        assert_not_called(ActiveRecord::Tasks::DatabaseTasks, :drop) do
          ActiveRecord::Tasks::DatabaseTasks.drop_all
        end
      end
    end

    def test_warning_for_remote_databases
      @configurations[:development]["host"] = "my.server.tld"

      with_stubbed_configurations do
        ActiveRecord::Tasks::DatabaseTasks.drop_all

        assert_match "This task only modifies local databases. my-db is on a remote host.",
          $stderr.string
      end
    end

    def test_drops_configurations_with_local_ip
      @configurations[:development]["host"] = "127.0.0.1"

      with_stubbed_configurations do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :drop) do
          ActiveRecord::Tasks::DatabaseTasks.drop_all
        end
      end
    end

    def test_drops_configurations_with_local_host
      @configurations[:development]["host"] = "localhost"

      with_stubbed_configurations do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :drop) do
          ActiveRecord::Tasks::DatabaseTasks.drop_all
        end
      end
    end

    def test_drops_configurations_with_blank_hosts
      @configurations[:development]["host"] = nil

      with_stubbed_configurations do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :drop) do
          ActiveRecord::Tasks::DatabaseTasks.drop_all
        end
      end
    end

    private
      def with_stubbed_configurations
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        yield
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksDropCurrentTest < ActiveRecord::TestCase
    def setup
      @configurations = {
        "development" => { "database" => "dev-db" },
        "test"        => { "database" => "test-db" },
        "production"  => { "url" => "abstract://prod-db-host/prod-db" }
      }
    end

    def test_drops_current_environment_database
      with_stubbed_configurations do
        assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop,
          ["database" => "test-db"]) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end

    def test_drops_current_environment_database_with_url
      with_stubbed_configurations do
        assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop,
          ["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"]) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("production")
          )
        end
      end
    end

    def test_drops_test_and_development_databases_when_env_was_not_specified
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["database" => "dev-db"],
            ["database" => "test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    def test_drops_testand_development_databases_when_rails_env_is_development
      old_env = ENV["RAILS_ENV"]
      ENV["RAILS_ENV"] = "development"

      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["database" => "dev-db"],
            ["database" => "test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    ensure
      ENV["RAILS_ENV"] = old_env
    end

    private
      def with_stubbed_configurations
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        yield
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksDropCurrentThreeTierTest < ActiveRecord::TestCase
    def setup
      @configurations = {
        "development" => { "primary" => { "database" => "dev-db" }, "secondary" => { "database" => "secondary-dev-db" } },
        "test" => { "primary" => { "database" => "test-db" }, "secondary" => { "database" => "secondary-test-db" } },
        "production" => { "primary" => { "url" => "abstract://prod-db-host/prod-db" }, "secondary" => { "url" => "abstract://secondary-prod-db-host/secondary-prod-db" } }
      }
    end

    def test_drops_current_environment_database
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end

    def test_drops_current_environment_database_with_url
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"],
            ["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("production")
          )
        end
      end
    end

    def test_drops_test_and_development_databases_when_env_was_not_specified
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"],
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    def test_drops_testand_development_databases_when_rails_env_is_development
      old_env = ENV["RAILS_ENV"]
      ENV["RAILS_ENV"] = "development"

      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :drop,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"],
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.drop_current(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    ensure
      ENV["RAILS_ENV"] = old_env
    end

    private
      def with_stubbed_configurations
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        yield
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  if current_adapter?(:SQLite3Adapter) && !in_memory_db?
    class DatabaseTasksMigrationTestCase < ActiveRecord::TestCase
      self.use_transactional_tests = false

      # Use a memory db here to avoid having to rollback at the end
      setup do
        migrations_path = MIGRATIONS_ROOT + "/valid"
        file = ActiveRecord::Base.connection.raw_connection.filename
        @conn = ActiveRecord::Base.establish_connection adapter: "sqlite3",
          database: ":memory:", migrations_paths: migrations_path
        source_db = SQLite3::Database.new file
        dest_db = ActiveRecord::Base.connection.raw_connection
        backup = SQLite3::Backup.new(dest_db, "main", source_db, "main")
        backup.step(-1)
        backup.finish
      end

      teardown do
        @conn.release_connection if @conn
        ActiveRecord::Base.establish_connection :arunit
      end
    end

    class DatabaseTasksMigrateTest < DatabaseTasksMigrationTestCase
      def test_can_migrate_from_pending_migration_error_action_dispatch
        verbose, version = ENV["VERBOSE"], ENV["VERSION"]
        ENV["VERSION"] = "2"
        ENV["VERBOSE"] = "false"

        # run down migration because it was already run on copied db
        assert_empty capture_migration_output

        ENV.delete("VERSION")
        ENV.delete("VERBOSE")

        # re-run up migration
        assert_includes(capture(:stdout) do
          ActiveSupport::ActionableError.dispatch ActiveRecord::PendingMigrationError, "Run pending migrations"
        end, "migrating")
      ensure
        ENV["VERBOSE"], ENV["VERSION"] = verbose, version
      end

      def test_migrate_set_and_unset_empty_values_for_verbose_and_version_env_vars
        verbose, version = ENV["VERBOSE"], ENV["VERSION"]

        ENV["VERSION"] = "2"
        ENV["VERBOSE"] = "false"

        # run down migration because it was already run on copied db
        assert_empty capture_migration_output

        ENV["VERBOSE"] = ""
        ENV["VERSION"] = ""

        # re-run up migration
        assert_includes capture_migration_output, "migrating"
      ensure
        ENV["VERBOSE"], ENV["VERSION"] = verbose, version
      end

      def test_migrate_set_and_unset_nonsense_values_for_verbose_and_version_env_vars
        verbose, version = ENV["VERBOSE"], ENV["VERSION"]

        # run down migration because it was already run on copied db
        ENV["VERSION"] = "2"
        ENV["VERBOSE"] = "false"

        assert_empty capture_migration_output

        ENV["VERBOSE"] = "yes"
        ENV["VERSION"] = "2"

        # run no migration because 2 was already run
        assert_empty capture_migration_output
      ensure
        ENV["VERBOSE"], ENV["VERSION"] = verbose, version
      end

      private
        def capture_migration_output
          capture(:stdout) do
            ActiveRecord::Tasks::DatabaseTasks.migrate
          end
        end
    end

    class DatabaseTasksMigrateStatusTest < DatabaseTasksMigrationTestCase
      def test_migrate_status_table
        ActiveRecord::SchemaMigration.create_table
        output = capture_migration_status
        assert_match(/database: :memory:/, output)
        assert_match(/down    001             Valid people have last names/, output)
        assert_match(/down    002             We need reminders/, output)
        assert_match(/down    003             Innocent jointable/, output)
        ActiveRecord::SchemaMigration.drop_table
      end

      private

        def capture_migration_status
          capture(:stdout) do
            ActiveRecord::Tasks::DatabaseTasks.migrate_status
          end
        end
    end
  end

  class DatabaseTasksMigrateErrorTest < ActiveRecord::TestCase
    self.use_transactional_tests = false

    def test_migrate_raise_error_on_invalid_version_format
      version = ENV["VERSION"]

      ENV["VERSION"] = "unknown"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "0.1.11"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1.1.11"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "0 "
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1."
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1_"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1_name"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
      assert_match(/Invalid format of target version/, e.message)
    ensure
      ENV["VERSION"] = version
    end

    def test_migrate_raise_error_on_failed_check_target_version
      ActiveRecord::Tasks::DatabaseTasks.stub(:check_target_version, -> { raise "foo" }) do
        e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.migrate }
        assert_equal "foo", e.message
      end
    end

    def test_migrate_clears_schema_cache_afterward
      assert_called(ActiveRecord::Base, :clear_cache!) do
        ActiveRecord::Tasks::DatabaseTasks.migrate
      end
    end
  end

  class DatabaseTasksPurgeTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_purge") do
        with_stubbed_new do
          assert_called(eval("@#{v}"), :purge) do
            ActiveRecord::Tasks::DatabaseTasks.purge "adapter" => k
          end
        end
      end
    end
  end

  class DatabaseTasksPurgeCurrentTest < ActiveRecord::TestCase
    def test_purges_current_environment_database
      old_configurations = ActiveRecord::Base.configurations
      configurations = {
        "development" => { "database" => "dev-db" },
        "test"        => { "database" => "test-db" },
        "production"  => { "database" => "prod-db" }
      }

      ActiveRecord::Base.configurations = configurations

      assert_called_with(
        ActiveRecord::Tasks::DatabaseTasks,
        :purge,
        ["database" => "prod-db"]
      ) do
        assert_called_with(ActiveRecord::Base, :establish_connection, [:production]) do
          ActiveRecord::Tasks::DatabaseTasks.purge_current("production")
        end
      end
    ensure
      ActiveRecord::Base.configurations = old_configurations
    end
  end

  class DatabaseTasksPurgeAllTest < ActiveRecord::TestCase
    def test_purge_all_local_configurations
      old_configurations = ActiveRecord::Base.configurations
      configurations = { development: { "database" => "my-db" } }
      ActiveRecord::Base.configurations = configurations

      assert_called_with(
        ActiveRecord::Tasks::DatabaseTasks,
        :purge,
        ["database" => "my-db"]
      ) do
        ActiveRecord::Tasks::DatabaseTasks.purge_all
      end
    ensure
      ActiveRecord::Base.configurations = old_configurations
    end
  end

  unless in_memory_db?
    class DatabaseTasksTruncateAllTest < ActiveRecord::TestCase
      self.use_transactional_tests = false

      fixtures :authors, :author_addresses

      def setup
        SchemaMigration.create_table
        SchemaMigration.create!(version: SchemaMigration.table_name)
        InternalMetadata.create_table
        InternalMetadata.create!(key: InternalMetadata.table_name)
      end

      def teardown
        SchemaMigration.delete_all
        InternalMetadata.delete_all
        ActiveRecord::Base.connection_handlers = { writing: ActiveRecord::Base.default_connection_handler }
      end

      def test_truncate_tables
        assert_operator SchemaMigration.count, :>, 0
        assert_operator InternalMetadata.count, :>, 0
        assert_operator Author.count, :>, 0
        assert_operator AuthorAddress.count, :>, 0

        old_configurations = ActiveRecord::Base.configurations
        configurations = { development: ActiveRecord::Base.configurations["arunit"] }
        ActiveRecord::Base.configurations = configurations

        ActiveRecord::Tasks::DatabaseTasks.stub(:root, nil) do
          ActiveRecord::Tasks::DatabaseTasks.truncate_all(
            ActiveSupport::StringInquirer.new("development")
          )
        end

        assert_operator SchemaMigration.count, :>, 0
        assert_operator InternalMetadata.count, :>, 0
        assert_equal 0, Author.count
        assert_equal 0, AuthorAddress.count
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
    end

    class DatabaseTasksTruncateAllWithPrefixTest < DatabaseTasksTruncateAllTest
      setup do
        ActiveRecord::Base.table_name_prefix = "p_"

        SchemaMigration.reset_table_name
        InternalMetadata.reset_table_name
      end

      teardown do
        ActiveRecord::Base.table_name_prefix = nil

        SchemaMigration.reset_table_name
        InternalMetadata.reset_table_name
      end
    end

    class DatabaseTasksTruncateAllWithSuffixTest < DatabaseTasksTruncateAllTest
      setup do
        ActiveRecord::Base.table_name_suffix = "_s"

        SchemaMigration.reset_table_name
        InternalMetadata.reset_table_name
      end

      teardown do
        ActiveRecord::Base.table_name_suffix = nil

        SchemaMigration.reset_table_name
        InternalMetadata.reset_table_name
      end
    end
  end

  class DatabaseTasksTruncateAllWithMultipleDatabasesTest < ActiveRecord::TestCase
    def setup
      @configurations = {
        "development" => { "primary" => { "database" => "dev-db" }, "secondary" => { "database" => "secondary-dev-db" } },
        "test" => { "primary" => { "database" => "test-db" }, "secondary" => { "database" => "secondary-test-db" } },
        "production" => { "primary" => { "url" => "abstract://prod-db-host/prod-db" }, "secondary" => { "url" => "abstract://secondary-prod-db-host/secondary-prod-db" } }
      }
    end

    def test_truncate_all_databases_for_environment
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :truncate_tables,
          [
            ["database" => "test-db"],
            ["database" => "secondary-test-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.truncate_all(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end

    def test_truncate_all_databases_with_url_for_environment
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :truncate_tables,
          [
            ["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"],
            ["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.truncate_all(
            ActiveSupport::StringInquirer.new("production")
          )
        end
      end
    end

    def test_truncate_all_development_databases_when_env_is_not_specified
      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :truncate_tables,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.truncate_all(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    end

    def test_truncate_all_development_databases_when_env_is_development
      old_env = ENV["RAILS_ENV"]
      ENV["RAILS_ENV"] = "development"

      with_stubbed_configurations do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :truncate_tables,
          [
            ["database" => "dev-db"],
            ["database" => "secondary-dev-db"]
          ]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.truncate_all(
            ActiveSupport::StringInquirer.new("development")
          )
        end
      end
    ensure
      ENV["RAILS_ENV"] = old_env
    end

    private
      def with_stubbed_configurations
        old_configurations = ActiveRecord::Base.configurations
        ActiveRecord::Base.configurations = @configurations

        yield
      ensure
        ActiveRecord::Base.configurations = old_configurations
      end
  end

  class DatabaseTasksCharsetTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_charset") do
        with_stubbed_new do
          assert_called(eval("@#{v}"), :charset) do
            ActiveRecord::Tasks::DatabaseTasks.charset "adapter" => k
          end
        end
      end
    end
  end

  class DatabaseTasksCollationTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_collation") do
        with_stubbed_new do
          assert_called(eval("@#{v}"), :collation) do
            ActiveRecord::Tasks::DatabaseTasks.collation "adapter" => k
          end
        end
      end
    end
  end

  class DatabaseTaskTargetVersionTest < ActiveRecord::TestCase
    def test_target_version_returns_nil_if_version_does_not_exist
      version = ENV.delete("VERSION")
      assert_nil ActiveRecord::Tasks::DatabaseTasks.target_version
    ensure
      ENV["VERSION"] = version
    end

    def test_target_version_returns_nil_if_version_is_empty
      version = ENV["VERSION"]

      ENV["VERSION"] = ""
      assert_nil ActiveRecord::Tasks::DatabaseTasks.target_version
    ensure
      ENV["VERSION"] = version
    end

    def test_target_version_returns_converted_to_integer_env_version_if_version_exists
      version = ENV["VERSION"]

      ENV["VERSION"] = "0"
      assert_equal ENV["VERSION"].to_i, ActiveRecord::Tasks::DatabaseTasks.target_version

      ENV["VERSION"] = "42"
      assert_equal ENV["VERSION"].to_i, ActiveRecord::Tasks::DatabaseTasks.target_version

      ENV["VERSION"] = "042"
      assert_equal ENV["VERSION"].to_i, ActiveRecord::Tasks::DatabaseTasks.target_version
    ensure
      ENV["VERSION"] = version
    end
  end

  class DatabaseTaskCheckTargetVersionTest < ActiveRecord::TestCase
    def test_check_target_version_does_not_raise_error_on_empty_version
      version = ENV["VERSION"]
      ENV["VERSION"] = ""
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
    ensure
      ENV["VERSION"] = version
    end

    def test_check_target_version_does_not_raise_error_if_version_is_not_setted
      version = ENV.delete("VERSION")
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
    ensure
      ENV["VERSION"] = version
    end

    def test_check_target_version_raises_error_on_invalid_version_format
      version = ENV["VERSION"]

      ENV["VERSION"] = "unknown"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "0.1.11"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1.1.11"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "0 "
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1."
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1_"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)

      ENV["VERSION"] = "1_name"
      e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
      assert_match(/Invalid format of target version/, e.message)
    ensure
      ENV["VERSION"] = version
    end

    def test_check_target_version_does_not_raise_error_on_valid_version_format
      version = ENV["VERSION"]

      ENV["VERSION"] = "0"
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }

      ENV["VERSION"] = "1"
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }

      ENV["VERSION"] = "001"
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }

      ENV["VERSION"] = "001_name.rb"
      assert_nothing_raised { ActiveRecord::Tasks::DatabaseTasks.check_target_version }
    ensure
      ENV["VERSION"] = version
    end
  end

  class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_structure_dump") do
        with_stubbed_new do
          assert_called_with(
            eval("@#{v}"), :structure_dump,
            ["awesome-file.sql", nil]
          ) do
            ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => k }, "awesome-file.sql")
          end
        end
      end
    end
  end

  class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase
    include DatabaseTasksSetupper

    ADAPTERS_TASKS.each do |k, v|
      define_method("test_#{k}_structure_load") do
        with_stubbed_new do
          assert_called_with(
            eval("@#{v}"),
            :structure_load,
            ["awesome-file.sql", nil]
          ) do
            ActiveRecord::Tasks::DatabaseTasks.structure_load({ "adapter" => k }, "awesome-file.sql")
          end
        end
      end
    end
  end

  class DatabaseTasksCheckSchemaFileTest < ActiveRecord::TestCase
    def test_check_schema_file
      assert_called_with(Kernel, :abort, [/awesome-file.sql/]) do
        ActiveRecord::Tasks::DatabaseTasks.check_schema_file("awesome-file.sql")
      end
    end
  end

  class DatabaseTasksCheckSchemaFileDefaultsTest < ActiveRecord::TestCase
    def test_check_schema_file_defaults
      ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, "/tmp") do
        assert_equal "/tmp/schema.rb", ActiveRecord::Tasks::DatabaseTasks.schema_file
      end
    end
  end

  class DatabaseTasksCheckSchemaFileSpecifiedFormatsTest < ActiveRecord::TestCase
    { ruby: "schema.rb", sql: "structure.sql" }.each_pair do |fmt, filename|
      define_method("test_check_schema_file_for_#{fmt}_format") do
        ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, "/tmp") do
          assert_equal "/tmp/#{filename}", ActiveRecord::Tasks::DatabaseTasks.schema_file(fmt)
        end
      end
    end
  end
end


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe 'SocketWrapper' do
  let(:eth_device) { 'eth0' }
  let(:eth_type) { 0x0800 }
  let(:mac) { Ethernet::RawSocket.mac eth_device }
  let(:dest_mac) { "\x00\x11\x22\x33\x44\x55" }
  let(:bcast_mac) { "\xff" * 6 }

  shared_examples_for 'a real socket' do
    it 'should output a packet' do
      @socket.send_to dest_mac, "\r\n"
    end

    it 'should receive some network noise' do
      @socket.recv_from.first.should_not be_empty
    end
  end

  describe 'on eth0' do
    before { @socket = Ethernet::SocketWrapper.new eth_device, eth_type }
    after { @socket.close }

    it_should_behave_like 'a real socket'
  end

  describe 'from raw socket' do
    before do
      raw_socket = Ethernet::RawSocket.socket eth_device, eth_type
      @socket = Ethernet::SocketWrapper.new raw_socket, eth_type, mac
    end
    after { @socket.close }

    it_should_behave_like 'a real socket'
  end

  describe 'stubbed' do
    let(:socket_stub) do
      RawSocketStub.new([
        [mac, dest_mac, "\x88\xB7", 'Wrong Ethernet type'].join,
        [bcast_mac, dest_mac, [eth_type].pack('n'), 'Wrong dest MAC'].join,
        [mac, bcast_mac, [eth_type].pack('n'), 'Bcast'].join,
        [mac, dest_mac, [eth_type].pack('n'), 'Correct'].join,
      ])
    end
    let(:socket) { Ethernet::SocketWrapper.new socket_stub, eth_type, mac }

    shared_examples_for 'after a small send call' do
      it 'should send a single packet' do
        socket_stub.sends.length.should == 1
      end
      it 'should pad the packet' do
        socket_stub.sends.first.length.should == 60
      end
      it 'should assemble packet correctly in send' do
        gold = [dest_mac, mac, [eth_type].pack('n'), 'Send data'].join
        socket_stub.sends.first[0, gold.length].should == gold
      end
    end

    describe 'send_to' do
      before { socket.send_to dest_mac, 'Send data' }
      it_should_behave_like 'after a small send call'
    end

    describe 'recv_from' do
      it 'should filter down to the correct packet' do
        socket.recv_from.should == ['Bcast', bcast_mac]
      end
    end

    describe 'unconnected' do
      it 'should complain in recv' do
        lambda { socket.recv }.should raise_error(RuntimeError)
      end

      it 'should complain in send' do
        lambda { socket.send 'Send data' }.should raise_error(RuntimeError)
      end
    end

    describe 'connected' do
      before { socket.connect dest_mac }

      describe 'send' do
        before { socket.send 'Send data' }
        it_should_behave_like 'after a small send call'
      end

      describe 'recv' do
        it 'should filter down to the correct packet' do
          socket.recv.should == 'Correct'
        end
      end
    end

    it 'should delegate close' do
      socket_stub.should_receive(:close).once
      socket.close
    end
  end
end


text:
package Pkg;

/**
 * Created by gimy on 11/9/2016.
 */
public class WeighedItem extends PurchaseItem {

    private double weight;

    public WeighedItem(String n, double u, double w) {

        super(n, u);
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    @Override
    public double getPrice() {
        return super.getUnitPrice() * this.weight;
    }

    @Override
    public String toString() {
        String info = "\t\t\t::Weighted Item::\n\nName : " + super.getName() + "\nWeight : " + this.getWeight() + "\nPrice : " + this.getPrice();
        return info;
    }
}


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * config.hpp                                             *
 *                                                        *
 * hprose config unit for cpp.                            *
 *                                                        *
 * LastModified: Jun 15, 2014                             *
 * Author: Chen fei <cf@hprose.com>                       *
 *                                                        *
\**********************************************************/

#ifndef HPROSE_CONFIG_HPP
#define HPROSE_CONFIG_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <cstdlib>
#include <ctime>

#include <string>
#include <sstream>
#include <vector>
#include <typeinfo>

#include <boost/config.hpp>
#include <boost/version.hpp>

//#include <boost/tr1/type_traits.hpp>

#define BOOST_MAJOR_VERSION (BOOST_VERSION / 100000)
#define BOOST_MINOR_VERSION (BOOST_VERSION / 100 % 1000)

#if BOOST_MAJOR_VERSION == 1
#   if BOOST_MINOR_VERSION < 36
#       error Boost version requires >= 1.36 // Asio requires >= 1.35, Unordered requires >= 1.36
#   elif BOOST_MINOR_VERSION < 44
#       if BOOST_MINOR_VERSION < 40
#           define BOOST_NO_AUTO_DECLARATIONS
#           define BOOST_NO_LAMBDAS
#           define BOOST_NO_NULLPTR
#       endif
#       if BOOST_MINOR_VERSION < 38
#           define BOOST_NO_INITIALIZER_LISTS
#       endif
#       ifndef BOOST_NO_STATIC_ASSERT
#           ifndef BOOST_HAS_STATIC_ASSERT
#               define BOOST_HAS_STATIC_ASSERT // Used in BOOST_STATIC_ASSERT
#           endif
#       endif
#   endif
#endif

#ifndef BOOST_NO_CXX11_HDR_ARRAY
#ifdef BOOST_NO_0X_HDR_ARRAY
#define BOOST_NO_CXX11_HDR_ARRAY
#endif
#endif

#ifndef BOOST_NO_CXX11_CHAR16_T
#ifdef BOOST_NO_CHAR16_T
#define BOOST_NO_CXX11_CHAR16_T
#endif
#endif

#ifndef BOOST_NO_CXX11_CHAR32_T
#ifdef BOOST_NO_CHAR32_T
#define BOOST_NO_CXX11_CHAR32_T
#endif
#endif

#ifndef BOOST_NO_CXX11_NULLPTR
#ifdef BOOST_NO_NULLPTR
#define BOOST_NO_CXX11_NULLPTR
#endif
#endif

#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES
#ifdef BOOST_NO_VARIADIC_TEMPLATES
#define BOOST_NO_CXX11_VARIADIC_TEMPLATES
#endif
#endif

#ifndef BOOST_NO_CXX11_VARIADIC_MACROS
#ifdef BOOST_NO_VARIADIC_MACROS
#define BOOST_NO_CXX11_VARIADIC_MACROS
#endif
#endif

#define HPROSE_NO_UNIQUE_PTR

#if defined(_MSC_VER) && (_MSC_VER >= 1600) // decltype supported by vc2010
#   ifdef BOOST_NO_DECLTYPE
#       undef BOOST_NO_DECLTYPE
#   endif
#   ifdef BOOST_NO_NULLPTR
#       undef BOOST_NO_NULLPTR
#   endif
#   undef HPROSE_NO_UNIQUE_PTR
#endif

#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) && defined(__GXX_EXPERIMENTAL_CXX0X__)
#undef HPROSE_NO_UNIQUE_PTR
#endif

#if defined(_MSC_VER) && defined(_DEBUG)
#define HPROSE_DEBUG_MODE
#elif defined(__BORLANDC__) && (__BORLANDC__ > 0x561)
#pragma defineonoption HPROSE_DEBUG_MODE -v
#endif

#include <boost/static_assert.hpp>

#ifndef BOOST_NO_STATIC_ASSERT
#define HPROSE_STATIC_ASSERT(Exp, Msg) static_assert(Exp, Msg)
#else
#define HPROSE_STATIC_ASSERT(Exp, Msg) BOOST_STATIC_ASSERT(Exp)
#endif

#ifdef BOOST_WINDOWS
#   ifdef __BORLANDC__
#       define _strcmpi strcmpi
#       define timezone _timezone
#   endif
#else
#   define _strcmpi strcasecmp
#   define _tzset tzset
#endif

#define HPROSE_STATIC_MEMBER(Type, Name) Type & Get##Name() { static Type Name; return Name; }

#endif // HPROSE_CONFIG_HPP


text:
<?php

declare(strict_types=1);

namespace Tests\Fixtures\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Employee.
 *
 * @author Niels Keurentjes <niels.keurentjes@omines.com>
 *
 * @ORM\Entity
 */
class Employee extends Person
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $employedSince;

    /**
     * @var Company
     *
     * @ORM\ManyToOne(targetEntity="Company", inversedBy="employees")
     */
    private $company;

    /**
     * Person constructor.
     */
    public function __construct(string $firstName, string $lastName, \DateTime $employedSince = null, Company $company)
    {
        parent::__construct($firstName, $lastName);

        $this->company = $company;
        $this->employedSince = $employedSince;
    }

    /**
     * @return mixed
     */
    public function getEmployedSince()
    {
        return $this->employedSince;
    }

    public function getCompany(): Company
    {
        return $this->company;
    }
}


text:
// TypeScript Version: 2.0

/// <reference types="@stdlib/types"/>

import { NumericArray } from '@stdlib/types/array';

/**
* Interface describing `mskmax`.
*/
interface Routine {
	/**
	* Computes the maximum value of a strided array according to a mask.
	*
	* @param N - number of indexed elements
	* @param x - input array
	* @param strideX - `x` stride length
	* @param mask - mask array
	* @param strideMask - `mask` stride length
	* @returns maximum value
	*
	* @example
	* var x = [ 1.0, -2.0, 4.0, 2.0 ];
	* var mask = [ 0, 0, 1, 0 ];
	*
	* var v = mskmax( x.length, x, 1, mask, 1 );
	* // returns 2.0
	*/
	( N: number, x: NumericArray, strideX: number, mask: NumericArray, strideMask: number ): number; // tslint:disable-line:max-line-length

	/**
	* Computes the maximum value of a strided array according to a mask and using alternative indexing semantics.
	*
	* @param N - number of indexed elements
	* @param x - input array
	* @param strideX - `x` stride length
	* @param offsetX - `x` starting index
	* @param mask - mask array
	* @param strideMask - `mask` stride length
	* @param offsetMask - `mask` starting index
	* @returns maximum value
	*
	* @example
	* var x = [ 1.0, -2.0, 4.0, 2.0 ];
	* var mask = [ 0, 0, 1, 0 ];
	*
	* var v = mskmax.ndarray( x.length, x, 1, 0, mask, 1, 0 );
	* // returns 2.0
	*/
	ndarray( N: number, x: NumericArray, strideX: number, offsetX: number, mask: NumericArray, strideMask: number, offsetMask: number ): number; // tslint:disable-line:max-line-length
}

/**
* Computes the maximum value of a strided array according to a mask.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param mask - mask array
* @param strideMask - `mask` stride length
* @returns maximum value
*
* @example
* var x = [ 1.0, -2.0, 4.0, 2.0 ];
* var mask = [ 0, 0, 1, 0 ];
*
* var v = mskmax( x.length, x, 1, mask, 1 );
* // returns 2.0
*
* @example
* var x = [ 1.0, -2.0, 4.0, 2.0 ];
* var mask = [ 0, 0, 1, 0 ];
*
* var v = mskmax.ndarray( x.length, x, 1, 0, mask, 1, 0 );
* // returns 2.0
*/
declare var mskmax: Routine;

// EXPORTS //

export = mskmax;


text:
import {NgModule} from "@angular/core";
import {JigsawMobileGraphModule} from "jigsaw/mobile_public_api";
import {JigsawDemoDescriptionModule} from "app/for-internal/description/demo-description";
import {BarGraphComponent} from "./demo.component";

import {JigsawMobileHeaderModule} from "jigsaw/mobile_public_api";

@NgModule({
    declarations: [BarGraphComponent],
    exports: [BarGraphComponent],
    imports: [JigsawMobileGraphModule, JigsawDemoDescriptionModule, JigsawMobileHeaderModule]
})
export class BarGraphModule {

}


text:
extern "C" {
#endif

#define UMSD_BLOCK_SIZE		512
#define UMSD_BLOCK_MASK		(UMSD_BLOCK_SIZE-1)
#define UMSD_BLOCK_SHIFT	9

#define UMSD_MAX_OFFSET		0x1FFFFFFFFFFULL		// 2TB

typedef struct TUSBBulkOnlyMassStorageDevice
{
	TUSBDevice m_USBDevice;

	TUSBEndpoint *m_pEndpointIn;
	TUSBEndpoint *m_pEndpointOut;

	unsigned m_nCWBTag;
	unsigned m_nBlockCount;
	unsigned long long m_ullOffset;
}
TUSBBulkOnlyMassStorageDevice;

void USBBulkOnlyMassStorageDevice (TUSBBulkOnlyMassStorageDevice *pThis, TUSBDevice *pDevice);
void _USBBulkOnlyMassStorageDevice (TUSBBulkOnlyMassStorageDevice *pThis);

boolean USBBulkOnlyMassStorageDeviceConfigure (TUSBDevice *pUSBDevice);

int USBBulkOnlyMassStorageDeviceRead (TUSBBulkOnlyMassStorageDevice *pThis, void *pBuffer, unsigned nCount);
int USBBulkOnlyMassStorageDeviceWrite (TUSBBulkOnlyMassStorageDevice *pThis, const void *pBuffer, unsigned nCount);

unsigned long long USBBulkOnlyMassStorageDeviceSeek (TUSBBulkOnlyMassStorageDevice *pThis, unsigned long long ullOffset);

unsigned USBBulkOnlyMassStorageDeviceGetCapacity (TUSBBulkOnlyMassStorageDevice *pThis);

#ifdef __cplusplus
}
#endif

#endif