package io.dropwizard.discovery.client;

import org.junit.Test;

import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class DiscoveryClientManagerTest {

    @SuppressWarnings("unchecked")
    DiscoveryClient<String> client = mock(DiscoveryClient.class);

    DiscoveryClientManager<String> manager = new DiscoveryClientManager<String>(client);

    @Test
    public void testConstructorInvalidClient() {
        try {
            new DiscoveryClientManager<String>(null);
            failBecauseExceptionWasNotThrown(NullPointerException.class);
        } catch (NullPointerException npe) {
        }
    }

    @Test
    public void testStart() throws Exception {
        manager.start();
        verify(client).start();
    }

    @Test
    public void testStop() throws Exception {
        manager.stop();
        verify(client).close();
    }
}

Add unit tests for DiscoveryClientManager


package com.io7m.jcanephora;

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

import com.io7m.jaux.UnreachableCodeException;

public final class LWJGL30BlendEquationES2Test
{
  /**
   * ∀f. blendEquationFromGL(blendEquationToGL(f)) = f.
   */

  @SuppressWarnings("static-method") @Test public void testBijection()
  {
    for (final BlendEquationES2 f : BlendEquationES2.values()) {
      Assert
        .assertEquals(
          GLTypeConversions.blendEquationES2FromGL(GLTypeConversions
            .blendEquationES2ToGL(f)),
          f);
    }
  }

  @SuppressWarnings("static-method") @Test(
    expected = UnreachableCodeException.class) public void testNonsense()
  {
    GLTypeConversions.blendEquationES2FromGL(-1);
  }
}

Add missing blend equation test

Add missing blend equation test


package org.owasp.appsensor.logging.impl;

/**
 * A simple no-op logger implementation for those that need it.
 *
 * @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
 */
public class NoopLogger implements org.owasp.appsensor.Logger {

	@Override
	public org.owasp.appsensor.Logger setLoggerClass(String className) {
		return null;
	}

	@Override
	public org.owasp.appsensor.Logger setLoggerClass(Class<?> clazz) {
		return null;
	}

	@Override
	public void fatal(String message) { }

	@Override
	public void fatal(String message, Throwable throwable) { }

	@Override
	public void error(String message) { }

	@Override
	public void error(String message, Throwable throwable) { }

	@Override
	public void warning(String message) { }

	@Override
	public void warning(String message, Throwable throwable) { }

	@Override
	public void info(String message) { }

	@Override
	public void info(String message, Throwable throwable) { }

	@Override
	public void debug(String message) { }

	@Override
	public void debug(String message, Throwable throwable) { }

}

Add new reference no-op logger

Add new reference no-op logger


package fortiss.gui;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 * Example: NotificationPopUp popup = new
 * NotificationPopUp(JOptionPane.INFORMATION_MESSAGE, "This is a message!",
 * IconStore.save, 1);
 */
public class NotificationPopUp extends JDialog {

	private static final long serialVersionUID = 1L;

	private final JOptionPane messagePane;
	private Timer timer;

	/**
	 *
	 * @param messageType JOptionPane.<INFORMATION_MESSAGE, ERROR_MESSAGE,
	 *                    WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE>
	 * @param message     A String
	 * @param icon        A ImageIcon
	 * @param duration    An Integer [seconds] or null
	 */
	public NotificationPopUp(int messageType, String message, ImageIcon icon, Integer duration) {
		messagePane = new JOptionPane(message, messageType, JOptionPane.DEFAULT_OPTION, icon, new Object[] {}, null);

		setTitle("MEMAP Notification");
		setContentPane(messagePane);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		pack();
		setLocationRelativeTo(null);

		if (duration != null) {
			timer = new Timer(duration * 1000, new AbstractAction() {
				private static final long serialVersionUID = 1L;

				@Override
				public void actionPerformed(ActionEvent ae) {
					dispose();
				}
			});
			timer.setRepeats(false);

			timer.start();
		}
		setVisible(true);
	}

}

Add class to display pop-up notification (disappering is an option)


package test.projects;

import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.github.sormuras.bach.Command;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class MultiRelease11Tests {

  @Test
  void build(@TempDir Path temp) throws Exception {
    var cli = new CLI("MultiRelease-11", temp);
    var out = cli.build("--verbose", "--project-targets-java", "11");
    var foo = cli.workspace("modules", "foo@0.jar");
    assertTrue(Files.exists(foo));
    assertLinesMatch(
        """
        >> BACH'S INITIALIZATION >>
        // Perform main action: `build`
        Build MultiRelease-11 0
        >> INFO + BUILD >>
        Build took .+
        Logbook written to .+
        """
            .lines(),
        out.lines());
    assertLinesMatch(
        """
        META-INF/
        META-INF/MANIFEST.MF
        module-info.class
        foo/
        foo/Foo.class
        META-INF/versions/16/
        META-INF/versions/16/foo/
        META-INF/versions/16/foo/Foo.class
        META-INF/versions/12/
        META-INF/versions/12/foo/
        META-INF/versions/12/foo/Foo.class
        META-INF/versions/13/
        META-INF/versions/13/foo/
        META-INF/versions/13/foo/Foo.class
        META-INF/versions/14/
        META-INF/versions/14/foo/
        META-INF/versions/14/foo/Foo.class
        META-INF/versions/15/
        META-INF/versions/15/foo/
        META-INF/versions/15/foo/Foo.class
        """
            .lines(),
        CLI.run(Command.jar().add("--list").add("--file", foo)).lines());
  }
}

Add build test for test project MultiRelease-11


package net.onrc.onos.core.datastore.utils;

import org.hamcrest.MatcherAssert;
import org.junit.Test;

import static net.onrc.onos.core.util.UtilityClassChecker.assertThatClassIsUtility;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

/**
 * Test cases for the ByteArrayUtil class.
 */

public class ByteArrayUtilTest {

    /**
     * Make sure that the ByteArrayUtil class is a utility class.
     */
    @Test
    public void testForWellDefinedUtilityClass() throws Exception {
        assertThatClassIsUtility(ByteArrayUtil.class);
    }

    /**
     * Test that when given a null array for the bytes to convert, the hex
     * conversion routines return an empty StringBuilder.
     */
    @Test
    public void testToHexStringBuilderNullParameter() {
        final StringBuilder allocatedBuilder =
                ByteArrayUtil.toHexStringBuilder(null, "");
        MatcherAssert.assertThat(allocatedBuilder, is(notNullValue()));
        MatcherAssert.assertThat(allocatedBuilder.toString(), is(equalTo("")));

        final StringBuilder providedBuilder = new StringBuilder();
        final StringBuilder returnedBuilder = ByteArrayUtil.toHexStringBuilder
                (null, "", providedBuilder);
        MatcherAssert.assertThat(providedBuilder, is(notNullValue()));
        MatcherAssert.assertThat(returnedBuilder, is(equalTo(providedBuilder)));
        MatcherAssert.assertThat(providedBuilder.toString(), is(equalTo("")));
    }

    /**
     * Test the array byte to String conversion routines to be sure the data
     * is converted properly.
     */
    @Test
    public void testToHexStringBuilder() {
        final byte[] testData = {0x1,  0x2,  0x3,  0x4,  0x5,
                                 0x3b, 0x3c, 0x3d, 0x3e, 0x3f};
        final String expectedResult = "1:2:3:4:5:3b:3c:3d:3e:3f";

        final StringBuilder result =
                ByteArrayUtil.toHexStringBuilder(testData, ":");

        MatcherAssert.assertThat(result, is(notNullValue()));
        MatcherAssert.assertThat(result.toString(),
                is(equalTo(expectedResult)));

        final StringBuilder providedBuilder = new StringBuilder();
        final StringBuilder returnedBuilder =
                ByteArrayUtil.toHexStringBuilder(testData, ":", providedBuilder);

        MatcherAssert.assertThat(returnedBuilder, is(notNullValue()));
        MatcherAssert.assertThat(returnedBuilder, is(equalTo(providedBuilder)));
        MatcherAssert.assertThat(returnedBuilder.toString(),
                is(equalTo(expectedResult)));
    }
}

Add a unit test for the ByteArrayUtil class

Test cases added:
- Ensure that the ByteArrayUtil class is a proper
  utility class.
- Test that passing in a null array results in an empty string
- Test the formatting of real data into a hex string

Change-Id: Ibbfd2ebdf8c5daff0569862ae3dc8c898d0d0384


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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

import java.nio.charset.StandardCharsets;

/**
 * Utility class related to encoding characters into (UTF-8) byte sequences.
 */
public class UTF8Encoder {

    private UTF8Encoder() {
    }

