text:
package com.cezarykluczynski.stapi.server.title.configuration;

import com.cezarykluczynski.stapi.server.common.endpoint.EndpointFactory;
import com.cezarykluczynski.stapi.server.title.endpoint.TitleRestEndpoint;
import com.cezarykluczynski.stapi.server.title.endpoint.TitleSoapEndpoint;
import com.cezarykluczynski.stapi.server.title.mapper.TitleBaseRestMapper;
import com.cezarykluczynski.stapi.server.title.mapper.TitleBaseSoapMapper;
import com.cezarykluczynski.stapi.server.title.mapper.TitleFullRestMapper;
import com.cezarykluczynski.stapi.server.title.mapper.TitleFullSoapMapper;
import org.apache.cxf.endpoint.Server;
import org.mapstruct.factory.Mappers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.inject.Inject;
import javax.xml.ws.Endpoint;

@Configuration
public class TitleConfiguration {

	@Inject
	private EndpointFactory endpointFactory;

	@Bean
	public Endpoint titleEndpoint() {
		return endpointFactory.createSoapEndpoint(TitleSoapEndpoint.class, TitleSoapEndpoint.ADDRESS);
	}

	@Bean
	public Server titleServer() {
		return endpointFactory.createRestEndpoint(TitleRestEndpoint.class, TitleRestEndpoint.ADDRESS);
	}

	@Bean
	public TitleBaseSoapMapper titleBaseSoapMapper() {
		return Mappers.getMapper(TitleBaseSoapMapper.class);
	}

	@Bean
	public TitleFullSoapMapper titleFullSoapMapper() {
		return Mappers.getMapper(TitleFullSoapMapper.class);
	}

	@Bean
	public TitleBaseRestMapper titleBaseRestMapper() {
		return Mappers.getMapper(TitleBaseRestMapper.class);
	}

	@Bean
	public TitleFullRestMapper titleFullRestMapper() {
		return Mappers.getMapper(TitleFullRestMapper.class);
	}

}


text:
/app/cassandra/bin/nodetool -h ${CASS_HOST} -p 7199 snapshot UserGrid
tar -cz /app/cassandra/  |  openssl enc -aes-256-cbc -k $(/root/backup.pwd.txt) -e > /app/downloads/backup.tar.gz.enc
/sbin/setuser app chown app:app /app/downloads/backup.tar.gz.enc
/app/cassandra/bin/nodetool -h ${CASS_HOST} -p 7199 clearsnapshot

redpajama_set_name: RedPajamaGithub


text:
from django.http import Http404
from django.views.generic import DetailView

from simplesite.models import Page

class PageBaseDetailView(DetailView):
    """
    Base View model specification. The remain views, will inherit from this
    across de application.
    """
    model = Page

    def get_queryset(self, *args, **kwargs):
        if self.request.user.is_staff:
            return Page.objects.all()
        return Page.objects.get_public_pages()

    def get_object(self):
        page_qs = self.get_queryset()
        page_slug = self.kwargs.get('slug', None)
        try:
            page = page_qs.get(slug=page_slug)
        except:
            raise Http404()
        return page

class IndexDetailView(PageBaseDetailView):
    """
    Render the Home Page. the templates must have one of these names.
    """

    def get_template_names(self):
        return [
            "simplesite/page_{0}.html".format(self.kwargs.get('slug')),
            "simplesite/{0}_page.html".format(self.kwargs.get('slug')),
            "simplesite/index.html",
            "simplesite/home.html",
        ]

class PageDetailView(PageBaseDetailView):
    """
    Render the NON home Page objects. This view takes the slug kwargs and
    searchs the template looking for the next pattern.
    """

    def get_template_names(self):
        return [
            "simplesite/page_{0}.html".format(self.kwargs.get('slug')),
            "simplesite/{0}_page.html".format(self.kwargs.get('slug')),
            "simplesite/page_detail.html",
        ]


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="StaticBody" inherits="PhysicsBody" category="Core" version="3.0.alpha.custom_build">
	<brief_description>
		Static body for 3D Physics.
	</brief_description>
	<description>
		Static body for 3D Physics. A static body is a simple body that is not intended to move. They don't consume any CPU resources in contrast to a [RigidBody3D] so they are great for scenario collision.
		A static body can also be animated by using simulated motion mode. This is useful for implementing functionalities such as moving platforms. When this mode is active the body can be animated and automatically computes linear and angular velocity to apply in that frame and to influence other bodies.
		Alternatively, a constant linear or angular velocity can be set for the static body, so even if it doesn't move, it affects other bodies as if it was moving (this is useful for simulating conveyor belts or conveyor wheels).
	</description>
	<tutorials>
	</tutorials>
	<demos>
	</demos>
	<methods>
		<method name="get_bounce" qualifiers="const">
			<return type="float">
			</return>
			<description>
				Return the body bounciness.
			</description>
		</method>
		<method name="get_constant_angular_velocity" qualifiers="const">
			<return type="Vector3">
			</return>
			<description>
				Return the constant angular velocity for the body.
			</description>
		</method>
		<method name="get_constant_linear_velocity" qualifiers="const">
			<return type="Vector3">
			</return>
			<description>
				Return the constant linear velocity for the body.
			</description>
		</method>
		<method name="get_friction" qualifiers="const">
			<return type="float">
			</return>
			<description>
				Return the body friction.
			</description>
		</method>
		<method name="set_bounce">
			<return type="void">
			</return>
			<argument index="0" name="bounce" type="float">
			</argument>
			<description>
				Set the body bounciness, from 0 (not bouncy) to 1 (bouncy).
			</description>
		</method>
		<method name="set_constant_angular_velocity">
			<return type="void">
			</return>
			<argument index="0" name="vel" type="Vector3">
			</argument>
			<description>
				Set a constant angular velocity for the body. This does not rotate the body, but affects other bodies touching it, as if it was rotating.
			</description>
		</method>
		<method name="set_constant_linear_velocity">
			<return type="void">
			</return>
			<argument index="0" name="vel" type="Vector3">
			</argument>
			<description>
				Set a constant linear velocity for the body. This does not move the body, but affects other bodies touching it, as if it was moving.
			</description>
		</method>
		<method name="set_friction">
			<return type="void">
			</return>
			<argument index="0" name="friction" type="float">
			</argument>
			<description>
				Set the body friction, from 0 (frictionless) to 1 (full friction).
			</description>
		</method>
	</methods>
	<members>
		<member name="bounce" type="float" setter="set_bounce" getter="get_bounce">
			The body bounciness.
		</member>
		<member name="constant_angular_velocity" type="Vector3" setter="set_constant_angular_velocity" getter="get_constant_angular_velocity">
			The constant angular velocity for the body. This does not rotate the body, but affects other bodies that touch it, as if it was in a state of rotation.
		</member>
		<member name="constant_linear_velocity" type="Vector3" setter="set_constant_linear_velocity" getter="get_constant_linear_velocity">
			The constant linear velocity for the body. This does not move the body, but affects other bodies that touch it, as if it was in a state of movement.
		</member>
		<member name="friction" type="float" setter="set_friction" getter="get_friction">
			The body friction, from 0 (frictionless) to 1 (full friction).
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
<?php

