/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jboss.as.protocol.StreamUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;

import javax.xml.namespace.QName;

/**
 * An XML configuration persister which backs up the old file before overwriting it.
 *
 * @author David M. Lloyd
 */
public final class BackupXmlConfigurationPersister extends XmlConfigurationPersister {

    /**
     * Construct a new instance.
     *
     * @param fileName the configuration base file name
     * @param rootElement the root element of the configuration file
     * @param rootParser the root model parser
     * @param rootDeparser the root model deparser
     */
    public BackupXmlConfigurationPersister(final File fileName, final QName rootElement, final XMLElementReader<ModelNode> rootParser, final XMLElementWriter<ModelNode> rootDeparser) {
        super(fileName, rootElement, rootParser, rootDeparser);
    }

    /** {@inheritDoc} */
    protected void backup(final File fileName) throws ConfigurationPersistenceException {
        File backup = new File(fileName.getParent(), fileName.getName() + ".last-known-good");
        try {
            moveFile(fileName, backup);
        } catch (IOException e) {
            throw new ConfigurationPersistenceException("Failed to back up " + fileName, e);
        }
    }

    private void moveFile(File file, File backup) throws IOException {

        if (backup.exists())
            backup.delete();

        if (!file.renameTo(backup) && file.exists()) {
            final FileInputStream fis = new FileInputStream(file);
            try {
                final FileOutputStream fos = new FileOutputStream(backup);
                try {
                    StreamUtils.copyStream(fis, fos);
                    fos.close();
                } finally {
                    StreamUtils.safeClose(fos);
                }
            } finally {
                StreamUtils.safeClose(fis);
            }
        }
    }
}

Add persister which backs up the original file


/*
 * Copyright 2016 Michael Rozumyanskiy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.michaelrocks.lightsaber.internal;

import io.michaelrocks.lightsaber.Injector;

public abstract class AbstractInjectingProvider<T> implements InjectingProvider<T> {
  private static final ThreadLocal<Injector> currentInjector = new ThreadLocal<Injector>();

  private final Injector injector;

  protected AbstractInjectingProvider(final Injector injector) {
    this.injector = injector;
  }

  @Override
  public final T get() {
    boolean ownsCurrentInjector = false;
    Injector contextInjector = currentInjector.get();
    if (contextInjector == null) {
      contextInjector = injector;
      currentInjector.set(contextInjector);
      ownsCurrentInjector = true;
    }

    try {
      return getWithInjector(contextInjector);
    } finally {
      if (ownsCurrentInjector) {
        currentInjector.remove();
      }
    }
  }
}

Introduce a base type for providers that support injection


/*
 * Copyright (c) 2010.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.broadinstitute.sting.playground.gatk.walkers;

import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;

import java.util.Arrays;

public class BeagleIntegrationTest extends WalkerTest {

    private static final String beagleValidationDataLocation = validationDataLocation + "/Beagle/";
    @Test
    public void testBeagleOutput() {
        WalkerTestSpec spec = new WalkerTestSpec(
                "-T BeagleOutputToVCF -R " + oneKGLocation + "reference/human_g1k_v37.fasta " +
                        "-B variant,VCF," + beagleValidationDataLocation + "inttestbgl.input.vcf " +
                        "-B beagleR2,BEAGLE," + beagleValidationDataLocation + "inttestbgl.r2 " +
                        "-B beagleProbs,BEAGLE," + beagleValidationDataLocation + "inttestbgl.gprobs " +
                        "-B beaglePhased,BEAGLE," + beagleValidationDataLocation + "inttestbgl.phased " +
                        "-output %s", 1, Arrays.asList("e7b9aac20246f26ffcc599850f6cb2a0"));
        executeTest("test BeagleOutputToVCF", spec);
    }

    @Test
    public void testBeagleInput() {
        WalkerTestSpec spec = new WalkerTestSpec(
                "-T ProduceBeagleInput -R " + oneKGLocation + "reference/human_g1k_v37.fasta " +
                        "-B variant,VCF," + beagleValidationDataLocation + "inttestbgl.input.vcf " +
                         "-beagle %s", 1, Arrays.asList("c0d30e5dbe903874f8422a0e63a5118e"));
        executeTest("test BeagleInput", spec);
    }

}

Add an integration test for Beagle (one for ProduceBeagleInput and one for BeagleOutputToVCFWalker)


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

import javax.jms.JMSException;

/**
 * JMSException derivative that defines that a TX outcome is unknown.
 */
public class JmsTransactionInDoubtException extends JMSException {

    private static final long serialVersionUID = 4937372602950141285L;

    public JmsTransactionInDoubtException(String reason, String errorCode) {
        super(reason, errorCode);
    }

    public JmsTransactionInDoubtException(String reason) {
        super(reason);
    }
}

Add a JMS exception for transaction commit being in doubt.


package io.github.uetoyo.patterns.specification;

import com.google.common.annotations.Beta;

@Beta
abstract class ValueBoundedSpecification<T, V> implements Specification<T> {

	private final V value;

	/* TODO
	public static <T, V> EqualValueSpecification<T, V> withEqualValue(V value) {
		return new EqualValueSpecification<T, V>(value);
	}*/

	protected ValueBoundedSpecification(V value) {
		this.value = value;
	}

	public V getValue() {
		return value;
	}
}

Add the sketch of value bounded specification


// Copyright (C) 2021 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.acceptance.rest.project;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.extensions.api.access.ProjectAccessInfo;
import com.google.gson.reflect.TypeToken;
import java.util.Map;
import org.junit.Test;

public class AccessIT extends AbstractDaemonTest {

  @Test
  public void listAccessWithoutSpecifyingProject() throws Exception {
    RestResponse r = adminRestSession.get("/access/");
    r.assertOK();
    Map<String, ProjectAccessInfo> infoByProject =
        newGson()
            .fromJson(r.getReader(), new TypeToken<Map<String, ProjectAccessInfo>>() {}.getType());
    assertThat(infoByProject).isEmpty();
  }

  @Test
  public void listAccessWithoutSpecifyingAnEmptyProjectName() throws Exception {
    RestResponse r = adminRestSession.get("/access/?p=");
    r.assertNotFound();
    assertThat(r.getEntityContent()).isEqualTo("Not Found");
  }

  @Test
  public void listAccessForNonExistingProject() throws Exception {
    RestResponse r = adminRestSession.get("/access/?project=non-existing");
    r.assertNotFound();
    assertThat(r.getEntityContent()).isEqualTo("non-existing");
  }

  @Test
  public void listAccess() throws Exception {
    RestResponse r = adminRestSession.get("/access/?project=" + project.get());
    r.assertOK();
    Map<String, ProjectAccessInfo> infoByProject =
        newGson()
            .fromJson(r.getReader(), new TypeToken<Map<String, ProjectAccessInfo>>() {}.getType());
    assertThat(infoByProject.keySet()).containsExactly(project.get());
  }
}

Add basic test for the ListAccess REST endpoint


package info.u_team.u_team_test.global_loot_modifier;

import java.util.List;
import java.util.stream.Collectors;

import com.google.gson.JsonObject;

import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.minecraftforge.common.loot.*;
import net.minecraftforge.items.ItemHandlerHelper;

public class AutoSmeltLootModifier extends LootModifier {

	private AutoSmeltLootModifier(ILootCondition[] conditions) {
		super(conditions);
	}

	@Override
	protected List<ItemStack> doApply(List<ItemStack> generatedLoot, LootContext context) {
		return generatedLoot.stream().map(stack -> smeltItem(stack, context)).collect(Collectors.toList());
	}

	private static ItemStack smeltItem(ItemStack stack, LootContext context) {
		return context.getWorld().getRecipeManager().getRecipe(IRecipeType.SMELTING, new Inventory(stack), context.getWorld()).map(FurnaceRecipe::getRecipeOutput).filter(itemStack -> !itemStack.isEmpty()).map(itemStack -> ItemHandlerHelper.copyStackWithSize(itemStack, stack.getCount() * itemStack.getCount())).orElse(stack);
	}