    /**
     * Get an encoder suitable for UTF-8, using the proper error handling flags.
     *
     * Note that the instance is kept in a thread local to avoid the cost of
     * constructing an encoder for every call. This actually mimics the
     * internals of {@link String#getBytes(String)}.
     */
    private static ThreadLocal<CharsetEncoder> CSE = new ThreadLocal<CharsetEncoder>() {
        @Override
        protected CharsetEncoder initialValue() {
            CharsetEncoder e = StandardCharsets.UTF_8.newEncoder();
            e.onUnmappableCharacter(CodingErrorAction.REPORT);
            e.onMalformedInput(CodingErrorAction.REPORT);
            return e;
        }
    };

    /**
     * Like {@link String#getBytes(java.nio.charset.Charset)} (with "UTF-8"),
     * except that invalid character sequences (such as unpaired surrogates) are
     * reported as exceptions (see {@link CodingErrorAction#REPORT}, instead of
     * being silently replaced by a replacement character as it would happen
     * otherwise.
     *
     * @param input
     *            String to encode
     * @return String encoded using {@link StandardCharsets#UTF_8}
     * @throws IOException
     *             on encoding error
     */
    public static byte[] encodeAsByteArray(String input) throws IOException {
        CharsetEncoder e = CSE.get();
        e.reset();
        return bytes(e.encode(CharBuffer.wrap(input.toCharArray())));
    }

    /**
     * @see {@link CharsetEncoder#canEncode(CharSequence)
     */
    public static boolean canEncode(CharSequence input) {
        CharsetEncoder e = CSE.get();
        e.reset();
        return e.canEncode(input);
    }

    private static byte[] bytes(ByteBuffer b) {
        byte[] a = new byte[b.remaining()];
        b.get(a);
        return a;
    }
}

OAK-7268: Create charset encoding utility that detects malformed input

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1824253 13f79535-47bb-0310-9956-ffa450edef68


/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.model;

import de.dfki.asr.compass.math.Vector3f;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class SceneNodeTest {

	@Test
	public void sceneNodeIsChildShouldReturnFalse () {
		SceneNode parent = new SceneNode();
		SceneNode noChild = new SceneNode();
		assertFalse(noChild.isChildOf(parent));
	}

	@Test
	public void sceneNodeIsChildShouldReturnTrue () {
		SceneNode parent = new SceneNode();
		SceneNode child = new SceneNode();
		child.setParent(parent);
		assertTrue(child.isChildOf(parent));
	}

	@Test(expectedExceptions = IllegalArgumentException.class)
	public void sceneNodeAddComponentShouldThrowIllegalArgument() {
		SceneNode sceneNode = new SceneNode();
		sceneNode.addComponent(null);
	}

	@Test
	public void sceneNodeWorldSpaceOfRootShouldBeLocal() {
		SceneNode sceneNode = new SceneNode();
		sceneNode.setLocalTranslation(new Vector3f(10.0f, 20.0f, 30.0f));
		sceneNode.setLocalRoll(40.0);
		assertEquals(sceneNode.getWorldSpaceTransform(), sceneNode.getLocalTransform());
	}
}

Test for childof SceneNode, addComponenta and worldspace transform of root


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-22
 * Site       : https://www.acmicpc.net/problem/2440
 */

public class Boj2440 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int i=0; i<n; i++){
            for(int j=i; j<n; j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }

}

Solve No.2440 from Baekjoon Online Judge


/*
 * Copyright 2012-2013 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.test;

import org.junit.Test;
import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.site.ApplicationConfiguration;

/**
 * @author Dave Syer
 *
 */
public class ApplicationConfigurationTests {

	@Test
	public void testContextLoading() throws Exception {
		AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext();
		context.register(ApplicationConfiguration.class);
		context.refresh();
		context.close();
	}

}

Add tests for CI build

Add tests for CI build


package net.rubyeye.xmemcached.test.unittest;

import java.net.InetSocketAddress;
import java.util.List;

import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class ConnectionPoolMemcachedClientTest extends XMemcachedClientTest {
	private static final int CONNECTION_POOL_SIZE = 3;

	@Override
	public MemcachedClientBuilder createBuilder() throws Exception {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil
				.getAddresses(this.properties
						.getProperty("test.memcached.servers")));
		builder.setConnectionPoolSize(CONNECTION_POOL_SIZE);
		return builder;
	}

	@Override
	public MemcachedClientBuilder createWeightedBuilder() throws Exception {
		List<InetSocketAddress> addressList = AddrUtil
				.getAddresses(this.properties
						.getProperty("test.memcached.servers"));
		int[] weights = new int[addressList.size()];
		for (int i = 0; i < weights.length; i++) {
			weights[i] = i + 1;
		}

		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				addressList, weights);
		builder.setConnectionPoolSize(CONNECTION_POOL_SIZE);
		builder.setCommandFactory(new BinaryCommandFactory());
		builder.setSessionLocator(new KetamaMemcachedSessionLocator());
		return builder;
	}
}

Add connection pool client unit test.

Add connection pool client unit test.


package org.lmdbjava;

import static java.lang.Long.BYTES;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.lmdbjava.Library.MDB_val;
import static org.lmdbjava.Library.runtime;

public class LibraryTest {

  @Test
  public void structureFieldOrder() throws Exception {
    MDB_val v = new MDB_val(runtime);
    assertThat(v.size.offset(), is(0L));
    assertThat(v.data.offset(), is((long) BYTES));
  }

}

Add a test to ensure MDB_val field order preserved


package org.realityforge.gwt.appcache.server;

import java.util.HashSet;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class PermutationTest
{
  @Test
  public void basicOperation()
    throws Exception
  {
    final Permutation permutation1 = new Permutation( "Foo" );
    final Permutation permutation2 = new Permutation( "Bar" );
    assertEquals( permutation1.getPermutationName(), "Foo" );
    assertEquals( permutation1.getBindingProperties().size(), 0 );
    permutation1.getBindingProperties().put( 0, new HashSet<BindingProperty>() );
    assertEquals( permutation1.getBindingProperties().size(), 1 );
    assertFalse( permutation1.equals( permutation2 ) );
    assertTrue( permutation1.equals( permutation1 ) );
  }
}

Add some basic tests around the permutation class


package com.statemachinesystems.envy.parsers;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class StringValueParserTest {

    @Test
    public void parsesStrings() {
        String value = "foo";
        assertThat(new StringValueParser().parseValue(value), is(value));
    }
}

Add missing test for StringValueParser

Add missing test for StringValueParser


/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates
 *
 * 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
 *
 * Contributors:
 *      Eurotech - initial APInd implementation
 *******************************************************************************/
package org.eclipse.kapua.commons.model.id;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.commons.setting.system.SystemSettingKey;

/**
 * Generates random identifier
 *
 * @since 1.0
 *
 */
public class IdGenerator
{
    private final static SecureRandom secureRandom = new SecureRandom();
    private static int                ID_SIZE      = SystemSetting.getInstance().getInt(SystemSettingKey.KAPUA_KEY_SIZE);

    /**
     * Generate a {@link BigInteger} random value.<br>
     * For more detail refer to: {@link SystemSettingKey#KAPUA_KEY_SIZE}
     *
     * @return
     */
    public static BigInteger generate()
    {
        byte[] bytes = new byte[ID_SIZE];
        secureRandom.nextBytes(bytes);
        return new BigInteger(bytes);
    }

}

/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates
 *
 * 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
 *
 * Contributors:
 *      Eurotech - initial APInd implementation
 *******************************************************************************/
package org.eclipse.kapua.commons.model.id;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.commons.setting.system.SystemSettingKey;

/**
 * Generates random identifier
 *
 * @since 1.0
 *
 */
public class IdGenerator {

    private final static SecureRandom secureRandom = new SecureRandom();
    private final static int ID_SIZE = SystemSetting.getInstance().getInt(SystemSettingKey.KAPUA_KEY_SIZE);

    /**
     * Generate a {@link BigInteger} random value.<br>
     * For more detail refer to: {@link SystemSettingKey#KAPUA_KEY_SIZE}
     *
     * @return
     */
    public static BigInteger generate() {
        byte[] bytes = new byte[ID_SIZE];
        secureRandom.nextBytes(bytes);
        return new BigInteger(bytes);
    }

}

Apply code formatter and code style

Apply code formatter and code style


package net.restlesscoder.sandbox;

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

public class CollectionReferenceRecursion {