namespace Oro\Bundle\TranslationBundle\Datagrid\Extension\MassAction;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Extension\MassAction\MassActionHandlerArgs;
use Oro\Bundle\DataGridBundle\Extension\MassAction\MassActionHandlerInterface;
use Oro\Bundle\DataGridBundle\Extension\MassAction\MassActionResponse;
use Oro\Bundle\SecurityBundle\ORM\Walker\AclHelper;
use Oro\Bundle\TranslationBundle\Manager\TranslationManager;
use Symfony\Contracts\Translation\TranslatorInterface;

class ResetTranslationsMassActionHandler implements MassActionHandlerInterface
{
    const FLUSH_BATCH_SIZE = 100;

    /**
     * @var TranslationManager
     */
    private $translationManager;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var AclHelper
     */
    private $aclHelper;

    /**
     * @param TranslationManager $translationManager
     * @param TranslatorInterface $translator
     * @param AclHelper $aclHelper
     */
    public function __construct(
        TranslationManager $translationManager,
        TranslatorInterface $translator,
        AclHelper $aclHelper
    ) {
        $this->translationManager = $translationManager;
        $this->translator = $translator;
        $this->aclHelper = $aclHelper;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(MassActionHandlerArgs $args)
    {
        $datasource = $args->getDatagrid()->getDatasource();

        if (!$datasource instanceof OrmDatasource) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Expected "%s", "%s" given',
                    OrmDatasource::class,
                    get_class($datasource)
                )
            );
        }

        $qb = clone $datasource->getQueryBuilder();

        $this->removeEmptyValuesFromQB($qb);
        $this->addRequiredParameters($qb);

        $this->aclHelper->apply($qb, 'TRANSLATE');

        $results = $qb->getQuery()->iterate(null, Query::HYDRATE_SCALAR);

        // if huge amount data must be deleted
        set_time_limit(0);

        $iteration = 0;
        foreach ($results as $result) {
            $translationData = reset($result);

            if ($translationData === false) {
                continue;
            }

            $this->processReset($translationData);
            $iteration++;

            if ($iteration % self::FLUSH_BATCH_SIZE === 0) {
                $this->finishBatch();
            }
        }

        if ($iteration % self::FLUSH_BATCH_SIZE > 0) {
            $this->finishBatch();
        }

        return $this->getResetResponse($iteration);
    }

    /**
     * Finish processed batch
     */
    private function finishBatch()
    {
        $this->translationManager->flush();
    }

    /**
     * @param int $entitiesCount
     * @return MassActionResponse
     */
    private function getResetResponse($entitiesCount)
    {
        $successful = $entitiesCount > 0;
        $options = ['count' => $entitiesCount];

        return new MassActionResponse(
            $successful,
            $this->translator->trans('oro.translation.action.reset.success'),
            $options
        );
    }

    /**
     * @param array $translationData
     */
    private function processReset(array $translationData)
    {
        if ($translationData['id'] === null) {
            return;
        }

        $this->translationManager->saveTranslation(
            $translationData['key'],
            null,
            $translationData['code'],
            $translationData['domain'],
            $translationData['translation_scope']
        );
    }

    /**
     * @param QueryBuilder $qb
     */
    private function removeEmptyValuesFromQB(QueryBuilder $qb)
    {
        $valuesParameter = $qb->getParameter('values');

        if (!$valuesParameter) {
            return;
        }

        $values = $valuesParameter->getValue();
        $values = array_filter($values);

        $valuesParameter->setValue($values);
    }

    /**
     * @param QueryBuilder $qb
     */
    private function addRequiredParameters(QueryBuilder $qb)
    {
        $qb->addSelect('translation.scope as translation_scope');
    }
}


text:
package br.com.codigocerto.controles;

import br.com.codigocerto.bancodados.*;
import br.com.codigocerto.conversores.ConversorTipos;
import br.com.codigocerto.modelos.MoedaCotacao;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author lis
 */
public class RegistroMoedaCotacao extends RegistroMovimentoChave {

    public interface BD {
        String  DATA = "cc_moedascotacoes_data",
                   MOEDA = "cc_moedascotacoes_moedas_id",
                   COMPRA = "cc_moedascotacoes_valorcompra",
                   VENDA = "cc_moedascotacoes_valorvenda";
    }

    /**
    * Gerar nova instancia de RegistroMoedaCotacao
    */
    public RegistroMoedaCotacao() {
    }

    @Override
    public boolean setDadosInsercao(Object dados) {
        boolean ok;
        MoedaCotacao modelo = (MoedaCotacao) dados;

        if (modelo != null) {
            InsertSqlBD sql = new InsertSqlBD();
            sql.setTabela(ligacao.getTabela());

            sql.insereColuna(BD.DATA, FormatacaoSQL.getDadoFormatado(
                                                            modelo.getData(),
                                                            TiposDadosQuery.DATA)
                                                            );
            ConversorTipos conv = new ConversorTipos();
            conv.setValorBase(modelo.getMoeda().getId());
            sql.insereColuna(BD.MOEDA, FormatacaoSQL.getDadoFormatado(
                                                            conv.getString(),
                                                            TiposDadosQuery.NUMERO)
                                                            );
            sql.insereColuna(BD.COMPRA, FormatacaoSQL.getDadoFormatado(
                                                            modelo.getValorCompra(),
                                                            TiposDadosQuery.NUMERO)
                                                            );
            sql.insereColuna(BD.VENDA, FormatacaoSQL.getDadoFormatado(
                                                            modelo.getValorVenda(),
                                                            TiposDadosQuery.NUMERO)
                                                            );

            if (ServidorBD.executaUpdate(sql.getQuery()) == 1) {
                ok = true;
            }
            else {
                ok = false;
            }
        }
        else {
            ok = false;
        }

        return ok;
    }

