text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Druid - a distributed column store.
  ~ Copyright 2012 - 2015 Metamarkets Group Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>druid-server</artifactId>
    <name>druid-server</name>
    <description>Druid Server</description>

    <parent>
        <groupId>io.druid</groupId>
        <artifactId>druid</artifactId>
        <version>0.12.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-processing</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-aws-common</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-console</artifactId>
            <version>0.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.metamx</groupId>
            <artifactId>java-util</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <!-- We use log4j2 and log4j-1.2-api as a bridge -->
            <exclusions>
              <exclusion>
                <artifactId>log4j</artifactId>
                <groupId>log4j</groupId>
              </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-x-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-smile-provider</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-smile</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-guice</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-proxy</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </dependency>
        <dependency>
            <groupId>io.tesla.aether</groupId>
            <artifactId>tesla-aether</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-api</artifactId>
        </dependency>
        <dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
        </dependency>
        <dependency>
            <groupId>net.jpountz.lz4</groupId>
            <artifactId>lz4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
        </dependency>
        <dependency>
            <groupId>com.ircclouds.irc</groupId>
            <artifactId>irc-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.maxmind.geoip2</groupId>
            <artifactId>geoip2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.11.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbynet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbyclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
        </dependency>
        <dependency>
            <groupId>it.unimi.dsi</groupId>
            <artifactId>fastutil</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>

        <!-- Tests -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.carrotsearch</groupId>
            <artifactId>junit-benchmarks</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-processing</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.caliper</groupId>
            <artifactId>caliper</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.jersey-test-framework</groupId>
            <artifactId>jersey-test-framework-core</artifactId>
            <version>${jersey.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>javax.servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.jersey-test-framework</groupId>
            <artifactId>jersey-test-framework-grizzly2</artifactId>
            <version>${jersey.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>javax.servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>pl.pragmatists</groupId>
            <artifactId>JUnitParams</artifactId>
            <version>1.0.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.caucho.hessian4.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * Serializing a stream object.
 */
public class InputStreamDeserializer extends AbstractDeserializer {
  public static final InputStreamDeserializer DESER
    = new InputStreamDeserializer();

  public InputStreamDeserializer()
  {
  }

  public Object readObject(AbstractHessianInput in)
    throws IOException
  {
    return in.readInputStream();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.shell;

import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.description.Description;
import com.facebook.buck.core.description.DescriptionCreationContext;
import com.facebook.buck.core.model.targetgraph.DescriptionProvider;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.downwardapi.config.DownwardApiConfig;
import com.facebook.buck.remoteexecution.config.RemoteExecutionConfig;
import com.facebook.buck.sandbox.SandboxConfig;
import com.facebook.buck.support.cli.config.CliConfig;
import com.facebook.buck.util.environment.Platform;
import java.util.Arrays;
import java.util.Collection;
import org.pf4j.Extension;

@Extension
public class ShellDescriptionsProvider implements DescriptionProvider {

  @Override
  public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
    ToolchainProvider toolchainProvider = context.getToolchainProvider();
    BuckConfig buckConfig = context.getBuckConfig();
    DownwardApiConfig downwardApiConfig = buckConfig.getView(DownwardApiConfig.class);
    CliConfig cliConfig = buckConfig.getView(CliConfig.class);
    SandboxConfig sandboxConfig = buckConfig.getView(SandboxConfig.class);
    RemoteExecutionConfig reConfig = buckConfig.getView(RemoteExecutionConfig.class);

    return Arrays.asList(
        new CommandAliasDescription(Platform.detect()),
        new ExportFileDescription(buckConfig),
        new GenruleDescription(
            toolchainProvider,
            sandboxConfig,
            reConfig,
            downwardApiConfig,
            cliConfig,
            context.getSandboxExecutionStrategy()),
        new ShBinaryDescription(),
        new ShTestDescription(buckConfig),
        new TestSuiteDescription(),
        new WorkerToolDescription(buckConfig));
  }
}


text:
package com.betfair.cougar.tests.clienttests.features;

import com.betfair.baseline.v2.BaselineSyncClient;
import com.betfair.cougar.api.ExecutionContext;
import com.betfair.cougar.api.RequestUUID;
import com.betfair.cougar.api.security.IdentityToken;
import com.betfair.cougar.tests.clienttests.ClientTestsHelper;
import com.betfair.cougar.tests.clienttests.CougarClientWrapper;
import com.betfair.cougar.transport.api.protocol.http.ExecutionContextFactory;
import com.betfair.cougar.util.RequestUUIDImpl;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.Date;
import java.util.LinkedList;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;

/**
 * Ensures that various request uuid features are working fine (root/sub uuids)
 */
public class ClientRequestUuidTest {

    @Test(dataProvider = "TransportType")
    public void nullRequestUUid(CougarClientWrapper.TransportType tt) throws Exception {
        // Set up the client to use rescript transport
        CougarClientWrapper wrapper = CougarClientWrapper.getInstance(tt);
        BaselineSyncClient client = wrapper.getClient();

        RequestUUID uuid = null;
        ExecutionContext context = ExecutionContextFactory.resolveExecutionContext(new LinkedList<IdentityToken>(), uuid, wrapper.getCtx().getLocation(), new Date(), false, 0, new Date(), true);

        String uuidResponse = client.echoRequestUuid(context);
        assertNotNull(uuidResponse);
        assertFalse(uuidResponse.contains(":"));
    }
    @Test(dataProvider = "TransportType")
    public void withSingleRequestUUid(CougarClientWrapper.TransportType tt) throws Exception {
        // Set up the client to use rescript transport
        CougarClientWrapper wrapper = CougarClientWrapper.getInstance(tt);
        BaselineSyncClient client = wrapper.getClient();

        RequestUUID uuid = new RequestUUIDImpl("localhost123-12345678-0000000001");
        ExecutionContext context = ExecutionContextFactory.resolveExecutionContext(new LinkedList<IdentityToken>(), uuid, wrapper.getCtx().getLocation(), new Date(), false, 0, new Date(), true);

        String uuidResponse = client.echoRequestUuid(context);
        assertTrue(uuidResponse.contains(":"));
        String[] components = uuidResponse.split(":");
        assertEquals("localhost123-12345678-0000000001", components[0]);
        assertEquals("localhost123-12345678-0000000001", components[1]);
        assertNotEquals("localhost123-12345678-0000000001", components[2]);
    }

    @Test(dataProvider = "TransportType")
    public void withCompoundRequestUUid(CougarClientWrapper.TransportType tt) throws Exception {
        // Set up the client to use rescript transport
        CougarClientWrapper wrapper = CougarClientWrapper.getInstance(tt);
        BaselineSyncClient client = wrapper.getClient();

        RequestUUID uuid = new RequestUUIDImpl("root123-12345678-0000000001:parent123-12345678-0000000001:child123-12345678-0000000001");
        ExecutionContext context = ExecutionContextFactory.resolveExecutionContext(new LinkedList<IdentityToken>(), uuid, wrapper.getCtx().getLocation(), new Date(), false, 0, new Date(), true);

        String uuidResponse = client.echoRequestUuid(context);
        assertTrue(uuidResponse.contains(":"));
        String[] components = uuidResponse.split(":");
        assertEquals("root123-12345678-0000000001", components[0]);
        assertEquals("child123-12345678-0000000001", components[1]);
        assertNotEquals("child123-12345678-0000000001", components[2]);
    }

    @DataProvider(name="TransportType")
    public Object[][] clients() {
        return ClientTestsHelper.clientsToTest();
    }
}


text:
class Conversion
  include Dynameek::Model

  field :client_id, :integer
  field :channel_id, :string
  field :goal_name, :string
  field :time, :datetime

  multi_column_hash_key [:client_id, :channel_id]
  range :time

end


text:
<?php namespace Tests\Types;

use Carbon\Carbon;
use Tests\TestCase;

/**
 * Variant Feature Tests
 *
 * @package default
 * @author Josh Sephton
 */
class VariantFeatureTest extends TestCase {

	/**
	 * Set up the tests
	 *
	 * @return void
	 */
	public function setUp() {
		parent::setUp();
	}

	/**
	 * Can create a Feature
	 *
	 * @return void
	 */
	public function testCanCreateFeature() {

		$bucketer = \Mockery::mock('\Venice\Bucketer');

		$feature = new \Venice\Types\VariantFeature($bucketer);

		$this->assertInstanceOf(
			'\Venice\Types\VariantFeature',
			$feature
		);

	}

	/**
	 * Can check if a Feature is active
	 *
	 * @return void
	 */
	public function testCanCheckIfFeatureIsActive() {

		$bucketer = \Mockery::mock('\Venice\Bucketer');

		$feature = new \Venice\Types\VariantFeature($bucketer);

		$this->assertInstanceOf(
			'\Venice\Interfaces\FeatureInterface',
			$feature
		);

	}

	/**
	 * Requests the variant from the Bucketer
	 *
	 * @return void
	 */
	public function testRequestsVariantFromBucketer() {

		$experiment = 'experiment-1';
		$variant = 'control';
		$rule = [
			'variants' => [
				'control',
				'variant-1',
			]
		];

		$bucketer = \Mockery::mock('\Venice\Bucketer');
		$bucketer->shouldReceive('variant')->once()->andReturn($variant);

		$feature = new \Venice\Types\VariantFeature($bucketer);
		$feature->applyRule($experiment, $rule);

		$this->assertEquals(
			$feature->variant(),
			$variant
		);

	}

}


text:
import { Inject, Injectable, InjectionToken } from '@angular/core';
import { ConfigOption, FormlyFieldConfig } from '@ngx-formly/core';

export const SALUTATION_OPTIONS = new InjectionToken<string[]>('SALUTATION_OPTIONS');

@Injectable()
export class SalutationPresetProvider {
  constructor(@Inject(SALUTATION_OPTIONS) private salutationOptions: string[]) {}
  getConfiguration(): FormlyFieldConfig {
    return {
      key: 'salutation',
      type: 'select',
      props: {
        label: 'Salutation',
        placeholder: 'Please Select',
        options: this.salutationOptions.map((salutation) => ({ label: salutation, value: salutation })),
      },
    };
  }
}

export function registerSalutationPreset(salutationOptions: string[]): ConfigOption {
  return {
    presets: [
      {
        name: 'salutation',
        config: new SalutationPresetProvider(salutationOptions),
      },
    ],
  };
}


text:
class User
  include ExcelImport
  attr_accessor :first_name, :last_name, :age, :adress, :role

  def initialize args={}
    @first_name = args[:first_name]
    @last_name = args[:last_name]
    @age = args[:age]
    @adress = args[:adress]
    @role = args[:role]
  end

  def ==(other)
    first_name == other.first_name &&
    last_name == other.last_name &&
    age == other.age &&
    adress == other.adress &&
    role == other.role
  end

end


text:
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.image('stars', 'assets/misc/starfield.jpg');
    game.load.spritesheet('ship', 'assets/sprites/humstar.png', 32, 32);
    game.load.image('ball', 'assets/sprites/shinyball.png');

}

var ship;
var starfield;
var cursors;

function create() {

    game.world.setBounds(0, 0, 1600, 1200);

    game.physics.startSystem(Phaser.Physics.P2JS);
    game.physics.p2.defaultRestitution = 0.9;

    starfield = game.add.tileSprite(0, 0, 800, 600, 'stars');
    starfield.fixedToCamera = true;

    balls = game.add.group();
    balls.enableBody = true;
    balls.physicsBodyType = Phaser.Physics.P2JS;

    for (var i = 0; i < 50; i++)
    {
        var ball = balls.create(game.world.randomX, game.world.randomY, 'ball');
        ball.body.setCircle(16);
    }

	ship = game.add.sprite(200, 200, 'ship');
    ship.scale.set(2);
    ship.smoothed = false;
    ship.animations.add('fly', [0,1,2,3,4,5], 10, true);
    ship.play('fly');

    //  Create our physics body - a 28px radius circle. Set the 'false' parameter below to 'true' to enable debugging
	game.physics.p2.enable(ship, false);
    ship.body.setCircle(28);

	game.camera.follow(ship);

    cursors = game.input.keyboard.createCursorKeys();

}

function update() {

    ship.body.setZeroVelocity();

    if (cursors.left.isDown)
    {
		ship.body.moveLeft(200);
    }
    else if (cursors.right.isDown)
    {
		ship.body.moveRight(200);
    }

    if (cursors.up.isDown)
    {
    	ship.body.moveUp(200);
    }
    else if (cursors.down.isDown)
    {
        ship.body.moveDown(200);
    }

    if (!game.camera.atLimit.x)
    {
        starfield.tilePosition.x -= (ship.body.velocity.x * game.time.physicsElapsed);
    }

    if (!game.camera.atLimit.y)
    {
        starfield.tilePosition.y -= (ship.body.velocity.y * game.time.physicsElapsed);
    }

}

function render() {

}


text:
<link rel="stylesheet" href="<?php echo base_url() ?>css/alertify.min.css">
<link rel="stylesheet" href="<?php echo base_url() ?>css/default.min.css">

    	<a href="<?php echo base_url() ?>" > Kembali ke Home
    	<a href="<?php echo base_url('customer/add_customer') ?>" class="pull-right">Tambah Customer

Daftar Customer

			        <input type="text" placeholder="Cari customer berdasarkan nama / tanggal lahir / tipe / telephone / email / alamat / outlet" id="filter" class="span12">

								No
								Kode Pelanggan
								Nama
								Tanggal Lahir
								No.KTP
								Tipe
								Telephone
								Email
								Alamat
								<?php if($role=='admin'):?>
									Grade
								<?php endif?>
								Action

							<?php if($customers!=NULL): ?>
								<?php $i=1; ?>
								<?php foreach($customers as $customer): ?>

									<?php echo $i ?>
									<?php echo $customer->customer_code?>
									<?php echo $customer->name ?>

										<?php if($customer->birthday!=NULL):?>
											<?php echo date('d M Y',strtotime($customer->birthday)) ?>
										<?php else:?>
											<?php echo '-' ?>
										<?php endif;?>

									<?php echo $customer->ktp?>
									<?php echo $customer->type ?>
									<a href="tel:<?php echo $customer->phone ?>"><?php echo $customer->phone ?>
									<?php echo $customer->email ?>
									<?php echo $customer->address ?>
									<?php if($role=='admin'):?>
										<?php echo $customer->customer_grade ?>
										<a href="<?php echo base_url('customer/edit_customer/'.$customer->id) ?>" class="btn btn-info">Edit<a class="btn btn-danger" href="#" onclick="delete_customer('<?php echo $customer->id ?>','<?php echo $customer->name ?>')">Hapus
									<?php endif?>

								<?php $i++; ?>
								<?php endforeach; ?>
							<?php else:?>

									<td colspan="<?php echo ($role=='admin')?'11':'9' ?>" class="nocontent">
Table kosong

							<?php endif; ?>

								<td colspan="<?php echo ($role=='admin')?'11':'9' ?>">


text:
sap.ui.define([
	"sap/ui/support/supportRules/Storage",
	"sap/ui/support/supportRules/Constants",
	"sap/ui/support/supportRules/ui/models/SelectionUtils",
	"sap/ui/support/supportRules/ui/models/SharedModel",
	"sap/ui/core/util/File",
	"sap/base/util/extend",
	"sap/ui/support/library"
], function (Storage, constants, SelectionUtils, SharedModel, File, extend, library) {
	"use strict";

	var PresetsUtils = {
		model: SharedModel,

		getSystemPresets: function () {
			var aSystemPresets = [],
				sKey;

			for (sKey in library.SystemPresets) {
				aSystemPresets.push(library.SystemPresets[sKey]);
			}

			return aSystemPresets;
		},

		/**
		 * Initializes the current selection preset
		 * @param {Array} aSelectedRulesPlain The plain list of selected rules (same format as in the presets json file)
		 */
		initializeSelectionPresets: function (aSelectedRulesPlain) {
			// if we persist settings - load any selection presets, else use the default ones
			if (this.model.getProperty("/persistingSettings")) {
				var aPersistedPresets = Storage.getSelectionPresets();
				if (aPersistedPresets) {
					this.model.setProperty("/selectionPresets", aPersistedPresets);
				}
			}

			var aPresets = this.model.getProperty("/selectionPresets"),
				iLastSystemPresetPosition = 0;

			// add System Presets to Rule Presets Popover
			this.getSystemPresets().forEach(function (oSystemPreset) {
				var isFound = aPresets.some(function (oPreset) {
					if (oSystemPreset.id === oPreset.id) {
						if (!oPreset.isModified) {
							var bIsSelected = oPreset.selected;
							oPreset = extend({}, oSystemPreset);
							oPreset.selected = bIsSelected;
							if (bIsSelected) {
								SelectionUtils.setSelectedRules(oPreset.selections);
							}
						}
						return true;
					}
				});

				if (!isFound) {
					var mSystemPresetConfig = {
						disableDelete: true,
						isSystemPreset: true
					};
					aPresets.splice(iLastSystemPresetPosition + 1, 0, extend(mSystemPresetConfig, oSystemPreset));
				}

				iLastSystemPresetPosition++;
			});

			// find the selected preset
			var oSelectedPreset = null;
			aPresets.some(function (oCurrent) {
				if (oCurrent.selected) {
					oSelectedPreset = oCurrent;
					return true;
				}
			});

			// sync 'My Selections' with current selections
			if (oSelectedPreset.isMySelection) {
				oSelectedPreset.selections = aSelectedRulesPlain;
			}

			// need to init the current preset
			this.model.setProperty("/selectionPresetsCurrent", oSelectedPreset);
		},

		/**
		 * Synchronizes the current rules selection with the current selection preset
		 * @param {Array} aSelectedRulesPlain The plain list of selected rules (same format as in the presets json file)
		 */
		syncCurrentSelectionPreset: function (aSelectedRulesPlain) {
			var oPreset = this.model.getProperty("/selectionPresetsCurrent");

			oPreset.selections = aSelectedRulesPlain;

			if (!(oPreset.isModified || oPreset.isMySelection)) {
				oPreset.isModified = true;
				oPreset.title = oPreset.title + " *";
			}

			this.model.setProperty("/selectionPresetsCurrent", oPreset);

			if (PresetsUtils.isPersistingAllowed()) {
				PresetsUtils.persistSelectionPresets();
			}
		},

		/**
		 * Exports the given selections to a file
		 * @param {string} sId The id of the export
		 * @param {string} sTitle The title of the export
		 * @param {string} sDescription Some description of what is exported
		 * @param {array} aSelections An array of rules IDs which are selected
		 */
		exportSelectionsToFile: function (sId, sTitle, sDescription, aSelections) {
			var oRulesToExport = {
				id: sId,
				title: sTitle,
				description: sDescription,
				dateExported: (new Date()).toISOString(),
				version: "1.0",
				selections: aSelections
			};

			var oExportObject = JSON.stringify(oRulesToExport);

			File.save(oExportObject, constants.RULE_SELECTION_EXPORT_FILE_NAME, 'json', 'text/plain');
		},

		/**
		 * Validates if the given import is in the correct format.
		 * @param {Object} oImport The preset object to import
		 * @return {boolean} Is the import data a valid rule preset file
		 */
		isValidSelectionImport: function (oImport) {
			var bIsFileValid = true;

			if (!oImport.hasOwnProperty("title")) {
				bIsFileValid = false;
			}

			if (!oImport.hasOwnProperty("selections")) {
				bIsFileValid = false;
			} else if (!Array.isArray(oImport.selections)) {
				bIsFileValid = false;
			} else {
				for (var i = 0; i < oImport.selections.length; i++) {
					var oRuleSelection = oImport.selections[i];
					if (!oRuleSelection.hasOwnProperty("ruleId") || !oRuleSelection.hasOwnProperty("libName")) {
						bIsFileValid = false;
						break;
					}
				}
			}

			return bIsFileValid;
		},

		/**
		 * Persists the current selection presets in the local storage
		 */
		persistSelectionPresets: function () {
			Storage.setSelectionPresets(this.model.getProperty("/selectionPresets"));
		},

		/**
		 * Persists all custom imported presets in the local storage
		 * @public
		 */
		persistCustomPresets: function () {
			Storage.setCustomPresets(this.model.getProperty("/customPresets"));
		},

		/**
		 * Checks if the user has allowed persistence.
		 * @return {boolean} If the persistence cookie is set
		 */
		isPersistingAllowed: function () {
			return !!Storage.readPersistenceCookie(constants.COOKIE_NAME);
		},

		/**
		 * Loads custom presets from local storage
		 * @public
		 */
		loadCustomPresets: function () {
			var aPersistedPresets = Storage.getCustomPresets();

			if (aPersistedPresets) {
				this.model.setProperty("/customPresets", aPersistedPresets);
			}
		}
	};

	return PresetsUtils;
});


text:
namespace blink {

using ::testing::ElementsAre;
using ::testing::UnorderedElementsAre;

class CaretDisplayItemClientTest : public PaintAndRasterInvalidationTest {
 protected:
  void SetUp() override {
    PaintAndRasterInvalidationTest::SetUp();
    Selection().SetCaretBlinkingSuspended(true);
  }

  FrameSelection& Selection() const {
    return GetDocument().View()->GetFrame().Selection();
  }

  const DisplayItemClient& GetCaretDisplayItemClient() const {
    return Selection().CaretDisplayItemClientForTesting();
  }

  const LayoutBlock* CaretLayoutBlock() const {
    return static_cast<const CaretDisplayItemClient&>(
               GetCaretDisplayItemClient())
        .layout_block_;
  }

  const LayoutBlock* PreviousCaretLayoutBlock() const {
    return static_cast<const CaretDisplayItemClient&>(
               GetCaretDisplayItemClient())
        .previous_layout_block_;
  }

  Text* AppendTextNode(const String& data) {
    Text* text = GetDocument().createTextNode(data);
    GetDocument().body()->AppendChild(text);
    return text;
  }

  Element* AppendBlock(const String& data) {
    Element* block = GetDocument().CreateRawElement(html_names::kDivTag);
    Text* text = GetDocument().createTextNode(data);
    block->AppendChild(text);
    GetDocument().body()->AppendChild(block);
    return block;
  }

  void UpdateAllLifecyclePhasesForCaretTest() {
    // Partial lifecycle updates should not affect caret paint invalidation.
    GetDocument().View()->UpdateLifecycleToLayoutClean(
        DocumentUpdateReason::kTest);
    UpdateAllLifecyclePhasesForTest();
    // Partial lifecycle updates should not affect caret paint invalidation.
    GetDocument().View()->UpdateLifecycleToLayoutClean(
        DocumentUpdateReason::kTest);
  }
};

INSTANTIATE_PAINT_TEST_SUITE_P(CaretDisplayItemClientTest);

TEST_P(CaretDisplayItemClientTest, CaretPaintInvalidation) {
  GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
  GetDocument().GetPage()->GetFocusController().SetActive(true);
  GetDocument().GetPage()->GetFocusController().SetFocused(true);

  Text* text = AppendTextNode("Hello, World!");
  UpdateAllLifecyclePhasesForCaretTest();
  const auto* block = To<LayoutBlock>(GetDocument().body()->GetLayoutObject());

  // Focus the body. Should invalidate the new caret.
  GetDocument().View()->SetTracksRasterInvalidations(true);
  GetDocument().body()->focus();

  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(block->ShouldPaintCursorCaret());
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  auto caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(1, caret_visual_rect.Width());
  EXPECT_EQ(block->Location(), LayoutPoint(caret_visual_rect.Location()));

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(RasterInvalidationInfo{
                  &GetCaretDisplayItemClient(), "Caret", caret_visual_rect,
                  PaintInvalidationReason::kAppeared}));
  GetDocument().View()->SetTracksRasterInvalidations(false);

  // Move the caret to the end of the text. Should invalidate both the old and
  // new carets.
  GetDocument().View()->SetTracksRasterInvalidations(true);
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder().Collapse(Position(text, 5)).Build());

  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());
  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(block->ShouldPaintCursorCaret());
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  auto new_caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(caret_visual_rect.Size(), new_caret_visual_rect.Size());
  EXPECT_EQ(caret_visual_rect.Y(), new_caret_visual_rect.Y());
  EXPECT_LT(caret_visual_rect.X(), new_caret_visual_rect.X());

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect,
                                         PaintInvalidationReason::kCaret},
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         new_caret_visual_rect,
                                         PaintInvalidationReason::kCaret}));
  GetDocument().View()->SetTracksRasterInvalidations(false);

  // Remove selection. Should invalidate the old caret.
  auto old_caret_visual_rect = new_caret_visual_rect;
  GetDocument().View()->SetTracksRasterInvalidations(true);
  Selection().SetSelectionAndEndTyping(SelectionInDOMTree());

  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());
  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_FALSE(block->ShouldPaintCursorCaret());
  // The caret display item client painted nothing, so is not validated.
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());
  EXPECT_EQ(IntRect(), GetCaretDisplayItemClient().VisualRect());

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(RasterInvalidationInfo{
                  &GetCaretDisplayItemClient(), "Caret", old_caret_visual_rect,
                  PaintInvalidationReason::kDisappeared}));
  GetDocument().View()->SetTracksRasterInvalidations(false);
}