	public static void main(final String... args) {
		final List<Object> l1 = new ArrayList<>(Arrays.asList(1, 2, 3));
		final List<Object> l2 = new ArrayList<>(Arrays.asList(4, 5, 6));

		System.out.println("-- BEFORE --");
		System.out.println("l1 = " + l1);
		System.out.println("l2 = " + l2);

		// Java is OK when a collection contains itself directly.
		l1.add(l1);
		l2.add(l2);
		System.out.println("-- DIRECT-REFERENCED --");
		System.out.println("l1 = " + l1);
		System.out.println("l2 = " + l2);

		// But Java fails when a collection contains itself indirectly.
		l1.add(l2);
		l2.add(l1);
		System.out.println("-- CROSS-REFERENCED --");
		System.out.println("l1 = " + l1);
		System.out.println("l2 = " + l2);
	}

}

Add a collections infinite recursion bug


/*
 * (C) Copyright 2017 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.test.docker;

import static io.github.bonigarcia.BrowserType.CHROME;
import static java.lang.System.setProperty;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

import java.io.File;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.remote.RemoteWebDriver;

import io.github.bonigarcia.DockerBrowser;
import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
@TestInstance(PER_CLASS)
public class DockerHtmlVncJupiterTest {

    File htmlFile;

    @BeforeAll
    void setup() {
        setProperty("sel.jup.vnc.create.redirect.html.page", "true");
    }

    @AfterAll
    void teardown() {
        setProperty("sel.jup.vnc.create.redirect.html.page", "false");
        assertTrue(htmlFile.exists());
        htmlFile.delete();
    }

    @Test
    public void testHtmlVnc(
            @DockerBrowser(type = CHROME) RemoteWebDriver driver) {
        driver.get("https://bonigarcia.github.io/selenium-jupiter/");
        assertThat(driver.getTitle(),
                containsString("A JUnit 5 extension for Selenium WebDriver"));

        htmlFile = new File(driver.getSessionId() + ".html");
    }

}

Include test using sel.jup.vnc.create.redirect.html.page key


package net.jgp.labs.spark.l000_ingestion;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

/**
 * Turning a custom data source to a Dataset/Dataframe.
 *
 * @author jgp
 */
public class CustomDataSourceToDataset {

	public static void main(String[] args) {
		System.out.println("Working directory = " + System.getProperty("user.dir"));
		CustomDataSourceToDataset app = new CustomDataSourceToDataset();
		app.start();
	}

	private void start() {
		SparkSession spark = SparkSession.builder().appName("Custom data set to Dataset").master("local").getOrCreate();

		String filename = "data/array-complex.json";
		long start = System.currentTimeMillis();
		Dataset<Row> df = spark.read().format("net.jgp.labs.spark.datasource.CharCounterDataSource")
				.option("char", "a") // count the number of 'a'
				.load(filename); // local file (line 40 in the stacks below)
		long stop = System.currentTimeMillis();
		System.out.println("Processing took " + (stop - start) + " ms");
		df.show();
		df.printSchema();
	}
}

Work on custom data souce

Work on custom data souce


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

import java.math.BigInteger;

import nom.bdezonia.zorbage.accessor.AccessorA;
import nom.bdezonia.zorbage.accessor.AccessorB;
import nom.bdezonia.zorbage.type.data.rational.RationalMember;

/**
 *
 * @author Barry DeZonia
 *
 */
public class SplatRational {

	/**
	 *
	 * @param value
	 * @param tuple
	 */
	public static <V extends AccessorA<BigInteger> & AccessorB<BigInteger>>
		void toTuple(RationalMember value, V tuple)
	{
		tuple.setA(value.n());
		tuple.setB(value.d());
	}

	/**
	 *
	 * @param tuple
	 * @param value
	 */
	public static <V extends AccessorA<BigInteger> & AccessorB<BigInteger>>
		void toValue(V tuple, RationalMember value)
	{
		value.setV(tuple.a(),tuple.b());
	}
}

Add a splat helper just for rational numbers


package org.apache.ddlutils.platform;

/*
 * Copyright 1999-2005 The Apache Software Foundation.
 *
 * 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.
 */

import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.dynabean.SqlDynaBean;
import org.apache.ddlutils.dynabean.SqlDynaClass;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

/**
 * Tests the {@link org.apache.ddlutils.PlatformImplBase} (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: 279421 $
 */
public class TestPlatformImplBase extends TestPlatformBase
{

    String xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
                 "<database name='ddlutils'>\n"+
                 "  <table name='TestTable'>\n"+
                 "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
                 "    <column name='name' type='VARCHAR' size='15'/>\n"+
                 "  </table>\n"+
                 "</database>";

    public void setUp()
    {
    }

    /**
     * Test the toColumnValues method
     */
    public void testToColumnValues()
    {
        Database database = parseDatabaseFromString(xml);
        PlatformImplBase platform = new PlatformBase();
        Table table = database.getTable(0);
        SqlDynaClass clz = SqlDynaClass.newInstance(table);
        DynaBean db = new SqlDynaBean(SqlDynaClass.newInstance(table));
        db.set("name", "name");
        Map map = platform.toColumnValues(clz.getSqlDynaProperties(), db);

        assertEquals("name", map.get("name"));
        assertEquals(true, map.containsKey("id"));
    }

    public class PlatformBase extends PlatformImplBase
    {
        public String getName()
        {
            return null;
        }
    }

    protected String getDatabaseName() {
        return null;
    }

}

Add test for abstract PlatformImplBase.

Add test for abstract PlatformImplBase.

git-svn-id: 9ba7b058a3825ad085cc988a898da8cc978da7ce@331926 13f79535-47bb-0310-9956-ffa450edef68


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

import com.github.pedrovgs.binarytree.BinaryNode;
import org.junit.Before;
import org.junit.Test;

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

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

  private IsTreeBalanced isTreeBalanced;

  @Before public void setUp() {
    isTreeBalanced = new IsTreeBalanced();
  }

  @Test public void shouldReturnTrueIfTreeIsNull() {
    boolean isBalanced = isTreeBalanced.check(null);

    assertTrue(isBalanced);
  }

  @Test public void shouldReturnFalseIfTreeIsNotBalanced() {
    BinaryNode<Integer> root = new BinaryNode<Integer>(0);
    BinaryNode<Integer> n1 = new BinaryNode<Integer>(1);
    BinaryNode<Integer> n2 = new BinaryNode<Integer>(2);
    BinaryNode<Integer> n3 = new BinaryNode<Integer>(3);
    BinaryNode<Integer> n4 = new BinaryNode<Integer>(4);
    root.setLeft(n1);
    root.setRight(n2);
    n1.setLeft(n3);
    n3.setLeft(n4);

    boolean isBalanced = isTreeBalanced.check(root);

    assertFalse(isBalanced);
  }

  @Test public void shouldReturnTrueIfTreeIsBalanced() {
    BinaryNode<Integer> root = new BinaryNode<Integer>(0);
    BinaryNode<Integer> n1 = new BinaryNode<Integer>(1);
    BinaryNode<Integer> n2 = new BinaryNode<Integer>(2);
    BinaryNode<Integer> n3 = new BinaryNode<Integer>(3);
    BinaryNode<Integer> n4 = new BinaryNode<Integer>(4);
    root.setLeft(n1);
    root.setRight(n2);
    n1.setLeft(n3);
    n2.setRight(n4);

    boolean isBalanced = isTreeBalanced.check(root);

    assertTrue(isBalanced);
  }
}

Add some tests to problem 65

Add some tests to problem 65


/*
 * Copyright 2013 That Amazing Web Ltd.
 *
 * 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.taw.dashtube;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;

/**
 * Dialog fragment for the About box.
 */
public class AboutDialogFragment extends DialogFragment {

    private static AboutDialogFragment about = null;

    public static AboutDialogFragment getInstance() {
        if (about == null) {
            about = new AboutDialogFragment();
        }
        return about;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View titleView = View.inflate(getActivity(), R.layout.about_dialog_title_view, null);
        View bodyView = View.inflate(getActivity(), R.layout.about_dialog_view, null);

        // Set up strings for URLs
        TextView txt = (TextView) bodyView.findViewById(R.id.about_dialog_text);
        txt.setText(Html.fromHtml(getString(R.string.about_dialog_text)));
        txt.setMovementMethod(LinkMovementMethod.getInstance());

        return new AlertDialog.Builder(getActivity())
                .setCustomTitle(titleView)
                .setView(bodyView)
                .setPositiveButton(getString(R.string.ok_button),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        })
                .create();
    }
};

Create fragment for About dialog

Create fragment for About dialog


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