    @Override
    public boolean setDadosAlteracao(Object dados) {
        boolean ok;
        MoedaCotacao modelo = (MoedaCotacao) dados;

        if (modelo != null) {
            UpdateSqlBD sql = new UpdateSqlBD();

            sql.setTabela(ligacao.getTabela());
            ConversorTipos conv = new ConversorTipos();
            conv.setValorBase(modelo.getMoeda().getId());
            sql.insereColuna(BD.MOEDA, FormatacaoSQL.getDadoFormatado(
                                                            conv.getString(),
                                                            TiposDadosQuery.NUMERO)
                                                            );
            sql.insereColuna(BD.COMPRA, FormatacaoSQL.getDadoFormatado(
                                                            modelo.getValorCompra(),
                                                            TiposDadosQuery.NUMERO)
                                                            );
            sql.insereColuna(BD.VENDA, FormatacaoSQL.getDadoFormatado(
                                                            modelo.getValorVenda(),
                                                            TiposDadosQuery.NUMERO)
                                                            );
            sql.insereCondicao(BD.DATA + " = "
                                         + FormatacaoSQL.getDadoFormatado(modelo.getData(), TiposDadosQuery.DATA));
            if (ServidorBD.executaUpdate(sql.getQuery()) == 1) {
                ok = true;
            }
            else {
                ok = false;
            }
        }
        else {
            ok = false;
        }

        return ok;
    }

    @Override
    public MoedaCotacao getDados(Object chave) {
        MoedaCotacao modelo = null;
        SelectSqlBD sql = new SelectSqlBD();
        sql.setTabela(ligacao.getTabela());
        sql.insereCondicao(BD.DATA + " = " + FormatacaoSQL.getDadoFormatado((Date) chave, TiposDadosQuery.DATA));
        TabelaBD tabela = ServidorBD.executaQuery(sql.getQuery());
        if (tabela.primeiro()) {
            modelo = new MoedaCotacao();
            ConversorTipos conversor = new ConversorTipos();
            conversor.setValorBase(tabela.getColuna(BD.MOEDA).toString());
            RegistroMoeda regMoeda = new RegistroMoeda();
            modelo.setMoeda(regMoeda.getDados(conversor.getLong()));
            modelo.setData((Date) tabela.getColuna(BD.DATA));
            if (tabela.getColuna(BD.COMPRA) != null) {
                modelo.setValorCompra((BigDecimal) tabela.getColuna(BD.COMPRA));
            }
            if (tabela.getColuna(BD.VENDA) != null) {
                modelo.setValorVenda((BigDecimal) tabela.getColuna(BD.VENDA));
            }
        }

        return modelo;
    }

    public BigDecimal getUltimaCotacao() {
        BigDecimal ultimaCotacao = null;
        Date hoje = new Date();
        MoedaCotacao modelo = null;
        SelectSqlBD sql = new SelectSqlBD();
        sql.setTabela(ligacao.getTabela());
        sql.insereColuna(BD.VENDA);
        sql.insereCondicao(BD.DATA + " < " + FormatacaoSQL.getDadoFormatado(hoje, TiposDadosQuery.DATA));
        sql.insereCondicao("not isnull(" + BD.VENDA + ")", "and");
        sql.insereOrdem("-" + BD.DATA + " limit 1");
        TabelaBD tabela = ServidorBD.executaQuery(sql.getQuery());
        if (tabela.primeiro()) {
            if (tabela.getColuna(BD.VENDA) != null) {
                ultimaCotacao = (BigDecimal) tabela.getColuna(BD.VENDA);
            }
        }

        return ultimaCotacao;
    }

    @Override
    protected void estabelecerLigacao() {
        if (this.ligacao == null) {
            ligacao = new Ligacao();
        }
        ligacao.setTabela("cc_moedascotacoes");
        setCampoChave(BD.DATA, TiposDadosQuery.DATA);
    }

}///~


text:
package org.carrot2.core;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import org.carrot2.util.attribute.AttributeDescriptor;
import org.carrot2.util.attribute.AttributeValueSets;
import org.carrot2.util.attribute.BindableDescriptor;
import org.carrot2.util.resource.ResourceUtilsFactory;
import org.simpleframework.xml.*;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;

import com.google.common.collect.*;

/**
 * Dumps information on processing components from the provided suite into one XML file.
 */
public class ProcessingComponentDumper
{
    @Root(name = "processing-component-docs")
    static class ProcessingComponentDocs
    {
        @ElementList
        final ArrayList<ProcessingComponentDoc> sources;

        @ElementList
        final ArrayList<ProcessingComponentDoc> algorithms;

        ProcessingComponentDocs(String suitePath) throws Exception
        {
            final ProcessingComponentSuite suite = ProcessingComponentSuite
                .deserialize(ResourceUtilsFactory.getDefaultResourceUtils().getFirst(
                    suitePath));

            final List<DocumentSourceDescriptor> sourceDescriptors = suite.getSources();
            this.sources = Lists.newArrayList();
            for (ProcessingComponentDescriptor descriptor : sourceDescriptors)
            {
                sources.add(new ProcessingComponentDoc(descriptor));
            }

            final List<ProcessingComponentDescriptor> algorithmDescriptors = suite
                .getAlgorithms();
            this.algorithms = Lists.newArrayList();
            for (ProcessingComponentDescriptor descriptor : algorithmDescriptors)
            {
                algorithms.add(new ProcessingComponentDoc(descriptor));
            }
            Collections.sort(algorithms, new Comparator<ProcessingComponentDoc>()
            {
                public int compare(ProcessingComponentDoc o1, ProcessingComponentDoc o2)
                {
                    return o1.componentDescriptor.getLabel().compareTo(
                        o2.componentDescriptor.getLabel());
                }
            });
        }
    }

    @SuppressWarnings("unused")
    @Root(name = "processing-component-doc")
    static class ProcessingComponentDoc
    {
        @ElementList
        private final ArrayList<String> groups;