TEST_P(CaretDisplayItemClientTest, CaretMovesBetweenBlocks) {
  GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
  GetDocument().GetPage()->GetFocusController().SetActive(true);
  GetDocument().GetPage()->GetFocusController().SetFocused(true);
  auto* block_element1 = AppendBlock("Block1");
  auto* block_element2 = AppendBlock("Block2");
  UpdateAllLifecyclePhasesForTest();
  auto* block1 = To<LayoutBlockFlow>(block_element1->GetLayoutObject());
  auto* block2 = To<LayoutBlockFlow>(block_element2->GetLayoutObject());

  // Focus the body.
  GetDocument().body()->focus();

  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  auto caret_visual_rect1 = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(1, caret_visual_rect1.Width());
  EXPECT_EQ(block1->FirstFragment().VisualRect().Location(),
            LayoutPoint(caret_visual_rect1.Location()));
  EXPECT_TRUE(block1->ShouldPaintCursorCaret());
  EXPECT_FALSE(block2->ShouldPaintCursorCaret());

  // Move the caret into block2. Should invalidate both the old and new carets.
  GetDocument().View()->SetTracksRasterInvalidations(true);
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element2, 0))
          .Build());

  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());
  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  auto caret_visual_rect2 = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(1, caret_visual_rect2.Width());
  EXPECT_EQ(block2->FirstFragment().VisualRect().Location(),
            caret_visual_rect2.Location());
  EXPECT_FALSE(block1->ShouldPaintCursorCaret());
  EXPECT_TRUE(block2->ShouldPaintCursorCaret());

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect1,
                                         PaintInvalidationReason::kCaret},
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect2,
                                         PaintInvalidationReason::kCaret}));
  GetDocument().View()->SetTracksRasterInvalidations(false);

  // Move the caret back into block1.
  GetDocument().View()->SetTracksRasterInvalidations(true);
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element1, 0))
          .Build());

  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());
  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  EXPECT_EQ(caret_visual_rect1, GetCaretDisplayItemClient().VisualRect());
  EXPECT_TRUE(block1->ShouldPaintCursorCaret());
  EXPECT_FALSE(block2->ShouldPaintCursorCaret());

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect1,
                                         PaintInvalidationReason::kCaret},
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect2,
                                         PaintInvalidationReason::kCaret}));
  GetDocument().View()->SetTracksRasterInvalidations(false);
}