/**
 * Write code to partition a linked list around a value x, such that all nodes less than x come
 * before after nodes greater than or equal to x.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PartitionList {

}

Add statement to problem 60

Add statement to problem 60


package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

import org.jdesktop.swingx.JXHeader;
import org.jdesktop.swingx.JXMultiSplitPane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.MultiSplitLayout;
import org.jdesktop.swingx.MultiSplitLayout.Node;

public class JXMultiSplitPaneVisualIssues extends InteractiveTestCase {

    private static void prepare(JFrame f) {
        prepare(f, MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));

    }

    private static void prepare(JFrame f, Node model) {
        final JXMultiSplitPane msp;
        JXPanel p = new JXPanel(new BorderLayout());
        JXHeader header = new JXHeader();
        header.setTitle("<html><B>JXMultiSplitPaneIssue</b>");
        header.setDescription("<html>This is a bit tricky ... To reproduce the issue move one of the dividers and then click reset. Expected behavior is that original layout is restored. Actual behavior (bug) is that only two cells stay displayed and no divider is visible.");
        p.add(header, BorderLayout.NORTH);
        msp = new JXMultiSplitPane();
        msp.setModel(model);
        p.add(msp);
        JButton green = new JButton("mid");
        green.setBackground(Color.GREEN);
        msp.add(green, "middle");
        msp.add(new JButton("l.t"), "left.top");
        msp.add(new JButton("l.b"), "left.bottom");
        msp.add(new JButton("r.t"), "right.top");
        msp.add(new JButton("r.b"), "right.bottom");
        f.add(p);
        JButton b = new JButton(new AbstractAction("Reset") {

            public void actionPerformed(ActionEvent e) {
                // just reset the model
                msp.setModel(MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));
                msp.revalidate();
                msp.repaint();
            }

        });
        f.add(b, BorderLayout.SOUTH);
        f.setPreferredSize(new Dimension(400, 400));
    }

    public void interactiveModelChange() {
        JFrame f = new JFrame();
        prepare(f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        JXMultiSplitPaneVisualIssues test = new JXMultiSplitPaneVisualIssues();
        try {
            test.runInteractiveTests();
          } catch (Exception e) {
              System.err.println("exception when executing interactive tests:");
              e.printStackTrace();
          }
    }

}

Test exposing MultiSplitPane model reset issue.


package com.google.sps.data;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/*
 * Ensure that the AnnotatedField.create() method throws the correct errors when
 * given illegal input.  Test that the getField() method works correctly.
 */
@RunWith(JUnit4.class)
public final class AnnotatedFieldTest {

  @Test(expected = IllegalArgumentException.class)
  public void invalidFieldName() {
    AnnotatedField.create("serialNumber");
  }

  @Test(expected = IllegalArgumentException.class)
  public void nullFieldName() {
    AnnotatedField.create(null);
  }

  @Test
  public void properFieldName() {
    AnnotatedField field = AnnotatedField.create("annotatedLocation");

    Assert.assertEquals(AnnotatedField.LOCATION, field);
  }

  @Test
  public void getsCorrectField() {
    AnnotatedField field = AnnotatedField.create("annotatedUser");

    ChromeOSDevice device = new ChromeOSDevice("assetId", "location", "user", "deviceId", "serialNumber");

    Assert.assertEquals(device.getAnnotatedUser(), field.getField(device));
  }

}

Add test coverage for some issues fixed in the AnnotatedField enum


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

import com.google.common.testing.EqualsTester;
import io.spine.server.model.ModelTests;
import org.junit.Test;

import static io.spine.server.delivery.given.ShardedStreamTestEnv.anotherZeroToProjects;
import static io.spine.server.delivery.given.ShardedStreamTestEnv.commandStreamToTasksOne;
import static io.spine.server.delivery.given.ShardedStreamTestEnv.commandStreamToTasksZero;
import static io.spine.server.delivery.given.ShardedStreamTestEnv.streamOneToProjects;
import static io.spine.server.delivery.given.ShardedStreamTestEnv.streamZeroToProjects;

/**
 * @author Alex Tymchenko
 */
public class ShardingKeyShould {

    @Test
    public void support_equality() {
        ModelTests.clearModel();

        final ShardingKey projectsZero = streamZeroToProjects().getKey();
        final ShardingKey theSameProjectsZero = anotherZeroToProjects().getKey();
        final ShardingKey projectsOne = streamOneToProjects().getKey();
        final ShardingKey tasksZeroKey = commandStreamToTasksZero().getKey();
        final ShardingKey tasksOneKey = commandStreamToTasksOne().getKey();

        new EqualsTester().addEqualityGroup(projectsZero, theSameProjectsZero)
                          .addEqualityGroup(projectsOne)
                          .addEqualityGroup(tasksZeroKey)
                          .addEqualityGroup(tasksOneKey)
                          .testEquals();
    }
}

Cover `ShardingKey` equality with tests.


package au.gov.dto.dibp.appointments.session;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ExtendSessionController {
    @RequestMapping(value = "/extend_session", method = RequestMethod.GET, produces = "application/json")
    public Map<String, Object> extendSession() {
        return new HashMap<>();
    }
}

Add endpoint to extend session cookies

Add endpoint to extend session cookies


package gov.nih.nci.cabig.caaers.web;

import gov.nih.nci.cabig.caaers.domain.Agent;
import gov.nih.nci.cabig.caaers.domain.repository.AgentRepository;
import gov.nih.nci.cabig.caaers.web.search.SearchStudyAjaxFacade;

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

import org.easymock.classextension.EasyMock;
import org.springframework.mock.web.MockHttpServletRequest;

public class SearchStudyAjaxFacadeTest extends DwrFacadeTestCase {

	private SearchStudyAjaxFacade searchStudyAjaxFacade;
	private AgentRepository agentRepository;
	private List<Agent> agents;
	private MockHttpServletRequest request;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		searchStudyAjaxFacade = new SearchStudyAjaxFacade();
		agentRepository = registerMockFor(AgentRepository.class);
		searchStudyAjaxFacade.setAgentRepository(agentRepository);
		agents = new ArrayList<Agent>();
		Agent agent = new Agent();
		agent.setId(1);
		agent.setName("name1");
		agent.setNscNumber("nsc1");
		agent.setRetiredIndicator(true);
		agent.setDescription("desc1");
		agents.add(agent);
		agent = new Agent();
		agent.setId(2);
		agent.setName("name2");
		agent.setNscNumber("nsc2");
		agent.setRetiredIndicator(true);
		agent.setDescription("desc2");
		agents.add(agent);
		request = new MockHttpServletRequest();
	}

	public void testGetAgentsTable(){
		EasyMock.expect(agentRepository.getAgentsByNameAndNsc("text", "nsc", false)).andReturn(agents);
		replayMocks();
		List<Agent> returnedAgents = searchStudyAjaxFacade.getAgentsTable(new HashMap(), "text", "nsc", request);
		assertEquals(2, returnedAgents.size());
		assertNull(returnedAgents.get(0).getDescription());
		assertNull(returnedAgents.get(1).getDescription());
		verifyMocks();
	}

}

Test case improvement for 'Add Expected AE to Agent.'

SVN-Revision: 16963


package com.dropwizard.steroids.quickstart.hello;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class HelloWorldResourceTest {
    @Test
    public void shouldBeTrue() {
        assertTrue(true);
    }
}

Create sample test case to validate if gradle test task works


package com.diogonunes.jcdp.tests.acceptance;

import com.diogonunes.jcdp.bw.Printer;
import com.diogonunes.jcdp.bw.Printer.Types;
import com.diogonunes.jcdp.color.ColoredPrinter;
import com.diogonunes.jcdp.color.api.Ansi.Attribute;
import com.diogonunes.jcdp.color.api.Ansi.BColor;
import com.diogonunes.jcdp.color.api.Ansi.FColor;
import org.junit.Test;

public class TestVisually {

    @Test
    public void TestHowItLooksOnConsole() {

        // =============================
        // Example of a terminal Printer
        // =============================

        Printer p = new Printer.Builder(Types.TERM).build();
        p.println(p);
        p.println("This is a normal message.");
        p.errorPrintln("This is an error message.");
        p.debugPrintln("This debug message is always printed.");
        p = new Printer.Builder(Types.TERM).level(1).timestamping(false).build();
        p.println(p);
        p.debugPrintln("This is printed because its level is <= 1", 1);
        p.debugPrintln("This isn't printed because its level is > 1", 2);
        p.setLevel(2);
        p.debugPrintln("Now this is printed because its level is <= 2", 2);

        // =======================================================
        // Example of a Colored terminal Printer (WINDOWS or UNIX)
        // =======================================================

        ColoredPrinter cp = new ColoredPrinter.Builder(1, false)
                .foreground(FColor.WHITE).background(BColor.BLUE)   //setting format
                .build();

        //printing according to that format
        cp.println(cp);
        cp.setAttribute(Attribute.REVERSE);
        cp.println("This is a normal message (with format reversed).");

        //resetting the terminal to its default colors
        cp.clear();
        cp.print(cp.getDateFormatted(), Attribute.NONE, FColor.CYAN, BColor.NONE);
        cp.debugPrintln(" This debug message is always printed.");
        cp.clear();
        cp.print("This example used JCDP 2.0.3   ");

        //temporarily overriding that format
        cp.print("\tMADE ", Attribute.BOLD, FColor.YELLOW, BColor.GREEN);
        cp.print("IN PORTUGAL\t\n", Attribute.BOLD, FColor.YELLOW, BColor.RED);
        cp.println("I hope you find it useful ;)");

        cp.clear(); //don't forget to clear the terminal's format before exiting
    }
}