        @Element(name = "component-descriptor")
        private final ProcessingComponentDescriptor componentDescriptor;

        @ElementMap(entry = "attribute", name = "attribute-descriptors", inline = true, attribute = true, key = "key")
        private final HashMap<String, AttributeDescriptor> attributeDescriptors;

        @Element
        private final AttributeValueSets attributeSets;

        public ProcessingComponentDoc(ProcessingComponentDescriptor descriptor)
            throws InstantiationException, IllegalAccessException
        {
            this.componentDescriptor = descriptor;
            this.attributeSets = descriptor.getAttributeSets();

            // Instantiate the component and get bindable metadata
            BindableDescriptor bindableDescriptor = descriptor.getBindableDescriptor();
            this.attributeDescriptors = Maps.newHashMap(bindableDescriptor.attributeDescriptors);

            // Determine groups (it's easier to do that here than in XSLT)
            final HashSet<String> groupSet = Sets.newHashSet();
            for (AttributeDescriptor attributeDescriptor : attributeDescriptors.values())
            {
                final String groupName = attributeDescriptor.metadata.getGroup();
                if (groupName != null)
                {
                    groupSet.add(groupName);
                }
            }

            this.groups = Lists.newArrayList(groupSet);
            Collections.sort(this.groups);
        }
    }

    public static void main(String [] args) throws Exception
    {
        String suite = "suites/suite-doc.xml";
        String output = null;

        if (args.length == 2)
        {
            suite = args[0];
            output = args[1];
        }

        final ProcessingComponentDocs components = new ProcessingComponentDocs(suite);

        final Format format = new Format(2,
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        if (output == null)
        {
            new Persister(format).write(components, System.out);
        }
        else
        {
            new Persister(format).write(components,
                new FileOutputStream(new File(output)), "UTF-8");
        }
    }
}


text:
#ifndef AVUTIL_INTFLOAT_READWRITE_H
#define AVUTIL_INTFLOAT_READWRITE_H

#include <stdint.h>
#include "attributes.h"

/* IEEE 80 bits extended float */
typedef struct AVExtFloat  {
    uint8_t exponent[2];
    uint8_t mantissa[8];
} AVExtFloat;

double av_int2dbl(int64_t v) av_const;
float av_int2flt(int32_t v) av_const;
double av_ext2dbl(const AVExtFloat ext) av_const;
int64_t av_dbl2int(double d) av_const;
int32_t av_flt2int(float d) av_const;
AVExtFloat av_dbl2ext(double d) av_const;

#endif /* AVUTIL_INTFLOAT_READWRITE_H */


text:
package com.featurefm.util.slug

import scala.concurrent.{ExecutionContextExecutor, Future}

/**
 * Created by yardena on 10/15/15.
 */
class UniqueSlugGeneratorAsync(slugify: SlugGenerator, defaultPrefix: String, check: (String) => Future[Boolean])
                         (implicit context: ExecutionContextExecutor)
      extends ((String) => Future[String]) {

  val inc = (suffix: Option[Int]) => if (suffix.isEmpty) Some(2) else suffix.map(_ + 1)

  override def apply(from: String): Future[String] = {
    var stage1 = slugify(from)
    if (stage1.isEmpty) stage1 = defaultPrefix
    def generate(s: String, suffix: Option[Int]): Future[String] = {
      val input = if (suffix.isEmpty) s else s"$s-${suffix.get.toString}"
      check(input).flatMap(if (_) Future.successful(input) else generate(s, inc(suffix)))
    }
    generate(stage1, None)
  }

}

object UniqueSlugGeneratorAsync {

  def apply(slugify: SlugGenerator, defaultPrefix: String)
           (check: (String) => Future[Boolean])
           (implicit context: ExecutionContextExecutor): UniqueSlugGeneratorAsync =
  new UniqueSlugGeneratorAsync(slugify, defaultPrefix, check)
}


text:
package com.gs.collections.impl.bag.sorted.mutable;

import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;

import com.gs.collections.api.bag.sorted.ImmutableSortedBag;
import com.gs.collections.api.bag.sorted.MutableSortedBag;
import com.gs.collections.api.bag.sorted.SortedBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.predicate.primitive.IntPredicate;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.list.primitive.MutableBooleanList;
import com.gs.collections.api.list.primitive.MutableByteList;
import com.gs.collections.api.list.primitive.MutableCharList;
import com.gs.collections.api.list.primitive.MutableDoubleList;
import com.gs.collections.api.list.primitive.MutableFloatList;
import com.gs.collections.api.list.primitive.MutableIntList;
import com.gs.collections.api.list.primitive.MutableLongList;
import com.gs.collections.api.list.primitive.MutableShortList;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.sortedbag.MutableSortedBagMultimap;
import com.gs.collections.api.ordered.OrderedIterable;
import com.gs.collections.api.partition.bag.sorted.PartitionMutableSortedBag;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.stack.MutableStack;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.primitive.ObjectIntPair;
import com.gs.collections.impl.collection.mutable.AbstractUnmodifiableMutableCollection;
import com.gs.collections.impl.collection.mutable.UnmodifiableCollectionSerializationProxy;

/**
 * An unmodifiable view of a SortedBag.
 *
 * @see MutableSortedBag#asUnmodifiable()
 * @since 4.2
 */
public class UnmodifiableSortedBag<T>
        extends AbstractUnmodifiableMutableCollection<T>
        implements MutableSortedBag<T>, Serializable
{
    UnmodifiableSortedBag(MutableSortedBag<? extends T> sortedBag)
    {
        super(sortedBag);
    }

    /**
     * This method will take a MutableSortedBag and wrap it directly in a UnmodifiableSortedBag.
     */
    public static <E, S extends MutableSortedBag<E>> UnmodifiableSortedBag<E> of(S bag)
    {
        if (bag == null)
        {
            throw new IllegalArgumentException("cannot create an UnmodifiableSortedBag for null");
        }
        return new UnmodifiableSortedBag<E>(bag);
    }

    protected MutableSortedBag<T> getSortedBag()
    {
        return (MutableSortedBag<T>) this.getMutableCollection();
    }

    @Override
    public MutableSortedBag<T> asUnmodifiable()
    {
        return this;
    }

    @Override
    public MutableSortedBag<T> asSynchronized()
    {
        return SynchronizedSortedBag.of(this);
    }

    @Override
    public ImmutableSortedBag<T> toImmutable()
    {
        throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".toImmutable() not implemented yet");
    }