TEST_P(CaretDisplayItemClientTest, UpdatePreviousLayoutBlock) {
  GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
  GetDocument().GetPage()->GetFocusController().SetActive(true);
  GetDocument().GetPage()->GetFocusController().SetFocused(true);
  auto* block_element1 = AppendBlock("Block1");
  auto* block_element2 = AppendBlock("Block2");
  UpdateAllLifecyclePhasesForCaretTest();
  auto* block1 = To<LayoutBlock>(block_element1->GetLayoutObject());
  auto* block2 = To<LayoutBlock>(block_element2->GetLayoutObject());

  // Set caret into block2.
  GetDocument().body()->focus();
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element2, 0))
          .Build());
  GetDocument().View()->UpdateLifecycleToLayoutClean(
      DocumentUpdateReason::kTest);
  EXPECT_TRUE(block2->ShouldPaintCursorCaret());
  EXPECT_EQ(block2, CaretLayoutBlock());
  EXPECT_FALSE(block1->ShouldPaintCursorCaret());
  EXPECT_FALSE(PreviousCaretLayoutBlock());

  // Move caret into block1. Should set previousCaretLayoutBlock to block2.
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element1, 0))
          .Build());
  GetDocument().View()->UpdateLifecycleToLayoutClean(
      DocumentUpdateReason::kTest);
  EXPECT_TRUE(block1->ShouldPaintCursorCaret());
  EXPECT_EQ(block1, CaretLayoutBlock());
  EXPECT_FALSE(block2->ShouldPaintCursorCaret());
  EXPECT_EQ(block2, PreviousCaretLayoutBlock());

  // Move caret into block2. Partial update should not change
  // previousCaretLayoutBlock.
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element2, 0))
          .Build());
  GetDocument().View()->UpdateLifecycleToLayoutClean(
      DocumentUpdateReason::kTest);
  EXPECT_TRUE(block2->ShouldPaintCursorCaret());
  EXPECT_EQ(block2, CaretLayoutBlock());
  EXPECT_FALSE(block1->ShouldPaintCursorCaret());
  EXPECT_EQ(block2, PreviousCaretLayoutBlock());

  // Remove block2. Should clear caretLayoutBlock and previousCaretLayoutBlock.
  block_element2->parentNode()->RemoveChild(block_element2);
  EXPECT_FALSE(CaretLayoutBlock());
  EXPECT_FALSE(PreviousCaretLayoutBlock());

  // Set caret into block1.
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder()
          .Collapse(Position(block_element1, 0))
          .Build());
  UpdateAllLifecyclePhasesForCaretTest();
  // Remove selection.
  Selection().SetSelectionAndEndTyping(SelectionInDOMTree());
  GetDocument().View()->UpdateLifecycleToLayoutClean(
      DocumentUpdateReason::kTest);
  EXPECT_EQ(block1, PreviousCaretLayoutBlock());
}