Add test to be manually checked by human-eye on a real console Hint: it uses the same example code released on the README.md


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

package org.spine3.server.entity.storage;

import org.junit.Test;

import static org.junit.Assert.assertSame;

/**
 * @author Dmytro Dashenkov
 */
public class SimpleColumnTypeShould {

    @Test
    public void perform_identity_conversion_of_given_value() {
        final ColumnType<Object, ?, ?, ?> columnType = new ColumnTypeImpl<>();
        final Object input = new Object();
        final Object output = columnType.convertColumnValue(input);
        assertSame(input, output);
    }

    private static class ColumnTypeImpl<T, R, C> extends SimpleColumnType<T, R, C> {

        @Override
        public void setColumnValue(Object storageRecord, Object value, Object columnIdentifier) {
            // NOP
        }

        @Override
        public void setNull(Object storageRecord, Object columnIdentifier) {
            // NOP
        }
    }
}

Cover the identity conversion method in `SimpleColumnType`.


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

package org.spine3.examples.todolist.validator;

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

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author Illia Shepilov
 */
@DisplayName("ApproveValidator should")
class ApproveValidatorTest {

    private final Validator validator = new ApproveValidator();

    @Test
    @DisplayName("pass the validation when input is `n`")
    public void passValidationWhenNegativeAnswer() {
        final boolean passed = validator.validate("n");
        assertTrue(passed);
    }

    @Test
    @DisplayName("pass the validation when input is `y`")
    public void passValidationWhenPositiveAnswer() {
        final boolean passed = validator.validate("y");
        assertTrue(passed);
    }

    @Test
    @DisplayName("not pass the validation when input is null")
    public void notPassValidationWhenInputIsNull() {
        final boolean passed = validator.validate(null);
        assertFalse(passed);
    }

    @Test
    @DisplayName("not pass the validation when input is empty")
    public void notPassTheValidationWhenInputIsEmpty() {
        final boolean passed = validator.validate("");
        assertFalse(passed);
    }

    @Test
    @DisplayName("not pass the validation when input neither positive neither negative")
    public void notPassTheValidationWhenIsputIsIncorrect() {
        final boolean passed = validator.validate("O");
        assertFalse(passed);
    }
}

Create tests for the `ApproveValidator` class.


package org.ow2.chameleon.rose.util;

import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;

public class DefaultLogService implements LogService {

	public void log(int level, String message) {
		System.out.println("["+getLevel(level)+"] "+ message);

	}

	public void log(int level, String message, Throwable exception) {
		log(level, message);
		System.out.println("\n\t(Exception)");
		exception.printStackTrace();
		System.out.println("\n\t(^Exception)");

	}

	public void log(ServiceReference sr, int level, String message) {
		log(level, message);
		System.out.println("\n\t(ServiceReference)\n\t"+sr.toString());
		System.out.println("\n\t(^ServiceReference)");
	}

	public void log(ServiceReference sr, int level, String message, Throwable exception) {
		log(sr, level, message);
		System.out.println("\n\t(Exception)");
		exception.printStackTrace();
		System.out.println("\n\t(^Exception)");
	}

	private static String getLevel(int level) {
		final String slevel;
		switch (level) {
		case LOG_DEBUG:
			slevel = "DEBUG";
			break;
		case LOG_ERROR:
			slevel = "ERROR";
			break;
		case LOG_INFO:
			slevel = "INFO";
			break;
		case LOG_WARNING:
			slevel = "WARNING";
			break;
		default:
			slevel = "BAD LEVEL";
			break;
		}

		return slevel;
	}

}

Add a default LogService Implementation.


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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

import java.nio.charset.StandardCharsets;

/**
 * Utility class related to encoding characters into (UTF-8) byte sequences.
 */
public class UTF8Encoder {

    private UTF8Encoder() {
    }

    /**
     * Get an encoder suitable for UTF-8, using the proper error handling flags.
     *
     * Note that the instance is kept in a thread local to avoid the cost of
     * constructing an encoder for every call. This actually mimics the
     * internals of {@link String#getBytes(String)}.
     */
    private static ThreadLocal<CharsetEncoder> CSE = new ThreadLocal<CharsetEncoder>() {
        @Override
        protected CharsetEncoder initialValue() {
            CharsetEncoder e = StandardCharsets.UTF_8.newEncoder();
            e.onUnmappableCharacter(CodingErrorAction.REPORT);
            e.onMalformedInput(CodingErrorAction.REPORT);
            return e;
        }
    };

    /**
     * Like {@link String#getBytes(java.nio.charset.Charset)} (with "UTF-8"),
     * except that invalid character sequences (such as unpaired surrogates) are
     * reported as exceptions (see {@link CodingErrorAction#REPORT}, instead of
     * being silently replaced by a replacement character as it would happen
     * otherwise.
     *
     * @param input
     *            String to encode
     * @return String encoded using {@link StandardCharsets#UTF_8}
     * @throws IOException
     *             on encoding error
     */
    public static byte[] encodeAsByteArray(String input) throws IOException {
        CharsetEncoder e = CSE.get();
        e.reset();
        return bytes(e.encode(CharBuffer.wrap(input.toCharArray())));
    }

    /**
     * @see {@link CharsetEncoder#canEncode(CharSequence)
     */
    public static boolean canEncode(CharSequence input) {
        CharsetEncoder e = CSE.get();
        e.reset();
        return e.canEncode(input);
    }

    private static byte[] bytes(ByteBuffer b) {
        byte[] a = new byte[b.remaining()];
        b.get(a);
        return a;
    }
}

OAK-7268: Create charset encoding utility that detects malformed input

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1824253 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright 2013 MovingBlocks
 *
 * 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.
 */

@API package org.terasology.world.sun;

import org.terasology.module.sandbox.API;

Make o.t.world.sun available for modules


/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.microsoft.azure.management.resources.core;

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestResourceProviderRegistration {
    @Test
    public void testManuallyUnregisteredRp() {
        String error = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription is not registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}";
        Matcher matcher = Pattern.compile(".*'(.*)'").matcher(error);
        matcher.find();
        Assert.assertEquals("Microsoft.Devices", matcher.group(1));
    }

    @Test
    public void testRpInNewSubscription() {
        String error = "{\"error\":{\"code\":\"MissingSubscriptionRegistration\",\"message\":\"The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.Devices'. See https://aka.ms/rps-not-found for how to register subscriptions.\"}}";
        Matcher matcher = Pattern.compile(".*'(.*)'").matcher(error);
        matcher.find();
        Assert.assertEquals("Microsoft.Devices", matcher.group(1));
    }
}

Add rp auto registration unit test

Add rp auto registration unit test


package es.tid.cosmos.mobility.activityarea;

import com.twitter.elephantbird.mapreduce.io.ProtobufWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.ReduceDriver;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import es.tid.cosmos.mobility.data.MobProtocol.RepeatedActivityAreas;

/**
 *
 * @author losa
 */
public class IndVarsOutReducerTest {
    private ReduceDriver<
        LongWritable,  ProtobufWritable<RepeatedActivityAreas>,
        NullWritable,  Text>
        reducer;

    @Before
    public void setUp() {
        this.reducer = new ReduceDriver<
            LongWritable,  ProtobufWritable<RepeatedActivityAreas>,
            NullWritable,  Text>
                (new IndVarsOutReducer());
    }

    @Test
    public void testMissingMonthsFilledWithMinusOnes() {
    }
}

Add test for missing months in text output

Missing months in the textual output should be filled with "-1" in all
activity area fields.


package org.cyclops.cyclopscore.client.model;

import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemOverride;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;

import java.util.Collections;
import java.util.List;

/**
 * A dynamic model that can be used for items and blocks.
 * @author rubensworks
 */
public abstract class DynamicItemAndBlockModel extends DynamicBaseModel {

    private final boolean factory;
    private final boolean item;
    private final ItemOverrides itemOverrides;

    public DynamicItemAndBlockModel(boolean factory, boolean item) {
        this.factory = factory;
        this.item = item;
        this.itemOverrides = new ItemOverrides();
    }

    protected boolean isItemStack() {
        return item;
    }