    @Override
    public UnmodifiableSortedBag<T> clone()
    {
        return this;
    }

    @Override
    public boolean equals(Object obj)
    {
        return this.getSortedBag().equals(obj);
    }

    @Override
    public int hashCode()
    {
        return this.getSortedBag().hashCode();
    }

    @Override
    public MutableSortedBag<T> newEmpty()
    {
        return this.getSortedBag().newEmpty();
    }

    public void addOccurrences(T item, int occurrences)
    {
        throw new UnsupportedOperationException("Cannot call addOccurrences() on " + this.getClass().getSimpleName());
    }

    public boolean removeOccurrences(Object item, int occurrences)
    {
        throw new UnsupportedOperationException("Cannot call removeOccurences() on " + this.getClass().getSimpleName());
    }

    public boolean setOccurrences(T item, int occurrences)
    {
        throw new UnsupportedOperationException("Cannot call setOccurrences() on " + this.getClass().getSimpleName());
    }

    @Override
    public MutableSortedBag<T> tap(Procedure<? super T> procedure)
    {
        this.forEach(procedure);
        return this;
    }

    @Override
    public MutableSortedBag<T> select(Predicate<? super T> predicate)
    {
        return this.getSortedBag().select(predicate);
    }

    @Override
    public <P> MutableSortedBag<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.getSortedBag().selectWith(predicate, parameter);
    }

    @Override
    public MutableSortedBag<T> reject(Predicate<? super T> predicate)
    {
        return this.getSortedBag().reject(predicate);
    }

    @Override
    public <P> MutableSortedBag<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.getSortedBag().rejectWith(predicate, parameter);
    }

    @Override
    public PartitionMutableSortedBag<T> partition(Predicate<? super T> predicate)
    {
        return this.getSortedBag().partition(predicate);
    }

    @Override
    public <P> PartitionMutableSortedBag<T> partitionWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.getSortedBag().partitionWith(predicate, parameter);
    }

    public PartitionMutableSortedBag<T> partitionWhile(Predicate<? super T> predicate)
    {
        return this.getSortedBag().partition(predicate);
    }

    public int sizeDistinct()
    {
        return this.getSortedBag().sizeDistinct();
    }

    public int occurrencesOf(Object item)
    {
        return this.getSortedBag().occurrencesOf(item);
    }

    public void forEachWithOccurrences(ObjectIntProcedure<? super T> procedure)
    {
        this.getSortedBag().forEachWithOccurrences(procedure);
    }

    public MutableSortedMap<T, Integer> toMapOfItemToCount()
    {
        return this.getSortedBag().toMapOfItemToCount();
    }

    public String toStringOfItemToCount()
    {
        return this.getSortedBag().toStringOfItemToCount();
    }

    public MutableSortedBag<T> selectByOccurrences(IntPredicate predicate)
    {
        return this.getSortedBag().selectByOccurrences(predicate);
    }

    public MutableList<ObjectIntPair<T>> topOccurrences(int count)
    {
        return this.getSortedBag().topOccurrences(count);
    }

    public MutableList<ObjectIntPair<T>> bottomOccurrences(int count)
    {
        return this.getSortedBag().bottomOccurrences(count);
    }

    @Override
    public <S> MutableSortedBag<S> selectInstancesOf(Class<S> clazz)
    {
        return this.getSortedBag().selectInstancesOf(clazz);
    }

    @Override
    public <V> MutableList<V> collect(Function<? super T, ? extends V> function)
    {
        return this.getSortedBag().collect(function);
    }

    @Override
    public MutableBooleanList collectBoolean(BooleanFunction<? super T> booleanFunction)
    {
        return this.getSortedBag().collectBoolean(booleanFunction);
    }

    @Override
    public MutableByteList collectByte(ByteFunction<? super T> byteFunction)
    {
        return this.getSortedBag().collectByte(byteFunction);
    }

    @Override
    public MutableCharList collectChar(CharFunction<? super T> charFunction)
    {
        return this.getSortedBag().collectChar(charFunction);
    }

    @Override
    public MutableDoubleList collectDouble(DoubleFunction<? super T> doubleFunction)
    {
        return this.getSortedBag().collectDouble(doubleFunction);
    }

    @Override
    public MutableFloatList collectFloat(FloatFunction<? super T> floatFunction)
    {
        return this.getSortedBag().collectFloat(floatFunction);
    }

    @Override
    public MutableIntList collectInt(IntFunction<? super T> intFunction)
    {
        return this.getSortedBag().collectInt(intFunction);
    }

    @Override
    public MutableLongList collectLong(LongFunction<? super T> longFunction)
    {
        return this.getSortedBag().collectLong(longFunction);
    }

    @Override
    public MutableShortList collectShort(ShortFunction<? super T> shortFunction)
    {
        return this.getSortedBag().collectShort(shortFunction);
    }

    @Override
    public <V> MutableList<V> flatCollect(Function<? super T, ? extends Iterable<V>> function)
    {
        return this.getSortedBag().flatCollect(function);
    }

    public MutableSortedSet<T> distinct()
    {
        return this.getSortedBag().distinct();
    }

    public <S> boolean corresponds(OrderedIterable<S> other, Predicate2<? super T, ? super S> predicate)
    {
        return this.getSortedBag().corresponds(other, predicate);
    }

    public void forEach(int startIndex, int endIndex, Procedure<? super T> procedure)
    {
        this.getSortedBag().forEach(startIndex, endIndex, procedure);
    }

    public void forEachWithIndex(int fromIndex, int toIndex, ObjectIntProcedure<? super T> objectIntProcedure)
    {
        this.getSortedBag().forEachWithIndex(fromIndex, toIndex, objectIntProcedure);
    }

    public MutableStack<T> toStack()
    {
        return this.getSortedBag().toStack();
    }

    public int indexOf(Object object)
    {
        return this.getSortedBag().indexOf(object);
    }

    public MutableSortedBag<T> takeWhile(Predicate<? super T> predicate)
    {
        return this.getSortedBag().takeWhile(predicate);
    }

    public MutableSortedBag<T> dropWhile(Predicate<? super T> predicate)
    {
        return this.getSortedBag().dropWhile(predicate);
    }

    @Override
    public <P, A> MutableList<A> collectWith(Function2<? super T, ? super P, ? extends A> function, P parameter)
    {
        return this.getSortedBag().collectWith(function, parameter);
    }

    @Override
    public <V> MutableList<V> collectIf(
            Predicate<? super T> predicate,
            Function<? super T, ? extends V> function)
    {
        return this.getSortedBag().collectIf(predicate, function);
    }

    public int detectIndex(Predicate<? super T> predicate)
    {
        return this.getSortedBag().detectIndex(predicate);
    }

    @Override
    public <V> MutableSortedBagMultimap<V, T> groupBy(Function<? super T, ? extends V> function)
    {
        return this.getSortedBag().groupBy(function);
    }

    @Override
    public <V> MutableSortedBagMultimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function)
    {
        return this.getSortedBag().groupByEach(function);
    }

    @Override
    public <S> MutableList<Pair<T, S>> zip(Iterable<S> that)
    {
        return this.getSortedBag().zip(that);
    }

    @Override
    public <S, R extends Collection<Pair<T, S>>> R zip(Iterable<S> that, R target)
    {
        return this.getSortedBag().zip(that, target);
    }

    @Override
    public MutableSortedSet<Pair<T, Integer>> zipWithIndex()
    {
        return this.getSortedBag().zipWithIndex();
    }

    @Override
    public <R extends Collection<Pair<T, Integer>>> R zipWithIndex(R target)
    {
        return this.getSortedBag().zipWithIndex(target);
    }

    public Comparator<? super T> comparator()
    {
        return this.getSortedBag().comparator();
    }

    @Override
    public MutableSortedBag<T> with(T element)
    {
        throw new UnsupportedOperationException("Cannot call with() on " + this.getClass().getSimpleName());
    }

    @Override
    public MutableSortedBag<T> without(T element)
    {
        throw new UnsupportedOperationException("Cannot call without() on " + this.getClass().getSimpleName());
    }

    @Override
    public MutableSortedBag<T> withAll(Iterable<? extends T> elements)
    {
        throw new UnsupportedOperationException("Cannot call withAll() on " + this.getClass().getSimpleName());
    }

    @Override
    public MutableSortedBag<T> withoutAll(Iterable<? extends T> elements)
    {
        throw new UnsupportedOperationException("Cannot call withoutAll() on " + this.getClass().getSimpleName());
    }

    public int compareTo(SortedBag<T> o)
    {
        return this.getSortedBag().compareTo(o);
    }

    protected Object writeReplace()
    {
        return new UnmodifiableCollectionSerializationProxy<T>(this.getSortedBag());
    }
}