TEST_P(CaretDisplayItemClientTest, CaretHideMoveAndShow) {
  GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
  GetDocument().GetPage()->GetFocusController().SetActive(true);
  GetDocument().GetPage()->GetFocusController().SetFocused(true);

  Text* text = AppendTextNode("Hello, World!");
  GetDocument().body()->focus();
  UpdateAllLifecyclePhasesForCaretTest();
  const auto* block = To<LayoutBlock>(GetDocument().body()->GetLayoutObject());

  auto caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(1, caret_visual_rect.Width());
  EXPECT_EQ(block->Location(), caret_visual_rect.Location());

  GetDocument().View()->SetTracksRasterInvalidations(true);
  // Simulate that the blinking cursor becomes invisible.
  Selection().SetCaretVisible(false);
  // Move the caret to the end of the text.
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder().Collapse(Position(text, 5)).Build());
  // Simulate that the cursor blinking is restarted.
  Selection().SetCaretVisible(true);

  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());
  GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
      DocumentUpdateReason::kTest);
  EXPECT_FALSE(GetCaretDisplayItemClient().IsValid());

  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_TRUE(GetCaretDisplayItemClient().IsValid());

  auto new_caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
  EXPECT_EQ(caret_visual_rect.Size(), new_caret_visual_rect.Size());
  EXPECT_EQ(caret_visual_rect.Y(), new_caret_visual_rect.Y());
  EXPECT_LT(caret_visual_rect.X(), new_caret_visual_rect.X());

  EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
              UnorderedElementsAre(
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         caret_visual_rect,
                                         PaintInvalidationReason::kCaret},
                  RasterInvalidationInfo{&GetCaretDisplayItemClient(), "Caret",
                                         new_caret_visual_rect,
                                         PaintInvalidationReason::kCaret}));
  GetDocument().View()->SetTracksRasterInvalidations(false);
}

TEST_P(CaretDisplayItemClientTest, CompositingChange) {
  SetBodyInnerHTML(
      ""
      "
"
      "
ABCDE
"
      "
");

  GetDocument().GetPage()->GetFocusController().SetActive(true);
  GetDocument().GetPage()->GetFocusController().SetFocused(true);
  auto* container = GetDocument().getElementById("container");
  auto* editor = GetDocument().getElementById("editor");
  auto* editor_block = To<LayoutBlock>(editor->GetLayoutObject());
  Selection().SetSelectionAndEndTyping(
      SelectionInDOMTree::Builder().Collapse(Position(editor, 0)).Build());
  UpdateAllLifecyclePhasesForCaretTest();

  EXPECT_TRUE(editor_block->ShouldPaintCursorCaret());
  EXPECT_EQ(editor_block, CaretLayoutBlock());
  EXPECT_EQ(IntRect(116, 105, 1, 1), GetCaretDisplayItemClient().VisualRect());

  // Composite container.
  container->setAttribute(html_names::kStyleAttr, "will-change: transform");
  UpdateAllLifecyclePhasesForCaretTest();
  // TODO(wangxianzhu): Why will-change:transform doens't trigger compositing
  // in CAP?
  if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
    EXPECT_EQ(IntRect(50, 50, 1, 1), GetCaretDisplayItemClient().VisualRect());
  }

  // Uncomposite container.
  container->setAttribute(html_names::kStyleAttr, "");
  UpdateAllLifecyclePhasesForCaretTest();
  EXPECT_EQ(IntRect(116, 105, 1, 1), GetCaretDisplayItemClient().VisualRect());
}

class ParameterizedComputeCaretRectTest
    : public EditingTestBase,
      private ScopedLayoutNGForTest,
      public testing::WithParamInterface<bool> {
 public:
  ParameterizedComputeCaretRectTest() : ScopedLayoutNGForTest(GetParam()) {}

 protected:
  PhysicalRect ComputeCaretRect(const PositionWithAffinity& position) const {
    return CaretDisplayItemClient::ComputeCaretRectAndPainterBlock(position)
        .caret_rect;
  }
};

INSTANTIATE_TEST_SUITE_P(All,
                         ParameterizedComputeCaretRectTest,
                         testing::Bool());

TEST_P(ParameterizedComputeCaretRectTest, CaretRectAfterEllipsisNoCrash) {
  SetBodyInnerHTML(
      ""
      "
long long long long long long text
");
  const Node* text = GetElementById("target")->firstChild();
  const Position position = Position::LastPositionInNode(*text);
  // Shouldn't crash inside. The actual result doesn't matter and may change.
  ComputeCaretRect(PositionWithAffinity(position));
}

}  // namespace blink


text:
package implemenation;

import common.UnionFindBase;
import interfaces.UnionFindInterface;

/**
 * Created by nars on 2/25/15.
 */
public class QuickUnionImpl extends UnionFindBase implements UnionFindInterface {
    @Override
    public void initializeInput() {
        this.initInputArraySize();
        for (int i = 0; i < this.getInputSize(); i++){
            this.setElementAt(i, i);
        }
    }

    @Override
    public boolean find(int p, int q) {
        return getRootOf(p) == getRootOf(q);
    }

    @Override
    public void union(int p, int q) {
        if (! find(p, q))
        {
            this.setRootOf(p, getRootOf(q));
        }
    }

    @Override
    public int getRootOf(int nodeP) {
        int parentNode = this.getElementAt(nodeP);
        if (parentNode == nodeP) return nodeP;
        else return getRootOf(parentNode);
    }

    @Override
    public void setRootOf(int nodeP, int newRoot) {
        this.setElementAt(getRootOf(nodeP), newRoot);
    }

    @Override
    public void process(String inputFilePath) {
        this.setFileParser(inputFilePath);
        this.setInputSize(this.readInputSize());
        this.initializeInput();
        while (this.hasOperationsLeft()){
                this.doOperation();
        }

    }
    public void doOperation()
    {
        String split[] = this.readOperation();

        assert split.length == 3;
        if (split[0].equals("F"))
        {
            System.out.println("Find between P:" + split[1] + " Q: "
                    + split[2]);
            boolean result = this.find(Integer.parseInt(split[1]),
                    Integer.parseInt(split[2]));
            System.out.println(result);
        }
        else
        {
            System.out.println("Union between P:" + split[1] + " Q: "
                    + split[2]);
            this.union(Integer.parseInt(split[1]),
                    Integer.parseInt(split[2]));
        }
    }
}


text:
package java.io;

/**
 * @skip
 */
public class PrintStream extends FilterOutputStream {

  public PrintStream(OutputStream out) {
    super(out);
  }