    @Override
    public List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long rand) {
        if(factory) {
            return handleBlockState(state, side, rand).getQuads(state, side, rand);
        }
        return getGeneralQuads();
    }

    public List<BakedQuad> getGeneralQuads() {
        return Collections.emptyList();
    }

    public abstract IBakedModel handleBlockState(IBlockState state, EnumFacing side, long rand);
    public abstract IBakedModel handleItemState(ItemStack stack, World world, EntityLivingBase entity);

    @Override
    public ItemOverrideList getOverrides() {
        return super.getOverrides();
    }

    public class ItemOverrides extends ItemOverrideList {

        public ItemOverrides() {
            super(Collections.<ItemOverride>emptyList());
        }

        @Override
        public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) {
            return DynamicItemAndBlockModel.this.handleItemState(stack, world, entity);
        }
    }

}

Add item and block model abstraction

Add item and block model abstraction


/*
 * 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.harmony.beans.tests.java.beans.beancontext;

import java.beans.beancontext.BeanContextServiceProvider;
import java.beans.beancontext.BeanContextServices;
import java.beans.beancontext.BeanContextServicesSupport;
import java.util.Iterator;

import junit.framework.TestCase;

/*
 * Regression test for HARMONY-1369
 */
public class BeanContextServicesSupport2Test extends TestCase {

    public void test() {
        BeanContextServiceProvider bcsp = new BCSP();
        BCSS serviceSupport = new BCSS(new BeanContextServicesSupport());
        assertTrue("Expected first addService to return true", serviceSupport
                .addService(Boolean.TYPE, bcsp, false));
        assertFalse("Expected second addService to return false", serviceSupport
                .addService(Boolean.TYPE, bcsp, false));
    }

    class BCSP implements BeanContextServiceProvider {
        public Iterator getCurrentServiceSelectors(BeanContextServices p0,
                Class p1) {
            return null;
        }

        public void releaseService(BeanContextServices p0, Object p1, Object p2) {
            return;
        }

        public Object getService(BeanContextServices p0, Object p1, Class p2,
                Object p3) {
            return null;
        }
    }

    class BCSS extends BeanContextServicesSupport {
        public BCSS() {
            super();
        }

        public BCSS(BeanContextServicesSupport peer) {
            super(peer);
        }

        public boolean addService(Class serviceClass,
                BeanContextServiceProvider bcsp, boolean firevent) {
            return super.addService(serviceClass, bcsp, firevent);
        }
    }

}

Add regression test for HARMONY-1369 ([classlib][beans] compatibility: java.beans.beancontext.BeanContextServicesSupport.addService(..) returns true on RI and false on Harmony)

svn path=/harmony/; revision=561851


package com.vaadin.tests.components.ui;

import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Label;

@Theme("tests-tickets")
public class TestUITheme extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        Label label = new Label("A red label");
        label.setStyleName("red");
        addComponent(label);
    }

    @Override
    public String getTestDescription() {
        return "UI with @Theme(\"tests-tickets\")";
    }

    @Override
    protected Integer getTicketNumber() {
        return Integer.valueOf(7885);
    }

}

package com.vaadin.tests.components.ui;

import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Label;

@Theme("tests-tickets")
public class TestUITheme extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        Label label = new Label("A green label");
        label.setStyleName("green");
        addComponent(label);
    }

    @Override
    public String getTestDescription() {
        return "UI with @Theme(\"tests-tickets\"). The label uses a stylename that should only be defined in the test-tickets theme.";
    }

    @Override
    protected Integer getTicketNumber() {
        return Integer.valueOf(7885);
    }

}

Update test to not use red for success.

Update test to not use red for success.


package com.sebastian.sokolowski.auctionhunter.database.models;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Created by Sebastian Sokołowski on 03.03.17.
 */

public class Cat extends RealmObject {
    @PrimaryKey
    private Integer catId;
    private String catName;
    private Integer catParent;
    private Integer catPosition;
    private Integer catIsProductCatalogueEnabled;

    public Integer getCatId() {
        return catId;
    }

    public void setCatId(Integer catId) {
        this.catId = catId;
    }

    public String getCatName() {
        return catName;
    }

    public void setCatName(String catName) {
        this.catName = catName;
    }

    public Integer getCatParent() {
        return catParent;
    }

    public void setCatParent(Integer catParent) {
        this.catParent = catParent;
    }

    public Integer getCatPosition() {
        return catPosition;
    }

    public void setCatPosition(Integer catPosition) {
        this.catPosition = catPosition;
    }

    public Integer getCatIsProductCatalogueEnabled() {
        return catIsProductCatalogueEnabled;
    }

    public void setCatIsProductCatalogueEnabled(Integer catIsProductCatalogueEnabled) {
        this.catIsProductCatalogueEnabled = catIsProductCatalogueEnabled;
    }
}

Add new category realm model.

Add new category realm model.


/*
 * Copyright (C) 2014  Ohm Data
 *
 *  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 c5db.interfaces.log;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

import java.util.List;

import static c5db.interfaces.log.SequentialEntryIterable.SequentialEntryIterator;

public class SequentialEntryIterableMatchers {
  public static <E extends SequentialEntry> TypeSafeMatcher<SequentialEntryIterator<E>>
  isIteratorContainingInOrder(List<E> entries) {

    return new TypeSafeMatcher<SequentialEntryIterator<E>>() {
      private Exception exception;

      @Override
      protected boolean matchesSafely(SequentialEntryIterator<E> iterator) {
        int listIndex = 0;

        try {
          while (iterator.hasNext()) {
            E next = iterator.next();
            if (listIndex >= entries.size()
                || !next.equals(entries.get(listIndex))) {
              return false;
            }

            listIndex++;
          }
        } catch (Exception e) {
          exception = e;
          return false;
        }

        return listIndex == entries.size();
      }

      @Override
      public void describeTo(Description description) {
        description.appendText(" a SequentialEntryIterator containing, in order, ")
            .appendValue(entries);
      }

      @Override
      protected void describeMismatchSafely(SequentialEntryIterator<E> item, Description mismatchDescription) {
        if (exception != null) {
          mismatchDescription.appendValue(exception);
        } else {
          super.describeMismatchSafely(item, mismatchDescription);
        }
      }
    };
  }
}

Add a matcher class for SequentialEntryIterable and its iterator


package leetcode.integer_to_roman;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public String intToRoman(int num) {
    	Map<Integer, String> map = new HashMap<Integer, String>();
    	StringBuilder sb = new StringBuilder();
    	String[] romans = new String[]{
    		"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    		"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    		"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
    		"M", "MM", "MMM",
    	};
    	for(int i = 0; i <= 9; i++){
    		map.put(i, romans[i]);
    	}
    	for(int i = 10; i <= 90; i += 10){
    		map.put(i, romans[i / 10 + 9]);
    	}
    	for(int i = 100; i <= 900; i += 100){
    		map.put(i, romans[i / 100 + 18]);
    	}
    	for(int i = 1000; i <= 3000; i += 1000){
    		map.put(i, romans[i / 1000 + 27]);
    	}
    	for(int x = 1000; x >= 1; x /= 10){
    		sb.append(map.get((num / x % 10) * x));
    	}
    	return sb.toString();
    }

    public static void main(String[] args){
    	for(int i = 1; i <= 3999; i++){
    		System.err.println(i + ":" + new Solution().intToRoman(i));
    	}
    }
}

Add java solution for 12. Integer to Roman

12. Integer to Roman: https://leetcode.com/problems/integer-to-roman/


package com.google.re2j;

import static org.junit.Assert.fail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class RE2CompileTest {
  // A list of regexp and expected error when calling RE2.compile. null implies that compile should
  // succeed.
  @Parameters()
  public static String[][] testData() {
    return new String[][]{
      {"", null},
      {".", null},
      {"^.$", null},
      {"a", null},
      {"a*", null},
      {"a+", null},
      {"a?", null},
      {"a|b", null},
      {"a*|b*", null},
      {"(a*|b)(c*|d)", null},
      {"[a-z]", null},
      {"[a-abc-c\\-\\]\\[]", null},
      {"[a-z]+", null},
      {"[abc]", null},
      {"[^1234]", null},
      {"[^\n]", null},
      {"\\!\\\\", null},
      {"abc]",  null}, // Matches the closing bracket literally.
      {"a??", null},
      {"*", "missing argument to repetition operator: `*`"},
      {"+", "missing argument to repetition operator: `+`"},
      {"?", "missing argument to repetition operator: `?`"},
      {"(abc", "missing closing ): `(abc`"},
      {"abc)", "regexp/syntax: internal error: `stack underflow`"},
      {"x[a-z", "missing closing ]: `[a-z`"},
      {"[z-a]", "invalid character class range: `z-a`"},
      {"abc\\", "trailing backslash at end of expression"},
      {"a**", "invalid nested repetition operator: `**`"},
      {"a*+", "invalid nested repetition operator: `*+`"},
      {"\\x", "invalid escape sequence: `\\x`"},
    };
  }

  private final String input;
  private final String expectedError;

  public RE2CompileTest(String input, String expectedError) {
    this.input = input;
    this.expectedError = expectedError;
  }

  @Test
  public void testCompile() {
    try {
      RE2.compile(input);
      if (expectedError != null) {
        fail("RE2.compile(" + input + ") was successful, expected " + expectedError);
      }
    } catch (PatternSyntaxException e) {
      if (expectedError == null ||
          !e.getMessage().equals("error parsing regexp: " + expectedError)) {
        fail("compiling " + input + "; unexpected error: " + e.getMessage());
      }
    }
  }
}

Split out RE2.compile test into its own parameterized JUnit4 test


package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;

public class TestItemTagsProvider extends CommonItemTagsProvider {

	public TestItemTagsProvider(GenerationData data, CommonBlockTagsProvider blockProvider) {
		super(data, blockProvider);
	}

	@Override
	protected void registerTags() {
	}

}

Add test item tags provider

Add test item tags provider


package uk.ac.ebi.spot.goci.curation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Future;

/**
 * Created by emma on 06/06/2016.
 *
 * @author emma
 *         <p>
 *         Service to create a printable view of all study details
 */
