package io.orchestrate.client.integration;

import static org.junit.Assert.assertNotNull;
import io.orchestrate.client.KvList;
import io.orchestrate.client.KvListOperation;
import io.orchestrate.client.OrchestrateFuture;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.junit.Test;

public class ListTest extends OperationTest {

    private <T> KvList<T> result(final KvListOperation<T> listOp)
            throws InterruptedException, ExecutionException, TimeoutException {
        final OrchestrateFuture<KvList<T>> future = client().execute(listOp);
        return future.get(3, TimeUnit.SECONDS);
    }

    @Test
    public void basicList()
            throws InterruptedException, ExecutionException, TimeoutException {
        final KvListOperation<String> listOp = new KvListOperation<String>(TEST_COLLECTION, String.class);
        final KvList<String> results = result(listOp);
        assertNotNull(results);
    }

    @Test
    public void listWithAfterKey()
            throws InterruptedException, ExecutionException, TimeoutException {
        final KvListOperation<String> listOp = new KvListOperation<String>(TEST_COLLECTION, "someKey", 3,
                false, String.class);
        final KvList<String> results = result(listOp);
        assertNotNull(results);
    }

    @Test
    public void listWithStartKey()
            throws InterruptedException, ExecutionException, TimeoutException {
        final KvListOperation<String> listOp = new KvListOperation<String>(TEST_COLLECTION, "someKey", 3,
                true, String.class);
        final KvList<String> results = result(listOp);
        assertNotNull(results);
    }

}

Add integration test for list operations


package net.sf.jabref.model.entry;

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

public class CanonicalBibEntryTest {

    /**
     * Simple test for the canonical format
     */
    @Test
    public void canonicalRepresentation() {
        BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE);
        e.setField(BibEntry.KEY_FIELD, "key");
        e.setField("author", "abc");
        e.setField("title", "def");
        e.setField("journal", "hij");
        String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e);
        Assert.assertEquals("@article{key,\n  author = {abc},\n  journal = {hij},\n  title = {def}\n}",
                canonicalRepresentation);
    }

}

package net.sf.jabref.model.entry;

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

public class CanonicalBibEntryTest {

    @Test
    public void simpleCanonicalRepresentation() {
        BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE);
        e.setField(BibEntry.KEY_FIELD, "key");
        e.setField("author", "abc");
        e.setField("title", "def");
        e.setField("journal", "hij");
        String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e);
        Assert.assertEquals("@article{key,\n  author = {abc},\n  journal = {hij},\n  title = {def}\n}",
                canonicalRepresentation);
    }

    @Test
    public void canonicalRepresentationWithNewlines() {
        BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE);
        e.setField(BibEntry.KEY_FIELD, "key");
        e.setField("abstract", "line 1\nline 2");
        String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e);
        Assert.assertEquals("@article{key,\n  abstract = {line 1\nline 2}\n}", canonicalRepresentation);
    }

}

Add multiline test for canonical representation


package uk.org.taverna.scufl2.api;

import org.junit.Test;

public class TestExampleWorkflow extends ExampleWorkflow {

	@Test
	public void makeflowBundle() throws Exception {
		makeWorkflowBundle();
	}

}

Make sure ExampleWorkflow can be created


package nl.hsac.fitnesse.junit;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Runs JUnit tests from the command line, with RunListeners attached.
 */
public class JUnitConsoleRunner {
    protected List<RunListener> getListeners() {
        return Arrays.asList(new JUnitXMLPerPageListener(), new ProgressLoggerListener());
    }

    protected List<Class> getTestClasses(String[] args) {
        List<Class> classes = new ArrayList<>();
        for (String arg : args) {
            try {
                classes.add(Class.forName(arg));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Unable to create instance of: " + arg);
            }
        }
        return classes;
    }

    public Result runTests(String... args) {
        JUnitCore core = new JUnitCore();
        for (RunListener r : getListeners()) {
            core.addListener(r);
        }
        List<Class> classes = getTestClasses(args);
        return core.run(classes.toArray(new Class[classes.size()]));
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("No test class names provided as argument.");
            System.exit(-1);
        }
        Result r = new JUnitConsoleRunner().runTests(args);
        System.exit(r.wasSuccessful()? 0 : 1);
    }
}

Add class to allow jUnit tests to be run directly from command line, with our RunListeners attached


/* This file is part of VoltDB.
 * Copyright (C) 2008-2014 VoltDB Inc.
 *
 * 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 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.voltdb.regressionsuites;

import java.io.IOException;

import org.voltdb.VoltTable;
import org.voltdb.VoltType;

import junit.framework.Test;

import org.voltdb.BackendTarget;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.client.Client;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.VoltProjectBuilder;

public class TestShutdown extends RegressionSuite
{
    public TestShutdown(String name) {
        super(name);
    }

    static VoltProjectBuilder getBuilderForTest() throws IOException {
        VoltProjectBuilder builder = new VoltProjectBuilder();
        builder.addLiteralSchema("");
        return builder;
    }

    public void testShutdown() throws Exception {
        final Client client = getClient();
        // sleep a little so that we have time for the IPC backend to actually be running
        // so it can screw us on empty results
        Thread.sleep(1000);

        boolean lostConnect = false;
        try {
            client.callProcedure("@Shutdown").getResults();
        }
        catch (ProcCallException pce) {
            lostConnect = pce.getMessage().contains("was lost before a response was received");
        }
        assertTrue(lostConnect);
        while (!((LocalCluster)getServerConfig()).areAllNonLocalProcessesDead()) {
            Thread.sleep(500);
        }
    }

    static public Test suite() throws IOException {
        // the suite made here will all be using the tests from this class
        MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestShutdown.class);

        // build up a project builder for the workload
        VoltProjectBuilder project = getBuilderForTest();
        boolean success;
        LocalCluster config = new LocalCluster("decimal-default.jar", 4, 5, 3, BackendTarget.NATIVE_EE_JNI);
        config.setHasLocalServer(false);
        success = config.compile(project);
        assertTrue(success);

        // add this config to the set of tests to run
        builder.addServerConfig(config);

        return builder;
    }
}

Add junit test for @Shutdown


/*
 * (C) Copyright 2019 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Edge Dev.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class EdgeDevTest {

    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        WebDriverManager.edgedriver().setup();
    }

    @Before
    public void setupTest() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setBinary(
                "C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe");
        EdgeOptions edgeOptions = new EdgeOptions().merge(chromeOptions);
        driver = new EdgeDriver(edgeOptions);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://bonigarcia.github.io/selenium-jupiter/");
        assertThat(driver.getTitle(),
                containsString("JUnit 5 extension for Selenium"));
    }

}

Include Edge in development version (Chromium based) test


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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.
 * #L%
 */

package net.imagej.ops.filter;

import net.imagej.ops.AbstractNamespaceTest;

import org.junit.Test;

/**
 * Tests {@link FilterNamespace}.
 *
 * @author Curtis Rueden
 */
public class FilterNamespaceTest extends AbstractNamespaceTest {

	/**
	 * Tests that the ops of the {@code filter} namespace have corresponding
	 * type-safe Java method signatures declared in the {@link FilterNamespace}
	 * class.
	 */
	@Test
	public void testCompleteness() {
		assertComplete("filter", FilterNamespace.class);
	}

}

Add filter namespace completeness test


/*
 *     Copyright (C) 2015  higherfrequencytrading.com
 *
 *     This program 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 3 of the License.
 *
 *     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 Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.openhft.chronicle.core.util;

@FunctionalInterface
public interface ThrowingFunction<I, T extends Throwable, R> {
    R apply(I in) throws T;
}

Add a test demonstrating how WiredFile can be used.


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content_shell;

import android.content.Context;
import android.os.PowerManager;
import android.test.suitebuilder.annotation.Smoke;

import org.chromium.base.test.util.Feature;

/**
 * Test that verifies preconditions for tests to run.
 */
public class ContentShellPreconditionsTest extends ContentShellTestBase {
    @Smoke
    @Feature({"TestInfrastructure"})
    public void testScreenIsOn() throws Exception {
        PowerManager pm = (PowerManager) getInstrumentation().getContext().getSystemService(
                Context.POWER_SERVICE);

        assertTrue("Many tests will fail if the screen is not on.", pm.isScreenOn());
    }
}