  public void print(String s) {
    try {
      write(s.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void println(String s) {
    print(s + System.lineSeparator());
  }

  public void print(boolean x) {
    print(String.valueOf(x));
  }

  public void print(char x) {
    print(String.valueOf(x));
  }

  public void print(char[] x) {
    println(String.valueOf(x));
  }

  public void print(double x) {
    print(String.valueOf(x));
  }

  public void print(float x) {
    print(String.valueOf(x));
  }

  public void print(int x) {
    print(String.valueOf(x));
  }

  public void print(long x) {
    print(String.valueOf(x));
  }

  public void print(Object x) {
    print(String.valueOf(x));
  }

  public void println() {
    println("");
  }

  public void println(boolean x) {
    println(String.valueOf(x));
  }

  public void println(char x) {
    println(String.valueOf(x));
  }

  public void println(char[] x) {
    println(String.valueOf(x));
  }

  public void println(double x) {
    println(String.valueOf(x));
  }

  public void println(float x) {
    println(String.valueOf(x));
  }

  public void println(int x) {
    println(String.valueOf(x));
  }

  public void println(long x) {
    println(String.valueOf(x));
  }

  public void println(Object x) {
    println(String.valueOf(x));
  }
}


text:
namespace aura {
class Window;
}

class Panel;

// EventHandler which implements special handling for resizing panels. Panels
// should use X11PanelResizer instead of X11WindowEventFilter.
// When resizing a panel:
// - The panel bounds should update in sync with the user's mouse movement
//   during the resize operation.
// - The layout of all of the panels should be updated once the resize operation
//   completes.
// X11PanelResizer does not hand off resizing to the window manager because it
// is not possible to determine when the window manager has finished resizing.
class X11PanelResizer : public ui::EventHandler {
 public:
  X11PanelResizer(Panel* panel, aura::Window* window);
  virtual ~X11PanelResizer();

 private:
  enum ResizeState {
    NOT_RESIZING,

    // The user has clicked on one of the panel's edges.
    RESIZE_CAN_START,

    // The user has dragged one of the panel's edges far enough for resizing to
    // begin.
    RESIZE_IN_PROGRESS
  };

  // Called as a result of ET_MOUSE_PRESSED.
  void OnMousePressed(ui::MouseEvent* event);

  // Called as a result of ET_MOUSE_DRAGGED.
  void OnMouseDragged(ui::MouseEvent* event);

  // Stops the resize operation if one is in progress. Consumes |event| if it
  // is not NULL and the resize operation was stopped.
  void StopResizing(ui::MouseEvent* event, bool canceled);

  // ui::EventHandler:
  virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE;

  // The panel being resized.
  Panel* panel_;

  // |panel|'s window.
  aura::Window* window_;

  ResizeState resize_state_;

  // The edge that the user is resizing.
  int resize_component_;

  // The location of the mouse click on the window border.
  gfx::Point initial_press_location_in_screen_;

  DISALLOW_COPY_AND_ASSIGN(X11PanelResizer);
};

#endif  // CHROME_BROWSER_UI_VIEWS_PANELS_X11_PANEL_RESIZER_H_


text:
package org.sakaiproject.accountvalidator.entity.impl;

import org.sakaiproject.accountvalidator.entity.ValidationEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;

public class ValidationEntityProviderImpl implements ValidationEntityProvider, AutoRegisterEntityProvider {

	public String getEntityPrefix() {
		return PREFIX;
	}

}


text:
#include <aws/rds-data/model/Field.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/HashingUtils.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace RDSDataService
{
namespace Model
{

Field::Field() :
    m_isNull(false),
    m_isNullHasBeenSet(false),
    m_booleanValue(false),
    m_booleanValueHasBeenSet(false),
    m_longValue(0),
    m_longValueHasBeenSet(false),
    m_doubleValue(0.0),
    m_doubleValueHasBeenSet(false),
    m_stringValueHasBeenSet(false),
    m_blobValueHasBeenSet(false),
    m_arrayValueHasBeenSet(false)
{
}

Field::Field(JsonView jsonValue) :
    m_isNull(false),
    m_isNullHasBeenSet(false),
    m_booleanValue(false),
    m_booleanValueHasBeenSet(false),
    m_longValue(0),
    m_longValueHasBeenSet(false),
    m_doubleValue(0.0),
    m_doubleValueHasBeenSet(false),
    m_stringValueHasBeenSet(false),
    m_blobValueHasBeenSet(false),
    m_arrayValueHasBeenSet(false)
{
  *this = jsonValue;
}

Field& Field::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("isNull"))
  {
    m_isNull = jsonValue.GetBool("isNull");

    m_isNullHasBeenSet = true;
  }

  if(jsonValue.ValueExists("booleanValue"))
  {
    m_booleanValue = jsonValue.GetBool("booleanValue");

    m_booleanValueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("longValue"))
  {
    m_longValue = jsonValue.GetInt64("longValue");

    m_longValueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("doubleValue"))
  {
    m_doubleValue = jsonValue.GetDouble("doubleValue");

    m_doubleValueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("stringValue"))
  {
    m_stringValue = jsonValue.GetString("stringValue");

    m_stringValueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("blobValue"))
  {
    m_blobValue = HashingUtils::Base64Decode(jsonValue.GetString("blobValue"));
    m_blobValueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("arrayValue"))
  {
    m_arrayValue = jsonValue.GetObject("arrayValue");

    m_arrayValueHasBeenSet = true;
  }

  return *this;
}

JsonValue Field::Jsonize() const
{
  JsonValue payload;

  if(m_isNullHasBeenSet)
  {
   payload.WithBool("isNull", m_isNull);

  }

  if(m_booleanValueHasBeenSet)
  {
   payload.WithBool("booleanValue", m_booleanValue);

  }

  if(m_longValueHasBeenSet)
  {
   payload.WithInt64("longValue", m_longValue);

  }

  if(m_doubleValueHasBeenSet)
  {
   payload.WithDouble("doubleValue", m_doubleValue);

  }

  if(m_stringValueHasBeenSet)
  {
   payload.WithString("stringValue", m_stringValue);

  }

  if(m_blobValueHasBeenSet)
  {
   payload.WithString("blobValue", HashingUtils::Base64Encode(m_blobValue));
  }

  if(m_arrayValueHasBeenSet)
  {
   payload.WithObject("arrayValue", m_arrayValue.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace RDSDataService
} // namespace Aws


text:
namespace PlayFab.Json.Serialization
{
  /// <summary>
  /// Represents a method that constructs an object.
  /// </summary>
  /// <typeparam name="T">The object type to create.</typeparam>
  public delegate object ObjectConstructor<T>(params object[] args);
}
#endif


text:
module Rulers
  class Application
    def get_controller_and_action(env)
      _, cont, action, after =
        env["PATH_INFO"].split('/', 4)
      cont = cont.capitalize
      cont += "Controller"

      [Object.const_get(cont), action]
    end
  end
end


text:
<?php

class TagTest extends CDbTestCase
{
	public $fixtures=array(
		'tags'=>'Tag',
	);

	public function testCreate()
	{

	}
}


text:
package org.apache.spark.sql.kafka010

import java.{util => ju}
import java.util.concurrent.TimeoutException

import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
import org.apache.kafka.common.TopicPartition

import org.apache.spark.TaskContext
import org.apache.spark.internal.Logging
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.expressions.UnsafeRow
import org.apache.spark.sql.catalyst.expressions.codegen.{BufferHolder, UnsafeRowWriter}
import org.apache.spark.sql.catalyst.util.DateTimeUtils
import org.apache.spark.sql.kafka010.KafkaSourceProvider.{INSTRUCTION_FOR_FAIL_ON_DATA_LOSS_FALSE, INSTRUCTION_FOR_FAIL_ON_DATA_LOSS_TRUE}
import org.apache.spark.sql.sources.v2.reader._
import org.apache.spark.sql.sources.v2.reader.streaming.{ContinuousDataReader, ContinuousReader, Offset, PartitionOffset}
import org.apache.spark.sql.types.StructType
import org.apache.spark.unsafe.types.UTF8String

/**
 * A [[ContinuousReader]] for data from kafka.
 *
 * @param offsetReader  a reader used to get kafka offsets. Note that the actual data will be
 *                      read by per-task consumers generated later.
 * @param kafkaParams   String params for per-task Kafka consumers.
 * @param sourceOptions The [[org.apache.spark.sql.sources.v2.DataSourceOptions]] params which
 *                      are not Kafka consumer params.
 * @param metadataPath Path to a directory this reader can use for writing metadata.
 * @param initialOffsets The Kafka offsets to start reading data at.
 * @param failOnDataLoss Flag indicating whether reading should fail in data loss
 *                       scenarios, where some offsets after the specified initial ones can't be
 *                       properly read.
 */
class KafkaContinuousReader(
    offsetReader: KafkaOffsetReader,
    kafkaParams: ju.Map[String, Object],
    sourceOptions: Map[String, String],
    metadataPath: String,
    initialOffsets: KafkaOffsetRangeLimit,
    failOnDataLoss: Boolean)
  extends ContinuousReader with SupportsScanUnsafeRow with Logging {

  private lazy val session = SparkSession.getActiveSession.get
  private lazy val sc = session.sparkContext

  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong

  // Initialized when creating reader factories. If this diverges from the partitions at the latest
  // offsets, we need to reconfigure.
  // Exposed outside this object only for unit tests.
  @volatile private[sql] var knownPartitions: Set[TopicPartition] = _

  override def readSchema: StructType = KafkaOffsetReader.kafkaSchema

  private var offset: Offset = _
  override def setStartOffset(start: ju.Optional[Offset]): Unit = {
    offset = start.orElse {
      val offsets = initialOffsets match {
        case EarliestOffsetRangeLimit => KafkaSourceOffset(offsetReader.fetchEarliestOffsets())
        case LatestOffsetRangeLimit => KafkaSourceOffset(offsetReader.fetchLatestOffsets())
        case SpecificOffsetRangeLimit(p) => offsetReader.fetchSpecificOffsets(p, reportDataLoss)
      }
      logInfo(s"Initial offsets: $offsets")
      offsets
    }
  }

  override def getStartOffset(): Offset = offset

  override def deserializeOffset(json: String): Offset = {
    KafkaSourceOffset(JsonUtils.partitionOffsets(json))
  }

  override def createUnsafeRowReaderFactories(): ju.List[DataReaderFactory[UnsafeRow]] = {
    import scala.collection.JavaConverters._

    val oldStartPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(offset)

    val currentPartitionSet = offsetReader.fetchEarliestOffsets().keySet
    val newPartitions = currentPartitionSet.diff(oldStartPartitionOffsets.keySet)
    val newPartitionOffsets = offsetReader.fetchEarliestOffsets(newPartitions.toSeq)

    val deletedPartitions = oldStartPartitionOffsets.keySet.diff(currentPartitionSet)
    if (deletedPartitions.nonEmpty) {
      reportDataLoss(s"Some partitions were deleted: $deletedPartitions")
    }

    val startOffsets = newPartitionOffsets ++
      oldStartPartitionOffsets.filterKeys(!deletedPartitions.contains(_))
    knownPartitions = startOffsets.keySet

    startOffsets.toSeq.map {
      case (topicPartition, start) =>
        KafkaContinuousDataReaderFactory(
          topicPartition, start, kafkaParams, pollTimeoutMs, failOnDataLoss)
          .asInstanceOf[DataReaderFactory[UnsafeRow]]
    }.asJava
  }

  /** Stop this source and free any resources it has allocated. */
  def stop(): Unit = synchronized {
    offsetReader.close()
  }

  override def commit(end: Offset): Unit = {}

  override def mergeOffsets(offsets: Array[PartitionOffset]): Offset = {
    val mergedMap = offsets.map {
      case KafkaSourcePartitionOffset(p, o) => Map(p -> o)
    }.reduce(_ ++ _)
    KafkaSourceOffset(mergedMap)
  }

  override def needsReconfiguration(): Boolean = {
    knownPartitions != null && offsetReader.fetchLatestOffsets().keySet != knownPartitions
  }

  override def toString(): String = s"KafkaSource[$offsetReader]"

  /**
   * If `failOnDataLoss` is true, this method will throw an `IllegalStateException`.
   * Otherwise, just log a warning.
   */
  private def reportDataLoss(message: String): Unit = {
    if (failOnDataLoss) {
      throw new IllegalStateException(message + s". $INSTRUCTION_FOR_FAIL_ON_DATA_LOSS_TRUE")
    } else {
      logWarning(message + s". $INSTRUCTION_FOR_FAIL_ON_DATA_LOSS_FALSE")
    }
  }
}

/**
 * A data reader factory for continuous Kafka processing. This will be serialized and transformed
 * into a full reader on executors.
 *
 * @param topicPartition The (topic, partition) pair this task is responsible for.
 * @param startOffset The offset to start reading from within the partition.
 * @param kafkaParams Kafka consumer params to use.
 * @param pollTimeoutMs The timeout for Kafka consumer polling.
 * @param failOnDataLoss Flag indicating whether data reader should fail if some offsets
 *                       are skipped.
 */
case class KafkaContinuousDataReaderFactory(
    topicPartition: TopicPartition,
    startOffset: Long,
    kafkaParams: ju.Map[String, Object],
    pollTimeoutMs: Long,
    failOnDataLoss: Boolean) extends DataReaderFactory[UnsafeRow] {
  override def createDataReader(): KafkaContinuousDataReader = {
    new KafkaContinuousDataReader(
      topicPartition, startOffset, kafkaParams, pollTimeoutMs, failOnDataLoss)
  }
}

/**
 * A per-task data reader for continuous Kafka processing.
 *
 * @param topicPartition The (topic, partition) pair this data reader is responsible for.
 * @param startOffset The offset to start reading from within the partition.
 * @param kafkaParams Kafka consumer params to use.
 * @param pollTimeoutMs The timeout for Kafka consumer polling.
 * @param failOnDataLoss Flag indicating whether data reader should fail if some offsets
 *                       are skipped.
 */
class KafkaContinuousDataReader(
    topicPartition: TopicPartition,
    startOffset: Long,
    kafkaParams: ju.Map[String, Object],
    pollTimeoutMs: Long,
    failOnDataLoss: Boolean) extends ContinuousDataReader[UnsafeRow] {
  private val consumer =
    CachedKafkaConsumer.createUncached(topicPartition.topic, topicPartition.partition, kafkaParams)
  private val converter = new KafkaRecordToUnsafeRowConverter

  private var nextKafkaOffset = startOffset
  private var currentRecord: ConsumerRecord[Array[Byte], Array[Byte]] = _

  override def next(): Boolean = {
    var r: ConsumerRecord[Array[Byte], Array[Byte]] = null
    while (r == null) {
      if (TaskContext.get().isInterrupted() || TaskContext.get().isCompleted()) return false
      // Our consumer.get is not interruptible, so we have to set a low poll timeout, leaving
      // interrupt points to end the query rather than waiting for new data that might never come.
      try {
        r = consumer.get(
          nextKafkaOffset,
          untilOffset = Long.MaxValue,
          pollTimeoutMs,
          failOnDataLoss)
      } catch {
        // We didn't read within the timeout. We're supposed to block indefinitely for new data, so
        // swallow and ignore this.
        case _: TimeoutException =>

        // This is a failOnDataLoss exception. Retry if nextKafkaOffset is within the data range,
        // or if it's the endpoint of the data range (i.e. the "true" next offset).
        case e: IllegalStateException  if e.getCause.isInstanceOf[OffsetOutOfRangeException] =>
          val range = consumer.getAvailableOffsetRange()
          if (range.latest >= nextKafkaOffset && range.earliest <= nextKafkaOffset) {
            // retry
          } else {
            throw e
          }
      }
    }
    nextKafkaOffset = r.offset + 1
    currentRecord = r
    true
  }

  override def get(): UnsafeRow = {
    converter.toUnsafeRow(currentRecord)
  }

  override def getOffset(): KafkaSourcePartitionOffset = {
    KafkaSourcePartitionOffset(topicPartition, nextKafkaOffset)
  }

  override def close(): Unit = {
    consumer.close()
  }
}


text:
from django.db.models import signals, get_app
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_noop as _

try:
    notification = get_app('notification')
    def create_notice_types(app, created_models, verbosity, **kwargs):
        notification.create_notice_type("squaretracker_testrun",
                                        _("Test Run"),
                                        _("a new test run has been executed"), default=2)
    signals.post_syncdb.connect(create_notice_types, sender=notification)
except ImproperlyConfigured:
    print "Skipping creation of NoticeTypes as notification app not found"


text:
module Vnstat
  module Traffic
    ##
    # A class encapsulating daily tracking information.
    class Daily < Base
      ##
      # Fetches a single {Result::Day} from the collection.
      #
      # @return [Result::Day]
      #
      # @overload [](date)
      #   @param [Date] date
      #
      # @overload [](year, month, day)
      #   @param [Integer] year
      #   @param [Integer] month
      #   @param [Integer] day
      def [](*args)
        date = case args.count
               when 1 then args.first
               when 3 then Date.new(*args)
               else
                 raise ArgumentError, 'wrong number of arguments ' \
                                     "(#{args.count} for 1 or 3)"
               end
        entries_hash[date]
      end

      private

      def entries_hash
        elements = traffic_data.xpath('days/day')
        elements.each_with_object({}) do |element, hash|
          result = Result::Day.extract_from_xml_element(element)
          hash[result.date] = result
        end
      end
    end
  end
end


text:
{% extends 'shipments/new_package_modal.html' %}
{% block title %}Edit package{% endblock %}
{% block modal-text %}Edit the package:{% endblock %}
{% block save_button_text %}Save Package{% endblock %}


text:
require 'spec_helper'

RSpec.describe BatchPushNotification::Client do

  let(:endpoint) {"https://api.batch.com/1.0/"}
  let(:api_key) {""}
  let(:rest_api_key) {""}

  # notification
  let(:group_id) {'test'}
  let(:tokens) { [""] }

  let(:title) { 'Title' }
  let(:body) { 'Body2' }
  let(:sandbox) { false }

  let(:custom_payload) { {:poll_id => 1} }
  let(:notification) { BatchPushNotification::Notification.new({group_id: group_id, tokens: tokens, title: title, body: body, custom_payload: custom_payload}) }

  before {
    BatchPushNotification.configure do |config|
      config.endpoint = endpoint
      config.api_key = api_key
      config.rest_api_key = rest_api_key
      config.sandbox = sandbox
    end
  }

  it "can send a notification" do
    client = BatchPushNotification::Client.new

    client.send_notification(notification)  do |response|
      expect(response['token']).to_not be_nil
    end
  end
end


text:
package com.f1000.rank.journal;

import java.util.List;

import com.f1000.rank.helper.RankingHelper;
import com.f1000.rank.helper.SimpleRankingHelper;
import com.f1000.rank.journal.model.Journal;

/**
 * The Class AppRank.
 *
 * @author mattiam
 * @version $Revision: 1.0 $
 */
public class AppRank {

	/** The helper. */
	private RankingHelper helper = new SimpleRankingHelper();

	/**
	 * Rank journals.
	 *
	 * @param list
	 *            the list
	 *
	 * @return the array list< journal>
	 */
	public List<Journal> rankJournals(List<Journal> list) {
		this.helper.ranking(list);
		return list;

	}
}


text:
package com.github.shu1jia1.common.utils.string;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class CrcHelper {
    public static byte getCrc8(byte[] data) {
        byte crc = 0;
        for (int i = 0; i < data.length; i++) {
            crc ^= data[i];
        }
        return crc;
    }

    public static void main(String[] args) throws DecoderException {
        byte crc = CrcHelper.getCrc8(
                Hex.decodeHex("55 AA 55 AA 00 1E 00 00 00 00 00 00 00 00 FF FF FF FF 00 01 00 01 00 01 00 00 00 00 03"
                        .replaceAll("\\s", "").toCharArray()));
        System.out.println(String.format("%02X", crc));
    }
}


text:
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Game.Configuration;
using osu.Game.Graphics.Cursor;
using osu.Game.Input.Handlers;
using osu.Game.Overlays;
using osu.Game.Replays;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;

namespace osu.Game.Rulesets.UI
{
    /// <summary>
    /// Displays an interactive ruleset gameplay instance.
    /// </summary>
    /// <typeparam name="TObject">The type of HitObject contained by this DrawableRuleset.</typeparam>
    public abstract class DrawableRuleset<TObject> : DrawableRuleset, IProvideCursor, ICanAttachKeyCounter
        where TObject : HitObject
    {
        /// <summary>
        /// The selected variant.
        /// </summary>
        public virtual int Variant => 0;

        /// <summary>
        /// The key conversion input manager for this DrawableRuleset.
        /// </summary>
        public PassThroughInputManager KeyBindingInputManager;

        public override double GameplayStartTime => Objects.First().StartTime - 2000;

        private readonly Lazy<Playfield> playfield;

        /// <summary>
        /// The playfield.
        /// </summary>
        public Playfield Playfield => playfield.Value;

        /// <summary>
        /// Place to put drawables above hit objects but below UI.
        /// </summary>
        public Container Overlays { get; private set; }

        /// <summary>
        /// Invoked when a <see cref="JudgementResult"/> has been applied by a <see cref="DrawableHitObject"/>.
        /// </summary>
        public event Action<JudgementResult> OnNewResult;

        /// <summary>
        /// Invoked when a <see cref="JudgementResult"/> is being reverted by a <see cref="DrawableHitObject"/>.
        /// </summary>
        public event Action<JudgementResult> OnRevertResult;

        /// <summary>
        /// The beatmap.
        /// </summary>
        public Beatmap<TObject> Beatmap;

        public override IEnumerable<HitObject> Objects => Beatmap.HitObjects;

        protected IRulesetConfigManager Config { get; private set; }

        /// <summary>
        /// The mods which are to be applied.
        /// </summary>
        private readonly IEnumerable<Mod> mods;

        private FrameStabilityContainer frameStabilityContainer;

        private OnScreenDisplay onScreenDisplay;

        /// <summary>
        /// Creates a ruleset visualisation for the provided ruleset and beatmap.
        /// </summary>
        /// <param name="ruleset">The ruleset being represented.</param>
        /// <param name="workingBeatmap">The beatmap to create the hit renderer for.</param>
        protected DrawableRuleset(Ruleset ruleset, WorkingBeatmap workingBeatmap)
            : base(ruleset)
        {
            Debug.Assert(workingBeatmap != null, "DrawableRuleset initialized with a null beatmap.");

            RelativeSizeAxes = Axes.Both;

            Beatmap = (Beatmap<TObject>)workingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo);

            mods = workingBeatmap.Mods.Value;
            applyBeatmapMods(mods);

            KeyBindingInputManager = CreateInputManager();
            playfield = new Lazy<Playfield>(CreatePlayfield);

            IsPaused.ValueChanged += paused =>
            {
                if (HasReplayLoaded.Value)
                    return;

                KeyBindingInputManager.UseParentInput = !paused.NewValue;
            };
        }

        protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
        {
            var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));

            onScreenDisplay = dependencies.Get<OnScreenDisplay>();

            Config = dependencies.Get<RulesetConfigCache>().GetConfigFor(Ruleset);
            if (Config != null)
            {
                dependencies.Cache(Config);
                onScreenDisplay?.BeginTracking(this, Config);
            }

            return dependencies;
        }

        protected virtual PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new PlayfieldAdjustmentContainer();

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            InternalChildren = new Drawable[]
            {
                frameStabilityContainer = new FrameStabilityContainer
                {
                    Child = KeyBindingInputManager
                        .WithChild(CreatePlayfieldAdjustmentContainer()
                            .WithChild(Playfield)
                        )
                },
                Overlays = new Container { RelativeSizeAxes = Axes.Both }
            };

            applyRulesetMods(mods, config);

            loadObjects();
        }

        /// <summary>
        /// Creates and adds drawable representations of hit objects to the play field.
        /// </summary>
        private void loadObjects()
        {
            foreach (TObject h in Beatmap.HitObjects)
                addHitObject(h);

            Playfield.PostProcess();

            foreach (var mod in mods.OfType<IApplicableToDrawableHitObjects>())
                mod.ApplyToDrawableHitObjects(Playfield.HitObjectContainer.Objects);
        }

        public override void RequestResume(Action continueResume) => continueResume();

        /// <summary>
        /// Creates and adds the visual representation of a <see cref="TObject"/> to this <see cref="DrawableRuleset{TObject}"/>.
        /// </summary>
        /// <param name="hitObject">The <see cref="TObject"/> to add the visual representation for.</param>
        private void addHitObject(TObject hitObject)
        {
            var drawableObject = CreateDrawableRepresentation(hitObject);

            if (drawableObject == null)
                return;

            drawableObject.OnNewResult += (_, r) => OnNewResult?.Invoke(r);
            drawableObject.OnRevertResult += (_, r) => OnRevertResult?.Invoke(r);

            Playfield.Add(drawableObject);
        }

        public override void SetReplayScore(Score replayScore)
        {
            if (!(KeyBindingInputManager is IHasReplayHandler replayInputManager))
                throw new InvalidOperationException($"A {nameof(KeyBindingInputManager)} which supports replay loading is not available");

            var handler = (ReplayScore = replayScore) != null ? CreateReplayInputHandler(replayScore.Replay) : null;

            replayInputManager.ReplayInputHandler = handler;
            frameStabilityContainer.ReplayInputHandler = handler;

            HasReplayLoaded.Value = replayInputManager.ReplayInputHandler != null;

            if (replayInputManager.ReplayInputHandler != null)
                replayInputManager.ReplayInputHandler.GamefieldToScreenSpace = Playfield.GamefieldToScreenSpace;
        }

        /// <summary>
        /// Creates a DrawableHitObject from a HitObject.
        /// </summary>
        /// <param name="h">The HitObject to make drawable.</param>
        /// <returns>The DrawableHitObject.</returns>
        public abstract DrawableHitObject<TObject> CreateDrawableRepresentation(TObject h);

        public void Attach(KeyCounterDisplay keyCounter) =>
            (KeyBindingInputManager as ICanAttachKeyCounter)?.Attach(keyCounter);

        /// <summary>
        /// Creates a key conversion input manager. An exception will be thrown if a valid <see cref="RulesetInputManager{T}"/> is not returned.
        /// </summary>
        /// <returns>The input manager.</returns>
        protected abstract PassThroughInputManager CreateInputManager();

        protected virtual ReplayInputHandler CreateReplayInputHandler(Replay replay) => null;

        /// <summary>
        /// Creates a Playfield.
        /// </summary>
        /// <returns>The Playfield.</returns>
        protected abstract Playfield CreatePlayfield();

        public override ScoreProcessor CreateScoreProcessor() => new ScoreProcessor<TObject>(this);

        /// <summary>
        /// Applies the active mods to the Beatmap.
        /// </summary>
        /// <param name="mods"></param>
        private void applyBeatmapMods(IEnumerable<Mod> mods)
        {
            if (mods == null)
                return;

            foreach (var mod in mods.OfType<IApplicableToBeatmap<TObject>>())
                mod.ApplyToBeatmap(Beatmap);
        }

        /// <summary>
        /// Applies the active mods to this DrawableRuleset.
        /// </summary>
        /// <param name="mods"></param>
        private void applyRulesetMods(IEnumerable<Mod> mods, OsuConfigManager config)
        {
            if (mods == null)
                return;

            foreach (var mod in mods.OfType<IApplicableToDrawableRuleset<TObject>>())
                mod.ApplyToDrawableRuleset(this);

            foreach (var mod in mods.OfType<IReadFromConfig>())
                mod.ReadFromConfig(config);
        }

        #region IProvideCursor

        protected override bool OnHover(HoverEvent e) => true; // required for IProvideCursor

        CursorContainer IProvideCursor.Cursor => Playfield.Cursor;

        public override GameplayCursorContainer Cursor => Playfield.Cursor;

        public bool ProvidingUserCursor => Playfield.Cursor != null && !HasReplayLoaded.Value;

        #endregion

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            if (Config != null)
            {
                onScreenDisplay?.StopTracking(this, Config);
                Config = null;
            }
        }
    }