@Service
public class StudyPrintService {

    private StudyRepository studyRepository;
    private AssociationRepository associationRepository;
    private AssociationViewService associationViewService;

    @Autowired
    public StudyPrintService(StudyRepository studyRepository,
                             AssociationRepository associationRepository,
                             AssociationViewService associationViewService) {
        this.studyRepository = studyRepository;
        this.associationRepository = associationRepository;
        this.associationViewService = associationViewService;
    }

    public Collection<SnpAssociationTableView> generatePrintView(Long studyId) {
        // Get relevant study details
        Study studyToView = studyRepository.findOne(studyId);

        // Association information
        Collection<Association> associations = new ArrayList<>();
        associations.addAll(associationRepository.findByStudyId(studyId));

        // For our associations create a table view object and return
        Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
        for (Association association : associations) {
            SnpAssociationTableView snpAssociationTableView =
                    associationViewService.createSnpAssociationTableView(association);
            snpAssociationTableViews.add(snpAssociationTableView);
        }
        return snpAssociationTableViews;
    }
}

Move the association view creation to this service rather that controller


package de.lmu.ifi.dbs.elki.math.statistics.distribution.estimator;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 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/>.
 */
import de.lmu.ifi.dbs.elki.math.statistics.distribution.WaldDistribution;
import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.NumberArrayAdapter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;

/**
 * Estimate parameter of the Wald distribution.
 *
 * @author Erich Schubert
 *
 * @apiviz.has WaldDistribution
 */
public class WaldMLEstimator implements DistributionEstimator<WaldDistribution> {
  /**
   * Static instance.
   */
  public static final WaldMLEstimator STATIC = new WaldMLEstimator();

  @Override
  public <A> WaldDistribution estimate(A data, NumberArrayAdapter<?, A> adapter) {
    final int len = adapter.size(data);
    double mean = 0.;
    for(int i = 0; i < len; i++) {
      double v = adapter.getDouble(data, i);
      mean += v;
    }
    mean /= len;
    double invmean = len / mean;
    double invdev = 0.;
    for(int i = 0; i < len; i++) {
      double v = adapter.getDouble(data, i);
      if(v > 0.) {
        invdev += len / v - invmean;
      }
    }
    return new WaldDistribution(mean, 1. / invdev);
  }

  @Override
  public Class<? super WaldDistribution> getDistributionClass() {
    return WaldDistribution.class;
  }

  /**
   * Parameterization class.
   *
   * @author Erich Schubert
   *
   * @apiviz.exclude
   */
  public static class Parameterizer extends AbstractParameterizer {
    @Override
    protected WaldMLEstimator makeInstance() {
      return STATIC;
    }
  }
}

Add estimator for Wald, untested.

Add estimator for Wald, untested.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.file;

import static org.junit.Assert.assertEquals;

import alluxio.AlluxioURI;
import alluxio.master.file.StartupConsistencyCheck.Status;

import com.google.common.collect.ImmutableList;
import org.junit.Test;

import java.util.Collections;
import java.util.List;

/**
 * Unit tests for {@link StartupConsistencyCheck}.
 */
public final class StartupConsistencyCheckTest {
    @Test
    public void createCompleteCheck() {
        List<AlluxioURI> uris = ImmutableList.of(new AlluxioURI("/"), new AlluxioURI("/dir"));
        StartupConsistencyCheck check = StartupConsistencyCheck.complete(uris);
        assertEquals(Status.COMPLETE, check.getStatus());
        assertEquals(uris, check.getInconsistentUris());
    }

    @Test
    public void createDisabledCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.disabled();
        assertEquals(Status.DISABLED, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }

    @Test
    public void createFailedCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.failed();
        assertEquals(Status.FAILED, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }

    @Test
    public void createRunningCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.running();
        assertEquals(Status.RUNNING, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }
}

Add startup consistency check unit test

Add startup consistency check unit test


package net.alcuria.umbracraft.definitions.skill.actions;

import net.alcuria.umbracraft.Game;
import net.alcuria.umbracraft.Listener;
import net.alcuria.umbracraft.engine.entities.Entity;

import com.badlogic.gdx.math.Vector3;

public class CameraChangeDefinition extends SkillActionDefinition {
	public static enum CameraDirection {
		CENTER(CENTER_POS, CENTER_POS), FAR(CENTER_POS - OFFSET, CENTER_POS + OFFSET), NEAR(CENTER_POS + OFFSET, CENTER_POS - OFFSET);

		private int friendly, nonFriendly;

		CameraDirection(int friendly, int nonFriendly) {
			this.friendly = friendly;
			this.nonFriendly = nonFriendly;
		}

		public int getPosition(final boolean isFriendly) {
			return isFriendly ? friendly : nonFriendly;
		}
	}

	private static final int CENTER_POS = 290; // center of the battle map
	private static final int OFFSET = 40; // offset for the left/right grid focus
	private final Entity cameraTarget;
	private final CameraDirection direction;
	private final boolean isFriendly;

	public CameraChangeDefinition(CameraDirection direction, boolean isFriendly, Entity cameraTarget) {
		this.direction = direction;
		this.cameraTarget = cameraTarget;
		this.isFriendly = isFriendly;
	}

	@Override
	public void start(Entity entity, Vector3 start, Vector3 target) {
		Game.view().setTarget(cameraTarget);
		cameraTarget.position.x = direction.getPosition(isFriendly);
	}

	@Override
	public void update(Entity entity, Listener stepCompleteListener) {
		stepCompleteListener.invoke();
	}

}

Add a definition to handle camera changes


/*
 * Copyright (c) 2016 Red Hat and others.  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
 */
/**
 * Black magic Mockito utility.
 *
 *
This artifact is "black magic" because by merely depending on it (by its
 * presence on the classpath, without ever using any of its classes), all usages
 * of core Mockito.mock() in your existing tests will suddenly behave
 * differently automagically all by themselves: They will throw
 * ThrowsUnstubbedMethodException instead of returning null etc. as in default
 * Mockito. (This "magic" is also the technical reason why this is package
 * org.mockito.configuration instead of org.opendaylight.*)
 *
 *
TODO Point to the "other/new artifact with more sane Mockito helper, with
 * explicit API.
 *
 * @see MockitoConfiguration
 * @see org.mockito.configuration.IMockitoConfiguration
 */
package org.mockito.configuration;

Package JavaDoc to clarify what this artifact is & does

Full disclosure: I LIKE the concept of what one could call
MockitoNotImplementedExceptionAnswer, and have separately implemented
the same (one can find this idea publicly on the web in several places).

I don't think having this configured by default automagically is good;
that is just too sneaky and surprising IMHO.  One should be able to use
a popular utility and expect it to behave as it's documented?

No offense meant to anyone.  None taken I hope.

Change-Id: Idf30e82c2cb1777065de781a5eecc220416161ca
Signed-off-by: Michael Vorburger <4d49e7cce9f97fb576795ab27509f7ee282641f6@redhat.com>


package com.cflint.plugins.core;

import ro.fortsoft.pf4j.Extension;
import net.htmlparser.jericho.Element;
import cfml.parsing.cfscript.CFExpression;
import cfml.parsing.cfscript.script.CFScriptStatement;