	public static class Serializer extends GlobalLootModifierSerializer<AutoSmeltLootModifier> {

		@Override
		public AutoSmeltLootModifier read(ResourceLocation name, JsonObject json, ILootCondition[] conditions) {
			return new AutoSmeltLootModifier(conditions);
		}
	}

}

Add auto smelt loot modifier


public class Binom {
  private static int[][] coeff = null;

  public static void main (String[] args) {
    int threshold = 20;
    int i = 0;
    for (int n = 0; n < threshold; ++n) {
      for (i = 0; i < threshold; ++i) {
        System.out.println("n = " + n + ", i = " + i + ": binom = " + binom(n, i));
      }
    }
  }

  public static int binom (final int n, final int i) {
    coeff = new int[n + 1][i + 1];

    int l = 0, k = 0;
    for (k = 0; k <= n; ++k) {
      for (l = 0; l <= i; ++l) {
        coeff[k][l] = Integer.MAX_VALUE;
      }
    }

    for (k = 0; k <= n; ++k) {
      coeff[k][0] = 1;
      for (l = 1; l <= i; ++l) {
        coeff[0][l] = 0;
      }
    }

    return lookupBinom(n, i);
  }

  public static int lookupBinom (final int n, final int i) {
    if (coeff[n][i] == Integer.MAX_VALUE) {
      coeff[n][i] = lookupBinom(n - 1, i) + lookupBinom(n - 1, i - 1);
    }

    return coeff[n][i];
  }
}

Add quick implementation of Aufgabe 22


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

import java.security.Principal;
import java.util.Collections;

import javax.jcr.RepositoryException;
import javax.security.auth.Subject;

import org.apache.jackrabbit.core.security.SecurityConstants;
import org.apache.jackrabbit.core.security.principal.AdminPrincipal;

public class SessionFactory {

    private final RepositoryContext context;

    public SessionFactory(RepositoryContext context) {
        this.context = context;
    }

    public SessionImpl createAdminSession(String workspace)
            throws RepositoryException {
        Principal admin = new AdminPrincipal(SecurityConstants.ADMIN_ID);
        Subject subject = new Subject(
                true, Collections.singleton(admin),
                Collections.emptySet(), Collections.emptySet());
        return context.getRepository().createSession(subject, workspace);
    }

}

Add a factory for creating new sessions


/*
 * Copyright (c) 2016 Qiscus.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qiscus.sdk.data.remote;

import com.schinizer.rxunfurl.RxUnfurl;
import com.schinizer.rxunfurl.model.PreviewData;

import rx.Observable;
import rx.schedulers.Schedulers;

/**
 * Created on : December 09, 2016
 * Author     : zetbaitsu
 * Name       : Zetra
 * GitHub     : https://github.com/zetbaitsu
 */
public enum QiscusUrlScraper {
    INSTANCE;

    private final RxUnfurl rxUnfurl;

    QiscusUrlScraper() {
        rxUnfurl = new RxUnfurl.Builder()
                .scheduler(Schedulers.io())
                .build();
    }

    public static QiscusUrlScraper getInstance() {
        return INSTANCE;
    }

    public Observable<PreviewData> generatePreviewData(String url) {
        return rxUnfurl.generatePreview(url);
    }
}

Add singleton for getting link preview data


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.cli.cmd;

import java.util.Map;

import org.jsimpledb.SessionMode;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.EnumNameParser;
import org.jsimpledb.parse.ParseContext;
import org.jsimpledb.parse.Parser;

@Command(modes = { SessionMode.KEY_VALUE, SessionMode.CORE_API, SessionMode.JSIMPLEDB })
public class SetSessionModeCommand extends AbstractCommand {

    public SetSessionModeCommand() {
        super("set-session-mode mode:mode");
    }

    @Override
    public String getHelpSummary() {
        return "Sets the CLI session mode";
    }

    @Override
    public String getHelpDetail() {
        return "Changes the current CLI session mode. Specify JSIMPLEDB, CORE_API, or KEY_VALUE.";
    }

    @Override
    protected Parser<?> getParser(String typeName) {
        return "mode".equals(typeName) ? new EnumNameParser<SessionMode>(SessionMode.class, false) : super.getParser(typeName);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final SessionMode mode = (SessionMode)params.get("mode");
        return new CliSession.Action() {
            @Override
            public void run(CliSession session) throws Exception {
                session.setMode(mode);
                session.getWriter().println("Set session mode to " + mode);
            }
        };
    }
}

Add new file accidentally forgotten in 7b297f45.


package se.kth.csc.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class BadNameException extends Exception {
    public BadNameException() {
    }

    public BadNameException(String message) {
        super(message);
    }

    public BadNameException(String message, Throwable cause) {
        super(message, cause);
    }

    public BadNameException(Throwable cause) {
        super(cause);
    }

    public BadNameException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Add new kind of exception


/*
 * Copyright 2013 Daniel Kurka
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.resources;

import com.google.gwt.resources.converter.DefCollectorVisitorTest;
import com.google.gwt.resources.converter.ElseNodeCreatorTest;
import com.google.gwt.resources.gss.ExternalClassesCollectorTest;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    DefCollectorVisitorTest.class, ElseNodeCreatorTest.class, ExternalClassesCollectorTest.class})
public class AllJUnitTests {
}

Add a testsuite for JUnit tests.


package fr.alecharp.picshare.repository;

import fr.alecharp.picshare.domain.Event;

import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author Adrien Lecharpentier
 */
@Singleton
public class EventRepository {
    private final Map<String, Event> eventStore = new HashMap<>();

    public Event save(Event event) {
        eventStore.put(event.id(), event);
        return event;
    }

    public void delete(String id) {
        eventStore.remove(id);
    }

    public Event findById(String id) {
        return eventStore.get(id);
    }
}

Create dumb repository for events


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.RegistryObject;

public class BlockRegistryObject<B extends Block, I extends Item> implements Supplier<B> {

	private final RegistryObject<B> block;
	private final RegistryObject<I> item;

	public BlockRegistryObject(RegistryObject<B> block, RegistryObject<I> item) {
		this.block = block;
		this.item = item;
	}

	@Override
	public B get() {
		return block.get();
	}

	public boolean hasItem() {
		return item.isPresent();
	}

	public I getItem() {
		return item.get();
	}

}

Add basic block registry object


/*
 * Zorbage: an Algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.storage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TrimmedStorage<T extends IndexedDataSource<T,U>, U>
	implements
		IndexedDataSource<T,U>
{
	private final IndexedDataSource<T,U> list;
	private final long first;
	private final long last;

	/**
	 *
	 * @param list
	 * @param first
	 * @param last
	 */
	public TrimmedStorage(IndexedDataSource<T,U> list, long first, long last) {
		if (first < 0 || last < 0 || first > last ||
				first >= list.size() || last >= list.size() ||
				(last - first) >= list.size())
			throw new IllegalArgumentException("poor definition of first/last/list size");
		this.list = list;
		this.first = first;
		this.last = last;
	}

	@Override
	public T duplicate() {
		// shallow copy
		// TODO: WTH? Why does this warning keep cropping up?
		return (T) new TrimmedStorage<>(list, first, last);
	}

	@Override
	public void set(long index, U value) {
		if (index < 0)
			throw new IllegalArgumentException("negative index exception");
		if (index > size())
			throw new IllegalArgumentException("out of bounds index exception");
		list.set(index+first, value);
	}

	@Override
	public void get(long index, U value) {
		if (index < 0)
			throw new IllegalArgumentException("negative index exception");
		if (index > size())
			throw new IllegalArgumentException("out of bounds index exception");
		list.get(index+first, value);
	}

	@Override
	public long size() {
		return last - first + 1;
	}

}

Add a list trimming storage container


package net.restlesscoder.sandbox.imagej;