text:
package edu.psu.compbio.seqcode.gse.viz.metagenes;

import java.util.*;

import edu.psu.compbio.seqcode.gse.clustering.*;
import edu.psu.compbio.seqcode.gse.clustering.hierarchical.*;
import edu.psu.compbio.seqcode.gse.clustering.vectorcluster.*;

public class ProfileClusteringHandler {

	private ProfileClusterRepresentative repr;
	private PairwiseElementMetric<ProfileClusterable> metric;
	private HierarchicalClustering<ProfileClusterable> clustering;

	public ProfileClusteringHandler(BinningParameters bps) {
		repr = new ProfileClusterRepresentative(bps);
		metric = new EuclideanDistance<ProfileClusterable>();
		clustering = new HierarchicalClustering<ProfileClusterable>(repr, metric);
	}

	public Vector<Integer> runClustering(Vector<Profile> profs) {
		Vector<Integer> indices = new Vector<Integer>();

		Vector<ProfileClusterable> clusterables = new Vector<ProfileClusterable>();
		for(int i = 0; i < profs.size(); i++) {
			clusterables.add(new ProfileClusterable(i, profs.get(i)));
		}

		Collection<Cluster<ProfileClusterable>> clusterTree = clustering.clusterElements(clusterables);
		for(Cluster<ProfileClusterable> tree : clusterTree) {
			appendIndices(indices, tree);
		}

		return indices;
	}

	private void appendIndices(Vector<Integer> indices, Cluster<ProfileClusterable> tree) {
		if(tree instanceof ClusterNode) {
			ClusterNode<ProfileClusterable> treeNode = (ClusterNode<ProfileClusterable>)tree;
			appendIndices(indices, treeNode.getLeft());
			appendIndices(indices, treeNode.getRight());
		} else {
			for(ProfileClusterable pc : tree.getElements()) {
				Integer idx = pc.getIndex();
				if(idx != null) {
					indices.add(idx);
				} else {
					System.err.println("Null index encountered...");
				}
			}
		}
	}
}

class ProfileClusterRepresentative implements ClusterRepresentative<ProfileClusterable> {

	private int index;
	private BinningParameters params;

	public ProfileClusterRepresentative(BinningParameters bps) {
		index = 0;
		params = bps;
	}

	public ProfileClusterable getRepresentative(Cluster<ProfileClusterable> c) {
		String name = String.format("cluster-rep-%d", index++);
		MetaProfile mp = new MetaProfile(name, params);

		for(ProfileClusterable pc : c.getElements()) {
			Profile p = pc.getProfile();
			mp.addProfile(p);
		}

		return new ProfileClusterable(mp);
	}

}


text:
package easy;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

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

class WhichDayTest {

    @ParameterizedTest
    @MethodSource("testCasesProvider")
    void getDay(String[] notOnThisDay, String want) {
        WhichDay whichDay = new WhichDay();

        String got = whichDay.getDay(notOnThisDay);

        assertThat(got).isEqualTo(want);
    }

    private static Stream<Arguments> testCasesProvider() {
        return Stream.of(
                Arguments.of(
                        new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"},
                        "Saturday"
                ),
                Arguments.of(
                        new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Thursday"},
                        "Saturday"
                ),
                Arguments.of(
                        new String[]{"Sunday", "Monday", "Tuesday", "Thursday", "Friday", "Saturday"},
                        "Wednesday"
                ),
                Arguments.of(
                        new String[]{"Sunday", "Friday", "Tuesday", "Wednesday", "Monday", "Saturday"},
                        "Thursday"
                )
        );
    }
}


text:
package gitlab

import (
	"fmt"
	"net/http"
	"net/url"
)

// ProtectedBranchesService handles communication with the protected branch
// related methods of the GitLab API.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type ProtectedBranchesService struct {
	client *Client
}