Add test that asserts screen is on.


/*
 * 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.io.comparator;

import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * A basic test suite that tests all the IO comparator package.
 */
public class PackageTestSuite {

    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite("IO Comparators");
        suite.addTest(new TestSuite(DefaultFileComparatorTest.class));
        suite.addTest(new TestSuite(ExtensionFileComparatorTest.class));
        suite.addTest(new TestSuite(LastModifiedFileComparatorTest.class));
        suite.addTest(new TestSuite(NameFileComparatorTest.class));
        suite.addTest(new TestSuite(PathFileComparatorTest.class));
        suite.addTest(new TestSuite(SizeFileComparatorTest.class));
        return suite;
    }
}

Add package test suite for comparators


package org.gwtbootstrap3.client.ui;

/*
 * #%L
 * GwtBootstrap3
 * %%
 * Copyright (C) 2013 GwtBootstrap3
 * %%
 * 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.
 * #L%
 */

import org.gwtbootstrap3.client.ui.base.ValueBoxBase;
import org.gwtbootstrap3.client.ui.constants.Styles;

import com.google.gwt.dom.client.Document;
import com.google.gwt.text.client.LongParser;
import com.google.gwt.text.client.LongRenderer;

public class LongBox extends ValueBoxBase<Long> {

    public LongBox() {
        super(Document.get().createTextInputElement(), LongRenderer.instance(), LongParser.instance());
        addStyleName(Styles.FORM_CONTROL);
    }
}

Add a missing type of box for completeness when using the editor framework


/*
 * Copyright 2018 the original author or authors.
 *
 * 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.springframework.vault.annotation;

import org.junit.Test;
import org.mockito.Mockito;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.vault.core.VaultTemplate;

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

/**
 * Unit test for {@link VaultPropertySource}.
 *
 * @author Mark Paluch
 */
public class VaultPropertySourceUnitTests {

	@Configuration
	static class Config {

		@Bean
		VaultTemplate vaultTemplate() {
			return Mockito.mock(VaultTemplate.class);
		}
	}

	@Configuration
	@Profile("demo")
	@VaultPropertySource("foo")
	static class DemoProfile {
	}

	@Configuration
	@Profile("dev")
	@VaultPropertySource("bar")
	static class DevProfile {
	}

	@Test
	public void shouldNotEnablePropertySource() {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

		ctx.register(Config.class);
		ctx.register(DemoProfile.class);
		ctx.register(DevProfile.class);
		ctx.refresh();

		VaultTemplate templateMock = ctx.getBean(VaultTemplate.class);

		verify(templateMock).afterPropertiesSet();
		verifyNoMoreInteractions(templateMock);
	}

	@Test
	public void shouldEnablePropertySourceByProfile() {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

		ctx.getEnvironment().addActiveProfile("demo");

		ctx.register(Config.class);
		ctx.register(DemoProfile.class);
		ctx.register(DevProfile.class);

		ctx.refresh();

		VaultTemplate templateMock = ctx.getBean(VaultTemplate.class);

		verify(templateMock).afterPropertiesSet();
		verify(templateMock).read("foo");
		verify(templateMock, never()).read("bar");
	}
}

Add unit test for VaultPropertySource with profiles.


package org.ovirt.engine.core.common.action;

import javax.validation.Valid;

import org.ovirt.engine.core.common.businessentities.network.VnicProfile;

public class VnicProfileParameters extends VdcActionParametersBase {

    private static final long serialVersionUID = 7238781812367042839L;

    @Valid
    private VnicProfile vnicProfile;
    private boolean publicUse;

    public VnicProfileParameters() {
    }

    public VnicProfileParameters(VnicProfile vnicProfile) {
        this.vnicProfile = vnicProfile;
    }

    public VnicProfile getVnicProfile() {
        return vnicProfile;
    }

    public void setVnicProfile(VnicProfile vnicProfile) {
        this.vnicProfile = vnicProfile;
    }

    public boolean isPublicUse() {
        return publicUse;
    }

    public void setPublicUse(boolean publicUse) {
        this.publicUse = publicUse;
    }
}

Add parameter class for vnic profile commands


package no.javazone;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class BigTest {

    private static final int COUNT = 10000;

    @Test
    public void testSingle() {
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++) {
            Big.task();
        }
        System.out.println("Result: " + COUNT + " in " + ((System.nanoTime() - start) / 1e9) + "s");
    }

    @Test
    public void testExec() throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<Long>> futures = new ArrayList<>(COUNT);
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++) {
            futures.add(executor.submit(Big::task));
        }
        for (Future<Long> future : futures) {
            future.get();
        }
        System.out.println("Result: " + COUNT + " in " + ((System.nanoTime() - start) / 1e9) + "s");
    }
}

Add example showing executors being num-of-processors orders faster.


/**
 * Copyright (c) 2010-2017 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package de.csdev.ebus.core.connection;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

/**
 * @author Christian Sowada - Initial contribution
 *
 */
public class EBusUDPConnection implements IEBusConnection {

    private DatagramChannel channel;

    /** The udp hostname */
    private String hostname;

    /** The udp port */
    private int port;

    // private SocketAddress server;

    /**
     * Constructor
     *
     * @param hostname
     * @param port
     */
    public EBusUDPConnection(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
    }

    /*
     * (non-Javadoc)
     *
     * @see de.csdev.ebus.core.connection.IEBusConnection#open()
     */
    @Override
    public boolean open() throws IOException {

        channel = DatagramChannel.open();
        channel.connect(new InetSocketAddress(this.hostname, this.port));

        return true;
    }

    @Override
    public boolean isOpen() throws IOException {
        return channel.isConnected();
    }

    @Override
    public boolean isReceiveBufferEmpty() throws IOException {
        return true;
    }

    @Override
    public void reset() throws IOException {
        // noop
    }

    @Override
    public void writeByte(int b) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        buffer.put((byte) b);
        channel.write(buffer);
    }

    @Override
    public int readByte(boolean lowLatency) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        channel.read(buffer);
        return buffer.get(0);
    }

    @Override
    public int readBytes(byte[] buffer) throws IOException {
        return channel.read(ByteBuffer.wrap(buffer));
    }

    /*
     * (non-Javadoc)
     *
     * @see de.csdev.ebus.core.connection.AbstractEBusConnection#close()
     */
    @Override
    public boolean close() throws IOException {

        channel.disconnect().close();
        channel = null;

        return true;
    }

}

Add first version of untested UDP connector


package org.mapdb.issues;

import org.junit.Test;
import org.mapdb.*;

import java.util.concurrent.ConcurrentMap;

import static org.junit.Assert.assertEquals;

public class MailList_HeapReopen {

    @Test
    public void test(){
        DB store = DBMaker.heapDB().make();

        ConcurrentMap map = store.hashMap("map").createOrOpen();
        map.put("fooKey","fooValue");

//get the map from store
        ConcurrentMap mapExisting = store.hashMap("map").createOrOpen();
        assertEquals("fooValue",mapExisting.get("fooKey"));
    }
}

Add test case from mailing list


package scratchlib.objects;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import scratchlib.project.ScratchProject;
import scratchlib.project.ScratchVersion;
import scratchlib.reader.ScratchInputStream;
import scratchlib.writer.ScratchOutputStream;

public class ScratchObjectTest
{
    private static class NonReferenceType extends ScratchObject
    {
        public NonReferenceType(int classID)
        {
            super(classID);
        }
    }

    private static class ReferenceType extends ScratchObject
            implements IScratchReferenceType
    {
        public ReferenceType(int classID)
        {
            super(classID);
        }
    }

    @Test
    public void returnsClassID()
    {
        assertEquals(42, new NonReferenceType(42).getClassID());
    }

    @Test
    public void createsSelfReferenceWhenReferenceType()
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ScratchReferenceTable table = new ScratchReferenceTable();
        assertEquals(0, table.size());

        assertFalse(new NonReferenceType(42).createReferences(table, project));
        assertEquals(0, table.size());