import net.imagej.Dataset;
import net.imagej.ImageJ;
import net.imagej.ops.Ops;
import net.imagej.ops.special.computer.Computers;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.algorithm.neighborhood.DiamondShape;
import net.imglib2.algorithm.neighborhood.HyperSphereShape;
import net.imglib2.algorithm.neighborhood.RectangleShape;
import net.imglib2.algorithm.neighborhood.Shape;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.real.FloatType;

public class MedianBySlice {

	public static void main(final String... args) throws Exception {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		Dataset mriStack = ij.scifio().datasetIO().open("/Users/curtis/data/mri-stack.tif");
		ij.ui().show("Original", mriStack);

		final Img<UnsignedByteType> img = mriStack.typedImg(new UnsignedByteType());
		final Img<FloatType> in = ij.op().convert().float32(img);
		final Img<FloatType> out = ij.op().create().img(in);

		ij.ui().show("Rectangle", median(ij, in, out, new RectangleShape(5, false)));
		ij.ui().show("Circle", median(ij, in, out, new HyperSphereShape(5)));
		ij.ui().show("Diamond", median(ij, in, out, new DiamondShape(5)));
	}

	private static Object median(ImageJ ij, Img<FloatType> in, Img<FloatType> out,
		Shape shape)
	{
		UnaryComputerOp op = Computers.unary(ij.op(), Ops.Filter.Median.class, out, in, shape);
		return ij.op().slice(out, in, op, new int[] {0, 1});
	}
}

Add example of slicewise op with median filter


package com.github.pgasync.impl;

import com.github.pgasync.ConnectionPool;
import com.github.pgasync.SqlException;
import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import static com.github.pgasync.impl.DatabaseRule.createPoolBuilder;
import static org.junit.Assert.assertEquals;

public class AuthenticationTest {

    @Test
    public void shouldThrowExceptionOnInvalidCredentials() throws Exception {
        try (ConnectionPool pool = createPoolBuilder(1).password("_invalid_").build()) {
            BlockingQueue<Throwable> result = new ArrayBlockingQueue<>(1);
            pool.query("SELECT 1", System.out::println, result::add);
            SqlException sqle = (SqlException) result.poll(5, TimeUnit.SECONDS);
            assertEquals("28P01", sqle.getCode());
        }
    }

}

Add test for authentication failure


package com.antew.redditinpictures.library.image;

import android.content.res.Resources;

import com.antew.redditinpictures.library.R;

public class ThumbnailInfo {
    private int thumbnailSize    = 0;
    private int thumbnailSpacing = 0;

    private ThumbnailInfo(Resources resources) {
        thumbnailSize = resources.getDimensionPixelSize(R.dimen.image_thumbnail_size);
        thumbnailSpacing = resources.getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
    }

    public static ThumbnailInfo getThumbnailInfo(Resources resources) {
        return new ThumbnailInfo(resources);
    }

    public int getSize() {
        return thumbnailSize;
    }

    public void setSize(int thumbnailSize) {
        this.thumbnailSize = thumbnailSize;
    }

    public int getSpacing() {
        return thumbnailSpacing;
    }

    public void setSpacing(int thumbnailSpacing) {
        this.thumbnailSpacing = thumbnailSpacing;
    }

}

Add utility class for handling thumbnail size/spacing.


package com.gmail.nossr50.util.blockmeta;

public class PrimitiveChunkletStore implements ChunkletStore {
    private static final long serialVersionUID = -3453078050608607478L;

    /** X, Z, Y */
    protected boolean[][][] store = new boolean[16][16][64];

    @Override
    public boolean isTrue(int x, int y, int z) {
        return store[x][z][y];
    }

    @Override
    public void setTrue(int x, int y, int z) {
        store[x][z][y] = true;
    }

    @Override
    public void setFalse(int x, int y, int z) {
        store[x][z][y] = false;
    }

    @Override
    public boolean isEmpty() {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    if(store[x][z][y]) return false;
                }
            }
        }
        return true;
    }

    @Override
    public void copyFrom(ChunkletStore otherStore) {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    store[x][z][y] = otherStore.isTrue(x, y, z);
                }
            }
        }
    }
}

package com.gmail.nossr50.util.blockmeta;

public class PrimitiveChunkletStore implements ChunkletStore {
    private static final long serialVersionUID = -3453078050608607478L;

    /** X, Z, Y */
    private boolean[][][] store = new boolean[16][16][64];

    @Override
    public boolean isTrue(int x, int y, int z) {
        return store[x][z][y];
    }

    @Override
    public void setTrue(int x, int y, int z) {
        store[x][z][y] = true;
    }

    @Override
    public void setFalse(int x, int y, int z) {
        store[x][z][y] = false;
    }

    @Override
    public boolean isEmpty() {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    if(store[x][z][y]) return false;
                }
            }
        }
        return true;
    }

    @Override
    public void copyFrom(ChunkletStore otherStore) {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    store[x][z][y] = otherStore.isTrue(x, y, z);
                }
            }
        }
    }
}

Change this back to private


package me.alivecode.algs4;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class WeightedQuickUnionUF {
    private int[] parent;
    private int[] size;
    private int count;

    public WeightedQuickUnionUF(int n) {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        count = n;
    }

    public int count() {
        return count;
    }

    public void validate(int p) {
        int n = parent.length;
        if (p < 0 || p >= n) {
            throw new IndexOutOfBoundsException("Index " + p + " is not between 0 and " + (n - 1) + ".");
        }
    }

    public int find(int p) {
        validate(p);
        while (p != parent[p]) {
            parent[p] = parent[parent[p]];
            p = parent[p];
        }
        return p;
    }

    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }
        if (size[pRoot] <= size[qRoot]) {
            parent[pRoot] = qRoot;
            size[qRoot] += size[pRoot];
        } else {
            parent[qRoot] = pRoot;
            size[pRoot] += size[qRoot];
        }
        count--;
    }

    // Print the structure for testing reason.
    void printStructure(){
        int n = parent.length;
        StdOut.printf("%-8s", "site:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", i);
        }
        StdOut.printf("\n%-8s", "linked:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", parent[i]);
        }
        StdOut.printf("\n%-8s", "size:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", size[i]);
        }
        StdOut.println();
    }

    public static void main(String[] args) {
        int n = StdIn.readInt();
        WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n);
        uf.printStructure();
        while (!StdIn.isEmpty()) {
            int p = StdIn.readInt();
            int q = StdIn.readInt();
            if (uf.connected(p, q)) {
                continue;
            }
            uf.union(p, q);
            uf.printStructure();
            StdOut.println(p + " + " + q);
        }
        uf.printStructure();
        StdOut.println(uf.count() + " components.");
    }
}

Add weighted quick union union find.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.scijava.jupyterkernel;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.scijava.Context;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptService;

/**
 *
 * @author Hadrien Mary
 */
public class TestScriptEngine {

    public static void main(String[] args) throws ScriptException {
        // Only for testing purpose

        Context context = new Context();
        ScriptService scriptService = context.getService(ScriptService.class);
        ScriptLanguage scriptLanguage = scriptService.getLanguageByName("python");
        ScriptEngine engine = scriptLanguage.getScriptEngine();

        engine.eval("print('Hello'");

        context.dispose();
    }

}

Move test code to ... test


// 6. ZigZag Conversion
/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * (you may want to display this pattern in a fixed font for better legibility)
 *
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 *
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:
 *
 * string convert(string text, int nRows);
 *
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 *
 * Tags: String
 *
 * Author: Xinyue Zhang
 */

public class Solution {
    public String convert(String s, int nRows) {
        if (s == null || s.isEmpty()) {
            return s;
        }

        int length = s.length();
        if (length <= nRows || nRows <= 1) {
            return s;
        }

        StringBuilder sb = new StringBuilder();

        int step = 2 * (nRows - 1);
        int count = 0;

        for (int i = 0; i < nRows; i++){
            int interval = step - 2 * i;

            for (int j = i; j < length; j += step){
                   sb.append(s.charAt(j));
                count++;
                if (interval > 0 && interval < step
                    && j + interval < length
                    && count <  length) {
                    sb.append(s.charAt(j + interval));
                    count++;
                }
            }
        }
        return sb.toString();
    }