    /// <summary>
    /// Displays an interactive ruleset gameplay instance.
    /// <remarks>
    /// This type is required only for adding non-generic type to the draw hierarchy.
    /// Once IDrawable is a thing, this can also become an interface.
    /// </remarks>
    /// </summary>
    public abstract class DrawableRuleset : CompositeDrawable
    {
        /// <summary>
        /// Whether a replay is currently loaded.
        /// </summary>
        public readonly BindableBool HasReplayLoaded = new BindableBool();

        /// <summary>
        /// Whether the game is paused. Used to block user input.
        /// </summary>
        public readonly BindableBool IsPaused = new BindableBool();

        /// <summary>~
        /// The associated ruleset.
        /// </summary>
        public readonly Ruleset Ruleset;

        /// <summary>
        /// Creates a ruleset visualisation for the provided ruleset.
        /// </summary>
        /// <param name="ruleset">The ruleset.</param>
        internal DrawableRuleset(Ruleset ruleset)
        {
            Ruleset = ruleset;
        }

        /// <summary>
        /// All the converted hit objects contained by this hit renderer.
        /// </summary>
        public abstract IEnumerable<HitObject> Objects { get; }

        /// <summary>
        /// The point in time at which gameplay starts, including any required lead-in for display purposes.
        /// Defaults to two seconds before the first <see cref="HitObject"/>. Override as necessary.
        /// </summary>
        public abstract double GameplayStartTime { get; }