        assertTrue(new ReferenceType(42).createReferences(table, project));
        assertEquals(1, table.size());
    }

    @Test
    public void writesNothingButClassID() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);
        ScratchReferenceTable ref = new ScratchReferenceTable();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ScratchOutputStream sout = new ScratchOutputStream(bout);

        new ReferenceType(42).writeTo(sout, ref, project);

        assertArrayEquals(new byte[] { 42 }, bout.toByteArray());
    }

    @Test(expected = IOException.class)
    public void readThrowsForWrongClassID() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);
        ScratchInputStream in = new ScratchInputStream(
                new ByteArrayInputStream(new byte[0]));

        new ReferenceType(42).readFrom(37, in, project);
    }
}

Add unit tests for ScratchObject


/*
 * 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.problem34;

/**
 * Given an array of strings, can you write a method to return return just words that matches with
 * a pattern containing the "." regular expression.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DotRegularExpression {
}

Add statement to problem 34


package com.blogspot.oraclestack.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.pluginframework.PluginException;
import oracle.iam.platformservice.api.PlatformService;
import oracle.iam.platformservice.api.PlatformUtilsService;
import oracle.iam.platformservice.exception.InvalidCacheCategoryException;
import oracle.iam.platformservice.exception.PlatformServiceAccessDeniedException;

/**
 * Registers or unregisters an OIM Plug-in.
 * @author oracle
 */
public class PluginRegistration
{
    private final PlatformService platformService;
    private final PlatformUtilsService platUtilOps;

    public PluginRegistration(OIMClient oimClient)
    {
        this.platformService = oimClient.getService(PlatformService.class);
        this.platUtilOps = oimClient.getService(PlatformUtilsService.class);
    }

    /**
     * Registers an plug-in to OIM
     * @param pathToPluginZipFile       Absolute Path to Plug-in zip file
     * @throws FileNotFoundException
     * @throws IOException
     * @throws PlatformServiceAccessDeniedException
     * @throws PluginException
     * @throws InvalidCacheCategoryException
     */
    public void registerOIMPlugin(String pathToPluginZipFile) throws FileNotFoundException, IOException, PlatformServiceAccessDeniedException, PluginException, InvalidCacheCategoryException
    {
        FileInputStream fis = null;

        try
        {
            // Zip file conversion to byte
            File zipFile = new File(pathToPluginZipFile);
            fis = new FileInputStream(zipFile);
            int size = (int) zipFile.length();
            byte[] b = new byte[size];
            int bytesRead = fis.read(b, 0, size);

            while (bytesRead < size)
            {
                bytesRead += fis.read(b, bytesRead, size - bytesRead);
            }

            // Register Plugin to OIM
            this.platformService.registerPlugin(b);
            System.out.println("Successfully registered plugin.");

            // Purge Cache
            this.platUtilOps.purgeCache("ALL");
            System.out.println("Cache Purged.");
        }

        finally
        {
            if (fis != null)
            {
                fis.close();
            }
        }
    }

    /**
     * Unregister an OIM Plug-in
     * @param pluginId          PLUGIN_ID
     * @param pluginVersion     PLUGIN_VERSION
     * @throws PlatformServiceAccessDeniedException
     * @throws InvalidCacheCategoryException
     * @throws PluginException
     */
    public void unRegisterOIMPlugin(String pluginId, String pluginVersion) throws PlatformServiceAccessDeniedException, InvalidCacheCategoryException, PluginException
    {
        // Remove single plugin
        this.platformService.unRegisterPlugin(pluginId, pluginVersion);

        // Purge Cache;
        this.platUtilOps.purgeCache("ALL");
    }
}

Add utility to register and remove OIM plugins


/*
 * Copyright 2014 Kevin Quan (kevin.quan@gmail.com)
 *
 * 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.kevinquan.android.ui;

import android.app.Activity;
import android.util.Log;
import android.view.View;

/**
 * Helper class to maintain system UI visibility across activity lifecycle
 * @author Kevin Quan (kevin.quan@gmail.com)
 *
 */
public class SystemUiVisibilityController {

    private static final String TAG = SystemUiVisibilityController.class.getSimpleName();

    protected int mVisibility;

    public SystemUiVisibilityController(int visibility) {
        mVisibility = visibility;
    }

    /**
     * Apply the desired system UI visibility.  The desired system UI visibility will be restored if a change is detected
     * @param activity The activity to apply the settings to
     * @return
     */
    public SystemUiVisibilityController apply(Activity activity) {
        if (activity == null) {
            Log.w(TAG, "No activity available to apply system visibility to.");
            return this;
        }
        final View decorView = activity.getWindow().getDecorView();
        decorView.setSystemUiVisibility(mVisibility);
        registerListener(activity);
        return this;
    }

    /**
     * Register a listener to restore the desired system UI visibility if/when it is changed
     * @param activity The activity to apply the settings to
     * @return
     */
    public SystemUiVisibilityController registerListener(Activity activity) {
        if (activity == null) {
            Log.w(TAG, "No activity available to register system UI visibility listener to.");
            return this;
        }
        final View decorView = activity.getWindow().getDecorView();
        // Based on http://stackoverflow.com/questions/21164836/immersive-mode-navigation-becomes-sticky-after-volume-press-or-minimise-restore
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override public void onSystemUiVisibilityChange(int visibility) {
                //Log.d(TAG, "Re-applying system UI visibility");
                decorView.setSystemUiVisibility(mVisibility);
            }
        });
        return this;
    }

}

Add helper to restore immersive modes


package com.google.sps.data;

import com.google.maps.model.LatLng;
import java.util.TimeZone;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** */
@RunWith(JUnit4.class)
public final class LocationTest {
  Location location = new Location("Los Angeles");
  Location blankLocation = new Location(" ");