    public static void main(String args[]) {
        String s = "PAYPALISHIRING";
        Solution sol = new Solution();
        String res = sol.convert(s, 3);
        System.out.println(res);
    }
}

Add solution for 6. ZigZag Conversion


import java.io.*;
import java.util.*;

// https://www.hackerrank.com/challenges/countingsort3
public class CountingSort3 {

    private Integer[] getNumbersArray() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int lines = Integer.parseInt(br.readLine());
        Integer[] numbers = new Integer[lines];
        for (int i = 0; i < lines; i++) {
            String[] splitArray = br.readLine().split(" ");
            numbers[i] = Integer.parseInt(splitArray[0]);
        }
        br.close();
        return numbers;
    }

    private Map<Integer, Integer> getNumberFrequencyMap(Integer[] numbers) {
        int zero = 0;
        Map<Integer, Integer> numberFrequencyMap = new Hashtable<>();
        for (Integer number : numbers) {
            Integer frequency = numberFrequencyMap.getOrDefault(number, zero);
            frequency++;
            numberFrequencyMap.put(number, frequency);
        }
        return numberFrequencyMap;
    }

    private String getCounterNumberFrequencyString(Map<Integer, Integer> numberFrequencyMap) {
        String counterNumberFrequency = "";
        int zero = 0;
        int counter = 0;
        int limit = 100;
        for (int i = 0; i < limit; i++) {
            Integer frequency = numberFrequencyMap.getOrDefault(i, zero);
            counter += frequency;
            counterNumberFrequency += counter + " ";
        }
        return counterNumberFrequency.trim();
    }

    public static void main(String[] args) throws IOException {
        CountingSort3 countingSort3 = new CountingSort3();
        Integer[] numbers = countingSort3.getNumbersArray();
        Map<Integer, Integer> numberFrequencyMap = countingSort3.getNumberFrequencyMap(numbers);
        String counterNumberFrequency = countingSort3.getCounterNumberFrequencyString(numberFrequencyMap);
        System.out.println(counterNumberFrequency);
    }
}

Solve the counting sort 3 problem.


package com.github.aureliano.achmed.resources.exec;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.github.aureliano.achmed.exception.ExecResourceException;

public final class CommandFacade {

	private CommandFacade() {
		super();
	}

	public static int executeCommand(CommandBuilder command) {
		boolean verbose = command.getVerbose() != null ? command.getVerbose() : true;
		CommandRunner runner = new CommandRunner(command.getCommand(), command.getWorkingDir(), verbose);

		ExecutorService executor = Executors.newSingleThreadExecutor();
		Future<Integer> future = executor.submit(runner);

		try {
			return future.get(command.getTimeout(), TimeUnit.MILLISECONDS);
		} catch (ExecutionException|TimeoutException|InterruptedException ex) {
			throw new ExecResourceException(ex);
		}
	}
}

Create command facade to encapsulate command execution.


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

import javax.mail.MessagingException;

import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.Matcher;

/**
 * Matcher which can be used to set a quota for users Mailbox. This {@link Matcher} need to
 * recalculate the used space of users mailbox on every call. So use it with caution!
 *
 *
 */
public class MailboxQuotaFixed extends AbstractStorageQuota {

    /*
     * (non-Javadoc)
     * @see org.apache.james.transport.matchers.AbstractQuotaMatcher#getQuota(org.apache.mailet.MailAddress, org.apache.mailet.Mail)
     */
    protected long getQuota(MailAddress arg0, Mail arg1) throws MessagingException {
        return parseQuota(this.getCondition());
    }

}

Add concrete implementation for MailboxQuota matching. Thanks Barry. See JAMES-1196


package org.usfirst.frc.team3335.robot.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

public class GateUpFlapperDown extends CommandGroup {

	public GateUpFlapperDown() {
		addSequential(new GateControl(true));
		addSequential(new FlapperControl(true));
	}

}

Add gate up / flapper down command group.


package de.retest.recheck.printer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;

import de.retest.recheck.report.SuiteReplayResult;
import de.retest.recheck.report.TestReplayResult;

class SuiteReplayResultTest {

	@Test
	void isEmpty_should_return_true_if_no_differences() throws Exception {
		final TestReplayResult test = mock( TestReplayResult.class );
		when( test.isEmpty() ).thenReturn( true );

		final SuiteReplayResult cut = new SuiteReplayResult( "foo", 0, null, null, null );
		cut.addTest( test );

		assertThat( cut.isEmpty() ).isTrue();
	}

	@Test
	void isEmpty_should_return_false_if_differences() throws Exception {
		final TestReplayResult test = mock( TestReplayResult.class );
		when( test.isEmpty() ).thenReturn( false );

		final SuiteReplayResult cut = new SuiteReplayResult( "foo", 0, null, null, null );
		cut.addTest( test );

		assertThat( cut.isEmpty() ).isFalse();
	}
}

Add test for wrong behavior


/*
 * Copyright 2015 The Mashub Project
 *
 * The Mashub Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.beatsbucket.mashub.kitchen;

public interface History {
}

Add history interface to store histories of recipe and scheduling info.


package util;

import bot.Bender.BotMove;
import bot.Bender.DirectionType;

/**
 * Created by Daniel Hofmeister on 21.11.2015.
 */
public class BotmoveDirectionConverter {

    public static DirectionType getDirectionTypeFromBotMove(BotMove move) {
        DirectionType result = null;
        if (move.equals(BotMove.EAST)) {
            result = DirectionType.EAST;
        } else if (move.equals(BotMove.SOUTH)) {
            result = DirectionType.SOUTH;
        } else if (move.equals(BotMove.WEST)) {
            result = DirectionType.WEST;
        } else if (move.equals(BotMove.NORTH)) {
            result = DirectionType.NORTH;
        } else {
            throw new IllegalArgumentException("no such BotMove");
        }
        return result;
    }

    public static BotMove getBotMoveFromDirectionType(DirectionType dir) {
        BotMove result = null;

        if(dir.equals(DirectionType.EAST)) {
            result = BotMove.EAST;
        } else if(dir.equals(DirectionType.SOUTH)) {
            result = BotMove.SOUTH;
        } else if(dir.equals(DirectionType.WEST)) {
            result = BotMove.WEST;
        } else if(dir.equals(DirectionType.NORTH)) {
            result = BotMove.NORTH;
        } else {
            throw new IllegalArgumentException("no such DirectionType");
        }
        return result;
    }
}

Add util class with botmove/dir converter


//
// ScriptEditor.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the names of the ImageJDev.org developers nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.script.editor;

import imagej.command.Command;
import imagej.command.CommandService;
import imagej.io.IOService;
import imagej.platform.PlatformService;
import imagej.plugin.Menu;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import imagej.script.ScriptService;

/**
 * The Script Editor. As plugin.
 *
 * @author Johannes Schindelin
 */
@Plugin(menu = { @Menu(label = "File"), @Menu(label = "New"),
	@Menu(label = "Script...", accelerator = "open_bracket") })
public class ScriptEditor implements Command {

	@Parameter
	private ScriptService scriptService;

	@Parameter
	private PlatformService platformService;

	@Parameter
	private IOService ioService;

	@Parameter
	private CommandService commandService;

	@Override
	public void run() {
		new TextEditor(scriptService, platformService, ioService, commandService).setVisible(true);
	}

}

Make the Script Editor a proper plugin


package yuku.alkitabconverter.daily_verse;