        /// <summary>
        /// The currently loaded replay. Usually null in the case of a local player.
        /// </summary>
        public Score ReplayScore { get; protected set; }

        /// <summary>
        /// The cursor being displayed by the <see cref="Playfield"/>. May be null if no cursor is provided.
        /// </summary>
        public abstract GameplayCursorContainer Cursor { get; }

        /// <summary>
        /// Sets a replay to be used, overriding local input.
        /// </summary>
        /// <param name="replayScore">The replay, null for local input.</param>
        public abstract void SetReplayScore(Score replayScore);

        /// <summary>
        /// Invoked when the interactive user requests resuming from a paused state.
        /// Allows potentially delaying the resume process until an interaction is performed.
        /// </summary>
        /// <param name="continueResume">The action to run when resuming is to be completed.</param>
        public abstract void RequestResume(Action continueResume);

        /// <summary>
        /// Create a <see cref="ScoreProcessor"/> for the associated ruleset  and link with this
        /// <see cref="DrawableRuleset"/>.
        /// </summary>
        /// <returns>A score processor.</returns>
        public abstract ScoreProcessor CreateScoreProcessor();
    }

    public class BeatmapInvalidForRulesetException : ArgumentException
    {
        public BeatmapInvalidForRulesetException(string text)
            : base(text)
        {
        }
    }
}


text: Lab Assignment of CS251 - Computing Laboratories


text:
type: doc
layout: reference
category: "Basics"
title: "Idioms"
---

# Idioms

A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.

### Creating DTOs (POJOs/POCOs)

``` kotlin
data class Customer(val name: String, val email: String)
```

provides a `Customer` class with the following functionality:

* getters (and setters in case of *var*{: .keyword }s) for all properties
* `equals()`
* `hashCode()`
* `toString()`
* `copy()`
* `component1()`, `component2()`, ..., for all properties (see [Data classes](data-classes.html))

### Default values for function parameters

``` kotlin
fun foo(a: Int = 0, b: String = "") { ... }
```

### Filtering a list

``` kotlin
val positives = list.filter { x -> x > 0 }
```

Or alternatively, even shorter:

``` kotlin
val positives = list.filter { it > 0 }
```

### String Interpolation

``` kotlin
println("Name $name")
```

### Instance Checks

``` kotlin
when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}
```

### Traversing a map/list of pairs

``` kotlin
for ((k, v) in map) {
    println("$k -> $v")
}
```

`k`, `v` can be called anything.

### Using ranges

``` kotlin
for (i in 1..100) { ... }  // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
```

### Read-only list

``` kotlin
val list = listOf("a", "b", "c")
```

### Read-only map

``` kotlin
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
```

### Accessing a map

``` kotlin
println(map["key"])
map["key"] = value
```

### Lazy property

``` kotlin
val p: String by lazy {
    // compute the string
}
```

### Extension Functions

``` kotlin
fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()
```

### Creating a singleton

``` kotlin
object Resource {
    val name = "Name"
}
```

### If not null shorthand

``` kotlin
val files = File("Test").listFiles()

println(files?.size)
```

### If not null and else shorthand

``` kotlin
val files = File("Test").listFiles()

println(files?.size ?: "empty")
```

### Executing a statement if null

``` kotlin
val values = ...
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
```

### Get first item of a possibly empty collection

``` kotlin
val emails = ... // might be empty
val mainEmail = emails.firstOrNull() ?: ""
```

### Execute if not null

``` kotlin
val value = ...

value?.let {
    ... // execute this block if not null
}
```

### Map nullable value if not null

``` kotlin
val value = ...

val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
```

### Return on when statement

``` kotlin
fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}
```

### 'try/catch' expression

``` kotlin
fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // Working with result
}
```

### 'if' expression

``` kotlin
fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}
```

### Builder-style usage of methods that return `Unit`

``` kotlin
fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}
```

### Single-expression functions

``` kotlin
fun theAnswer() = 42
```

This is equivalent to

``` kotlin
fun theAnswer(): Int {
    return 42
}
```

This can be effectively combined with other idioms, leading to shorter code. E.g. with the *when*{: .keyword }-expression:

``` kotlin
fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}
```

### Calling multiple methods on an object instance ('with')

``` kotlin
class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
    penDown()
    for(i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}
```

### Java 7's try with resources

``` kotlin
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}
```

### Convenient form for a generic function that requires the generic type information

``` kotlin
//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
```

### Consuming a nullable Boolean

``` kotlin
val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // `b` is false or null
}
```


text:
<?php

namespace Magento\Ups\Test\Unit\Model;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Ups\Model\Carrier;
use Magento\Directory\Model\Country;
use PHPUnit_Framework_MockObject_MockObject as MockObject;