  @Test
  public void checkAddressField() {
    String actual = location.getAddress();
    String expected = "Los Angeles";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkFormattedAddressField() {
    String actual = location.getAddressFormatted();
    String expected = "Los Angeles, CA, USA";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkLatitude() {
    Double actual = location.getLat();
    Double expected = 34.05223420;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkLongitude() {
    Double actual = location.getLng();
    Double expected = -118.24368490;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkCoords() {
    LatLng actual = location.getCoords();
    LatLng expected = new LatLng(34.05223420, -118.24368490);
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkTimeZoneID() {
    String actual = location.getTimeZoneID();
    String expected = "America/Los_Angeles";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkTimeZone() {
    TimeZone actual = location.getTimeZone();
    TimeZone expected = TimeZone.getTimeZone("America/Los_Angeles");
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankAddressField() {
    String actual = blankLocation.getAddress();
    String expected = " ";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankFormattedAddressField() {
    String actual = blankLocation.getAddressFormatted();
    String expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankLatitude() {
    Double actual = blankLocation.getLat();
    Double expected = 0.0;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankLongitude() {
    Double actual = blankLocation.getLng();
    Double expected = 0.0;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankCoords() {
    LatLng actual = blankLocation.getCoords();
    LatLng expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankTimeZoneID() {
    String actual = blankLocation.getTimeZoneID();
    String expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankTimeZone() {
    TimeZone actual = blankLocation.getTimeZone();
    TimeZone expected = null;
    Assert.assertEquals(expected, actual);
  }
}

Add testing for Location class


package org.eclipse.birt.report.engine.css.dom;

import org.eclipse.birt.report.engine.content.IStyle;
import org.w3c.dom.css.CSSValue;

/**
 * FixedStyle is a fixed image of styles. It simply holds all the style references.

 * It avoids the cache and cascade computing facility provided by the ComputedStyle, which leads to unwanted behavior.

 * The main drawback of this class is the memory consumption, since no cache is used. Use it with caution.
 */
public class FixedStyle extends AbstractStyle
{

	private CSSValue[] values = new CSSValue[NUMBER_OF_STYLE];

	public FixedStyle( AbstractStyle style )
	{
		super( style.engine );
		mergeStyle( style );
	}

	/**
	 * Merge style with current styles. New styles always overwrite the old ones, except the null values.
	 * @param style
	 */
	public void mergeStyle( IStyle style )
	{
		for(int i = 0; i < NUMBER_OF_STYLE; i++)
		{
			CSSValue value = style.getProperty(i);
			if(value != null)
			{
				values[i] = style.getProperty( i );
			}
		}
	}

	/**
	 * One should never change the value returned, may cause obscure bugs.
	 */
	@Override
	public CSSValue getProperty( int index )
	{
		return values[index];
	}

	@Override
	public void setProperty( int index, CSSValue value )
	{
		values[index] = value;
	}

	@Override
	public boolean isEmpty( )
	{
		for( CSSValue value : values )
		{
			if( value != null )
				return false;
		}
		return true;
	}

}

Fix one total cell format will affect the other total cells when export to excel and enable pivot table. (T 50403)


/*
 * 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.problem38;

/**
 * Given a binary tree, can you write a method to calculate every path to every leaf in the tree.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PathToEveryLeaf {
}

Add statement to problem 38


package org.objenesis;

import org.junit.Test;

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

/**
 * This test makes sure an issue mentioned is not occurring.
 * @author Henri Tremblay
 */
public class ExternalizableTest {

    public static class A extends ArrayList<String> implements Externalizable {

        public A() {
        }

        @Override
        public void writeExternal(ObjectOutput out) throws IOException {

        }

        @Override
        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

        }
    }

    @Test
    public void test() {
        A a = ObjenesisHelper.newSerializableInstance(A.class);
        // This call should work because the ArrayList constructor as been called. This is required by A implementing Externalizable
        a.add("Test");
    }
}

Add a specific test for externalizable


package jenkins.plugins.jsonHelper;

import hudson.model.Hudson;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

/**
 * @author Joost van der Griendt
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({FromJsonStep.DescriptorImpl.class, Jenkins.class})
public class FromJsonStepTest {

    /** Class under test. */
    private FromJsonStep fixture;

    private JSONObject json;
    private Hudson jenkins;

    @Test
    public void doesntCrashWhenInputIsEmpty(){
        fixture = new FromJsonStep(null);
    }

    @Test
    public void returnObjectFromSimpleJson(){
        String jsonString = "{ \"foo\" : \"bar\" }";
        fixture = new FromJsonStep(jsonString);
        Object object = fixture.fromJson();
        assertNotNull(object);
        assertTrue(object instanceof groovy.json.internal.LazyMap);
    }
}

Add a first unit test


package org.jenkinsci.plugins.ghprb.downstreambuilds;

import org.jenkinsci.plugins.ghprb.GhprbDefaultBuildManager;

import com.cloudbees.plugins.flow.FlowRun;

import hudson.model.AbstractBuild;

/**
 * @author mdelapenya (Manuel de la Peña)
 */
public class DownstreamBuildManagerFactoryUtil {

	public static IDownstreamBuildManager getBuildManager(AbstractBuild build) {
		if (build instanceof FlowRun) {
			return new DownstreamBuildFlowManager(build);
		}

		return new GhprbDefaultBuildManager(build);
	}

}

Use a factory to decide which downstream manager to use


/**
 * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.deploy.cli;

import java.lang.reflect.Field;

import net.stickycode.configured.ConfigurationSystem;
import net.stickycode.reflector.AnnotatedFieldProcessor;

public class OptionFieldProcessor
    extends AnnotatedFieldProcessor {

  private final ConfigurationSystem configuration;

  public OptionFieldProcessor(ConfigurationSystem configuration) {
    super(Option.class);
    this.configuration = configuration;
  }

  @Override
  public void processField(Object target, Field field) {
    configuration.registerField(target, field);
  }

}

/**
 * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.deploy.cli;

import java.lang.reflect.Field;

import net.stickycode.configured.ConfigurationSystem;
import net.stickycode.reflector.AnnotatedFieldProcessor;
import net.stickycode.stereotype.Configured;

public class OptionFieldProcessor
    extends AnnotatedFieldProcessor {

  private final ConfigurationSystem configuration;

  public OptionFieldProcessor(ConfigurationSystem configuration) {
    super(Configured.class);
    this.configuration = configuration;
  }

  @Override
  public void processField(Object target, Field field) {
    configuration.registerField(target, field);
  }

}

Use the @Configured stereotype for command line parameters no need for a special option...


package com.google.android.gnd.ui.map;

/** Abstract class defining objects that need to be rendered on map. */
public abstract class MapFeature {

  // TODO: Pull common attributes from concrete classes to here.
  // TODO: Define enum for supported MapFeatures and replace all instanceOf checks

}

Create abstract class for objects that need to be rendered


package com.rackspacecloud.blueflood.inputs.processors;

import com.rackspacecloud.blueflood.concurrent.ThreadPoolBuilder;
import com.rackspacecloud.blueflood.io.DiscoveryIO;
import com.rackspacecloud.blueflood.types.Metric;

import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

public class DiscoveryWriterTest {
    private static int WRITE_THREADS = 50;
    @Test
    public void testProcessor() throws Exception {
        DiscoveryIO discovererA = mock(DiscoveryIO.class);
        DiscoveryIO discovererB = mock(DiscoveryIO.class);
        DiscoveryWriter discWriter =
                new DiscoveryWriter(new ThreadPoolBuilder()
                        .withName("Metric Discovery Writing")
                        .withCorePoolSize(WRITE_THREADS)
                        .withMaxPoolSize(WRITE_THREADS)
                        .withUnboundedQueue()
                        .withRejectedHandler(new ThreadPoolExecutor.AbortPolicy())
                        .build());
        discWriter.registerIO(discovererA);
        discWriter.registerIO(discovererB);

        List<List<Metric>> testdata = new ArrayList<List<Metric>>();
        testdata.add(mock(List.class));
        testdata.add(mock(List.class));
        testdata.add(mock(List.class));
        testdata.add(mock(List.class));

        discWriter.apply(testdata);

        for (List<Metric> metrics : testdata) {
            verify(discovererA).insertDiscovery(metrics);
            verify(discovererB).insertDiscovery(metrics);
        }
    }
}

Add unit test for DiscoveryWriter


package eu.mosaic_cloud.tools.callbacks.tools;

import java.util.ArrayDeque;
import java.util.concurrent.Callable;

import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion;
import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletionObserver;

import com.google.common.base.Preconditions;

public class CallbackCompletionWorkflows
{
	public static final CallbackCompletion<Void> executeSequence (final Callable<CallbackCompletion<Void>> ... operations_)
	{
		Preconditions.checkNotNull (operations_);
		final ArrayDeque<Callable<CallbackCompletion<Void>>> operations = new ArrayDeque<Callable<CallbackCompletion<Void>>> (operations_.length);
		for (final Callable<CallbackCompletion<Void>> operation : operations_) {
			Preconditions.checkNotNull (operation);
			operations.add (operation);
		}
		final CallbackCompletionDeferredFuture<Void> future = CallbackCompletionDeferredFuture.create (Void.class);
		final Runnable chainer = new Runnable () {
			@Override
			public void run ()
			{
				final Runnable chainer = this;
				if (operations.isEmpty ()) {
					future.trigger.triggerSucceeded (null);
					return;
				}
				final CallbackCompletion<Void> completion;
				try {
					final Callable<CallbackCompletion<Void>> operation = operations.removeFirst ();
					completion = operation.call ();
				} catch (final Throwable exception) {
					// FIXME: log...
					future.trigger.triggerFailed (exception);
					return;
				}
				if (completion.isCompleted ()) {
					final Throwable exception = completion.getException ();
					if (exception != null) {
						future.trigger.triggerFailed (exception);
						return;
					} else
						return;
				}
				completion.observe (new CallbackCompletionObserver () {
					@Override
					public CallbackCompletion<Void> completed (final CallbackCompletion<?> completion_)
					{
						Preconditions.checkArgument (completion_ == completion);
						final Throwable exception = completion.getException ();
						if (exception != null)
							future.trigger.triggerFailed (exception);
						else
							chainer.run ();
						return (null);
					}
				});
			}
		};
		chainer.run ();
		return (future.completion);
	}
}

Implement simple callback completion based workflows (currently only "sequence")


/*
 * Copyright (C) 2006 WTSI & EBI
 *
 * This library 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 library 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 library;
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check for HGNCs that have been assigned as display labels more than one gene.
 */

public class HGNCMultipleGenes extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of Ditag.
	 */
	public HGNCMultipleGenes() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for HGNCs that have been assigned as display labels more than one gene.");

	}

	/**
	 * This test only applies to core databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

	/**
	 * Test various things about ditag features.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return Result.
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		// this has to be done the slow way, don't think there's a way to do this all at once
		int rows = getRowCount(con, "SELECT DISTINCT(x.display_label), COUNT(*) AS count FROM gene g, xref x, external_db e WHERE e.external_db_id=x.external_db_id AND e.db_name='HUGO' AND x.xref_id=g.display_xref_id GROUP BY x.display_label HAVING COUNT > 1");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " HGNC symbols have been assigned to more than one gene");
			result = false;

		} else {

			ReportManager.correct(this, con, "All HGNC symbols only assigned to one gene");
		}

		return result;

	}

	// ----------------------------------------------------------------------

}


/**
 * 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.fusesource.amqpjms.sasl;

/**
 * Used to find a SASL Mechanism that most closely matches the preferred set
 * of Mechanisms supported by the remote peer.
 *
 * The Matching mechanism is chosen by first find all instances of SASL
 * mechanism types that are supported on the remote peer, and then making a
 * final selection based on the Mechanism in the found set that has the
 * highest priority value.
 */
public class SaslMechanismFinder {

    public static Mechanism findMatchingMechanism(String...remoteMechanisms) {
        return null;
    }
}

Add a class that can find and select the best SASL mechanism based on the remote peers reported mechanisms.


package com.github.havarunner.beforeafter;

import com.github.havarunner.HavaRunner;
import com.github.havarunner.annotation.RunSequentially;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;

import java.util.concurrent.atomic.AtomicReference;

import static org.junit.Assert.assertTrue;

public class WhenAfterFails {

    @Test
    public void HavaRunner_will_mark_the_test_as_finished() {
        final AtomicReference<Boolean> finished = new AtomicReference<>(false);
        new HavaRunner(AfterFails.class).run(new RunNotifier() {
            @Override
            public void fireTestFinished(Description description) {
                finished.set(true);
            }
        });
        assertTrue(finished.get());
    }

    @RunSequentially
    static class AfterFails {

        @Test
        public void test() { }

        @After
        public void fail() {
            throw new RuntimeException("Fail intentionally");
        }
    }
}

Add example of finish even when @After fails


package org.jenkinsci.plugins.deploydb;

import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.AbstractProject;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import static org.junit.Assert.assertNotNull;

public class JobConfigTest {

    @Rule public final JenkinsRule jenkins = new JenkinsRule();

    @Test public void newJobConfigurationShouldNotFail() throws Exception {
        // Given we create a brand new job
        AbstractProject<?, ?> job = jenkins.createFreeStyleProject();

        // When we open its configuration page
        HtmlPage page = jenkins.createWebClient().getPage(job, "configure");

        // Then nothing untoward should happen (i.e. no 500 error)
        assertNotNull(page);
    }

}

Add test to ensure that a newly-created job can be configured via the web UI.


package org.bitcoinj.examples;

import org.bitcoinj.core.*;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.MemoryBlockStore;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class DownloadBlocks {
    public static void main(String[] args) throws BlockStoreException, ExecutionException, InterruptedException {
        System.out.println("Connecting to node");
        final NetworkParameters params = MainNetParams.get();
        BlockStore blockStore = new MemoryBlockStore(params);
        BlockChain chain = new BlockChain(params, blockStore);
        PeerGroup peerGroup = new PeerGroup(params, chain);
        peerGroup.addPeerDiscovery(new DnsDiscovery(params));
        peerGroup.setUseLocalhostPeerWhenPossible(false);

        peerGroup.start();
        peerGroup.waitForPeers(10).get();
        Peer peer = peerGroup.getDownloadPeer();

        for (String hash : new String[]{
                "0000000000000011fbdfb7ebea7b3b68c11c82f68fe792e4a376f0f3e1ebfee5",
                "000000000000001b7c5666cbda73912a5bcff8fc179fdd421fc9bfe7b7e7be73",
                "000000000000000cdf5cc24c3beb0669b31e942d1301e07b53d6f0c7db10860d", // <<<<< doesn't work with dashj-0.13 branch
        }) {

            Sha256Hash blockHash = Sha256Hash.wrap(hash);
            Future<Block> future = peer.getBlock(blockHash);
            System.out.println("Waiting for node to send us the requested block: " + blockHash);
            Block block = future.get();
            System.out.println(block);
            try {
                UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(block.getMessageSize());
                block.bitcoinSerialize(bos);
                System.out.println(Utils.HEX.encode(bos.toByteArray()));
            } catch(IOException x) {
                throw new RuntimeException(x.getMessage());
            }
        }
        peerGroup.stopAsync();
    }
}

Add Download blocks to test block processing


/**
 * <License>
 */
package edu.colorado.csdms.wmt.client.ui.widgets;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;

/**
 * Makes a {@link HorizontalPanel} with a centered "Close" button. Reusable!
 *
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class ClosePanel extends HorizontalPanel {

  private Button button;

  /**
   * Makes a new {@link ClosePanel} with a centered "Close" button.
   */
  public ClosePanel() {

    this.setWidth("100%");
    this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

    button = new Button("<i class='fa fa-times'></i> Close");
    button.getElement().getStyle().setMarginTop(1, Unit.EM);
    button.getElement().getStyle().setMarginBottom(0.5, Unit.EM);

    this.add(button);
  }

  public Button getButton() {
    return button;
  }

  public void setButton(Button button) {
    this.button = button;
  }
}

Make a reusable panel with a centered "Close" button


/*
 * Copyright 2002-2020 the original author or authors.
 *
 * 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 org.springframework.core.convert.support;

import org.junit.jupiter.api.Test;

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

/**
 * @author Adilson Antunes
 */
class IntegerToEnumConverterFactoryTests {

	enum Colors {
		RED,
		BLUE,
		GREEN
	}

	@Test
	void convertIntegerToEnum() {
		final IntegerToEnumConverterFactory enumConverterFactory = new IntegerToEnumConverterFactory();
		assertThat(enumConverterFactory.getConverter(Colors.class).convert(0)).isEqualTo(Colors.RED);
		assertThat(enumConverterFactory.getConverter(Colors.class).convert(1)).isEqualTo(Colors.BLUE);
		assertThat(enumConverterFactory.getConverter(Colors.class).convert(2)).isEqualTo(Colors.GREEN);
	}

	@Test
	void throwsArrayIndexOutOfBoundsExceptionIfInvalidEnumInteger() {
		final IntegerToEnumConverterFactory enumConverterFactory = new IntegerToEnumConverterFactory();
		assertThatExceptionOfType(ArrayIndexOutOfBoundsException.class)
				.isThrownBy(() -> enumConverterFactory.getConverter(Colors.class).convert(999));
	}

}

Introduce unit tests for IntegerToEnumConverterFactory


/*
 * 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.problem78;

/**
 * Some integers returns the same instance if you apply autoboxing, you can check it with this
 * code and the related test.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrick {

}

Add statement to problem 78


/*
 * This file is part of LibrePlan
 *
 * Copyright (C) 2011 Igalia, S.L.
 *
 * 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 org.libreplan.business.planner.entities.visitors;

/**
 * Visits a task graph resetting task statuses.
 *
 * @author Nacho Barrientos <nacho@igalia.com>
 */
import org.libreplan.business.planner.entities.Task;
import org.libreplan.business.planner.entities.TaskGroup;
import org.libreplan.business.util.TaskElementVisitor;

public class ResetTasksStatusVisitor extends TaskElementVisitor {

    public ResetTasksStatusVisitor() {
    }

    public void visit(Task task) {
        task.resetStatus();
    }

    public void visit(TaskGroup taskGroup) {
        taskGroup.resetStatus();
    }

}

Add visitor to reset task statuses.


/*
Copyright (c) 2016, Colorado State University
All rights reserved.

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 holder 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.sigpipe.sing.dataset.feature;

public class IllegalFeatureComparisonException extends ClassCastException {

    public IllegalFeatureComparisonException(
            FeatureData<?> a, FeatureData<?> b) {
        super(
                "[" + a.getType() + ", " + a.data + "]"
                + " cannot be compared to "
                + "[" + b.getType() + ", " + b.data + "]");
    }
}

Add custom class for illegal feature comparisons


package leetcode.maximum_gap;

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

public class Solution {
    public int maximumGap(int[] num) {
        if(num == null || num.length < 2) return 0;
        int length = num.length;
        List<List<Integer>> buckets = new ArrayList<List<Integer>>(length - 1);
        for(int i = 0; i < length - 1; i++){
        	buckets.add(new ArrayList<Integer>());
        }
        int min = num[0], max = num[0];
        for(int x : num){
        	if(x < min){
        		min = x;
        	}
        	if(x > max){
        		max = x;
        	}
        }
        int range = max - min;
        for(int x : num){
        	long diff = x - min;
        	if(x < max){
        		int idx = (int)(diff * (length - 1) / range);
        		buckets.get(idx).add(x);
        	}
        }
        List<Integer> bmins = new ArrayList<Integer>();
        List<Integer> bmaxs = new ArrayList<Integer>();
        for(List<Integer> bucket : buckets){
        	if(bucket.size() > 0){
        		int bmin = bucket.get(0);
        		int bmax = bucket.get(0);
        		for(int b : bucket){
        			if(b < bmin)
        				bmin = b;
        			if(b > bmax)
        				bmax = b;
        		}
        		bmins.add(bmin);
        		bmaxs.add(bmax);
        	}
        }
        int maxgap = 0;
        int currmin = min;
        int bsize = bmins.size();
        for(int i = 0; i < bsize; i++){
        	maxgap = Math.max(maxgap, bmins.get(i) - currmin);
        	currmin = bmaxs.get(i);
        }
        maxgap = Math.max(maxgap, max - currmin);
        return maxgap;
    }
}

Add java solution for 164. Maximum Gap


/*
 * Licensed to the University of California, Berkeley 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 tachyon;

import org.powermock.reflect.Whitebox;

import tachyon.util.CommonUtils;
import tachyon.worker.file.FileDataManager;
import tachyon.worker.file.FileSystemWorker;

/**
 * Util methods for writing integration tests.
 */
public final class IntegrationTestUtils {

  /**
   * Convenience method for calling
   * {@link #waitForPersist(LocalTachyonClusterResource, long, long)} with a timeout of 5
   * seconds.
   *
   * @param localTachyonClusterResource the cluster for the worker that will persist the file
   * @param fileId the file id to wait to be persisted
   */
  public static void waitForPersist(LocalTachyonClusterResource localTachyonClusterResource,
      long fileId) {
    waitForPersist(localTachyonClusterResource, fileId, 5 * Constants.SECOND_MS);
  }

  /**
   * Blocks until the specified file is persisted or a timeout occurs.
   *
   * @param localTachyonClusterResource the cluster for the worker that will persist the file
   * @param fileId the file id to wait to be persisted
   * @param timeoutMs the number of milliseconds to wait before giving up and throwing an exception
   */
  public static void waitForPersist(LocalTachyonClusterResource localTachyonClusterResource,
      long fileId, int timeoutMs) {
    long start = System.currentTimeMillis();
    FileSystemWorker fileSystemWorker = Whitebox
        .getInternalState(localTachyonClusterResource.get().getWorker(), "mFileSystemWorker");
    FileDataManager fileDataManager =
        Whitebox.getInternalState(fileSystemWorker, "mFileDataManager");
    while (!fileDataManager.isFilePersisted(fileId)) {
      if (System.currentTimeMillis() - start > timeoutMs) {
        throw new RuntimeException("Timed out waiting for " + fileId + " to be persisted");
      }
      CommonUtils.sleepMs(20);
    }
  }

  private IntegrationTestUtils() {} // This is a utils class not intended for instantiation
}

Add method for blocking on file persist in tests


package net.imagej.ops.filter;

import net.imagej.ops.AbstractComputerOp;
import net.imagej.ops.ComputerOp;
import net.imagej.ops.OpService;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.neighborhood.Shape;
import net.imglib2.outofbounds.OutOfBoundsFactory;
import net.imglib2.view.Views;

import org.scijava.plugin.Parameter;

/**
 * Abstract superclass of all non-linear filters.
 *
 * @author Jonathan Hale (University of Konstanz)
 * @param <I> type of the input {@link RandomAccessibleInterval}
 * @param <O> type of the output {@link RandomAccessibleInterval}
 */
public abstract class AbstractNonLinearFilter<I, O> extends
	AbstractComputerOp<RandomAccessibleInterval<I>, RandomAccessibleInterval<O>>
{

	@Parameter
	protected OpService ops;

	@Parameter
	private Shape shape;

	@Parameter(required = false)
	private OutOfBoundsFactory<I, RandomAccessibleInterval<I>> outOfBoundsFactory;

	@Override
	public void compute(final RandomAccessibleInterval<I> input,
		final RandomAccessibleInterval<O> output)
	{
		// optionally extend input if outOfBoundsFactory is set
		RandomAccessibleInterval<I> extInput = input;
		if (outOfBoundsFactory != null) {
			extInput = Views.interval(Views.extend(input, outOfBoundsFactory), input);
		}

		I in = input.randomAccess().get();
		O out = output.randomAccess().get();

		// map computer to neighborhoods
		ops.map(output, extInput, getComputer(in.getClass(), out.getClass()),
			getShape());
	}

	/**
	 * Get the shape (structuring element) used by this filter.
	 *
	 * @return the shape
	 */
	public Shape getShape() {
		return shape;
	}

	/**
	 * Set the shape (structuring element) to be used by this filter.
	 *
	 * @param s the shape
	 */
	public void setShape(Shape s) {
		shape = s;
	}

	/**
	 * @return the {@link ComputerOp} to evaluate for every neighborhood of every
	 *         pixel
	 */
	protected abstract ComputerOp<Iterable<I>, O> getComputer(
		final Class<?> inClass, final Class<?> outClass);

}

Add abstract class for non-linear filters


package son.graph;

import java.util.List;

import son.graph.algorithms.RoutesContraint;
import son.graph.algorithms.RoutesFinder;
import son.graph.models.interfaces.Node;

public abstract class RoutesFinderByConstraint extends RoutesFinder {
	public RoutesFinderByConstraint(RoutesFinder routesFinder) {
		super(routesFinder.getGraph());
		this.routesFinder = routesFinder;
	}

	private final RoutesFinder routesFinder;

	@Override
	public void calculate(String beginName, String endName, RoutesContraint routesContraints) {
		routesFinder.calculate(beginName, endName, routesContraints);
	}

	@Override
	public List<List<Node>> getRoutes() {
		return routesFinder.getRoutes();
	}
}

Add route finder by constraint so that we can apply different constraint


package hu.kazocsaba.math.matrix;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Kazó Csaba
 */
public class EigenTest {
	@Test
	public void testEig() {
		Matrix3 m=MatrixFactory.createMatrix3(new double[][] {
			{0,1,-1},
			{1,1,0},
			{-1,0,1}
		});
		EigenDecomposition eig = m.eig();
		SortedMap<Double,Vector> eigenvalues=new TreeMap<Double, Vector>();
		for (int i=0; i<3; i++)
			eigenvalues.put(eig.getEigenvalue(i), eig.getEigenvector(i));
		Iterator<Entry<Double, Vector>> iterator = eigenvalues.entrySet().iterator();

		Entry<Double, Vector> entry = iterator.next();
		assertEquals(-1, entry.getKey(), 1e-8);
		assertEquals(1, Math.abs(entry.getValue().normalized().dot(MatrixFactory.createVector(2, -1, 1).normalized())), 1e-8);

		entry = iterator.next();
		assertEquals(1, entry.getKey(), 1e-8);
		assertEquals(1, Math.abs(entry.getValue().normalized().dot(MatrixFactory.createVector(0, 1, 1).normalized())), 1e-8);

		entry = iterator.next();
		assertEquals(2, entry.getKey(), 1e-8);
		assertEquals(1, Math.abs(entry.getValue().normalized().dot(MatrixFactory.createVector(1, 1, -1).normalized())), 1e-8);
	}
}

Add test for eigen decomposition.


package gov.nih.nci.cbiit.cdms.formula.gui.listener;

import gov.nih.nci.cbiit.cdms.formula.gui.FormulaButtonPane;
import gov.nih.nci.cbiit.cdms.formula.gui.FormulaMainPanel;
import gov.nih.nci.cbiit.cdms.formula.gui.FrameMain;
import gov.nih.nci.cbiit.cdms.formula.gui.NodeContentElement;
import gov.nih.nci.cbiit.cdms.formula.gui.properties.PanelDefaultProperties;
import gov.nih.nci.cbiit.cdms.formula.core.BaseMeta;
import gov.nih.nci.cbiit.cdms.formula.core.TermMeta;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

/**
 * Created by IntelliJ IDEA.
 * User: umkis
 * Date: Nov 19, 2010
 * Time: 12:04:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class FormulaMouseListener implements MouseListener
{
    FormulaButtonPane parentButton;

    PanelDefaultProperties propertiePanel = null;
    BaseMeta beforeMeta = null;
    public FormulaMouseListener(FormulaButtonPane pane)
    {
        parentButton = pane;
    }
    public void mouseClicked(MouseEvent e)
    {
    }

    public void mousePressed(MouseEvent ae)
    {
    }

    public void mouseReleased(MouseEvent ae)
    {
    }

    public void mouseEntered(MouseEvent ae)
    {
        NodeContentElement element = parentButton.getNodeContentElement();
        if (element == null) return;

        //System.out.println("TTTT4 element " + element.toString() + " : " + element.convertToMeta());
        TermMeta termMeta = element.convertToMeta();
        if (termMeta == null) return;

        try
        {
            propertiePanel = FrameMain.getSingletonInstance().getMainPanel().getRightSplitPanel().getPropertiePanel();
            beforeMeta = propertiePanel.getCurrentBaseMeta();
        }
        catch(Exception ee)
        {
            beforeMeta = null;
            return;
        }

        propertiePanel.updateProptiesDisplay(element.convertToMeta());

    }
    public void mouseExited(MouseEvent ae)
    {
        if (beforeMeta == null) return;
        if (propertiePanel == null) return;
        propertiePanel.updateProptiesDisplay(beforeMeta);
        beforeMeta = null;
        propertiePanel = null;
    }
}

Add a mouse listener for displaying term meta properties.


package net.sf.jabref.logic.l10n;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * Checks that all property files are correctly encoded and can be loaded without errors.
 */
public class TestL10nFiles {

    @Test
    public void testi10nFiles() throws IOException {
        for(Path p : Files.list(Paths.get("src/main/resources/l10n")).collect(Collectors.toList())) {
            String[] parts = p.getFileName().toString().split("\\.")[0].split("_");
            String prefix = "l10n/" + parts[0];
            Locale locale;
            if(parts.length == 3) {
                locale = new Locale(parts[1], parts[2]);
            }  else {
                locale = new Locale(parts[1]);
            }

            checkPropertiesFile(locale, prefix);
        }
    }

    private void checkPropertiesFile(Locale locale, String prefix) {
        Locale oldLocale = Locale.getDefault();
        try {
            Locale.setDefault(locale);

            ResourceBundle.getBundle(prefix, locale, new EncodingControl("UTF-8"));
        } finally {
            Locale.setDefault(oldLocale);
        }
    }

}

Add test that we can detect wrongly encoded language property files automatically.


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.PermuteCoordinatesInverse;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.IntervalView;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.PermuteCoordinatesInverse.class, name = PermuteCoordinatesInverse.NAME)
public class DefaultPermuteCoordinatesInverse<T> extends
		AbstractView<RandomAccessibleInterval<T>, IntervalView<T>> implements
		PermuteCoordinatesInverse<RandomAccessibleInterval<T>, IntervalView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private int[] permutation;

	@Parameter(type = ItemIO.INPUT)
	private int d;

	@Override
	public IntervalView<T> compute(RandomAccessibleInterval<T> input) {
		throw new UnsupportedOperationException();
	}

}

Add default implementation of PermuteCoordinatesInverse interface.


/*
 * Copyright (C) 2003 EBI, GRL
 *
 * This library 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 library 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 library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that not all xrefs have the same identifier.
 */

public class XrefIdentifiers extends SingleDatabaseTestCase {

	/**
	 * Create a new XrefIdentifiers testcase.
	 */
	public XrefIdentifiers() {

		addToGroup("post_genebuild");
		addToGroup("release");
		addToGroup("core_xrefs");
		setDescription("Check that not all xrefs have the same identifier.");
		setPriority(Priority.AMBER);
		setEffect("Web display and all other uses of xrefs are broken");
		setFix("Re-import or recalculate xrefs");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test pased.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		// TODO - do this on a per-xref-type basis
		try {

			Statement stmt = con.createStatement();

			ResultSet rs = stmt.executeQuery("SELECT COUNT(DISTINCT(dbprimary_acc)) FROM xref");

			rs.next();

			int count = rs.getInt(1);
			if (count == 1) {
				ReportManager.problem(this, con, "All xrefs appear to have the same identifier.");
				result = false;
			} else {
				ReportManager.correct(this, con, "Not all xrefs have the same identifier.");
			}

			stmt.close();

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

		if (result) {

			ReportManager.correct(this, con, "All external dbs are only associated with one Ensembl object type");

		}

		return result;

	} // run

	// ----------------------------------------------------------------------

} // XrefIdentifiers


/*-
 * Copyright (c) 2014 Mikolaj Izdebski
 *
 * 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.lbzip2.impl;

import static org.junit.Assert.assertEquals;

import java.io.FileInputStream;
import java.io.InputStream;

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class LBzip2InputStreamTest
{
    @Test
    public void test()
        throws Exception
    {
        InputStream fis = new FileInputStream( "test-data/concat.bz2" );
        LBzip2InputStream zis = new LBzip2InputStream( fis );

        assertEquals( 'T', zis.read() );
        assertEquals( 'E', zis.read() );
        assertEquals( 'S', zis.read() );
        assertEquals( 'T', zis.read() );
        assertEquals( '\n', zis.read() );
        assertEquals( -1, zis.read() );
    }
}

Add unit test for LBzip2InputStream


package com.units.constants;

import com.units.mass.SolarMasses;

public class PlanetaryMasses {

	//the mass of the sun
	static public final SolarMasses sunMass = new SolarMasses(1.0);

	//the mass of mercury
	static public final SolarMasses mercuryMass = new SolarMasses(1.6601E-7);

	//the mass of venus
	static public final SolarMasses venusMass = new SolarMasses(2.4478383E-6);

	//the mass of earth
	static public final SolarMasses earthMass = new SolarMasses(3.00348959632E-6);

	//the mass of mars
	static public final SolarMasses marsMass = new SolarMasses(3.227151E-7);

	//the mass of jupiter
	static public final SolarMasses jupiterMass = new SolarMasses(9.5479194E-4);

	//the mass of saturn
	static public final SolarMasses saturnMass = new SolarMasses(2.85886E-4);

	//the mass of uranus
	static public final SolarMasses uranusMass = new SolarMasses(4.366244E-5);

	//the mass of neptune
	static public final SolarMasses neptuneMass = new SolarMasses(5.151389E-5);

}

Add planetary masses constants in java


//-----------------------------------------------------------------------//
//                                                                       //
//                  T e s t C o m p o n e n t E v e n t                  //
//                                                                       //
//  Copyright (C) Herve Bitteur 2000-2006. All rights reserved.          //
//  This software is released under the terms of the GNU General Public  //
//  License. Please contact the author at herve.bitteur@laposte.net      //
//  to report bugs & suggestions.                                        //
//-----------------------------------------------------------------------//

package omr.ui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class TestComponentEvent
        extends ComponentAdapter
        implements ChangeListener
{
    JFrame frame = new JFrame(getClass().getName().toString());
    JTabbedPane tabbedPane = new JTabbedPane();
    JButton button = new JButton(new ToggleAction());

    public static void main (String... args)
    {
        new TestComponentEvent().play();
    }

    public void play ()
    {
        frame.setName("LaFrame");
        frame.addComponentListener(this);
        Container pane = frame.getContentPane();
        pane.setLayout(new BorderLayout());

        button.setText("Toggle");
        button.setName("LeBouton");
        pane.add(button, BorderLayout.NORTH);

        tabbedPane.setName("LeTabbedPane");
        pane.add(tabbedPane, BorderLayout.CENTER);
        tabbedPane.addComponentListener(this);
        tabbedPane.addChangeListener(this);

        for (int i = 0; i < 5; i++) {
            createTab(i);
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocation(100, 100);
        frame.setSize(300, 120);
        frame.setVisible(true);

        System.out.println("**** Frame shown ****");
    }

    private void createTab (int index)
    {
        JPanel tab = new JPanel();
        tab.setName("Tab#" + index);
        tab.addComponentListener(this);
        tab.add(new JLabel("Texte de " + tab.getName()));
        tabbedPane.addTab(tab.getName(), tab);
    }

    class ToggleAction
            extends AbstractAction
    {
        public void actionPerformed(ActionEvent e) {
            tabbedPane.setVisible(!tabbedPane.isVisible());
        }
    }

    public void componentShown(ComponentEvent e) {
        System.out.println("Shown" + " " + e.getComponent().getName());
        if (e.getComponent() == tabbedPane) {
            System.out.println("Forcing selection to tab " + tabbedPane.getSelectedIndex());
            tabbedPane.setSelectedIndex(tabbedPane.getSelectedIndex());
        }
    }

    public void componentHidden(ComponentEvent e) {
        System.out.println("Hidden" + " " + e.getComponent().getName());
    }

    public void stateChanged(ChangeEvent e) {
        // This is for tabbed pane
        System.out.println("Changed " + e.getSource().getClass().getName()
        + " to " + tabbedPane.getTitleAt(tabbedPane.getSelectedIndex()));
    }
}

Test of events originated from components


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.tinylog.core;

/**
 * Severity levels for log entries and configuration.
 */
public enum Level {

	/**
	 * The off severity level is for configuration use only and disables any logging. Log entries must never have
	 * an off severity level assigned.
	 */
	OFF,

	/**
	 * Error log entries contain severe technical errors that prevent normal operation.
	 */
	ERROR,

	/**
	 * Warn log entries contain technical warnings that indicate that something has gone wrong, but do not prevent
	 * operation.
	 */
	WARN,

	/**
	 * Info log entries contain important and relevant information.
	 */
	INFO,

	/**
	 * Debug log entries contain detailed debug information for developers.
	 */
	DEBUG,

	/**
	 * Trace log entries contain very fine-grained debug information for developers, typically the flow through.
	 */
	TRACE

}

Add enumeration for severity levels


package com.andela.webservice.model;

/**
 * Created by Spykins on 08/06/16.
 */
public class Flower {
    private int productId;
    private String name;
    private String category;
    private String instruction;
    private double price;
    private String photo;

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getInstruction() {
        return instruction;
    }

    public void setInstruction(String instruction) {
        this.instruction = instruction;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }
}

Create the data object that will be used when fetching from server


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2008, Red Hat Middleware LLC, 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.arquillian.container;

import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

/**
 * A simple MBeanProxy
 *
 * @author Thomas.Diesler@jboss.com
 * @since 24-Feb-2009
 */
public class MBeanProxy {

    public static <T> T get(MBeanServerConnection server, String name, Class<T> interf) {
        ObjectName oname;
        try {
            oname = ObjectName.getInstance(name);
        } catch (MalformedObjectNameException ex) {
            throw new IllegalArgumentException("Invalid object name: " + name);
        }
        return (T) MBeanProxy.get(server, oname, interf);
    }

    public static <T> T get(MBeanServerConnection server, ObjectName name, Class<T> interf) {
        return (T) MBeanServerInvocationHandler.newProxyInstance(server, name, interf, false);
    }
}

Add transactional integration endpoint (STOMP)


package org.jboss.shamrock.maven;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

@Mojo(name = "create-example-config", defaultPhase = LifecyclePhase.NONE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class ExampleConfigMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    protected MavenProject project;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            File out = new File(project.getBasedir(), "src/main/resources/META-INF/example-microprofile-config.properties");
            out.getParentFile().mkdirs();

            Properties properties = new Properties();
            for (Artifact a : project.getArtifacts()) {
                if (!"jar".equals(a.getType())) {
                    continue;
                }
                try (ZipFile zip = openZipFile(a)) {
                    ZipEntry deps = zip.getEntry("META-INF/shamrock-descriptions.properties");
                    if (deps != null) {
                        try (InputStream in = zip.getInputStream(deps)) {
                            properties.load(in);
                        }
                    }

                }
            }
            StringBuilder sb = new StringBuilder("Example shamrock config\n\n");
            for(Map.Entry<Object, Object> e : new TreeMap<Object, Object>( properties).entrySet()) {
                sb.append("# ")
                        .append(e.getValue().toString().replace("\n", " "))
                        .append("\n#")
                        .append(e.getKey())
                        .append("=\n\n");
            }
            getLog().error("Creating example File at " + out);
            try(FileOutputStream f = new FileOutputStream(out)) {
                f.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to generate config", e);
        }

    }

    private ZipFile openZipFile(final Artifact a) {
        final File file = a.getFile();
        if (file == null) {
            throw new RuntimeException("No file for Artifact:" + a.toString());
        }
        if (!Files.isReadable(file.toPath())) {
            throw new RuntimeException("File not existing or not allowed for reading: " + file.getAbsolutePath());
        }
        try {
            return new ZipFile(file);
        } catch (IOException e) {
            throw new RuntimeException("Error opening zip stream from artifact: " + a.toString());
        }
    }

}

Add ability to generate example config


package org.ops4j.pax.exam;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class TestDirectory
{
    private static final TestDirectory instance = new TestDirectory();

    private Map<TestAddress, TestInstantiationInstruction> map = new HashMap<TestAddress, TestInstantiationInstruction>();
    private URI accessPoint;

    private TestDirectory()
    {
    }

    public static TestDirectory getInstance() {
        return instance;
    }

    public void add(TestAddress address, TestInstantiationInstruction instruction) {
        map.put(address, instruction);
    }

    public TestInstantiationInstruction lookup(TestAddress address) {
        return map.get(address);
    }

    public void clear() {
        map.clear();
    }

    public URI getAccessPoint()
    {
        return accessPoint;
    }

    public void setAccessPoint( URI accessPoint )
    {
        this.accessPoint = accessPoint;
    }
}

Test directory for associating test addresses to test methods (preliminary solution)


package fr.insalyon.citi.golo.compiler.parser;

/**
 *
 * @author david
 */
public class GoloTokenBase {
    public int startOffset;
    public int endOffset;
    public Token previousToken;
}

Create a Token superclass implementation to add offsets and previous token


package com.cloudera.crunch.io;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;

import com.cloudera.crunch.io.text.TextFileReaderFactory;
import com.cloudera.crunch.test.FileHelper;
import com.cloudera.crunch.types.writable.Writables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;

public class CompositePathIterableTest {

  @Test
  public void testCreate_FilePresent() throws IOException{
    String inputFilePath = FileHelper.createTempCopyOf("set1.txt");
    Configuration conf = new Configuration();
    LocalFileSystem local = FileSystem.getLocal(conf);

    Iterable<String> iterable = CompositePathIterable.create(local, new Path(inputFilePath), new TextFileReaderFactory<String>(Writables.strings(), conf));

    assertEquals(Lists.newArrayList("b", "c", "a", "e"), Lists.newArrayList(iterable));

  }

  @Test
  public void testCreate_DirectoryPresentButNoFiles() throws IOException{
    String inputFilePath = Files.createTempDir().getAbsolutePath();

    Configuration conf = new Configuration();
    LocalFileSystem local = FileSystem.getLocal(conf);

    Iterable<String> iterable = CompositePathIterable.create(local, new Path(inputFilePath), new TextFileReaderFactory<String>(Writables.strings(), conf));

    assertTrue(Lists.newArrayList(iterable).isEmpty());
  }

  @Test(expected=IOException.class)
  public void testCreate_DirectoryNotPresent() throws IOException{
    File inputFileDir = Files.createTempDir();
    inputFileDir.delete();

    // Sanity check
    assertFalse(inputFileDir.exists());

    Configuration conf = new Configuration();
    LocalFileSystem local = FileSystem.getLocal(conf);

    CompositePathIterable.create(local, new Path(inputFileDir.getAbsolutePath()), new TextFileReaderFactory<String>(Writables.strings(), conf));
  }

}

Add tests for creation of CompositePathIterable