import yuku.alkitab.yes2.io.RandomOutputStream;
import yuku.bintex.BintexWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DailyVerseProses {

	private static final String INPUT_FILE = System.getProperty("user.dir") + "/AlkitabConverter/file/daily_verse.csv";
	private static final String OUTPUT_FILE = System.getProperty("user.dir") + "/AlkitabConverter/file/daily_verse.bt";
	private List<Integer> aris = new ArrayList<>();
	private List<Integer> verseCounts = new ArrayList<>();

	public static void main(String[] args) {
		DailyVerseProses proses = new DailyVerseProses();
		proses.parse();
		try {
			File file = new File(OUTPUT_FILE);
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			raf.setLength(0);
			RandomOutputStream output = new RandomOutputStream(raf);
			BintexWriter bw = new BintexWriter(output);
			proses.write(bw);
			bw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("Process finished.");

	}
	private void parse() {
		try {
			Scanner scanner = new Scanner(new File(INPUT_FILE), "utf-8");

			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				String[] data = line.split(",");
				aris.add(Integer.parseInt(data[0]));
				verseCounts.add(Integer.parseInt(data[1]));
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	private void write(BintexWriter bw) {
		if (aris.size() == verseCounts.size()) {
			for (int i = 0; i < aris.size(); i++) {
				try {
					bw.writeInt(aris.get(i));
					bw.writeUint8(verseCounts.get(i));
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
	}

}

Add Daily verses writer (to bintex format).


package org.mapdb;

import org.junit.Test;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class HTreeMap_Expiration_Multithreaded {

    final long duration = 10 * 60 * 1000;

    static byte[] b = new byte[100];

    @Test public void expireUUID(){
        if(TT.shortTest())
            return;

        final long endTime = duration+System.currentTimeMillis();

        DB db = DBMaker.memoryDB().cacheSize(10000).make();
        final Map m = db.hashMapCreate("aa")
                .keySerializer(Serializer.UUID)
                .valueSerializer(Serializer.BYTE_ARRAY)
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .expireTick(0)
                .make();

        Exec.execNTimes(10, new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    Random r = new Random(1);
                    for (int i = 0; i < 2e5; i++) {
                        UUID u = new UUID(r.nextLong(), r.nextLong());
                        m.put(u, b);
                    }

                    while (System.currentTimeMillis()<endTime) {
                        r = new Random(1);
                        for (int i = 0; i < 1e5; i++) {
                            UUID u = new UUID(r.nextLong(), r.nextLong());
                            m.get(u);
                            m.put(u,b);
                        }
                        for (int i = (int) 1e5; i < 2e5; i++) {
                            UUID u = new UUID(r.nextLong(), r.nextLong());
                            m.get(u);
                        }
                    }
                }catch(Throwable e){
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}

Add test for multithreaded expiration


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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.json.spi.JsonProvider;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author	Heng Yuan
 */
public class BsonParserTest
{
	void testFile (String f1, String f2) throws IOException
	{
		File file1 = new File (f1.replace ('/', File.separatorChar));
		File file2 = new File (f2.replace ('/', File.separatorChar));

		StringWriter out1 = new StringWriter ();
		JsonParser p1 = new BsonParser (new FileInputStream (file1));
		TextJsonGenerator g1 = new TextJsonGenerator (out1);
		Utils.convert (p1, g1);
		p1.close ();
		g1.close ();

		StringWriter out2 = new StringWriter ();
		JsonProvider provider = new org.glassfish.json.JsonProviderImpl ();
		JsonParser p2 = provider.createParser (new FileInputStream (file2));
		JsonGenerator g2 = new TextJsonGenerator (out2);
		Utils.convert (p2, g2);
		p2.close ();
		g2.close ();

		Assert.assertEquals (out1.toString (), out2.toString ());
	}

	@Test
	public void test () throws IOException
	{
		// data1.bson has 0 in Document / Array length
		testFile ("../tests/data/data1.bson", "../tests/data/data3.json");
		// data2.bson has the correct length
		testFile ("../tests/data/data2.bson", "../tests/data/data3.json");
	}
}

Add a simple BSON unit test.


// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "
AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gwtexpui.safehtml.client;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;

public class SafeHtml_WikifyQuoteTest {
  private static final String B = "
";
  private static final String E = "
";

  private static String quote(String raw) {
    return B + raw + E;
  }

  @Test
  public void testQuote1() {
    final SafeHtml o = html("> I'm happy\n > with quotes!\n\nSee above.");
    final SafeHtml n = o.wikify();
    assertNotSame(o, n);
    assertEquals(
        quote("I'm happy\nwith quotes!")
        + "
See above.
",
      n.asString());
  }

  @Test
  public void testQuote2() {
    final SafeHtml o = html("See this said:\n\n > a quoted\n > string block\n\nOK?");
    final SafeHtml n = o.wikify();
    assertNotSame(o, n);
    assertEquals(
        "
See this said:
"
        + quote("a quoted\nstring block")
        + "
OK?
",
      n.asString());
  }

  @Test
  public void testNestedQuotes1() {
    final SafeHtml o = html(" > > prior\n > \n > next\n");
    final SafeHtml n = o.wikify();
    assertEquals(
      quote(quote("prior") + "next\n"),
      n.asString());
  }

  private static SafeHtml html(String text) {
    return new SafeHtmlBuilder().append(text).toSafeHtml();
  }
}

Add test for reply quoting in wikify()


/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.

The Node class is defined as follows:*/

/**
 * Hackerrank: Trees: Is This a Binary Search Tree?
 *
 * @see Trees: Is This a Binary Search Tree?
 */
class Node {
    int data;
    Node left;
    Node right;

    /**
     * Check whether the current binary tree is a binary search tree
     *
     * @param root Root node of the binary tree
     * @return true if it is a binary search tree and false otherwise
     */
    boolean checkBST(Node root) {
        if (root == null) {
            return true;
        }
        if ((root.left != null) && (root.left.data >= root.data)) {
            return false;
        }
        if ((root.right != null) && (root.right.data <= root.data)) {
            return false;
        }
        return checkBST(root.right) && checkBST(root.left) && checkLeft(root.data, root.left) && checkRight(root.data, root.right);
    }

    /**
     * Checking the left subtree if there are no values greater than the root value max
     *
     * @param max  value of the root of the current subtree
     * @param node current node
     * @return true if the values in the subtree are smaller than the max value and false otherwise
     */
    boolean checkLeft(int max, Node node) {
        if (node == null) {
            return true;
        }
        if (node.data < max) {
            return checkLeft(max, node.left) && checkLeft(max, node.right);
        } else {
            return false;
        }
    }

    /**
     * Checking the right subtree if there are no values smaller than the root value min
     *
     * @param min  value of the root of the current subtree
     * @param node current node
     * @return true if the values in the subtree are greater than the min value and false otherwise
     */
    boolean checkRight(int min, Node node) {
        if (node == null) {
            return true;
        }
        if (node.data > min) {
            return checkRight(min, node.left) && checkRight(min, node.right);
        } else {
            return false;
        }
    }

}

Check binary tree whether it is a binary search tree


package com.github.aureliano.achmed.os.pkg;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public interface IPackageManager {

	public abstract CommandResponse install();

	public abstract CommandResponse uninstall();

	public abstract String latest();

	public abstract void setPackageProperties(PackageProperties properties);

	public abstract PackageProperties getPackageProperties();
}

Create interface to package manager implementations.


/*
 * Copyright 2012-2014 TORCH GmbH
 *
 * This file is part of Graylog2.
 *
 * Graylog2 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Graylog2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Graylog2.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.graylog2.gelfclient.transport;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.graylog2.gelfclient.Configuration;
import org.graylog2.gelfclient.GelfMessage;
import org.graylog2.gelfclient.GelfMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Bernd Ahlers <bernd@torch.sh>
 */
public class GelfTcpTransport implements GelfTransport {
    private final Logger LOG = LoggerFactory.getLogger(GelfTcpTransport.class);
    private final Configuration config;
    private final GelfMessageEncoder encoder;

    private final EventLoopGroup workerGroup;
    private final Bootstrap bootstrap;
    private final GelfTcpChannelHandler handler;
    private final ChannelFuture channelFuture;

    public GelfTcpTransport(Configuration config, GelfMessageEncoder encoder) {
        this.config = config;
        this.encoder = encoder;

        this.workerGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.handler = new GelfTcpChannelHandler(config, encoder);

        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(config.getHost(), config.getPort())
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(handler);
                    }
                });

        this.channelFuture = bootstrap.connect();

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    LOG.debug("Connected!");
                } else {
                    LOG.error("Connection failed", future.cause());
                    future.cause().printStackTrace();
                }
            }
        });
    }

    @Override
    public void send(GelfMessage message) {
        handler.send(message);
    }

    @Override
    public void stop() {
        handler.stop();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void sync() throws InterruptedException {
        channelFuture.sync();
    }
}

Add GELF TCP transport class.


package de.fau.amos.virtualledger.android.dagger.module;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import de.fau.amos.virtualledger.android.api.savings.SavingsProvider;
import de.fau.amos.virtualledger.android.data.SavingsAccountsDataManager;

@Module(includes = {SavingsModule.class})
public class SavingsAccountsDataModule {

    @Provides
    @Singleton
    SavingsAccountsDataManager provideBankingDataManager(final SavingsProvider savingsProvider) {
        return new SavingsAccountsDataManager(savingsProvider);
    }
}

Add dagger module for SavingsAccountsDataManager


/*
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.gnd.workers;

import androidx.lifecycle.LiveData;
import androidx.work.Constraints;
import androidx.work.ExistingWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

/** Enqueues file download work to be done in the background. */
public class FileDownloadWorkManager {
  private final WorkManager workManager;

  public FileDownloadWorkManager() {
    this.workManager = WorkManager.getInstance();
  }

  /**
   * Enqueues a worker that downloads files when a network connection is available, returning live
   * data that contains {@link WorkInfo}. Observe the returned live data to do something with the
   * worker's result.
   */
  public LiveData<WorkInfo> enqueueFileDownloadWorker(String url, String filename) {
    return getWorkManager()
        .getWorkInfoByIdLiveData(enqueueFileDownloadWorkerInternal(url, filename).getId());
  }

  private OneTimeWorkRequest enqueueFileDownloadWorkerInternal(String url, String filename) {
    OneTimeWorkRequest request = buildWorkerRequest(url, filename);

    getWorkManager()
        .enqueueUniqueWork(FileDownloadWorker.class.getName(), ExistingWorkPolicy.APPEND, request);

    // Return the request in order to fetch the {@link WorkInfo} for the request using the request id.
    return request;
  }

  private WorkManager getWorkManager() {
    return workManager;
  }

  private Constraints getWorkerConstraints() {
    return new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
  }

  private OneTimeWorkRequest buildWorkerRequest(String url, String filename) {
    return new OneTimeWorkRequest.Builder(FileDownloadWorker.class)
        .setConstraints(getWorkerConstraints())
        .setInputData(FileDownloadWorker.createInputData(url, filename))
        .build();
  }
}

Add file download work manager


public class Solution {

    public boolean judgeSquareSum(int c) {

        int low = 0;
        int high = (int) Math.sqrt(c);

        while (low <= high) {

            int sum = low * low + high * high;

            if (sum == c) {
                return true;
            }

            if (sum < c) {
                low++;
            } else if (sum > c) {
                high--;
            }

        }

        return false;

    }

}

Create : 633 Sum of Square Numbers


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        String a;
        float b, c;

        a = in.readLine();
        b = Float.parseFloat(in.readLine());
        c = Float.parseFloat(in.readLine());

        System.out.printf("TOTAL = R$ %.2f\n", b + (c * 0.15));
    }
}