// ProtectedBranch represents a protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ProtectedBranch struct {
	ID                        int                        `json:"id"`
	Name                      string                     `json:"name"`
	PushAccessLevels          []*BranchAccessDescription `json:"push_access_levels"`
	MergeAccessLevels         []*BranchAccessDescription `json:"merge_access_levels"`
	UnprotectAccessLevels     []*BranchAccessDescription `json:"unprotect_access_levels"`
	CodeOwnerApprovalRequired bool                       `json:"code_owner_approval_required"`
}

// BranchAccessDescription represents the access description for a protected
// branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type BranchAccessDescription struct {
	AccessLevel            AccessLevelValue `json:"access_level"`
	AccessLevelDescription string           `json:"access_level_description"`
	UserID                 int              `json:"user_id"`
	GroupID                int              `json:"group_id"`
}

// ListProtectedBranchesOptions represents the available ListProtectedBranches()
// options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ListProtectedBranchesOptions ListOptions

// ListProtectedBranches gets a list of protected branches from a project.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
func (s *ProtectedBranchesService) ListProtectedBranches(pid interface{}, opt *ListProtectedBranchesOptions, options ...RequestOptionFunc) ([]*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest(http.MethodGet, u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	var p []*ProtectedBranch
	resp, err := s.client.Do(req, &p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// GetProtectedBranch gets a single protected branch or wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#get-a-single-protected-branch-or-wildcard-protected-branch
func (s *ProtectedBranchesService) GetProtectedBranch(pid interface{}, branch string, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest(http.MethodGet, u, nil, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// ProtectRepositoryBranchesOptions represents the available
// ProtectRepositoryBranches() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
type ProtectRepositoryBranchesOptions struct {
	Name                      *string                    `url:"name,omitempty" json:"name,omitempty"`
	PushAccessLevel           *AccessLevelValue          `url:"push_access_level,omitempty" json:"push_access_level,omitempty"`
	MergeAccessLevel          *AccessLevelValue          `url:"merge_access_level,omitempty" json:"merge_access_level,omitempty"`
	UnprotectAccessLevel      *AccessLevelValue          `url:"unprotect_access_level,omitempty" json:"unprotect_access_level,omitempty"`
	AllowedToPush             []*BranchPermissionOptions `url:"allowed_to_push,omitempty" json:"allowed_to_push,omitempty"`
	AllowedToMerge            []*BranchPermissionOptions `url:"allowed_to_merge,omitempty" json:"allowed_to_merge,omitempty"`
	AllowedToUnprotect        []*BranchPermissionOptions `url:"allowed_to_unprotect,omitempty" json:"allowed_to_unprotect,omitempty"`
	CodeOwnerApprovalRequired *bool                      `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// BranchPermissionOptions represents a branch permission option.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
type BranchPermissionOptions struct {
	UserID      *int              `url:"user_id,omitempty" json:"user_id,omitempty"`
	GroupID     *int              `url:"group_id,omitempty" json:"group_id,omitempty"`
	AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"`
}

// ProtectRepositoryBranches protects a single repository branch or several
// project repository branches using a wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
func (s *ProtectedBranchesService) ProtectRepositoryBranches(pid interface{}, opt *ProtectRepositoryBranchesOptions, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest(http.MethodPost, u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// UnprotectRepositoryBranches unprotects the given protected branch or wildcard
// protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#unprotect-repository-branches
func (s *ProtectedBranchesService) UnprotectRepositoryBranches(pid interface{}, branch string, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest(http.MethodDelete, u, nil, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}

// RequireCodeOwnerApprovalsOptions represents the available
// RequireCodeOwnerApprovals() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
type RequireCodeOwnerApprovalsOptions struct {
	CodeOwnerApprovalRequired *bool `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// RequireCodeOwnerApprovals updates the code owner approval.
//
// Gitlab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
func (s *ProtectedBranchesService) RequireCodeOwnerApprovals(pid interface{}, branch string, opt *RequireCodeOwnerApprovalsOptions, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest(http.MethodPatch, u, opt, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}


text:
package org.elasticsearch.xpack.core.watcher.client;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse;
import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest;
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.ack.AckWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.ack.AckWatchRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.ack.AckWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.ack.AckWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.delete.DeleteWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.delete.DeleteWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.put.PutWatchAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.put.PutWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.service.WatcherServiceAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.service.WatcherServiceRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.service.WatcherServiceRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsAction;
import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsRequest;
import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsResponse;

import java.util.Map;

public class WatcherClient {

    private final Client client;

    public WatcherClient(Client client) {
        this.client = client;
    }

    /**
     * Creates a request builder that gets an watch by id
     *
     * @param id the id of the watch
     * @return The request builder
     */
    public GetWatchRequestBuilder prepareGetWatch(String id) {
        return new GetWatchRequestBuilder(client, id);
    }

    /**
     * Creates a request builder that gets an watch
     *
     * @return the request builder
     */
    public GetWatchRequestBuilder prepareGetWatch() {
        return new GetWatchRequestBuilder(client);
    }

    /**
     * Gets an watch from the watch index
     *
     * @param request The get watch request
     * @param listener The listener for the get watch response containing the GetResponse for this watch
     */
    public void getWatch(GetWatchRequest request, ActionListener<GetWatchResponse> listener) {
        client.execute(GetWatchAction.INSTANCE, request, listener);
    }

    /**
     * Gets an watch from the watch index
     *
     * @param request The get watch request with the watch id
     * @return The response containing the GetResponse for this watch
     */
    public ActionFuture<GetWatchResponse> getWatch(GetWatchRequest request) {
        return client.execute(GetWatchAction.INSTANCE, request);
    }

    /**
     * Creates a request builder to delete an watch by id
     *
     * @param id the id of the watch
     * @return The request builder
     */
    public DeleteWatchRequestBuilder prepareDeleteWatch(String id) {
        return new DeleteWatchRequestBuilder(client, id);
    }

    /**
     * Creates a request builder that deletes an watch
     *
     * @return The request builder
     */
    public DeleteWatchRequestBuilder prepareDeleteWatch() {
        return new DeleteWatchRequestBuilder(client);
    }

    /**
     * Deletes an watch
     *
     * @param request The delete request with the watch id to be deleted
     * @param listener The listener for the delete watch response containing the DeleteResponse for this action
     */
    public void deleteWatch(DeleteWatchRequest request, ActionListener<DeleteWatchResponse> listener) {
        client.execute(DeleteWatchAction.INSTANCE, request, listener);
    }

    /**
     * Deletes an watch
     *
     * @param request The delete request with the watch id to be deleted
     * @return The response containing the DeleteResponse for this action
     */
    public ActionFuture<DeleteWatchResponse> deleteWatch(DeleteWatchRequest request) {
        return client.execute(DeleteWatchAction.INSTANCE, request);
    }

    /**
     * Creates a request builder to build a request to put an watch
     *
     * @param id The id of the watch to put
     * @return The builder to create the watch
     */
    public PutWatchRequestBuilder preparePutWatch(String id) {
        return new PutWatchRequestBuilder(client, id);
    }

    /**
     * Creates a request builder to build a request to put a watch
     *
     * @return The builder
     */
    public PutWatchRequestBuilder preparePutWatch() {
        return new PutWatchRequestBuilder(client);
    }

    /**
     * Adds the given watch to the watcher
     *
     * @param request The request containing the watch to be added
     * @param listener The listener for the response containing the IndexResponse for this watch
     */
    public void putWatch(PutWatchRequest request, ActionListener<PutWatchResponse> listener) {
        client.execute(PutWatchAction.INSTANCE, request, listener);
    }

    /**
     * Adds a new watch
     *
     * @param request The request containing the watch to be added
     * @return The response containing the IndexResponse for this watch
     */
    public ActionFuture<PutWatchResponse> putWatch(PutWatchRequest request) {
        return client.execute(PutWatchAction.INSTANCE, request);
    }

    /**
     * Gets the watcher stats
     *
     * @param request The request for the watcher stats
     * @return The response containing the StatsResponse for this action
     */
    public ActionFuture<WatcherStatsResponse> watcherStats(WatcherStatsRequest request) {
        return client.execute(WatcherStatsAction.INSTANCE, request);
    }

    /**
     * Creates a request builder to build a request to get the watcher stats
     *
     * @return The builder get the watcher stats
     */
    public WatcherStatsRequestBuilder prepareWatcherStats() {
        return new WatcherStatsRequestBuilder(client);
    }

    /**
     * Gets the watcher stats
     *
     * @param request The request for the watcher stats
     * @param listener The listener for the response containing the WatcherStatsResponse
     */
    public void watcherStats(WatcherStatsRequest request, ActionListener<WatcherStatsResponse> listener) {
        client.execute(WatcherStatsAction.INSTANCE, request, listener);
    }

    /**
     * Creates a request builder to ack a watch by id
     *
     * @param id the id of the watch
     * @return The request builder
     */
    public AckWatchRequestBuilder prepareAckWatch(String id) {
        return new AckWatchRequestBuilder(client, id);
    }

    /**
     * Ack a watch
     *
     * @param request The ack request with the watch id to be acked
     * @param listener The listener for the ack watch response
     */
    public void ackWatch(AckWatchRequest request, ActionListener<AckWatchResponse> listener) {
        client.execute(AckWatchAction.INSTANCE, request, listener);
    }

    /**
     * Acks a watch
     *
     * @param request The ack request with the watch id to be acked
     * @return The AckWatchResponse
     */
    public ActionFuture<AckWatchResponse> ackWatch(AckWatchRequest request) {
        return client.execute(AckWatchAction.INSTANCE, request);
    }

    /**
     * Creates a request builder to activate a watch by id
     *
     * @param id the id of the watch
     * @param activate indicates whether to activate or deactivate the watch
     * @return The request builder
     */
    public ActivateWatchRequestBuilder prepareActivateWatch(String id, boolean activate) {
        return new ActivateWatchRequestBuilder(client, id, activate);
    }

    /**
     * Activate a watch
     *
     * @param request The activate request with the watch id
     * @param listener The listener for the activate watch response
     */
    public void activateWatch(ActivateWatchRequest request, ActionListener<ActivateWatchResponse> listener) {
        client.execute(ActivateWatchAction.INSTANCE, request, listener);
    }

    /**
     * Activates a watch
     *
     * @param request The de/activate request with the watch id.
     */
    public ActionFuture<ActivateWatchResponse> activateWatch(ActivateWatchRequest request) {
        return client.execute(ActivateWatchAction.INSTANCE, request);
    }

    /**
     * Prepare a watch service request.
     */
    public WatcherServiceRequestBuilder prepareWatchService() {
        return new WatcherServiceRequestBuilder(client);
    }

    /**
     * Perform an watcher service request to either start, stop or restart the service.
     */
    public void watcherService(WatcherServiceRequest request, ActionListener<AcknowledgedResponse> listener) {
        client.execute(WatcherServiceAction.INSTANCE, request, listener);
    }

    /**
     * Perform an watcher service request to either start, stop or restart the service.
     */
    public ActionFuture<AcknowledgedResponse> watcherService(WatcherServiceRequest request) {
        return client.execute(WatcherServiceAction.INSTANCE, request);
    }

    /**
     * Creates a request builder to execute a watch by id
     *
     * @param id the id of the watch
     * @return The request builder
     */
    public ExecuteWatchRequestBuilder prepareExecuteWatch(String id) {
        return new ExecuteWatchRequestBuilder(client, id);
    }

    /**
     * Creates a request builder that executes a watch
     *
     * @return The request builder
     */
    public ExecuteWatchRequestBuilder prepareExecuteWatch() {
        return new ExecuteWatchRequestBuilder(client);
    }

    /**
     * executes a watch
     *
     * @param request The run request with the watch id to be executed
     * @param listener The listener for the run watch response
     */
    public void executeWatch(ExecuteWatchRequest request, ActionListener<ExecuteWatchResponse> listener) {
        client.execute(ExecuteWatchAction.INSTANCE, request, listener);
    }

    /**
     * Executes an watch
     *
     * @param request The execute request with the watch id to be executed
     * @return The AckWatchResponse
     */
    public ActionFuture<ExecuteWatchResponse> executeWatch(ExecuteWatchRequest request) {
        return client.execute(ExecuteWatchAction.INSTANCE, request);
    }

    public WatcherClient filterWithHeader(Map<String, String> headers) {
        return new WatcherClient(client.filterWithHeader(headers));
    }
}