import com.cflint.BugInfo;
import com.cflint.BugList;
import com.cflint.plugins.CFLintScannerAdapter;

@Extension
public class FileCaseChecker extends CFLintScannerAdapter {
	final String severity = "INFO";

	public void startFile(String fileName, BugList bugs) {
		String actualFileName = fileName;
		String separator = System.getProperty("file.separator");
    	int seperatorPosition = fileName.lastIndexOf(separator);

    	if (seperatorPosition >= 0) {
    		actualFileName = fileName.substring(seperatorPosition + 1);
    	}

		if (actualFileName.contains(".cfm")) {
			if (Character.isUpperCase(actualFileName.charAt(0))) {
				bugs.add(new BugInfo.BugInfoBuilder().setLine(1).setMessageCode("FILE_SHOULD_START_WITH_LOWERCASE")
						.setSeverity(severity).setFilename(fileName)
						.setMessage("File " + actualFileName + " starts with a upper case letter. Only components (.cfc files) should start with an upper case letter.")
						.build());
			}
		}
	}
}

Add rule to check if .cfm files start with an upper case letter


package nl.ekholabs.nlp;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class ElsieDeeApplicationTest {

  @Autowired
  private MockMvc mvc;

  @Test
  public void statusOk() throws Exception {
    final RequestBuilder request = get("/");
    mvc.perform(request).andExpect(status().is4xxClientError());
  }
}

Add test to check if the application is starting.


package nom.bdezonia.zorbage.misc;

import static org.junit.Assert.*;

import org.junit.Test;

public class TestLongUtils {

	@Test
	public void test() {
		assertEquals(0, LongUtils.numElements(new long[] {}));
		assertEquals(1, LongUtils.numElements(new long[] {1}));
		assertEquals(6, LongUtils.numElements(new long[] {2,3}));
		assertEquals(120, LongUtils.numElements(new long[] {4,5,6}));
		try {
			LongUtils.numElements(new long[] {-1});
			fail();
		} catch (IllegalArgumentException e) {
			assertTrue(true);
		}
		try {
			LongUtils.numElements(new long[] {2, Long.MAX_VALUE});
			fail();
		} catch (IllegalArgumentException e) {
			assertTrue(true);
		}
	}

}

Define tests for LongUtils class

Define tests for LongUtils class


package pl.vgtworld.imagedraw.filters.edgedetect;

import pl.vgtworld.imagedraw.ImageDrawEntity;
import pl.vgtworld.imagedraw.filters.ImageDrawFilter;
import pl.vgtworld.imagedraw.filters.matrix.MatrixFilter;

public class EdgeDetectFilter implements ImageDrawFilter {

	@Override
	public void doFilter(ImageDrawEntity image, int x, int y, int width, int height) {
		float[][] matrix = new float[][] {
				{ 0, 1, 0 },
				{ 1, -4, 1 },
				{ 0, 1, 0 }
		};
		MatrixFilter filter = new MatrixFilter(matrix);
		filter.doFilter(image, x, y, width, height);
	}

}

Add edge detection filter implementation.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package be.fror.password.rule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.google.common.collect.ImmutableList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Olivier Grégoire <https://github.com/fror>
 */
public class RuleResultTest {

  public RuleResultTest() {
  }

  /**
   *
   */
  @BeforeClass
  public static void setUpClass() {
  }

  /**
   *
   */
  @AfterClass
  public static void tearDownClass() {
  }

  /**
   *
   */
  @Before
  public void setUp() {
  }

  /**
   *
   */
  @After
  public void tearDown() {
  }

  /**
   * Test of isValid method, of class RuleResult.
   */
  @Test
  public void testIsValid() {
  }

  /**
   * Test of getFailures method, of class RuleResult.
   */
  @Test
  public void testGetFailures() {
  }

  /**
   * Test of ok method, of class RuleResult.
   */
  @Test
  public void testOk() {
    RuleResult result = RuleResult.ok();

    assertThat(result.isValid(), is(true));
    assertThat(result.getFailures(), is(equalTo(ImmutableList.of())));
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_0args() {
    RuleResult result = RuleResult.failed();

    assertThat(result.isValid(), is(false));
    assertThat(result.getFailures(), is(equalTo(ImmutableList.of())));
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_String() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_3args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_5args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_7args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_String_Map() {
  }

}

Add basic unit tests for RuleResult.

Add basic unit tests for RuleResult.


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsSwfTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsSwfTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Camel-AWS: Create single Karaf feature tests for single components, aws-swf test


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

import junit.framework.Test;

import org.apache.commons.collections4.trie.PatriciaTrie;
import org.apache.commons.collections4.trie.UnmodifiableTrie;

/**
 * Tests for TrieUtils factory methods.
 *
 * @version $Id$
 */
public class TrieUtilsTest extends BulkTest {

    public TrieUtilsTest(final String name) {
        super(name);
    }

    public static Test suite() {
        return BulkTest.makeSuite(TrieUtilsTest.class);
    }

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

    public void testUnmodifiableTrie() {
        Trie<String, Object> trie = TrieUtils.unmodifiableTrie(new PatriciaTrie<Object>());
        assertTrue("Returned object should be an UnmodifiableTrie.",
            trie instanceof UnmodifiableTrie);
        try {
            TrieUtils.unmodifiableTrie(null);
            fail("Expecting IllegalArgumentException for null trie.");
        } catch (final IllegalArgumentException ex) {
            // expected
        }
    }

}

Add unit test for TrieUtils.

Add unit test for TrieUtils.

git-svn-id: 53f0c1087cb9b05f99ff63ab1f4d1687a227fef1@1540644 13f79535-47bb-0310-9956-ffa450edef68


package leetcode;

/**
 * https://leetcode.com/problems/trapping-rain-water/
 */
public class Problem42 {
    public int trap(int[] height) {
        return 0;
    }

    public static void main(String[] args) {
        Problem42 prob = new Problem42();
        System.out.println(prob.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})); // 6
    }
}

Create a skeleton for problem 42

Create a skeleton for problem 42


package io.github.droidkaigi.confsched2017.util;

import android.app.Activity;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.URLUtil;

import io.github.droidkaigi.confsched2017.R;

/**
 * Created by shihochan on 2017/02/15.
 */

public class AppUtil {

    public static void openCustomTab(Activity activity, @NonNull String url) {
        if (TextUtils.isEmpty(url) || !URLUtil.isNetworkUrl(url)) {
            return;
        }

        CustomTabsIntent intent = new CustomTabsIntent.Builder()
                .setShowTitle(true)
                .setToolbarColor(ContextCompat.getColor(activity, R.color.theme))
                .build();

        intent.launchUrl(activity, Uri.parse(url));
    }
}

Implement app utility class and open chrome custom tabs method


package de.biomedical_imaging.traJ.features;

import javax.vecmath.Point3d;

import de.biomedical_imaging.traJ.Trajectory;

/**
 * Maximum distance from start point
 * @author Thorsten Wagner
 *
 */
public class MaxDistanceFromStartPointFeature extends AbstractTrajectoryFeature{
	Trajectory t;

	public MaxDistanceFromStartPointFeature(Trajectory t) {
		this.t = t;
	}

	@Override
	public double[] evaluate() {
		double maxDist = Double.MIN_VALUE;
		Point3d start = t.get(0);

		for(int i = 1; i < t.size(); i++){
			double d =start.distance(t.get(i));

			if(d > maxDist){
				maxDist = d;
			}
		}

		return new double[]{maxDist};
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Max distances from start point";
	}

	@Override
	public String getShortName() {
		// TODO Auto-generated method stub
		return "MaxDist";
	}

	@Override
	public void setTrajectory(Trajectory t) {
		this.t = t;

	}

}

Add feature: maximum distance from start point


package seedu.address.model.datastructure;

import java.util.HashSet;
import java.util.Set;

/**
 * This class will handle the partial search algorithm and the search function itself
 */
public class PartialSearch {

    private final Set<String> infixes = new HashSet<>();

    private String itemToSearch;

    public PartialSearch(String itemToSearch) {
        this.itemToSearch = itemToSearch;
        prepareSearch();
    }

    /**
     * This method prepares the infix set for search
     */
    public void prepareSearch() {
        for (int i = 0; i < itemToSearch.length(); i++) {
            for (int j = i + 1; j <= itemToSearch.length(); j++) {
                infixes.add(itemToSearch.substring(i, j).toLowerCase());
            }
        }
    }

    /**
     * This method does the search by matching the hash set for match
     * @param searchString
     * @return true if exist and false if otherwise
     */
    public boolean search(String searchString) { // O(1) search
        return infixes.contains(searchString.toLowerCase());
    }
}

Add partial search algorithm and data structure