Solve Salary with Bonus in java


package org.cyclops.cyclopscore.helper;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Helper methods for collections.
 * @author rubensworks
 */
public final class CollectionHelpers {

    /**
     * Add the given key value pair in a map structure where multiple values for a key can exist.
     * This will take care of making a new list into the map when one did not exist before.
     * @param map The map.
     * @param key The key.
     * @param value The value.
     * @param <K> The key type.
     * @param <V> The value type.
     */
    public static <K, V> void addToMapList(Map<K, List<V>> map, K key, V value) {
        if(!map.containsKey(key)) {
            map.put(key, Lists.<V>newLinkedList());
        }
        map.get(key).add(value);
    }

    /**
     * Add the given key value pair in a map structure where multiple values for a key can exist.
     * This will take care of making a new set into the map when one did not exist before.
     * @param map The map.
     * @param key The key.
     * @param value The value.
     * @param <K> The key type.
     * @param <V> The value type.
     */
    public static <K, V> void addToMapSet(Map<K, Set<V>> map, K key, V value) {
        if(!map.containsKey(key)) {
            map.put(key, Sets.<V>newHashSet());
        }
        map.get(key).add(value);
    }

}

Add collection helper methods Adds convenience methods for insertion into Map<?, List<?>> and Map<?, Set<?>>.


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem22;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedListTest {
}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem22;

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedListTest {

  private ReverseLinkedList reverseLinkedList;

  @Before public void setUp() {
    reverseLinkedList = new ReverseLinkedList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullElements() {
    reverseLinkedList.reverse(null);
  }

  @Test public void shouldAcceptLinkedListWithJustOneElement() {
    ListNode<Integer> head = new ListNode<Integer>(1);

    assertEquals(head, reverseLinkedList.reverse(head));
  }

  @Test public void shouldReverseLinkedList() {
    ListNode<Integer> head = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    ListNode<Integer> n3 = new ListNode<Integer>(3);
    ListNode<Integer> n4 = new ListNode<Integer>(4);
    head.setNext(n2);
    n2.setNext(n3);

    ListNode reversedList = reverseLinkedList.reverse(head);

    assertEquals(n4, reversedList);
  }
}

Add some tests to problem 22


package parser.model;

import java.util.ArrayList;

public class FindBubbles {

	private Graph graph;

	public FindBubbles(Graph graph) {
		this.graph = graph;
	}

	public void calculateFlows() {
		sendFlow();
	}

	private void sendFlow() {
		double flowStart = (double)graph.getSize();
		graph.getRoot().setFlow(flowStart);

		for (Node node : graph.getNodes()) {
			System.out.println(node);
			ArrayList<Edge> outEdges = node.getOut();
			double remainingFlow = node.getFlow();

			for (int i = 0; i < outEdges.size(); i++) {
				Node target = outEdges.get(i).getTarget();

				if (i == node.getOut().size() - 1) {
					target.addFlow(remainingFlow);
				} else {
					double random = Math.random();
					double flowToAdd = random * remainingFlow;
					remainingFlow -= flowToAdd;
					target.addFlow(flowToAdd);
				}
			}
		}
	}
}

Send flow through graph to easily detect what bubbles there are


package com.easternedgerobotics.rov.io;

import com.easternedgerobotics.rov.event.EventPublisher;
import com.easternedgerobotics.rov.value.ThrusterValue;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Thruster {

    private static final int BYTE_SIZE = 8;

    private static final byte WRITE_ADDRESS = 0x00;

    private static final byte READ_ADDRESS = 0x02;

    private static final int READ_BUFFER_SIZE = 9;

    private static final int VOLTAGE_INDEX = 0;

    private static final int CURRENT_INDEX = 2;

    private static final float CURRENT_SCALAR = 5.0f * 6.45f / 65536.0f;

    private static final int TEMPERATURE_INDEX = 6;

    private static final float TEMPERATURE_OFFSET = 32767;

    private static final float TEMPERATURE_SCALAR =  5.0f * 14.706f / 65535.0f;

    private final byte[] zeroBuffer = new byte[] {0x00, 0x00};

    private Device device;

    private ThrusterValue thrusterValue;

    private EventPublisher eventPublisher;

    public Thruster(final EventPublisher event, final ThrusterValue thruster, final Device dev) {

        device = dev;

        eventPublisher = event;

        thrusterValue = thruster;

        eventPublisher.valuesOfType(ThrusterValue.class).subscribe(t -> {
            if (thrusterValue.getName().equals(t.getName())) {
                thrusterValue = t;
            }
        });
    }

    public final void write() throws IOException {
        final short speed = (short) (thrusterValue.getSpeed() * Short.MAX_VALUE);
        final byte[] writeBuffer = ByteBuffer.allocate(2).putShort(speed).array();
        device.write(WRITE_ADDRESS, zeroBuffer);
        device.write(WRITE_ADDRESS, writeBuffer);
    }

    public final void writeZero() throws IOException {
        device.write(WRITE_ADDRESS, zeroBuffer);
    }

    public final void read() throws IOException {
        final byte[] readBuffer = device.read(READ_ADDRESS, READ_BUFFER_SIZE);

        final float voltage = parseShort(readBuffer, VOLTAGE_INDEX);
        final float current = parseShort(readBuffer, CURRENT_INDEX) * CURRENT_SCALAR;
        final float temperature = (parseShort(readBuffer, TEMPERATURE_INDEX) - TEMPERATURE_OFFSET) * TEMPERATURE_SCALAR;

        eventPublisher.emit(ThrusterValue.create(
            thrusterValue.getName(),
            thrusterValue.getSpeed(),
            voltage,
            current,
            temperature
        ));
    }

    // reads a short from two consecutive bytes.
    // MSB located at offset.
    // LSB located at offset + 1.
    private short parseShort(final byte[] bytes, final int offset) {
        return (short) (((bytes[offset]) << BYTE_SIZE) | bytes[offset + 1]);
    }
}

Send speed commands and read status of a thruster


// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.events;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class SupplierDeserializer implements JsonDeserializer<Supplier<?>> {

  @Override
  public Supplier<?> deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {
    checkArgument(typeOfT instanceof ParameterizedType);
    ParameterizedType parameterizedType = (ParameterizedType) typeOfT;
    if (parameterizedType.getActualTypeArguments().length != 1) {
      throw new JsonParseException(
          "Expected one parameter type in Supplier interface.");
    }
    Type supplierOf = parameterizedType.getActualTypeArguments()[0];
    return Suppliers.ofInstance(context.deserialize(json, supplierOf));
  }
}