class CarrierTest extends \PHPUnit_Framework_TestCase
{
    const FREE_METHOD_NAME = 'free_method';

    const PAID_METHOD_NAME = 'paid_method';

    /**
     * Model under test
     *
     * @var \Magento\Quote\Model\Quote\Address\RateResult\Error|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $error;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $helper;

    /**
     * Model under test
     *
     * @var \Magento\Ups\Model\Carrier|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $model;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $errorFactory;

    /**
     * @var \Magento\Ups\Model\Carrier|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $carrier;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $scope;

    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    protected $countryFactory;

    /**
     * @var Country|MockObject
     */
    protected $country;

    /**
     * @var \Magento\Framework\Model\AbstractModel
     */
    protected $abstractModel;

    /**
     * @var \Magento\Shipping\Model\Rate\Result
     */
    protected $rate;

    protected function setUp()
    {
        $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->scope = $this->getMockBuilder(
            '\Magento\Framework\App\Config\ScopeConfigInterface'
        )->disableOriginalConstructor()->getMock();

        $this->scope->expects(
            $this->any()
        )->method(
            'getValue'
        )->will(
            $this->returnCallback([$this, 'scopeConfiggetValue'])
        );

        $this->error = $this->getMockBuilder('\Magento\Quote\Model\Quote\Address\RateResult\Error')
            ->setMethods(['setCarrier', 'setCarrierTitle', 'setErrorMessage'])
            ->getMock();

        $this->errorFactory = $this->getMockBuilder('Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();

        $this->errorFactory->expects($this->any())->method('create')->willReturn($this->error);

        $this->rate = $this->getMock('Magento\Shipping\Model\Rate\Result', ['getError'], [], '', false);
        $rateFactory = $this->getMock('Magento\Shipping\Model\Rate\ResultFactory', ['create'], [], '', false);

        $rateFactory->expects($this->any())->method('create')->willReturn($this->rate);

        $this->country = $this->getMockBuilder('\Magento\Directory\Model\Country')
            ->disableOriginalConstructor()
            ->setMethods(['load'])
            ->getMock();

        $this->abstractModel = $this->getMockBuilder('Magento\Framework\Model\AbstractModel')
            ->disableOriginalConstructor()
            ->setMethods(['getData'])
            ->getMock();

        $this->country->expects($this->any())->method('load')->willReturn($this->abstractModel);

        $this->countryFactory = $this->getMockBuilder('\Magento\Directory\Model\CountryFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();

        $this->countryFactory->expects($this->any())->method('create')->willReturn($this->country);

        $this->model = $this->helper->getObject(
            'Magento\Ups\Model\Carrier',
            [
                'scopeConfig' => $this->scope,
                'rateErrorFactory' => $this->errorFactory,
                'countryFactory' => $this->countryFactory,
                'rateFactory' => $rateFactory
            ]
        );
    }

    /**
     * Callback function, emulates getValue function
     * @param $path
     * @return null|string
     */
    public function scopeConfiggetValue($path)
    {
        $pathMap = [
            'carriers/ups/free_method' => 'free_method',
            'carriers/ups/free_shipping_subtotal' => 5,
            'carriers/ups/showmethod' => 1,
            'carriers/ups/title' => 'ups Title',
            'carriers/ups/specificerrmsg' => 'ups error message',
            'carriers/ups/min_package_weight' => 2,
            'carriers/ups/type' => 'UPS',
        ];

        return isset($pathMap[$path]) ? $pathMap[$path] : null;
    }

    /**
     * @dataProvider getMethodPriceProvider
     * @param int $cost
     * @param string $shippingMethod
     * @param bool $freeShippingEnabled
     * @param int $requestSubtotal
     * @param int $expectedPrice
     * @covers       \Magento\Shipping\Model\Carrier\AbstractCarrierOnline::getMethodPrice
     */
    public function testGetMethodPrice(
        $cost,
        $shippingMethod,
        $freeShippingEnabled,
        $requestSubtotal,
        $expectedPrice
    ) {
        $path = 'carriers/' . $this->model->getCarrierCode() . '/';
        $this->scope->expects($this->any())->method('isSetFlag')->with($path . 'free_shipping_enable')->will(
            $this->returnValue($freeShippingEnabled)
        );

        $request = new \Magento\Quote\Model\Quote\Address\RateRequest();
        $request->setBaseSubtotalInclTax($requestSubtotal);
        $this->model->setRawRequest($request);
        $price = $this->model->getMethodPrice($cost, $shippingMethod);
        $this->assertEquals($expectedPrice, $price);
    }

    /**
     * Data provider for testGenerate method
     *
     * @return array
     */
    public function getMethodPriceProvider()
    {
        return [
            [3, self::FREE_METHOD_NAME, true, 6, 0],
            [3, self::FREE_METHOD_NAME, true, 4, 3],
            [3, self::FREE_METHOD_NAME, false, 6, 3],
            [3, self::FREE_METHOD_NAME, false, 4, 3],
            [3, self::PAID_METHOD_NAME, true, 6, 3],
            [3, self::PAID_METHOD_NAME, true, 4, 3],
            [3, self::PAID_METHOD_NAME, false, 6, 3],
            [3, self::PAID_METHOD_NAME, false, 4, 3],
            [7, self::FREE_METHOD_NAME, true, 6, 0],
            [7, self::FREE_METHOD_NAME, true, 4, 7],
            [7, self::FREE_METHOD_NAME, false, 6, 7],
            [7, self::FREE_METHOD_NAME, false, 4, 7],
            [7, self::PAID_METHOD_NAME, true, 6, 7],
            [7, self::PAID_METHOD_NAME, true, 4, 7],
            [7, self::PAID_METHOD_NAME, false, 6, 7],
            [7, self::PAID_METHOD_NAME, false, 4, 7],
            [3, self::FREE_METHOD_NAME, true, 0, 3],
            [3, self::FREE_METHOD_NAME, true, 0, 3],
            [3, self::FREE_METHOD_NAME, false, 0, 3],
            [3, self::FREE_METHOD_NAME, false, 0, 3],
            [3, self::PAID_METHOD_NAME, true, 0, 3],
            [3, self::PAID_METHOD_NAME, true, 0, 3],
            [3, self::PAID_METHOD_NAME, false, 0, 3],
            [3, self::PAID_METHOD_NAME, false, 0, 3]
        ];
    }

    public function testCollectRatesErrorMessage()
    {
        $this->scope->expects($this->once())->method('isSetFlag')->willReturn(false);

        $this->error->expects($this->once())->method('setCarrier')->with('ups');
        $this->error->expects($this->once())->method('setCarrierTitle');
        $this->error->expects($this->once())->method('setErrorMessage');

        $request = new RateRequest();
        $request->setPackageWeight(1);

        $this->assertSame($this->error, $this->model->collectRates($request));
    }

    public function testCollectRatesFail()
    {
        $this->scope->expects($this->once())->method('isSetFlag')->willReturn(true);

        $request = new RateRequest();
        $request->setPackageWeight(1);

        $this->assertSame($this->rate, $this->model->collectRates($request));
    }

    /**
     * @param string $data
     * @param array $maskFields
     * @param string $expected
     * @dataProvider logDataProvider
     */
    public function testFilterDebugData($data, array $maskFields, $expected)
    {
        $refClass = new \ReflectionClass(Carrier::class);
        $property = $refClass->getProperty('_debugReplacePrivateDataKeys');
        $property->setAccessible(true);
        $property->setValue($this->model, $maskFields);

        $refMethod = $refClass->getMethod('filterDebugData');
        $refMethod->setAccessible(true);
        $result = $refMethod->invoke($this->model, $data);
        $expectedXml = new \SimpleXMLElement($expected);
        $resultXml = new \SimpleXMLElement($result);
        static::assertEquals($expectedXml->asXML(), $resultXml->asXML());
    }

    /**
     * Get list of variations
     */
    public function logDataProvider()
    {
        return [
            [
                '<?xml version="1.0" encoding="UTF-8"?>
                <RateRequest>
                    <UserId>42121</UserId>
                    <Password>TestPassword</Password>
                    <Package ID="0">
                        <Service>ALL</Service>
                    </Package>
                </RateRequest>',
                ['UserId', 'Password'],
                '<?xml version="1.0" encoding="UTF-8"?>
                <RateRequest>
                    <UserId>****</UserId>
                    <Password>****</Password>
                    <Package ID="0">
                        <Service>ALL</Service>
                    </Package>
                </RateRequest>',
            ],
            [
                '<?xml version="1.0" encoding="UTF-8"?>
                <RateRequest>
                    <Auth>
                        <UserId>1231</UserId>
                    </Auth>
                    <Package ID="0">
                        <Service>ALL</Service>
                    </Package>
                </RateRequest>',
                ['UserId'],
                '<?xml version="1.0" encoding="UTF-8"?>
                <RateRequest>
                    <Auth>
                        <UserId>****</UserId>
                    </Auth>
                    <Package ID="0">
                        <Service>ALL</Service>
                    </Package>
                </RateRequest>',
            ]
        ];
    }

    /**
     * @covers \Magento\Ups\Model\Carrier::setRequest
     * @param string $countryCode
     * @param string $foundCountryCode
     * @dataProvider countryDataProvider
     */
    public function testSetRequest($countryCode, $foundCountryCode)
    {
        /** @var RateRequest $request */
        $request = $this->helper->getObject(RateRequest::class);
        $request->setData([
            'orig_country' => 'USA',
            'orig_region_code' => 'CA',
            'orig_post_code' => 90230,
            'orig_city' => 'Culver City',
            'dest_country_id' => $countryCode,
        ]);

        $this->country->expects(static::at(1))
            ->method('load')
            ->with($countryCode)
            ->willReturnSelf();

        $this->country->expects(static::any())
            ->method('getData')
            ->with('iso2_code')
            ->willReturn($foundCountryCode);

        $this->model->setRequest($request);
    }

    /**
     * Get list of country variations
     * @return array
     */
    public function countryDataProvider()
    {
        return [
            ['countryCode' => 'PR', 'foundCountryCode' => null],
            ['countryCode' => 'US', 'foundCountryCode' => 'US'],
        ];
    }
}