text:
import sensor_base
import __builtin__
if not __builtin__.testmode:
    import grovepi
import logging, sys

class PumpRelay(sensor_base.SensorBase):
    def __init__(self,port_number):
        self.port_num = port_number
        if not __builtin__.testmode:
            grovepi.pinMode(self.port_num, "OUTPUT")
        self.name = "PumpRelay " + str(self.port_num)
        self.simple_name = "pump"
        self.state = 0

    def get_state(self):
        return self.state

    def get_states(self):
        return self.state

    def set_state(self, val):
        assert val == 1 or val == 0
        if not __builtin__.testmode:
            if val:
                grovepi.digitalWrite(self.port_num, 1);
                self.state = 1
            else:
                grovepi.digitalWrite(self.port_num, 0);
                self.state = 0
        logging.debug('Set val to actor (%s, port %s): %s', self.name, self.port_num, self.state)

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 67 (1934)

#### Original name
Tympanis bupleuri Velen.

### Remarks
null


text:
CREATE TABLE IF NOT EXISTS `award_threshold` (
`ID` bigint(20) NOT NULL,
  `contestID` bigint(20) NOT NULL,
  `gradeID` bigint(20) NOT NULL,
  `awardID` bigint(20) NOT NULL,
  `nbContestants` int(11) NOT NULL,
  `minScore` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `award_threshold`
 ADD PRIMARY KEY (`ID`), ADD UNIQUE KEY `all` (`contestID`,`gradeID`,`awardID`,`nbContestants`);

ALTER TABLE `award_threshold`
MODIFY `ID` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;


text:
``cmd`` - Run remote commands
=============================

::

   halonctl cmd [-i|--interactive] [command...]

The ``cmd`` module runs a shell command. Refer to the individual commands' manuals for details on their flags and invocations.

Halon runs FreeBSD (currently version 10.1) under the hood. Other \*nix flavors (such as Linux) may have subtle, but important, differences in command invocations.

The module will wait for the command to exit before printing any output, unless ``Ctrl+C`` is pressed, in which case it will send a SIGTERM to the remote process. If the command does not terminate in a timely fashion, you can press ``Ctrl+C`` again to forcibly terminate the remote process.

.. note::
   Everything after the ``cmd`` in the invocation of this module is passed straight to the commandline. Normal escaping rules apply.

Interactive Mode
----------------

.. warning::
   Due to technical limitations, Interactive Mode is not available on Windows.

By default, the ``cmd`` module will run the command on each matched node, and print the results, node-by-node. But some commands don't work this way - they let you interact with them, and thus need an interactive session. This is what the ``-i`` (``--interactive``) flag is for.

In Interactive Mode, you can only target a single node - if your filters match several, you're presented with a menu from which you can use your arrow keys to choose which one to use.

Output from the remote command in Interactive Mode will be piped directly to your terminal, which will be kept informed of the size of your window, and your input is sent directly. This means that Ctrl+C and the like will not work as it does in noninteractive mode - it will instead be sent to the other side, and will trigger the signal there.

Input **will** have some amount of latency, so give your keypresses a moment to register before treating them as lost.

Available Commands
------------------

The most up-to-date list can always be viewed under ``System -> Commands`` in the web UI.

* `arp <https://www.freebsd.org/cgi/man.cgi?query=arp&manpath=FreeBSD+10.1-RELEASE>`_
* `host <https://www.freebsd.org/cgi/man.cgi?query=host&manpath=FreeBSD+10.1-RELEASE>`_
* `ping <https://www.freebsd.org/cgi/man.cgi?query=ping&manpath=FreeBSD+10.1-RELEASE>`_
* `ping6 <https://www.freebsd.org/cgi/man.cgi?query=ping6&manpath=FreeBSD+10.1-RELEASE>`_
* `smtpping <https://github.com/halonsecurity/smtpping>`_
* `traceroute <https://www.freebsd.org/cgi/man.cgi?query=traceroute&manpath=FreeBSD+10.1-RELEASE>`_
* `traceroute6 <https://www.freebsd.org/cgi/man.cgi?query=traceroute6&manpath=FreeBSD+10.1-RELEASE>`_
* `tcpdump <https://www.freebsd.org/cgi/man.cgi?query=tcpdump&manpath=FreeBSD+10.1-RELEASE>`_
* `df <https://www.freebsd.org/cgi/man.cgi?query=df&manpath=FreeBSD+10.1-RELEASE>`_
* `ifconfig <https://www.freebsd.org/cgi/man.cgi?query=ifconfig&manpath=FreeBSD+10.1-RELEASE>`_
* `iostat <https://www.freebsd.org/cgi/man.cgi?query=iostat&manpath=FreeBSD+10.1-RELEASE>`_
* `mfiutil <https://www.freebsd.org/cgi/man.cgi?query=mfiutil&manpath=FreeBSD+10.1-RELEASE>`_
* `sysctl <https://www.freebsd.org/cgi/man.cgi?query=sysctl&manpath=FreeBSD+10.1-RELEASE>`_

Interactive Commands
--------------------

These commands are interactive, and will only work properly when run in interactive mode.

* `nc <https://www.freebsd.org/cgi/man.cgi?query=nc&manpath=FreeBSD+10.1-RELEASE>`_
* `telnet <https://www.freebsd.org/cgi/man.cgi?query=telnet&manpath=FreeBSD+10.1-RELEASE>`_
* hsh - `HSL <http://wiki.halon.se/HSL>`_ shell
* `login <https://www.freebsd.org/cgi/man.cgi?query=login&manpath=FreeBSD+10.1-RELEASE>`_
* `top <https://www.freebsd.org/cgi/man.cgi?query=top&manpath=FreeBSD+10.1-RELEASE>`_

Support Commands
----------------

These are internal tools to solve very specific problems, and should generally not be used.

* lostfiles - interactive recovery program
* truncsvn - truncates configuration history


text:
package sword.bitstream;

import java.io.IOException;

import sword.collections.IntPairMap;

public final class IntPairMapWriter implements ProcedureWithIOException<IntPairMap> {

    private final CollectionLengthEncoder _lengthEncoder;
    private final IntProcedureWithIOException _keyWriter;
    private final IntProcedure2WithIOException _diffKeyWriter;
    private final IntProcedureWithIOException _valueWriter;

    IntPairMapWriter(CollectionLengthEncoder lengthEncoder,
                     IntProcedureWithIOException keyWriter,
                     IntProcedure2WithIOException diffKeyWriter,
                     IntProcedureWithIOException valueWriter) {
        _lengthEncoder = lengthEncoder;
        _keyWriter = keyWriter;
        _diffKeyWriter = diffKeyWriter;
        _valueWriter = valueWriter;
    }

    @Override
    public void apply(IntPairMap map) throws IOException {
        final int mapSize = map.size();
        _lengthEncoder.encodeLength(mapSize);

        boolean first = true;
        int previous = 0;
        for (int key : map.keySet()) {
            if (_diffKeyWriter == null || first) {
                _keyWriter.apply(key);
                first = false;
            }
            else {
                _diffKeyWriter.apply(previous, key);
            }
            previous = key;

            _valueWriter.apply(map.get(key));
        }
    }
}


text:
---
external help file: Microsoft.Azure.Commands.HDInsight.dll-Help.xml
Module Name: AzureRM.HDInsight
ms.assetid: 677E19F2-CC6C-4C16-B1FD-3A15D0FF1ECA
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.hdinsight/wait-azurermhdinsightjob
schema: 2.0.0
---

# Wait-AzureRmHDInsightJob

## SYNOPSIS
Waits for the completion or failure of a specified job.

## SYNTAX

```
Wait-AzureRmHDInsightJob [-ClusterName] <String> [-JobId] <String> [-HttpCredential] <PSCredential>
 [-ResourceGroupName <String>] [-TimeoutInSeconds <Int32>] [-WaitIntervalInSeconds <Int32>]
 [-DefaultProfile <IAzureContextContainer>] [<CommonParameters>]
```

## DESCRIPTION
The **Wait-AzureRmHDInsightJob** cmdlet awaits the completion or failure of an Azure HDInsight job.

## EXAMPLES

### Example 1: Wait for the completion or failure of a job
```
PS C:\># Cluster info
PS C:\> $clusterResourceGroupName = "Group"
PS C:\> $clusterName = "your-hadoop-001"
PS C:\> $clusterCreds = Get-Credential

# Hive job details
PS C:\> $statusFolder = "tempStatusFolder/"
PS C:\> $query = "SHOW TABLES"

PS C:\> New-AzureRmHDInsightHiveJobDefinition -StatusFolder $statusFolder `
            -Query $query `
        | Start-AzureRmHDInsightJob -ResourceGroupName $clusterResourceGroupName `
            -ClusterName $clusterName `
            -ClusterCredential $clusterCreds `
        | Wait-AzureRmHDInsightJob -ResourceGroupName $clusterResourceGroupName `
            -ClusterName $clusterName `
            -ClusterCredential $clusterCreds
```

This command waits for the completion or failure of a job.

## PARAMETERS

### -ClusterName
Specifies the name of the cluster.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure

```yaml
Type: IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -HttpCredential
Specifies the cluster login (HTTP) credentials for the cluster.

```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases: ClusterCredential

Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -JobId
Specifies the job ID of the job.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -ResourceGroupName
Specifies the name of the resource group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -TimeoutInSeconds
The total time to wait for job completion, in seconds.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WaitIntervalInSeconds
The time to wait between job status checks, in seconds.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### String
Parameter 'JobId' accepts value of type 'String' from the pipeline

## OUTPUTS

### Microsoft.Azure.Commands.HDInsight.Models.AzureHDInsightJob

## NOTES

## RELATED LINKS

[Get-AzureRmHDInsightJob](./Get-AzureRmHDInsightJob.md)

[Start-AzureRmHDInsightJob](./Start-AzureRmHDInsightJob.md)

[Stop-AzureRmHDInsightJob](./Stop-AzureRmHDInsightJob.md)


text:
package qualify.remote;

import java.io.File;

public class RemoteProcess implements RemoteProcessMBean {

	public RemoteProcess() {
		System.out.println("RemoteProcess is called");
	}

	public int execute(String[] commandLine, File workingDir, File logFile,	double timeoutInSeconds) {

		System.out.println("execute is called");
		return 0;
	}

	public void sayHello() {
		System.out.println("hello");
	}

}


text:
package org.jboss.elasticsearch.river.sysinfo;

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import org.jboss.elasticsearch.river.sysinfo.esclient.SourceClientESClient;
import org.jboss.elasticsearch.river.sysinfo.esclient.SourceClientESTransportClient;
import org.jboss.elasticsearch.river.sysinfo.testtools.ESRealClientTestBase;
import org.jboss.elasticsearch.river.sysinfo.testtools.TestUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import static org.mockito.Mockito.mock;

/**
 * Unit test for {@link SysinfoRiver}.
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public class SysinfoRiverTest extends ESRealClientTestBase {

	private static final String RIVER_NAME = "my_sysinfo_river";

	@SuppressWarnings("unchecked")
	@Test
	public void configure_sourceClient() throws Exception {

		// case - local es_connection
		{
			Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_local.json");
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			tested.configure(settings);
			Assert.assertEquals(SourceClientESClient.class, tested.sourceClient.getClass());
		}

		// case - remote es_connection
		{
			Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_remote.json");
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			tested.configure(settings);
			Assert.assertEquals(SourceClientESTransportClient.class, tested.sourceClient.getClass());
			Assert.assertEquals(2, ((SourceClientESTransportClient) tested.sourceClient).getTransportAddresses().length);
		}

		// case - REST es_connection
		{
			Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_rest.json");
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			tested.configure(settings);
			Assert.assertEquals(SourceClientREST.class, tested.sourceClient.getClass());
			Assert.assertEquals("http://localhost:9200/", ((SourceClientREST) tested.sourceClient).restAPIUrlBase);
		}

		// case - invalid es_connection
		{
			try {
				Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_local.json");
				((Map<String, Object>) settings.get("es_connection")).put("type", "nonsense");
				SysinfoRiver tested = prepareRiverInstanceForTest(null);
				tested.configure(settings);
				Assert.fail("SettingsException must be thrown");
			} catch (SettingsException e) {
				// OK
			}
		}
	}

	@Test
	public void configure_indexers() throws Exception {

		// case - missing indexers
		{
			try {
				Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_local.json");
				settings.remove("indexers");
				SysinfoRiver tested = prepareRiverInstanceForTest(null);
				tested.configure(settings);
				Assert.fail("SettingsException must be thrown");
			} catch (SettingsException e) {
				// OK
			}
		}

		// case - empty indexers
		{
			try {
				Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_local.json");
				((Map<?, ?>) settings.get("indexers")).clear();
				SysinfoRiver tested = prepareRiverInstanceForTest(null);
				tested.configure(settings);
				Assert.fail("SettingsException must be thrown");
			} catch (SettingsException e) {
				// OK
			}
		}

		// case - OK read
		{
			Map<String, Object> settings = Utils.loadJSONFromJarPackagedFile("/river_configuration_test_conn_local.json");
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			tested.configure(settings);
			Assert.assertEquals(10, tested.indexers.size());
			SysinfoIndexer idxr = tested.indexers.get("cluster_health");
			Assert.assertEquals("cluster_health", idxr.name);
			Assert.assertEquals(tested.sourceClient, idxr.sourceClient);
			Assert.assertEquals(tested.client, idxr.targetClient);
			Assert.assertEquals(SysinfoType.CLUSTER_HEALTH, idxr.infoType);
			Assert.assertEquals("my_sysinfo_index", idxr.indexName);
			Assert.assertEquals("cluster_health", idxr.typeName);
			Assert.assertEquals(30 * 1000, idxr.indexingPeriod);
			Assert.assertNotNull(idxr.params);
		}

	}

	@Test
	public void start() throws Exception {
		SysinfoRiver tested = prepareRiverInstanceForTest(null);
		SourceClient scMock = tested.sourceClient;
		SysinfoRiver.clearRunningInstances();

		// case - exception if started already
		{
			tested.closed = false;
			try {
				tested.start();
				Assert.fail("IllegalStateException must be thrown");
			} catch (IllegalStateException e) {
				// OK
				Assert.assertFalse(tested.closed);
				Assert.assertEquals(0, tested.indexerThreads.size());
				Mockito.verifyZeroInteractions(scMock);
				Assert.assertEquals(0, SysinfoRiver.getRunningInstances().size());
			}
		}

		// case - no exception if indexers list is empty
		{
			Mockito.reset(scMock);
			tested.closed = true;
			tested.start();
			Assert.assertFalse(tested.closed);
			Assert.assertEquals(0, tested.indexerThreads.size());
			Mockito.verify(scMock).start();
			Assert.assertEquals(1, SysinfoRiver.getRunningInstances().size());
		}

		// case - check threads created and started for indexers
		{
			Mockito.reset(scMock);
			tested.closed = true;
			tested.indexers.put("ch", indexerMock("ch", SysinfoType.CLUSTER_HEALTH));
			tested.indexers.put("cs", indexerMock("cs", SysinfoType.CLUSTER_STATE));
			tested.start();
			Assert.assertFalse(tested.closed);
			Assert.assertEquals(2, tested.indexerThreads.size());
			Mockito.verify(scMock).start();
			// give threads chance to run so we can do next assertion on this method
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// nothing to do
			}
			for (SysinfoIndexer i : tested.indexers.values()) {
				Mockito.verify(i).run();
			}
		}
		SysinfoRiver.clearRunningInstances();
	}

	@Test
	public void close() throws Exception {
		SysinfoRiver tested = prepareRiverInstanceForTest(null);
		SourceClient scMock = tested.sourceClient;
		SysinfoRiver.clearRunningInstances();
		SysinfoRiver.addRunningInstance(tested);
		try {
			// case - no errors on empty indexers list and unstarted river
			{
				tested.close();
				Assert.assertTrue(tested.closed);
				Mockito.verify(scMock).close();
				Assert.assertEquals(0, SysinfoRiver.getRunningInstances().size());
			}

			// case - successful close
			{
				SysinfoRiver.addRunningInstance(tested);
				Mockito.reset(scMock);
				tested.closed = false;
				tested.indexers.put("ch", indexerMock("ch", SysinfoType.CLUSTER_HEALTH));
				tested.indexers.put("cs", indexerMock("cs", SysinfoType.CLUSTER_STATE));
				List<Thread> t = new ArrayList<Thread>();
				t.add(Mockito.mock(Thread.class));
				t.add(Mockito.mock(Thread.class));
				tested.indexerThreads.put("ch", t.get(0));
				tested.indexerThreads.put("cs", t.get(1));
				tested.close();
				Assert.assertTrue(tested.closed);
				Assert.assertEquals(0, tested.indexerThreads.size());
				Mockito.verify(scMock).close();
				for (SysinfoIndexer i : tested.indexers.values()) {
					Mockito.verify(i).close();
				}
				for (Thread i : t) {
					Mockito.verify(i).interrupt();
				}
				Assert.assertEquals(0, SysinfoRiver.getRunningInstances().size());
			}
		} finally {
			SysinfoRiver.clearRunningInstances();
		}
	}

	@Test
	public void stop() throws Exception {
		SysinfoRiver tested = prepareRiverInstanceForTest(null);
		SourceClient scMock = tested.sourceClient;
		SysinfoRiver.clearRunningInstances();
		SysinfoRiver.addRunningInstance(tested);
		try {
			// case - no errors on empty indexers list and unstarted river
			{
				tested.stop();
				Assert.assertTrue(tested.closed);
				Mockito.verify(scMock).close();
			}

			// case - successful stop
			{
				Mockito.reset(scMock);
				tested.closed = false;
				tested.indexers.put("ch", indexerMock("ch", SysinfoType.CLUSTER_HEALTH));
				tested.indexers.put("cs", indexerMock("cs", SysinfoType.CLUSTER_STATE));
				List<Thread> t = new ArrayList<Thread>();
				t.add(Mockito.mock(Thread.class));
				t.add(Mockito.mock(Thread.class));
				tested.indexerThreads.put("ch", t.get(0));
				tested.indexerThreads.put("cs", t.get(1));

				tested.stop();
				Assert.assertTrue(tested.closed);
				Assert.assertEquals(0, tested.indexerThreads.size());
				Mockito.verify(scMock).close();
				for (SysinfoIndexer i : tested.indexers.values()) {
					Mockito.verify(i).close();
				}
				for (Thread i : t) {
					Mockito.verify(i).interrupt();
				}
				Assert.assertEquals(1, SysinfoRiver.getRunningInstances().size());
			}
		} finally {
			SysinfoRiver.clearRunningInstances();
		}
	}

	@Test
	public void reconfigure() throws Exception {

		// case - exception when not stopped
		{
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			try {
				tested.closed = false;
				tested.reconfigure();
				Assert.fail("IllegalStateException must be thrown");
			} catch (IllegalStateException e) {
				// OK
			}
		}

		// case - config reload error because no document
		{
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			try {
				tested.client = prepareESClientForUnitTest();
				tested.closed = true;
				indexCreate(tested.getRiverIndexName());
				tested.reconfigure();
				Assert.fail("IllegalStateException must be thrown");
			} catch (IllegalStateException e) {
				// OK
			} finally {
				finalizeESClientForUnitTest();
			}
		}

		// case - config reload performed
		{
			SysinfoRiver tested = prepareRiverInstanceForTest(null);
			try {
				tested.client = prepareESClientForUnitTest();
				tested.closed = true;
				tested.client.prepareIndex(tested.getRiverIndexName(), tested.riverName().getName(), "_meta")
						.setSource(TestUtils.readStringFromClasspathFile("/river_configuration_test_conn_local.json")).execute()
						.actionGet();

				tested.reconfigure();
				Assert.assertEquals(10, tested.indexers.size());
				Assert.assertTrue(tested.sourceClient instanceof SourceClientESClient);
			} finally {
				finalizeESClientForUnitTest();
			}
		}
	}

	@Test
	public void changeIndexerPeriod() throws Exception {
		SysinfoRiver tested = prepareRiverInstanceForTest(null);

		// case - no indexer to change send, no NPE
		Assert.assertTrue(tested.changeIndexerPeriod(null, 1000));

		// case - no indexers
		Assert.assertFalse(tested.changeIndexerPeriod(new String[] { "myIndexer" }, 1000));

		// case - no indexer found if some exists
		SysinfoIndexer chi = indexerMock("ch", SysinfoType.CLUSTER_HEALTH);
		tested.indexers.put("ch", chi);
		SysinfoIndexer csi = indexerMock("cs", SysinfoType.CLUSTER_HEALTH);
		tested.indexers.put("cs", csi);
		Thread cht = Mockito.mock(Thread.class);
		Thread cst = Mockito.mock(Thread.class);
		tested.indexerThreads.put("ch", cht);
		tested.indexerThreads.put("cs", cst);
		Assert.assertFalse(tested.changeIndexerPeriod(new String[] { "myIndexer" }, 1000));
		Assert.assertFalse(tested.changeIndexerPeriod(new String[] { "myIndexer", "myIndexer2" }, 1000));
		Mockito.verifyZeroInteractions(chi);
		Mockito.verifyZeroInteractions(csi);
		Mockito.verifyZeroInteractions(cht);
		Mockito.verifyZeroInteractions(cst);

		// case - one indexer found from two, increase, no thread restarted
		Mockito.reset(chi, csi, cht, cst);
		Assert.assertTrue(tested.changeIndexerPeriod(new String[] { "myIndexer", "ch" }, 4000));
		Assert.assertEquals(4000, chi.indexingPeriod);
		Mockito.verifyZeroInteractions(chi);
		Mockito.verifyZeroInteractions(csi);
		Mockito.verifyZeroInteractions(cht);
		Mockito.verifyZeroInteractions(cst);

		// case - two indexers found, increase, no threads restarted
		Mockito.reset(chi, csi, cht, cst);
		Assert.assertTrue(tested.changeIndexerPeriod(new String[] { "cs", "ch" }, 5000));
		Assert.assertEquals(5000, chi.indexingPeriod);
		Assert.assertEquals(5000, csi.indexingPeriod);
		Mockito.verifyZeroInteractions(chi);
		Mockito.verifyZeroInteractions(csi);
		Mockito.verifyZeroInteractions(cht);
		Mockito.verifyZeroInteractions(cst);

		// case - one indexer, decrease, thread restarted if old period is long
		Mockito.reset(chi, csi, cht, cst);
		Mockito.when(cht.getState()).thenReturn(State.TERMINATED);
		Assert.assertTrue(tested.changeIndexerPeriod(new String[] { "ch" }, 2000));
		Assert.assertEquals(2000, chi.indexingPeriod);
		Assert.assertNotSame(cht, tested.indexerThreads.get("ch"));
		Mockito.verify(chi).close();
		Mockito.verify(cht).interrupt();
		Mockito.verifyZeroInteractions(csi);
		Mockito.verifyZeroInteractions(cst);
		tested.indexerThreads.get("ch").interrupt();

		// case - one indexer, decrease, thread restarted if old period is long
		Mockito.reset(chi, csi, cht, cst);
		Mockito.when(cht.getState()).thenReturn(State.TERMINATED);
		Assert.assertTrue(tested.changeIndexerPeriod(new String[] { "ch" }, 1000));
		Assert.assertEquals(1000, chi.indexingPeriod);
		Mockito.verifyZeroInteractions(chi);
		Mockito.verifyZeroInteractions(csi);
		Mockito.verifyZeroInteractions(cht);
		Mockito.verifyZeroInteractions(cst);

	}

	/**
	 * Prepare mock indexer of given type
	 *
	 * @return
	 */
	protected SysinfoIndexer indexerMock(String name, SysinfoType type) {
		SysinfoIndexer i = Mockito.mock(SysinfoIndexer.class);
		i.infoType = type;
		i.name = name;
		return i;
	}

	/**
	 * Prepare {@link JiraRiver} instance for unit test, with Mockito mocked elasticSearchClient.
	 *
	 * @param toplevelSettings settings to be passed to the river configuring constructor. If null then river is
	 *          constructed without configuration.
	 * @return instance for tests
	 * @throws Exception from constructor
	 */
	public static SysinfoRiver prepareRiverInstanceForTest(Map<String, Object> toplevelSettings) throws Exception {
		Map<String, Object> settings = new HashMap<String, Object>();
		if (toplevelSettings != null)
			settings.putAll(toplevelSettings);

		Settings gs = mock(Settings.class);
		RiverSettings rs = new RiverSettings(gs, settings);
		Client clientMock = mock(Client.class);
		SysinfoRiver ret;
		if (toplevelSettings != null) {
			ret = new SysinfoRiver(new RiverName("sysinfo", RIVER_NAME), rs, clientMock);
		} else {
			ret = new SysinfoRiver(new RiverName("sysinfo", RIVER_NAME), rs);
			ret.client = clientMock;
		}
		ret.sourceClient = Mockito.mock(SourceClient.class);
		return ret;

	}

}


text:
package org.o3project.ocnrm.lib.flow;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.o3project.ocnrm.lib.JSONParser;
import org.o3project.ocnrm.lib.flow.model.ActionsData;
import org.o3project.ocnrm.lib.flow.model.OduMatchData;
import org.o3project.ocnrm.model.FlowData;
import org.o3project.ocnrm.model.TerminationPoints;
import org.o3project.ocnrm.model.bind.OduBindingData;
import org.o3project.ocnrm.model.bind.RmData;
import org.o3project.ocnrm.model.odu.OptFlow;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ OduFlowCreator.class })
public class OduFlowCreatorTest {
    private OduFlowCreator target;
    private RmData data;
    private TerminationPoints point;
    private String seqNo = "#1";

    @Before
    public void setUp() throws Exception {
        target = spy(new OduFlowCreator());
    }

    @After
    public void tearDown() throws Exception {
        point = null;
        target = null;
        data = null;
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeMatch()}
     */
    @Test
    public void testMakeMatch() throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);

        OduMatchData result = (OduMatchData) target.makeMatch(data, point);

        assertThat(result.getIn_port(), is("srcPort"));
        assertThat(result.getOdu_sigtype(), is("srcOdutype"));
        assertThat(result.getOdu_sigid().getTpn(), is("4095"));
        assertThat(result.getOdu_sigid().getTsmap(), is("srcTs,ts2"));
        assertThat(result.getOdu_sigid().getTslen(), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeMatch()}
     */
    @Test
    public void testMakeMatchWithEmptyPort()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);

        OduMatchData result = (OduMatchData) target.makeMatch(data, point);

        assertThat(result.getIn_port(), is(nullValue()));
        assertThat(result.getOdu_sigtype(), is("srcOdutype"));
        assertThat(result.getOdu_sigid().getTpn(), is("4095"));
        assertThat(result.getOdu_sigid().getTsmap(), is("srcTs,ts2"));
        assertThat(result.getOdu_sigid().getTslen(), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeMatch()}
     */
    @Test
    public void testMakeMatchWithEmptyOduType()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);

        OduMatchData result = (OduMatchData) target.makeMatch(data, point);

        assertThat(result.getIn_port(), is("srcPort"));
        assertThat(result.getOdu_sigtype(), is(nullValue()));
        assertThat(result.getOdu_sigid().getTpn(), is("4095"));
        assertThat(result.getOdu_sigid().getTsmap(), is("srcTs,ts2"));
        assertThat(result.getOdu_sigid().getTslen(), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeMatch()}
     */
    @Test
    public void testMakeMatchWithEmptyTs()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);

        OduMatchData result = (OduMatchData) target.makeMatch(data, point);

        assertThat(result.getIn_port(), is("srcPort"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeMatch()}
     */
    @Test
    public void testMakeMatchWithEmptyTpn()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);

        OduMatchData result = (OduMatchData) target.makeMatch(data, point);

        assertThat(result.getIn_port(), is("srcPort"));
        assertThat(result.getOdu_sigtype(), is("srcOdutype"));
        assertThat(result.getOdu_sigid().getTpn(), is(nullValue()));
        assertThat(result.getOdu_sigid().getTsmap(), is("srcTs,ts2"));
        assertThat(result.getOdu_sigid().getTslen(), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeInstruments()}
     */
    @Test
    public void testMakeInstruments() throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setOutPoint("dst");

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getOutPoint(), dstJson);

        List<ActionsData> actions = target.makeActions(data, point);

        assertThat(actions.size(), is(2));

        assertThat(actions.get(0).getType(), is("OUTPUT"));
        assertThat(actions.get(0).getPort(), is("dstPort"));

        assertThat(actions.get(1).getType(), is("SET_FIELD"));
        assertThat(actions.get(1).getField().get(0), is("tsmap"));
        assertThat(actions.get(1).getValue().get(0), is("dstTs,ts2"));

        assertThat(actions.get(1).getField().get(1), is("tpn"));
        assertThat(actions.get(1).getValue().get(1), is("4095"));

        assertThat(actions.get(1).getField().get(2), is("tslen"));
        assertThat(actions.get(1).getValue().get(2), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeInstruments()}
     */
    @Test
    public void testMakeInstrumentsWithEmptyTpn()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setOutPoint("dst");

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getOutPoint(), dstJson);

        List<ActionsData> actions = target.makeActions(data, point);

        assertThat(actions.size(), is(2));

        assertThat(actions.get(0).getType(), is("OUTPUT"));
        assertThat(actions.get(0).getPort(), is("dstPort"));

        assertThat(actions.get(1).getType(), is("SET_FIELD"));

        assertThat(actions.get(1).getField().get(0), is("tsmap"));
        assertThat(actions.get(1).getValue().get(0), is("dstTs,ts2"));

        assertThat(actions.get(1).getField().get(1), is("tslen"));
        assertThat(actions.get(1).getValue().get(1), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeInstruments()}
     */
    @Test
    public void testMakeInstrumentsWithEmptyTs()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setOutPoint("dst");

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"tpn\": \"-1\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getOutPoint(), dstJson);

        List<ActionsData> actions = target.makeActions(data, point);

        assertThat(actions.size(), is(1));

        assertThat(actions.get(0).getType(), is("OUTPUT"));
        assertThat(actions.get(0).getPort(), is("dstPort"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeInstruments()}
     */
    @Test
    public void testMakeInstrumentsWithEmptyActionField()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setOutPoint("dst");

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"port\": \"dstPort\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getOutPoint(), dstJson);

        List<ActionsData> actions = target.makeActions(data, point);

        assertThat(actions.size(), is(1));

        assertThat(actions.get(0).getType(), is("OUTPUT"));
        assertThat(actions.get(0).getPort(), is("dstPort"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeInstruments()}
     */
    @Test
    public void testMakeInstrumentsWithEmptyPort()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setOutPoint("dst");

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getOutPoint(), dstJson);

        List<ActionsData> actions = target.makeActions(data, point);

        assertThat(actions.size(), is(1));

        assertThat(actions.get(0).getType(), is("SET_FIELD"));
        assertThat(actions.get(0).getField().get(0), is("tsmap"));
        assertThat(actions.get(0).getValue().get(0), is("dstTs,ts2"));

        assertThat(actions.get(0).getField().get(1), is("tpn"));
        assertThat(actions.get(0).getValue().get(1), is("4095"));

        assertThat(actions.get(0).getField().get(2), is("tslen"));
        assertThat(actions.get(0).getValue().get(2), is("8"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#createFlow()}
     */
    @Test
    public void testCreateFlow()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");
        point.setOutPoint("dst");

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);
        data.bind(point.getOutPoint(), dstJson);

        TerminationPoints point2 = new TerminationPoints();
        point2.setInPoint("dst");
        point2.setOutPoint("src");

        List<TerminationPoints> points = new ArrayList<TerminationPoints>();
        points.add(point);
        points.add(point2);

        OptFlow flow = new OptFlow();
        flow.setTerminationPointPairs(points);

        List<String> result = target.createFlow(flow, data, seqNo);

        JSONObject resultJson1 = new JSONObject(result.get(0));

        assertThat(resultJson1.get("dpid").toString(), is("srcDpid"));
        assertThat(resultJson1.getJSONObject("match").get("in_port").toString(),
                is("srcPort"));
        assertThat(resultJson1.getJSONArray("actions")
                .getJSONObject(0).get("port").toString(),
                is("dstPort"));

        JSONObject resultJson2 = new JSONObject(result.get(1));

        assertThat(resultJson2.get("dpid").toString(), is("dstDpid"));
        assertThat(resultJson2.getJSONObject("match").get("in_port").toString(),
                is("dstPort"));
        assertThat(resultJson2.getJSONArray("actions")
                .getJSONObject(0).get("port").toString(),
                is("srcPort"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#createFlow()}
     */
    @Test
    public void testCreateFlowWithEmptyTerminationPoints()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();

        String srcJson = "{"
                + "\"dpid\": \"srcDpid\","
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        String dstJson = "{"
                + "\"dpid\": \"dstDpid\","
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind("src", srcJson);
        data.bind("dst", dstJson);

        OptFlow flow = new OptFlow();
        flow.setTerminationPointPairs(new ArrayList<TerminationPoints>());

        List<String> result = target.createFlow(flow, data, seqNo);

        assertThat(result.toString(),
                is("[]"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#createFlow()}
     */
    @Test
    public void testCreateFlowWithEmptyDpid()
            throws JsonParseException, JsonMappingException, IOException {
        point = new TerminationPoints();
        point.setInPoint("src");
        point.setOutPoint("dst");

        String srcJson = "{"
                + "\"odutype\": \"srcOdutype\","
                + "\"port\": \"srcPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"srcTs,ts2\""
                + "}";

        String dstJson = "{"
                + "\"odutype\": \"dstOdutype\","
                + "\"port\": \"dstPort\","
                + "\"tpn\": \"-1\","
                + "\"ts\": \"dstTs,ts2\""
                + "}";

        data = new OduBindingData();
        data.bind(point.getInPoint(), srcJson);
        data.bind(point.getOutPoint(), dstJson);

        TerminationPoints point2 = new TerminationPoints();
        point2.setInPoint("dst");
        point2.setOutPoint("src");

        List<TerminationPoints> points = new ArrayList<TerminationPoints>();
        points.add(point);
        points.add(point2);

        OptFlow flow = new OptFlow();
        flow.setTerminationPointPairs(points);

        List<String> result = target.createFlow(flow, data, seqNo);

        JSONObject resultJson1 = new JSONObject(result.get(0));

        assertFalse(resultJson1.has("dpid"));
        assertThat(resultJson1.getJSONObject("match").get("in_port").toString(),
                is("srcPort"));
        assertThat(resultJson1.getJSONArray("actions").getJSONObject(0)
                .get("port").toString(),
                is("dstPort"));

        JSONObject resultJson2 = new JSONObject(result.get(1));

        assertFalse(resultJson2.has("dpid"));
        assertThat(resultJson2.getJSONObject("match").get("in_port").toString(),
                is("dstPort"));
        assertThat(resultJson2.getJSONArray("actions").getJSONObject(0)
                .get("port").toString(),
                is("srcPort"));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#createFlow()}
     */
    @Test
    public void testCreateFlowWithJsonProcessingException() throws Exception {
        Logger dummyLogger = mock(Logger.class);
        Field field = target.getClass().getSuperclass().getSuperclass().getDeclaredField("logger");
        field.setAccessible(true);
        field.set(target, dummyLogger);

        JSONParser parser = mock(JSONParser.class);
        PowerMockito.whenNew(JSONParser.class).withNoArguments().thenReturn(parser);

        OptFlow flow = new OptFlow();
        flow.setTerminationPointPairs(new ArrayList<TerminationPoints>());

        PowerMockito.doThrow(mock(JsonProcessingException.class)).when(parser)
                .convertToJson(anyList(), eq(seqNo));
        List<String> result = target.createFlow(flow, data, seqNo);

        assertThat(result.toString(), is("[]"));
        verify(dummyLogger, times(1)).error(seqNo + "\t" + "JsonProcessingException occured.");
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#createFlow()}
     */
    @Test
    public void testCreateFlowWithJSONException() throws Exception {
        Logger dummyLogger = mock(Logger.class);
        Field field = target.getClass().getSuperclass().getSuperclass().getDeclaredField("logger");
        field.setAccessible(true);
        field.set(target, dummyLogger);

        JSONParser parser = mock(JSONParser.class);
        PowerMockito.whenNew(JSONParser.class).withNoArguments().thenReturn(parser);

        OptFlow flow = new OptFlow();
        flow.setTerminationPointPairs(new ArrayList<TerminationPoints>());

        PowerMockito.doThrow(mock(JSONException.class)).when(parser)
                .convertToJson(anyListOf(FlowData.class), eq(seqNo));
        List<String> result = target.createFlow(flow, data, seqNo);

        assertThat(result.toString(), is("[]"));
        verify(dummyLogger, times(1)).error(seqNo + "\t" + "JSONException occured.");
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeOutput()}
     */
    @Test
    public void testMakeOutput() {
        String type = "type";
        String output = "output";

        ActionsData result = target.makeOutput(type, output);

        assertThat(result.getType(), is(type));
        assertThat(result.getPort(), is(output));
    }

    /**
     * Test method for
     * {@link org.o3project.ocnrm.lib.flow.OduFlowCreator#makeAction()}
     */
    @Test
    public void testMakeAction() {
        String type = "type";
        List<String> field = new ArrayList<>();
        List<String> value = new ArrayList<>();

        ActionsData result = target.makeAction(type, field, value);

        assertThat(result.getType(), is(type));
        assertThat(result.getField(), is(field));
        assertThat(result.getValue(), is(value));
    }
}


text:
package com.adyen;

import com.adyen.model.Amount;
import com.adyen.model.notification.NotificationRequestItem;
import com.adyen.util.HMACValidator;
import com.adyen.util.Util;
import org.junit.Test;

import java.math.BigDecimal;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.adyen.constants.ApiConstants.AdditionalData.HMAC_SIGNATURE;
import static com.adyen.constants.HPPConstants.Fields.CURRENCY_CODE;
import static com.adyen.constants.HPPConstants.Fields.MERCHANT_ACCOUNT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Tests for Util class
 */
public class UtilTest {

    @Test
    public void testAmountDecimals() {
        Amount amount = new Amount();
        amount.setCurrency("EUR");
        amount.setValue(1001L);

        assertEquals(new BigDecimal("10.01"), amount.getDecimalValue());
    }

    @Test
    public void testCreateAmount() {
        Amount amount = Util.createAmount("12.345234", "EUR");
        Amount amountJPY = Util.createAmount("1234", "JPY");
        Amount amountBHD = Util.createAmount("1.2345234", "BHD");

        assertEquals(1235L, amount.getValue().longValue());
        assertEquals(1234L, amountJPY.getValue().longValue());
        assertEquals(1235L, amountBHD.getValue().longValue());
    }

    @Test
    public void testGetDataToSign() {
        SortedMap<String, String> postParameters;

        postParameters = new TreeMap<>();
        postParameters.put(MERCHANT_ACCOUNT, "ACC");
        postParameters.put(CURRENCY_CODE, "EUR");

        HMACValidator hmacValidator = new HMACValidator();
        String dataToSign = hmacValidator.getDataToSign(postParameters);
        assertEquals("currencyCode:merchantAccount:EUR:ACC", dataToSign);

        //Test escaping and sorting
        postParameters = new TreeMap<>();
        postParameters.put(CURRENCY_CODE, "EUR");
        postParameters.put(MERCHANT_ACCOUNT, "ACC:\\'");

        dataToSign = hmacValidator.getDataToSign(postParameters);
        assertEquals("currencyCode:merchantAccount:EUR:ACC\\:\\\\'", dataToSign);
    }

    @Test
    public void testImplode() {
        List<String> data = new ArrayList<>();
        data.add(null);
        data.add(null);
        data.add("NL");
        data.add(null);
        data.add("reference");
        data.add(null);
        data.add("merchantAccount");

        String dataToSign = Util.implode(":", data);
        assertEquals("::NL::reference::merchantAccount", dataToSign);
    }

    @Test
    public void testHmac() throws SignatureException {
        String data = "countryCode:currencyCode:merchantAccount:merchantReference:paymentAmount:sessionValidity:skinCode:NL:EUR:MagentoMerchantTest2:TEST-PAYMENT-2017-02-01-14\\:02\\:05:199:2017-02-02T14\\:02\\:05+01\\:00:PKz2KML1";
        String key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
        HMACValidator hmacValidator = new HMACValidator();
        String encrypted = hmacValidator.calculateHMAC(data, key);
        assertEquals("34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=", encrypted);
    }

    @Test
    public void testNotificationHmac() throws SignatureException {
        NotificationRequestItem notificationRequestItem = new NotificationRequestItem();
        notificationRequestItem.setPspReference("pspReference");
        notificationRequestItem.setOriginalReference("originalReference");
        notificationRequestItem.setMerchantAccountCode("merchantAccount");
        notificationRequestItem.setMerchantReference("reference");
        notificationRequestItem.setAmount(Util.createAmount(BigDecimal.TEN, "EUR"));
        notificationRequestItem.setEventCode("EVENT");
        notificationRequestItem.setSuccess(true);

        String expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc=";
        Map<String, String> additionalData = new HashMap<>();
        notificationRequestItem.setAdditionalData(additionalData);
        additionalData.put(HMAC_SIGNATURE, expectedSign);

        HMACValidator hmacValidator = new HMACValidator();
        String data = hmacValidator.getDataToSign(notificationRequestItem);
        assertEquals("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true", data);

        String key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
        String encrypted = hmacValidator.calculateHMAC(notificationRequestItem, key);
        assertEquals(expectedSign, encrypted);
        assertTrue(hmacValidator.validateHMAC(notificationRequestItem, key));

        additionalData.put(HMAC_SIGNATURE, "notValidSign");
        assertFalse(hmacValidator.validateHMAC(notificationRequestItem, key));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidateHMACException() throws SignatureException {
        NotificationRequestItem notificationRequestItem = new NotificationRequestItem();
        HMACValidator hmacValidator = new HMACValidator();
        String key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
        hmacValidator.validateHMAC(notificationRequestItem, key);
    }

    @Test
    public void testValidateHMACWithEmptyHmacException() throws SignatureException {
        NotificationRequestItem notificationRequestItem = new NotificationRequestItem();
        Map<String, String> additionalData = new HashMap<>();
        additionalData.put(HMAC_SIGNATURE, "");
        notificationRequestItem.setAdditionalData(additionalData);
        HMACValidator hmacValidator = new HMACValidator();
        String key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
        try {
            hmacValidator.validateHMAC(notificationRequestItem, key);
        } catch (IllegalArgumentException e) {
            assertEquals("Missing hmacSignature", e.getMessage());
        }
    }
}


text:
module MkmApi
  module Resources
    class Order < Hashie::Dash
      include Hashie::Extensions::Dash::Coercion, Hashie::Extensions::Dash::PropertyTranslation

      property :id, from: :idOrder
      property :buyer?, from: :isBuyer
      property :buyer, coerce: Account
      property :seller, coerce: Account
      property :state, coerce: State
      property :shipping_method, from: :shippingMethod, coerce: ShippingMethod
      property :presale?, from: :isPresale
      property :shipping_address, from: :shippingAddress, coerce: Address
      property :article_count, from: :articleCount
      property :evaluation, coerce: Evaluation
      property :articles, from: :article, coerce: Array[Article]
      property :article_value, from: :articleValue
      property :service_fee_value, from: :serviceFeeValue
      property :total_value, from: :totalValue
      property :partner, coerce: Account
      property :unread_messages, from: :unreadMessages, coerce: Integer
    end
  end
end


text:
#ifndef IIO_DDS_H_
#define IIO_DDS_H_

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_frequencyY
 */

#define IIO_DEV_ATTR_FREQ(_channel, _num, _mode, _show, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_frequency##_num,	\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_frequencyY_scale
 */

#define IIO_CONST_ATTR_FREQ_SCALE(_channel, _string)			\
	IIO_CONST_ATTR(out_altvoltage##_channel##_frequency_scale, _string)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_frequencysymbol
 */

#define IIO_DEV_ATTR_FREQSYMBOL(_channel, _mode, _show, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_frequencysymbol,	\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_phaseY
 */

#define IIO_DEV_ATTR_PHASE(_channel, _num, _mode, _show, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_phase##_num,		\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_phaseY_scale
 */

#define IIO_CONST_ATTR_PHASE_SCALE(_channel, _string)			\
	IIO_CONST_ATTR(out_altvoltage##_channel##_phase_scale, _string)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_phasesymbol
 */

#define IIO_DEV_ATTR_PHASESYMBOL(_channel, _mode, _show, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_phasesymbol,		\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_pincontrol_en
 */

#define IIO_DEV_ATTR_PINCONTROL_EN(_channel, _mode, _show, _store, _addr)\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_pincontrol_en,	\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_pincontrol_frequency_en
 */

#define IIO_DEV_ATTR_PINCONTROL_FREQ_EN(_channel, _mode, _show, _store, _addr)\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_pincontrol_frequency_en,\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_pincontrol_phase_en
 */

#define IIO_DEV_ATTR_PINCONTROL_PHASE_EN(_channel, _mode, _show, _store, _addr)\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_pincontrol_phase_en,	\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_out_enable
 */

#define IIO_DEV_ATTR_OUT_ENABLE(_channel, _mode, _show, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_out_enable,		\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_outY_enable
 */

#define IIO_DEV_ATTR_OUTY_ENABLE(_channel, _output,			\
			_mode, _show, _store, _addr)			\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_out##_output##_enable,\
			_mode, _show, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_outY_wavetype
 */

#define IIO_DEV_ATTR_OUT_WAVETYPE(_channel, _output, _store, _addr)	\
	IIO_DEVICE_ATTR(out_altvoltage##_channel##_out##_output##_wavetype,\
			S_IWUSR, NULL, _store, _addr)

/**
 * /sys/bus/iio/devices/.../out_altvoltageX_outY_wavetype_available
 */

#define IIO_CONST_ATTR_OUT_WAVETYPES_AVAILABLE(_channel, _output, _modes)\
	IIO_CONST_ATTR(							\
	out_altvoltage##_channel##_out##_output##_wavetype_available, _modes)

#endif /* IIO_DDS_H_ */


text:
class BankAuthorisation(object):
    """A thin wrapper around a bank_authorisation, providing easy access to its
    attributes.

    Example:
      bank_authorisation = client.bank_authorisations.get()
      bank_authorisation.id
    """

    def __init__(self, attributes, api_response):
        self.attributes = attributes
        self.api_response = api_response

    @property
    def authorisation_type(self):
        return self.attributes.get('authorisation_type')

    @property
    def authorised_at(self):
        return self.attributes.get('authorised_at')

    @property
    def created_at(self):
        return self.attributes.get('created_at')

    @property
    def expires_at(self):
        return self.attributes.get('expires_at')

    @property
    def id(self):
        return self.attributes.get('id')

    @property
    def last_visited_at(self):
        return self.attributes.get('last_visited_at')

    @property
    def links(self):
        return self.Links(self.attributes.get('links'))

    @property
    def redirect_uri(self):
        return self.attributes.get('redirect_uri')

    @property
    def url(self):
        return self.attributes.get('url')

    class Links(object):
        """Wrapper for the response's 'links' attribute."""

        def __init__(self, attributes):
            self.attributes = attributes

        @property
        def billing_request(self):
            return self.attributes.get('billing_request')

        @property
        def institution(self):
            return self.attributes.get('institution')


text:
from django.conf.urls import url
from django.conf import settings
from django.urls import path

from rest_framework import routers

from . import views
from . import views_relations

router = routers.DefaultRouter(trailing_slash=False)

router.register(
    r'biomes',
    views.BiomeViewSet,
    basename='biomes'
)

router.register(
    r'studies',
    views.StudyViewSet,
    basename='studies'
)

router.register(
    r'super-studies',
    views.SuperStudyViewSet,
    basename='super-studies'
)

router.register(
    r'samples',
    views.SampleViewSet,
    basename='samples'
)

router.register(
    r'runs',
    views.RunViewSet,
    basename='runs'
)

router.register(
    r'assemblies',
    views.AssemblyViewSet,
    basename='assemblies'
)

router.register(
    r'analyses',
    views.AnalysisJobViewSet,
    basename='analyses'
)

router.register(
    r'experiment-types',
    views.ExperimentTypeViewSet,
    basename='experiment-types'
)

router.register(
    r'pipelines',
    views.PipelineViewSet,
    basename='pipelines'
)

router.register(
    r'pipeline-tools',
    views.PipelineToolViewSet,
    basename='pipeline-tools'
)

router.register(
    r'publications',
    views.PublicationViewSet,
    basename='publications'
)

router.register(
    r'pipeline-tools/(?P<tool_name>[^/]+)',
    views.PipelineToolVersionViewSet,
    basename='pipeline-tools-version'
)

router.register(
    r'analyses/(?P<accession>[^/]+)',
    views.AnalysisQCChartViewSet,
    basename='analysis-qcchart'
)

router.register(
    r'analyses/(?P<accession>[^/]+)/krona',
    views.KronaViewSet,
    basename='analysis-krona'
)

router.register(
    r'analyses/(?P<accession>[^/]+)/downloads',
    views.AnalysisResultDownloadsViewSet,
    basename='analysisdownload'
)

router.register(
    r'analyses/(?P<accession>[^/]+)/file',
    views.AnalysisResultDownloadViewSet,
    basename='analysisdownload'
)

router.register(
    r'studies/(?P<accession>[^/]+)/downloads',
    views.StudiesDownloadsViewSet,
    basename='studydownload'
)

# relationship views
router.register(
    r'studies/(?P<accession>[^/]+)/analyses',
    views_relations.StudyAnalysisResultViewSet,
    basename='studies-analyses'
)

router.register(
    r'super-studies/(?P<super_study_id>[^/]+)/flagship-studies',
    views_relations.SuperStudyFlagshipStudiesViewSet,
    basename='super-studies-flagship-studies'
)

router.register(
    r'super-studies/(?P<super_study_id>[^/]+)/related-studies',
    views_relations.SuperStudyRelatedStudiesViewSet,
    basename='super-studies-related-studies'
)

router.register(
    r'runs/(?P<accession>[^/]+)/analyses',
    views_relations.RunAnalysisViewSet,
    basename='runs-analyses'
)

router.register(
    r'runs/(?P<accession>[^/]+)/assemblies',
    views_relations.RunAssemblyViewSet,
    basename='runs-assemblies'
)

router.register(
    r'assemblies/(?P<accession>[^/]+)/analyses',
    views_relations.AssemblyAnalysisViewSet,
    basename='assemblies-analyses'
)

router.register(
    r'assemblies/(?P<accession>[^/]+)/runs',
    views_relations.AssemblyRunsViewSet,
    basename='assemblies-runs'
)

router.register(
    r'studies/(?P<accession>[^/]+)'
    r'/pipelines/(?P<release_version>[0-9\.]+)/file',
    views_relations.StudiesDownloadViewSet,
    basename='studydownload'
)

router.register(
    r'biomes/(?P<lineage>[^/]+)/children',
    views_relations.BiomeTreeViewSet,
    basename='biomes-children'
)

router.register(
    r'biomes/(?P<lineage>[^/]+)/studies',
    views_relations.BiomeStudyRelationshipViewSet,
    basename='biomes-studies'
)

router.register(
    r'biomes/(?P<lineage>[^/]+)/samples',
    views_relations.BiomeSampleRelationshipViewSet,
    basename='biomes-samples'
)

router.register(
    r'biomes/(?P<lineage>[^/]+)/genomes',
    views_relations.BiomeGenomeRelationshipViewSet,
    basename='biomes-genomes'
)

router.register(
    r'biomes/(?P<lineage>[^/]+)/genome-catalogues',
    views_relations.BiomeGenomeCatalogueRelationshipViewSet,
    basename='biomes-genome-catalogues'
)

router.register(
    r'publications/(?P<pubmed_id>[0-9\.]+)/studies',
    views_relations.PublicationStudyRelationshipViewSet,
    basename='publications-studies'
)

router.register(
    r'studies/(?P<accession>[^/]+)/geocoordinates',
    views_relations.StudyGeoCoordinateRelationshipViewSet,
    basename='studies-geoloc'
)

router.register(
    r'studies/(?P<accession>[a-zA-Z0-9]+)/studies',
    views_relations.StudyStudyRelationshipViewSet,
    basename='studies-studies'
)

router.register(
    r'studies/(?P<accession>[^/]+)/samples',
    views_relations.StudySampleRelationshipViewSet,
    basename='studies-samples'
)

router.register(
    r'studies/(?P<accession>[^/]+)/publications',
    views_relations.StudyPublicationRelationshipViewSet,
    basename='studies-publications'
)

# router.register(
#     r'pipelines/(?P<release_version>[0-9\.]+)/studies',
#     views_relations.PipelineStudyRelationshipViewSet,
#     basename='pipelines-studies'
# )

router.register(
    r'pipelines/(?P<release_version>[0-9\.]+)/samples',
    views_relations.PipelineSampleRelationshipViewSet,
    basename='pipelines-samples'
)

router.register(
    r'pipelines/(?P<release_version>[0-9\.]+)/analyses',
    views_relations.PipelineAnalysisRelationshipViewSet,
    basename='pipelines-analyses'
)

router.register(
    r'pipelines/(?P<release_version>[0-9\.]+)/tools',
    views_relations.PipelinePipelineToolRelationshipViewSet,
    basename='pipelines-pipeline-tools'
)

router.register(
    r'experiment-types/(?P<experiment_type>[^/]+)/samples',
    views_relations.ExperimentTypeSampleRelationshipViewSet,
    basename='experiment-types-samples'
)

router.register(
    r'publications/(?P<pubmed_id>[0-9\.]+)/samples',
    views_relations.PublicationSampleRelationshipViewSet,
    basename='publications-samples'
)

router.register(
    r'samples/(?P<accession>[^/]+)/runs',
    views_relations.SampleRunRelationshipViewSet,
    basename='samples-runs'
)

router.register(
    r'experiment-types/(?P<experiment_type>[^/]+)/runs',
    views_relations.ExperimentTypeRunRelationshipViewSet,
    basename='experiment-types-runs'
)

router.register(
    r'experiment-types/(?P<experiment_type>[^/]+)/analyses',
    views_relations.ExperimentTypeAnalysisRelationshipViewSet,
    basename='experiment-types-analyses'
)

router.register(
    r'samples/(?P<accession>[^/]+)/studies',
    views_relations.SampleStudiesRelationshipViewSet,
    basename='samples-studies'
)

router.register(
    r'samples/(?P<accession>[^/]+)/metadata',
    views_relations.SampleMetadataRelationshipViewSet,
    basename='samples-metadata'
)

mydata_router = routers.DefaultRouter(trailing_slash=False)
mydata_router.register(
    r'mydata',
    views.MyDataViewSet,
    basename='mydata'
)

utils_router = routers.DefaultRouter(trailing_slash=False)
utils_router.register(
    r'utils',
    views.UtilsViewSet,
    basename='csrf'
)

router.register(
    r'genomes',
    views.GenomeViewSet,
    basename='genomes'
)

# Proxy Genome Search requests to microservice backend
router.register(
    r'genome-search',
    views.GenomeFragmentSearchViewSet,
    basename='genome-search'
)

# Sourmash search
router.register(
    r'genomes-search/gather',
    views.GenomeSearchGatherViewSet,
    basename='genomes-gather'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/cogs',
    views_relations.GenomeCogsRelationshipsViewSet,
    basename='genome-cog'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/kegg-class',
    views_relations.GenomeKeggClassRelationshipsViewSet,
    basename='genome-kegg-class'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/kegg-module',
    views_relations.GenomeKeggModuleRelationshipsViewSet,
    basename='genome-kegg-module'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/kegg-class',
    views_relations.GenomeKeggClassRelationshipsViewSet,
    basename='genome-kegg-class'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/antismash-genecluster',
    views_relations.GenomeAntiSmashGeneClustersRelationshipsViewSet,
    basename='genome-antismash-genecluster'
)

router.register(
    r'genomes/(?P<accession>[^/]+)/downloads',
    views.GenomeDownloadViewSet,
    basename='genome-download'
)

router.register(
    r'genome-catalogues',
    views.GenomeCatalogueViewSet,
    basename='genome-catalogues'
)

router.register(
    r'genome-catalogues/(?P<catalogue_id>[^/]+)/genomes',
    views_relations.GenomeCatalogueGenomeRelationshipViewSet,
    basename='genome-catalogue-genomes'
)

router.register(
    r'genome-catalogues/(?P<catalogue_id>[^/]+)/downloads',
    views.GenomeCatalogueDownloadViewSet,
    basename='genome-catalogue-downloads'
)

router.register(
    r'genomeset',
    views.GenomeSetViewSet,
    basename='genomeset'
)

router.register(
    r'genomeset/(?P<name>[^/]+)/genomes',
    views_relations.GenomeSetGenomes,
    basename='genomeset-genomes'
)

router.register(
    r'cogs',
    views.CogCatViewSet,
    basename='cogs'
)

router.register(
    r'kegg-modules',
    views.KeggModuleViewSet,
    basename='kegg-modules'
)

router.register(
    r'kegg-classes',
    views.KeggClassViewSet,
    basename='kegg-classes'
)

router.register(
    r'antismash-geneclusters',
    views.AntiSmashGeneClustersViewSet,
    basename='antismash-geneclusters'
)

urlpatterns = [
    path(r'v1/banner-message',
        views.BannerMessageView.as_view(),
        name='banner-message'),
    path(r'v1/ebi-search-download/<str:domain>',
        views.EBISearchCSVDownload.as_view(),
        name='ebi-search-download'),
    url(r'^v1/genomes-search/status/(?P<job_id>[^/]+)',
        views.GenomeSearchStatusView.as_view(),
        name='genomes-status'),
    url(r'^v1/genomes-search/results/(?P<job_id>[^/]+)',
        views.GenomeSearchResultsView.as_view(),
        name='genomes-results')
]

if settings.ADMIN:
    urlpatterns += [
        path(r'v1/biom-prediction',
            views.BiomePrediction.as_view(),
            name='biom-prediction')
    ]


text:
use strict;
use warnings;

package Search::Kino03::KSx::Search::LongFieldSim;
BEGIN { our @ISA = qw( Search::Kino03::KinoSearch::Search::Similarity ) }

sub length_norm {
    my ( $self, $num_tokens ) = @_;
    $num_tokens = $num_tokens < 100 ? 100 : $num_tokens;
    return 1 / sqrt($num_tokens);
}

1;

__END__

__POD__

=head1 NAME

Search::Kino03::KSx::Search::LongFieldSim - Similarity optimized for long fields.

=head1 SYNOPSIS

    package MySchema::body;
    use base qw( Search::Kino03::KinoSearch::FieldType::FullTextType );
    use Search::Kino03::KSx::Search::LongFieldSim;
    sub similarity { Search::Kino03::KSx::Search::LongFieldSim->new }

=head1 DESCRIPTION

KinoSearch's default L<Similarity|Search::Kino03::KinoSearch::Search::Similarity>
implmentation produces a bias towards extremely short fields.

    Search::Kino03::KinoSearch::Search::Similarity

    | more weight
    | *
    |  **
    |    ***
    |       **********
    |                 ********************
    |                                     *******************************
    | less weight                                                        ****
    |------------------------------------------------------------------------
      fewer tokens                                              more tokens

LongFieldSim eliminates this bias.

    Search::Kino03::KSx::Search::LongFieldSim

    | more weight
    |
    |
    |
    |*****************
    |                 ********************
    |                                     *******************************
    | less weight                                                        ****
    |------------------------------------------------------------------------
      fewer tokens                                              more tokens

In most cases, the default bias towards short fields is desirable.  For
instance, say you have two documents:

=over

=item *

"George Washington"

=item *

"George Washington Carver"

=back

If a user searches for "george washington", we want the exact title match to
appear first.  Under the default Similarity implementation it will, because
the "Carver" in "George Washington Carver" dilutes the impact of the other two
tokens.

However, under LongFieldSim, the two titles will yield equal scores.  That
would be bad in this particular case, but it could be good in another.

     "George Washington Carver is cool."

     "George Washington Carver was born on the eve of the US Civil War, in
     1864.  His exact date of birth is unknown... Carver's research in crop
     rotation revolutionized agriculture..."

The first document is succinct, but useless.  Unfortunately, the default
similarity will assess it as extremely relevant to a query of "george
washington carver".  However, under LongFieldSim, the short-field bias is
eliminated, and the addition of other mentions of Carver's name in the second
document yield a higher score and a higher rank.

=head1 COPYRIGHT

Copyright 2005-2009 Marvin Humphrey

=head1 LICENSE, DISCLAIMER, BUGS, etc.

See L<KinoSearch> version 0.30.

=cut


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Utaite World</title>
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="icon" type="image/png" href="public/favicon-32x32.png" sizes="32x32">
    <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet" type="text/css">


text:
@implementation MJPopupBackgroundView

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    size_t locationsCount = 2;
    CGFloat locations[2] = {0.0f, 1.0f};
    CGFloat colors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, locationsCount);
    CGColorSpaceRelease(colorSpace);

    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    float radius = MIN(self.bounds.size.width , self.bounds.size.height) ;
    CGContextDrawRadialGradient (context, gradient, center, 0, center, radius, kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);
}

@end


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}

module Duckling.Quantity.HR.Rules
  ( rules ) where

import Data.String
import Prelude
import qualified Data.Text as Text

import Duckling.Dimensions.Types
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Quantity.Helpers
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
import qualified Duckling.Quantity.Types as TQuantity

ruleNumberUnits :: Rule
ruleNumberUnits = Rule
  { name = "<number> <units>"
  , pattern =
    [ dimension Numeral
    , regex "k(il(o|e|a))?(g(rama?)?)?"
    ]
  , prod = \tokens -> case tokens of
      (Token Numeral NumeralData {TNumeral.value = v}:_) ->
        Just . Token Quantity $ quantity TQuantity.Gram (1000 * v)
      _ -> Nothing
  }

ruleQuantityProduct :: Rule
ruleQuantityProduct = Rule
  { name = "<quantity> product"
  , pattern =
    [ dimension Quantity
    , regex "(mes(o|a)|soli?)"
    ]
  , prod = \tokens -> case tokens of
      (Token Quantity qd:
       Token RegexMatch (GroupMatch (match:_)):
       _) -> case Text.toLower match of
         "meso" -> Just . Token Quantity $ withProduct "meso" qd
         "mesa" -> Just . Token Quantity $ withProduct "meso" qd
         "sol" -> Just . Token Quantity $ withProduct "sol" qd
         "soli" -> Just . Token Quantity $ withProduct "sol" qd
         _      -> Nothing
      _ -> Nothing
  }

rules :: [Rule]
rules =
  [ ruleNumberUnits
  , ruleQuantityProduct
  ]


text:
package com.codepath.apps.simpletweets;

import android.content.Context;

import com.codepath.oauth.OAuthBaseClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.scribe.builder.api.Api;
import org.scribe.builder.api.TwitterApi;

/*
 *
 * This is the object responsible for communicating with a REST API.
 * Specify the constants below to change the API being communicated with.
 * See a full list of supported API classes:
 *   https://github.com/fernandezpablo85/scribe-java/tree/master/src/main/java/org/scribe/builder/api
 * Key and Secret are provided by the developer site for the given API i.e dev.twitter.com
 * Add methods for each relevant endpoint in the API.
 *
 * NOTE: You may want to rename this object based on the service i.e TwitterClient or FlickrClient
 *
 */
public class TwitterClient extends OAuthBaseClient {
	public static final Class<? extends Api> REST_API_CLASS = TwitterApi.class; // Change this
	public static final String REST_URL = "https://api.twitter.com/1.1/"; // Change this, base API URL
	public static final String REST_CONSUMER_KEY = "GBLVkRzV8iwlo38qGTOqbtUZQ";       // Change this
	public static final String REST_CONSUMER_SECRET = "wX85FqCFJThF1sHEoTLwcekmMGRjWZTTRnfKiafjdlsliZIxrW"; // Change this
	public static final String REST_CALLBACK_URL = "oauth://cpsimpletweets"; // Change this (here and in manifest)

	public TwitterClient(Context context) {
		super(context, REST_API_CLASS, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET, REST_CALLBACK_URL);
	}

	//method - endpoint
	//home timeline
	public void getHomeTimeLine(long maxId, AsyncHttpResponseHandler handler) {
	    String apiUrl = getApiUrl("statuses/home_timeline.json");

		// Params
		RequestParams params = new RequestParams();
		params.put("count",25);
		params.put("since_id",1);

		// max_id
		if(maxId!=0)
			params.put("max_id",maxId-1);

		getClient().get(apiUrl,params,handler);
	}

	//home timeline
	public void getCurrentUserInfo(AsyncHttpResponseHandler handler) {
		String apiUrl = getApiUrl("account/verify_credentials.json");

		getClient().get(apiUrl,handler);
	}

	//compose tweet
	// statuses/update.json
	// status
	public void postUpdate(String post, AsyncHttpResponseHandler handler) {
		String apiUrl = getApiUrl("statuses/update.json");

		// Params
		RequestParams params = new RequestParams();
		params.put("status",post);

		getClient().post(apiUrl,params,handler);
	}

	public void postUpdate(String post, Long replyToId, AsyncHttpResponseHandler handler) {
		String apiUrl = getApiUrl("statuses/update.json");

		// Params
		RequestParams params = new RequestParams();
		params.put("status",post);
		params.put("in_reply_to_status_id",replyToId);

		getClient().post(apiUrl,params,handler);
	}

	/* 1. Define the endpoint URL with getApiUrl and pass a relative path to the endpoint
	 * 	  i.e getApiUrl("statuses/home_timeline.json");
	 * 2. Define the parameters to pass to the request (query or body)
	 *    i.e RequestParams params = new RequestParams("foo", "bar");
	 * 3. Define the request method and make a call to the client
	 *    i.e client.get(apiUrl, params, handler);
	 *    i.e client.post(apiUrl, params, handler);
	 */
}


text:
using System.Runtime.CompilerServices;
namespace System
{
#if CODE_ANALYSIS
    [IgnoreNamespace, Imported]
#endif
    public delegate void JSAsyncCallback(object ar);
}


text:
package com.wizzardo.tools.evaluation;

import com.wizzardo.tools.interfaces.Supplier;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: moxa
 * Date: 11/19/13
 */
public class TemplateBuilder extends Expression {
    private List<Expression> parts = new ArrayList<Expression>();

    @Override
    public void setVariable(Variable v) {
        for (Expression e : parts)
            e.setVariable(v);
    }

    @Override
    public Expression clone() {
        TemplateBuilder tb = new TemplateBuilder();
        for (Expression e : parts) {
            tb.parts.add(e.clone());
        }
        return tb;
    }

    @Override
    public Object get(Map<String, Object> model) {
        if (hardcoded)
            return result;

        Supplier<String>[] suppliers = new Supplier[parts.size()];
        hardcoded = true;
        for (int i = 0; i < parts.size(); i++) {
            Expression e = parts.get(i);
            final Object o = e.get(model);
            hardcoded &= e.hardcoded;
            if (e.hardcoded) {
                final String s = String.valueOf(o);
                suppliers[i] = new Supplier<String>() {
                    @Override
                    public String supply() {
                        return s;
                    }
                };
            } else if (o instanceof ClosureExpression) {
                final ClosureExpression expression = (ClosureExpression) o;
                suppliers[i] = new Supplier<String>() {
                    @Override
                    public String supply() {
                        return String.valueOf(expression.get());
                    }
                };
            } else {
                suppliers[i] = new Supplier<String>() {
                    @Override
                    public String supply() {
                        return String.valueOf(o);
                    }
                };
            }
        }
        GString gString = new GString(suppliers);
        if (hardcoded)
            result = gString;
        return gString;
    }

    public TemplateBuilder append(Expression e) {
        parts.add(e);
        return this;
    }

    public TemplateBuilder append(String s) {
        parts.add(new Holder(s, true));
        return this;
    }

    public static class GString {
        final Supplier<String>[] parts;

        public GString(Supplier<String>[] parts) {
            this.parts = parts;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (Supplier<String> part : parts) {
                sb.append(part.supply());
            }
            return sb.toString();
        }
    }
}


text:
define([
    'esri/layers/ImageParameters'
], function (ImageParameters) {

    var style = document.createElement('style');
    style.type = 'text/css';
    var styles = '.identifyContent_parent .titlePaneIcon{color:#00C;}';
    style.appendChild(document.createTextNode(styles));
    document.head.appendChild(style);

    var imageParameters = new ImageParameters();
    imageParameters.format = 'png32';

    return {
        isDebug: false,

        defaultMapClickMode: 'identify',
        mapOptions: {
            basemap: 'streets',
            center: [-96.59179687497497, 39.09596293629694],
            zoom: 4,
            sliderStyle: 'small'
        },

        titles: {
            header: 'CMV Identify Panel Example',
            subHeader: 'This is an example of the Identify Panel Widget',
            pageTitle: 'CMV Identify Panel Example'
        },

        collapseButtonsPane: 'center', //center or outer

        operationalLayers: [
            {
                type: 'dynamic',
                url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyOperationalLayers/MapServer',
                title: 'Louisville Public Safety',
                options: {
                    id: 'louisvillePubSafety',
                    opacity: 1.0,
                    visible: true,
                    imageParameters: imageParameters
                }
            },
            {
                type: 'dynamic',
                url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/MapServer',
                title: 'Damage Assessment',
                options: {
                    id: 'DamageAssessment',
                    opacity: 1.0,
                    visible: true,
                    imageParameters: imageParameters
                }
            },
            {
                type: 'dynamic',
                url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer',
                title: 'Cities',
                options: {
                    id: 'cities',
                    opacity: 0.7,
                    visible: true,
                    imageParameters: imageParameters
                }
            }
        ],

        widgets: {

            identifyPanel: {
                include: true,
                type: 'titlePane',
                path: 'widgets/IdentifyPanel',
                position: 0,
                title: 'Identify Features',
                iconClass: 'fas fa-info-circle',
                open: true,
                options: {
                    map: true,
                    mapClickMode: true,
                    buttons: [
                        {
                            id: 'identifypanel-button-example',
                            label: 'This is an example button',
                            iconClass: 'fas fa-fw fa-comment',
                            showLabel: false,
                            style: 'float:left;margin-right:10px;display:none;',
                            onClick: function () {
                                /*eslint no-alert: 0*/
                                alert('Hello from the Test Button');
                            }
                        }
                    ]
                }
            },

            identify: {
                include: true,
                type: 'invisible',
                path: 'gis/dijit/Identify',
                preload: true,
                options: {
                    map: true,
                    mapClickMode: true,
                    identifyLayerInfos: true,
                    identifyTolerance: 10
                }
            },

            exportDialog: {
                include: true,
                id: 'export',
                type: 'floating',
                path: 'widgets/Export',
                title: 'Export',
                iconClass: 'fas fa-download',
                preload: true,
                options: {
                    excel: false,
                    xlsExcel: true,
                    csv: true,

                    shapefile: true,
                    kml: true,
                    kmz: true,
                    geojson: true,
                    topojson: true,
                    wkt: true,

                    defaultExportType: 'shapefile',
                    // this option can be a string or a function that returns
                    // a string.
                    //
                    // filename: 'my_results'
                    filename: function () {
                        var date = new Date();
                        return 'identified_feature_' + date.toLocaleDateString();
                    }
                }
            }
        }
    };
});


text:
			  <form  novalidate name="listDebentureForm" class="form-horizontal">

Debentures/Discharges

										<input type="search" ng-model="filter.search" ng-change="filter()" class="form-control" id="inputLocation" placeholder="search" required>

          Serial Number ^v

         Inventory Number^v

         Person ^v

         Location ^v

         Model^v

          Type ^v

          Debenture Date ^v

         Discharge Date ^v

										{{row.equipment.serialNumber}}
										{{row.equipment.inventoryNumber}}
										{{row.person.firstName}} {{row.person.lastName}}
										{{row.location.location}}
        								{{row.equipmentModel.model}}
										{{row.equipmentType.type}}
										{{row.debenture.debentureDate | date:'dd/MM/yyyy @ HH:mm'}}
										{{row.debenture.dischargeDate | date:'dd/MM/yyyy @ HH:mm'}}

										<pagination
													num-pages="numPages"
													total-items="totalItems"
													ng-model="currentPage"
													max-size="maxSize"
													items-per-page="itemsPerPage"
													class="pagination-sm"
													boundary-links="true" rotate="false">
										</pagination>

			</from>


text:
import sqlalchemy as sql

def upgrade(migrate_engine):
    meta = sql.MetaData()
    meta.bind = migrate_engine

    revocation_event = sql.Table('revocation_event', meta, autoload=True)
    sql.Index('ix_revocation_event_issued_before',
              revocation_event.c.issued_before).create()
    sql.Index('ix_revocation_event_project_id_issued_before',
              revocation_event.c.project_id,
              revocation_event.c.issued_before).create()
    sql.Index('ix_revocation_event_user_id_issued_before',
              revocation_event.c.user_id,
              revocation_event.c.issued_before).create()
    sql.Index('ix_revocation_event_audit_id_issued_before',
              revocation_event.c.audit_id,
              revocation_event.c.issued_before).create()


text:
try:
    import ustruct as struct
except:
    try:
        import struct
    except ImportError:
        print("SKIP")
        raise SystemExit

print(struct.calcsize('0s'))
print(struct.unpack('0s', b''))
print(struct.pack('0s', b'123'))

print(struct.calcsize('2s'))
print(struct.unpack('2s', b'12'))
print(struct.pack('2s', b'123'))

print(struct.calcsize('2H'))
print(struct.unpack('<2H', b'1234'))
print(struct.pack('<2H', 258, 515))

print(struct.calcsize('0s1s0H2H'))
print(struct.unpack('<0s1s0H2H', b'01234'))
print(struct.pack('<0s1s0H2H', b'abc', b'abc', 258, 515))

# check that we get an error if the buffer is too small
try:
    struct.unpack('2H', b'\x00\x00')
except:
    print('Exception')
try:
    struct.pack_into('2I', bytearray(4), 0, 0)
except:
    print('Exception')

# check that unknown types raise an exception
try:
    struct.unpack('z', b'1')
except:
    print('Exception')

try:
    struct.pack('z', (b'1',))
except:
    print('Exception')

try:
    struct.calcsize('0z')
except:
    print('Exception')

# check that a count without a type specifier raises an exception

try:
    struct.calcsize('1')
except:
    print('Exception')

try:
    struct.pack('1')
except:
    print('Exception')

try:
    struct.pack_into('1', bytearray(4), 0, 'xx')
except:
    print('Exception')

try:
    struct.unpack('1', 'xx')
except:
    print('Exception')

try:
    struct.unpack_from('1', 'xx')
except:
    print('Exception')


text:
// <copyright file="Trie.cs" company="Yojowa, LLC">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Alex Bulankou</author>
// <date>11/09/2016</date>
namespace Yojowa.StopByStop.Utils
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Trie or prefix tree
    /// </summary>
    /// <typeparam name="T">Element type</typeparam>
    public class Trie<T>
    {
        /// <summary>
        /// The alphabet size. Includes all letters, '-' and ' ' and '.' and '
        /// </summary>
        private const int AlphabetSize = 30;

        /// <summary>
        /// The key selector
        /// </summary>
        private Func<T, string> keySelector;

        /// <summary>
        /// The root node
        /// </summary>
        private TrieNode root;

        /// <summary>
        /// Initializes a new instance of the <see cref="Trie{T}"/> class.
        /// </summary>
        /// <param name="keySelector">The key selector.</param>
        public Trie(Func<T, string> keySelector)
        {
            this.keySelector = keySelector;
            this.root = new TrieNode();
        }

        /// <summary>
        /// Adds the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        public void Add(T item)
        {
            string key = this.keySelector(item);
            this.root.Add(key, 0, item);
        }

        /// <summary>
        /// Gets the items matching prefix.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <returns>Items matching prefix</returns>
        public IEnumerable<T> GetItemsMatchingPrefix(string prefix)
        {
            return this.root.GetItemsMatchingPrefix(prefix, 0);
        }

        /// <summary>
        /// Translates the character into alphabet index
        /// </summary>
        /// <param name="c">The character</param>
        /// <returns>Alphabet index</returns>
        private static int GetAlphabetIndex(char c)
        {
            switch (c)
            {
                case '-':
                    return 26;
                case ' ':
                    return 27;
                case '.':
                    return 28;
                case '\'':
                    return 29;
                default:
                    if (c >= 'a' && c <= 'z')
                    {
                        return c - 'a';
                    }
                    else if (c >= 'A' && c <= 'Z')
                    {
                        return c - 'A';
                    }

                    throw new ArgumentOutOfRangeException("Character argument can only be between a and z, space or dash.");
            }
        }

        /// <summary>
        /// Trie node
        /// </summary>
        private class TrieNode
        {
            /// <summary>
            /// Child nodes
            /// </summary>
            private TrieNode[] nodes;

            /// <summary>
            /// Values associated with the node
            /// </summary>
            private List<T> values;

            /// <summary>
            /// Initializes a new instance of the <see cref="TrieNode"/> class.
            /// </summary>
            public TrieNode()
            {
                this.nodes = new TrieNode[AlphabetSize];

                this.values = new List<T>();
            }

            /// <summary>
            /// Adds the item
            /// </summary>
            /// <param name="key">The key.</param>
            /// <param name="position">Character position in the key.</param>
            /// <param name="value">The value.</param>
            public void Add(string key, int position, T value)
            {
                if (key.Length <= position)
                {
                    this.values.Add(value);
                }
                else
                {
                    char charAtPosition = key[position];
                    var index = GetAlphabetIndex(charAtPosition);
                    TrieNode node = this.nodes[index];
                    if (node == null)
                    {
                        node = new TrieNode();
                        this.nodes[index] = node;
                    }

                    node.Add(key, position + 1, value);
                }
            }

            /// <summary>
            /// Gets the items matching prefix.
            /// </summary>
            /// <param name="prefix">The prefix.</param>
            /// <param name="prefixPosition">Character position in prefix</param>
            /// <returns>Items matching prefix</returns>
            public IEnumerable<T> GetItemsMatchingPrefix(string prefix, int prefixPosition)
            {
                if (prefix.Length == prefixPosition)
                {
                    return this.GetItemsRecursive();
                }
                else
                {
                    char charAtPosition = prefix[prefixPosition];
                    var index = GetAlphabetIndex(charAtPosition);
                    if (this.nodes[index] == null)
                    {
                        return Enumerable.Empty<T>();
                    }
                    else
                    {
                        return this.nodes[index].GetItemsMatchingPrefix(prefix, prefixPosition + 1);
                    }
                }
            }

            /// <summary>
            /// Gets the items recursively
            /// </summary>
            /// <returns>Items associated with the node</returns>
            private IEnumerable<T> GetItemsRecursive()
            {
                foreach (var trieNode in this.nodes)
                {
                    if (trieNode != null)
                    {
                        foreach (var item in trieNode.GetItemsRecursive())
                        {
                            yield return item;
                        }
                    }
                }

                foreach (var item in this.values)
                {
                    yield return item;
                }
            }
        }
    }
}


text:
package com.amazonaws.services.servermigration.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.servermigration.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * UserDataMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UserDataMarshaller {

    private static final MarshallingInfo<StructuredPojo> S3LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("s3Location").build();

    private static final UserDataMarshaller instance = new UserDataMarshaller();

    public static UserDataMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(UserData userData, ProtocolMarshaller protocolMarshaller) {

        if (userData == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(userData.getS3Location(), S3LOCATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
TEST_FOLDER='test-simple-generation'

rm -rf node_modules

rm -rf $TEST_FOLDER

mkdir $TEST_FOLDER

cp -r './test/src/todomvc-ng2/' $TEST_FOLDER

cd $TEST_FOLDER

npm i

npm run doc


text:
using System;
using d60.Cirqus.Config.Configurers;
using d60.Cirqus.Events;
using d60.Cirqus.PostgreSql.Events;
using Npgsql;

namespace d60.Cirqus.PostgreSql.Config
{
    public static class PostgreSqlConfigurationExtensions
    {
        /// <summary>
        /// Configures Cirqus to use Postgres as the event store
        /// </summary>
        public static void UsePostgreSql(this EventStoreConfigurationBuilder builder, string connectionStringOrConnectionStringName, string tableName, bool automaticallyCreateSchema = true, Action<NpgsqlConnection> additionalConnectionSetup = null)
        {
            if (builder == null) throw new ArgumentNullException("builder");
            if (connectionStringOrConnectionStringName == null) throw new ArgumentNullException("connectionStringOrConnectionStringName");
            if (tableName == null) throw new ArgumentNullException("tableName");

            builder.Register<IEventStore>(context => new PostgreSqlEventStore(connectionStringOrConnectionStringName, tableName, automaticallyCreateSchema: automaticallyCreateSchema, additionalConnectionSetup: additionalConnectionSetup));
        }
    }
}


text:
namespace Microsoft.Azure.Management.StorageSync.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Defines headers for ListByStorageSyncService operation.
    /// </summary>
    public partial class PrivateEndpointConnectionsListByStorageSyncServiceHeaders
    {
        /// <summary>
        /// Initializes a new instance of the
        /// PrivateEndpointConnectionsListByStorageSyncServiceHeaders class.
        /// </summary>
        public PrivateEndpointConnectionsListByStorageSyncServiceHeaders()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// PrivateEndpointConnectionsListByStorageSyncServiceHeaders class.
        /// </summary>
        /// <param name="xMsRequestId">request id.</param>
        /// <param name="xMsCorrelationRequestId">correlation request
        /// id.</param>
        public PrivateEndpointConnectionsListByStorageSyncServiceHeaders(string xMsRequestId = default(string), string xMsCorrelationRequestId = default(string))
        {
            XMsRequestId = xMsRequestId;
            XMsCorrelationRequestId = xMsCorrelationRequestId;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets request id.
        /// </summary>
        [JsonProperty(PropertyName = "x-ms-request-id")]
        public string XMsRequestId { get; set; }

        /// <summary>
        /// Gets or sets correlation request id.
        /// </summary>
        [JsonProperty(PropertyName = "x-ms-correlation-request-id")]
        public string XMsCorrelationRequestId { get; set; }

    }
}