Add custom JSON deserializer for Supplier


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.validate;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.List;

import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toList;

@DisplayName("ValidatorFactoryLoader should")
class ValidatorFactoryLoaderTest {

    @Test
    @DisplayName("load common options")
    void loadCommon() {
        List<ValidatorFactory> implementations = ValidatorFactoryLoader.INSTANCE
                .implementations()
                .collect(toList());
        assertThat(implementations).hasSize(1);
        assertThat(implementations.get(0)).isInstanceOf(CommonValidatorFactory.class);
    }
}

Add a test for service loading.


package com.kevlindev.tvm.display;

public class FontInfo {
	public String name;
	public int columns;
	public int rows;
	public int defaultScale;
	public int offset;

	public FontInfo(String name, int columns, int rows) {
		this(name, columns, rows, 1, 0);
	}

	public FontInfo(String name, int columns, int rows, int defaultScale) {
		this(name, columns, rows, defaultScale, 0);
	}

	public FontInfo(String name, int columns, int rows, int defaultScale, int offset) {
		this.name = name;
		this.columns = columns;
		this.rows = rows;
		this.defaultScale = defaultScale;
		this.offset = offset;
	}
}

Create a custom class to contain info about each needed. This info is used to decompose the tiles and to account for any offsets that need to be applied to get the right tile for a given ascii code.


/*
 * Copyright 2018 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.perspicuus.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class CatalogApplication extends Application {

    public CatalogApplication() {
    }
}

Add jax-rs app file, as newer versions of swarm will no longer infer it.


package de.retest.recheck.ui.diff;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;

import org.junit.Before;
import org.junit.Test;

import de.retest.recheck.image.ImageDifference;
import de.retest.recheck.image.ImageDifferenceCalculator;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.RootElement;
import de.retest.recheck.ui.descriptors.ScreenshotAttributeDifference;
import de.retest.recheck.ui.image.Screenshot;

public class RootElementDifferenceTest {

	RootElementDifference cut;

	@Before
	public void setup() {
		final Screenshot expected = mock( Screenshot.class );
		final Screenshot actual = mock( Screenshot.class );
		final AttributeDifference screenshotDiff = new ScreenshotAttributeDifference( expected, actual,
				TestImageDifferenceCalculator.class.getName(), 0.99 );
		final AttributesDifference attributesDiff =
				new AttributesDifference( Collections.singletonList( screenshotDiff ) );
		final Element eleme = mock( Element.class );
		when( eleme.getIdentifyingAttributes() ).thenReturn( mock( IdentifyingAttributes.class ) );
		final ElementDifference elementDifference = new ElementDifference( eleme, attributesDiff,
				mock( IdentifyingAttributesDifference.class ), expected, actual, new ArrayList<>() );
		cut = new RootElementDifference( elementDifference, mock( RootElement.class ), mock( RootElement.class ) );
	}

	@Test
	public void getScreenshotDifference_should_find_difference() {
		assertThat( cut.getScreenshotDifference() ).isNotNull();
	}

	@Test
	public void getExpectedScreenshot_should_recalc_diff() throws Exception {
		// image2Screenshot will return null instead of mocked screenshot.
		assertThat( cut.getExpectedScreenshot() ).isNull();
	}

	static class TestImageDifferenceCalculator implements ImageDifferenceCalculator {

		@Override
		public ImageDifference compare( final BufferedImage img1, final BufferedImage img2 ) {
			return mock( ImageDifference.class );
		}

		@Override
		public ImageDifference compare( final Screenshot expected, final Screenshot actual ) {
			return mock( ImageDifference.class );
		}

	}

}

Move tests for RootElementDifference from review


/*
 * Copyright 2017, Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.instrumentation.internal;

import com.google.instrumentation.common.Clock;
import com.google.instrumentation.common.Timestamp;

/**
 * A {@link Clock} that uses {@link System#currentTimeMillis()} and {@link System#nanoTime()}.
 */
public final class MillisClock extends Clock {
  private static final MillisClock INSTANCE = new MillisClock();

  private MillisClock() {}

  /**
   * Returns a {@code MillisClock}.
   *
   * @return a {@code MillisClock}.
   */
  public static MillisClock getInstance() {
    return INSTANCE;
  }

  @Override
  public Timestamp now() {
    return Timestamp.fromMillis(System.currentTimeMillis());
  }

  @Override
  public long nowNanos() {
    return System.nanoTime();
  }
}

Add a clock that uses System.currentTimeMillis() and System.nanoTime().


package com.proofpoint.http.client.testing;

import com.google.common.base.Function;
import com.proofpoint.http.client.AsyncHttpClient.AsyncHttpResponseFuture;
import com.proofpoint.http.client.Request;
import com.proofpoint.http.client.Response;
import com.proofpoint.http.client.ResponseHandler;
import org.testng.annotations.Test;

import java.net.URI;

import static com.proofpoint.http.client.Request.Builder.prepareGet;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.fail;

public class TestTestingHttpClient
{
    @Test
    public void testExceptionFromProcessor()
            throws Exception
    {
        Request request = prepareGet()
                .setUri(URI.create("http://example.org"))
                .build();

        final RuntimeException expectedException = new RuntimeException("test exception");

        AsyncHttpResponseFuture<String,CapturedException> future = new TestingHttpClient(
                new Function<Request, Response>()
                {
                    @Override
                    public Response apply(Request input)
                    {
                        throw expectedException;
                    }
                }).executeAsync(request, new CaptureExceptionResponseHandler());

        try {
            future.checkedGet();
            fail("expected exception");
        }
        catch (CapturedException e) {
            assertSame(e.getCause(), expectedException);
        }
    }

    @Test
    public void testExceptionFromProcessorWithDefaultingHandler()
            throws Exception
    {
        Request request = prepareGet()
                .setUri(URI.create("http://example.org"))
                .build();

        final RuntimeException testingException = new RuntimeException("test exception");
        final Object expectedResponse = new Object();

        AsyncHttpResponseFuture<Object,RuntimeException> future = new TestingHttpClient(
                new Function<Request, Response>()
                {
                    @Override
                    public Response apply(Request input)
                    {
                        throw testingException;
                    }
                }).executeAsync(request, new DefaultExceptionResponseHandler(testingException, expectedResponse));

        assertSame(future.checkedGet(), expectedResponse);
    }

    public static class CaptureExceptionResponseHandler implements ResponseHandler<String, CapturedException>
    {
        @Override
        public String handleException(Request request, Exception exception)
                throws CapturedException
        {
            throw new CapturedException(exception);
        }

        @Override
        public String handle(Request request, Response response)
                throws CapturedException
        {
            throw new UnsupportedOperationException();
        }

    }

    protected static class CapturedException extends Exception
    {
        public CapturedException(Exception exception)
        {
            super(exception);
        }
    }

    private class DefaultExceptionResponseHandler implements ResponseHandler<Object, RuntimeException>
    {
        private final RuntimeException expectedException;
        private final Object response;

        public DefaultExceptionResponseHandler(RuntimeException expectedException, Object response)
        {
            this.expectedException = expectedException;
            this.response = response;
        }

        @Override
        public Object handleException(Request request, Exception exception)
        {
            assertEquals(exception, expectedException);
            return response;
        }

        @Override
        public Object handle(Request request, Response response)
        {
            throw new UnsupportedOperationException();
        }
    }
}

Test exception handling behavior of TestingHttpClient


/*
 * MIT License
 *
 * Copyright (c) 2018 Ilia Rogozhin (@smallcreep) <ilia.rogozhin@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.github.smallcreep.cucumber.seeds.context;

import com.github.smallcreep.cucumber.seeds.Context;
import java.util.Properties;
import org.cactoos.map.MapEntry;
import org.cactoos.map.MapOf;

/**
 * Context from properties.
 * @since 0.1.1
 */
public final class CxProperties implements Context {

    /**
     * Origin context.
     */
    private final Context origin;

    /**
     * Ctor.
     * @param properties Properties
     */
    CxProperties(final Properties properties) {
        this(
            new CxSimple(
                new MapOf<String, Object>(
                    (name) -> new MapEntry<>(
                        name,
                        properties.getProperty(name)
                    ),
                    properties.stringPropertyNames()
                )
            )
        );
    }

    /**
     * Ctor.
     * @param origin Origin context
     */
    private CxProperties(final Context origin) {
        this.origin = origin;
    }

    @Override
    public Object value(final String key) {
        return this.origin.value(key);
    }

    @Override
    public void add(final String key, final Object value) {
        throw new UnsupportedOperationException(
            "Can not add value to properties context"
        );
    }

    @Override
    public boolean contains(final String key) {
        return this.origin.contains(key);
    }
}

Add Context which read properties file


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

@Version("1.3.1")
package org.apache.sling.commons.classloader;

import org.osgi.annotation.versioning.Version;

Update to parent pom 27


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class SelectValuesUpsidedown {
	public static void main(String[] args) throws SQLException{
		Connection con=DBInfo2.getConnection();
		String query="SELECT * FROM login";

		PreparedStatement stmt=con.prepareStatement(query);
		ResultSet rs=stmt.executeQuery();

		// getting meta data
		System.out.println("Getting Meta Data\n---------------------------------------");
		ResultSetMetaData rsmd=rs.getMetaData();
		int count=rsmd.getColumnCount();
		System.out.println("Column count : "+count);
		for(int i=1;i<=count;i++){
			System.out.println(rsmd.getColumnName(i)+":::"+rsmd.getColumnDisplaySize(i)+":::"+rsmd.getColumnTypeName(i));
		}
		System.out.println("---------------------------------------\nGetting Records Data\n---------------------------------------");

		// getting records data
		rs.afterLast();
		while(rs.previous()){
			System.out.println(rs.getInt(1)+":::"+rs.getString(2)+":::"+rs.getString(3)+":::"+rs.getString(4));
		}
		rs.close();
		con.close();
		stmt.close();
	}
}

Select querry implementation with meta data upsidedown


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

package org.apache.ode.axis2.util;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionManager;

public class JBossFactory {

    public static final String JNDI_LOOKUP_PATH = "java:/TransactionManager";

    /* Public no-arg contructor is required */
    public JBossFactory() {
    }

    public TransactionManager getTransactionManager() {
        InitialContext ctx;
        try {
           ctx = new InitialContext();
        } catch (NamingException except) {
            throw new RuntimeException( "Can't create InitialContext", except);
        }
        try {
            return (TransactionManager) ctx.lookup(JNDI_LOOKUP_PATH);
        } catch (NamingException except) {
            throw new RuntimeException( "Error while looking up TransactionManager at " + JNDI_LOOKUP_PATH, except);
        }
    }

}

Add JBoss transaction manager factory


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

import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;

public class XXHash32OverflowTest {

    /**
     * This test hits an edge case where a very large number of bytes is added to the incremental
     * hash. The data is constructed so that an integer counter of unprocessed bytes will
     * overflow. If this is not handled correctly then the code throws an exception when it
     * copies more data into the unprocessed bytes array.
     */
    @Test
    public void testIncrementalHashWithUnprocessedBytesAndHugeLengthArray() {
        // Assert the test precondition that a large array added to unprocessed bytes
        // will overflow an integer counter. We use the smallest hugeLength possible
        // as some VMs cannot allocate maximum length arrays.
        final int bufferSize = 16;
        final int unprocessedSize = bufferSize - 1;
        final int hugeLength = Integer.MAX_VALUE - (unprocessedSize - 1);
        Assert.assertTrue("This should overflow to negative", unprocessedSize + hugeLength < bufferSize);

        // Check the test can be run
        byte[] bytes = null;
        try {
            bytes = new byte[hugeLength];
        } catch (OutOfMemoryError ignore) {
            // Some VMs cannot allocate an array this large.
            // Some test environments may not have enough available memory for this.
        }
        Assume.assumeTrue("Cannot allocate array of length " + hugeLength, bytes != null);

        final XXHash32 inc = new XXHash32();
        // Add bytes that should be unprocessed
        inc.update(bytes, 0, unprocessedSize);
        // Add a huge number of bytes to overflow an integer counter of unprocessed bytes.
        inc.update(bytes, 0, hugeLength);
    }
}

Test XXHash32 with huge length array added to unprocessed bytes.


package com.amalgam.app;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.os.Build;

/**
 * @author KeithYokoma
 */
@SuppressWarnings("unused")
public final class FragmentUtils {
    private FragmentUtils() {
        throw new AssertionError();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void invalidateOptionsMenu(android.app.Fragment fragment) {
        fragment.getActivity().invalidateOptionsMenu();
    }

    public static void supportInvalidateOptionsMenu(android.support.v4.app.Fragment fragment) {
        fragment.getActivity().supportInvalidateOptionsMenu();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static ContentResolver getContentResolver(android.app.Fragment fragment) {
        return fragment.getActivity().getContentResolver();
    }

    public static ContentResolver getContentResolver(android.support.v4.app.Fragment fragment) {
        return fragment.getActivity().getContentResolver();
    }
}

Add utility for the fragment


/*
 * digitalpetri OPC-UA SDK
 *
 * Copyright (C) 2015 Kevin Herron
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.digitalpetri.opcua.sdk.server.identity;

import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;

public class AnonymousIdentityValidator extends IdentityValidator {

    @Override
    public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
                                         SecureChannel channel, Session session) throws UaException {
        return new Object();
    }

}

/*
 * digitalpetri OPC-UA SDK
 *
 * Copyright (C) 2015 Kevin Herron
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.digitalpetri.opcua.sdk.server.identity;

import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;

public class AnonymousIdentityValidator extends IdentityValidator {

    public static final Object ANONYMOUS_IDENTITY_OBJECT = new Object();

    @Override
    public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
                                         SecureChannel channel, Session session) throws UaException {
        return ANONYMOUS_IDENTITY_OBJECT;
    }

}

Use a singleton object for anonymous identities