package com.haxademic.core.draw.filters.shaders;

import com.haxademic.core.draw.filters.shaders.shared.BaseFilter;

import processing.core.PApplet;
import processing.core.PImage;

public class BlendTowardsTexture
extends BaseFilter {

	public static BlendTowardsTexture instance;

	public BlendTowardsTexture(PApplet p) {
		super(p, "haxademic/shaders/filters/texture-blend-towards-texture.glsl");
		setBlendLerp(0.25f);
	}

	public static BlendTowardsTexture instance(PApplet p) {
		if(instance != null) return instance;
		instance = new BlendTowardsTexture(p);
		return instance;
	}

	public void setBlendLerp(float blendLerp) {
		shader.set("blendLerp", blendLerp);
	}

	public void setSourceTexture(PImage source) {
		shader.set("targetTexture", source);
	}

}

Add wrapper for texture lerp shader


/**
 *
 */
package org.robotbrains.data.cloud.timeseries.server.database;

import org.kairosdb.client.HttpClient;
import org.kairosdb.client.response.GetResponse;

/**
 * @author Keith M. Hughes
 *
 */
public class KairosDbDatabaseRelay {
  private static final String KAIROS_CONNECTION_URL = "http://localhost:8090";

  public void startup() throws Exception {
    HttpClient client = new HttpClient(KAIROS_CONNECTION_URL);
    GetResponse response = client.getMetricNames();

    System.out.println("Response Code =" + response.getStatusCode());
    for (String name : response.getResults()) {
      System.out.println(name);
    }
    client.shutdown();
  }
}

Add in simple Kairos connection test


public class Solution {

    public int trailingZeroes(int n) {

        int result = 0;

        while (n > 0) {

            result += (n / 5);
            n /= 5;

        }

        return result;

    }

}

Create : 172 Factorial Trailing Zeroes


public class TestaOrdenacao {

  public static void main(String[] args) {

    Produto produtos[] = {
      new Produto("Lamborghini", 1000000),
      new Produto("Jipe", 46000),
      new Produto("Brasília", 16000),
      new Produto("Smart", 46000),
      new Produto("Fusca", 17000)
    };

    for(int atual = 0; atual < produtos.length; atual++) {
      int menor = buscaMenor(produtos, atual, produtos.length - 1);
      Produto produtoAtual = produtos[atual];
      Produto produtoMenor = produtos[menor];
      produtos[atual] = produtoMenor;
      produtos[menor] = produtoAtual;
    }

    for(Produto produto : produtos) {
      System.out.println(produto.getNome() + " custa " + produto.getPreco());
    }

  }

  private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
    int maisBarato = inicio;
    for(int atual = inicio; atual <= termino; atual++) {
      if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
        maisBarato = atual;
      }
    }
    return maisBarato;
  }

}

Insert new files, Alura, Projeto de Algoritmos 1, Aula 19


package com.hashnot.u.compare;

import java.util.Comparator;

/**
 * @author Rafał Krupiński
 */
public interface CompareOp<T> {
    /**
     * Allows parameters to be null
     */
    boolean eq(T o1, T o2);

    /**
     * Allows parameters to be null
     */
    boolean ne(T o1, T o2);

    boolean lt(T o1, T o2);

    boolean lte(T o1, T o2);

    boolean gt(T o1, T o2);

    /**
     * @return o1 >= o2
     */
    boolean gte(T o1, T o2);

    static <T> CompareOp<T> from(Comparator<T> from) {
        return new ComparatorOperator<>(from);
    }

    class ComparatorOperator<T> implements CompareOp<T> {
        final private Comparator<T> cmp;

        public ComparatorOperator(Comparator<T> cmp) {
            this.cmp = cmp;
        }

        /**
         * Allows parameters to be null
         */
        public boolean eq(T o1, T o2) {
            return o1 == o2 || o1 != null && o2 != null && cmp.compare(o1, o2) == 0;
        }

        /**
         * Allows parameters to be null
         */
        public boolean ne(T o1, T o2) {
            return o1 != o2 || o1 == null || cmp.compare(o1, o2) != 0;
        }

        public boolean lt(T o1, T o2) {
            return cmp.compare(o1, o2) < 0;
        }

        public boolean lte(T o1, T o2) {
            return cmp.compare(o1, o2) <= 0;
        }

        public boolean gt(T o1, T o2) {
            return cmp.compare(o1, o2) > 0;
        }

        /**
         * @return o1 >= o2
         */
        public boolean gte(T o1, T o2) {
            return cmp.compare(o1, o2) >= 0;
        }
    }
}

Add comparsion operators as a wrapper for Comparator


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

package io.spine.tools.protoc;

import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse.File;
import io.spine.type.MessageType;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

@DisplayName("ProtocPluginFiles should")
final class ProtocPluginFilesTest {

    @DisplayName("prepare File builder for supplied Type")
    @Test
    void prepareFileBuilderForType() {
        MessageType type = new MessageType(TestMessage.getDescriptor());
        File.Builder result = ProtocPluginFiles.prepareFile(type);

        assertEquals("io/spine/tools/protoc/TestMessage.java", result.getName());
    }
}

Cover ProtocPluginFiles with unit test


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

/**
 * An array A contains all the integers from 0 through N, except for one number which is missing.
 * Can you write a method to find that number?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindTheMissingNumber {

}

Add statement to problem 72


package de.uulm.mi.gdg;

import processing.core.PApplet;

/**
 * The Equalizer class is the main controller for the Animation.
 *
 * @author Tobias Lahmann
 */
public class Equalizer extends PApplet {
    /**
     * The settings() method runs before the sketch has been set up, so other Processing functions cannot be used at
     * this point.
     */
    public void settings() {
        setSize(1240, 720);
    }

    /**
     * The setup method is called before displaying any objects. The Method calls commands in the Processing API.
     */
    public void setup() {

    }

    /**
     * Draw method is responsible for displaying all objects.
     */
    public void draw() {

    }

    /**
     * Main method to instantiate the PApplet.
     *
     * @param args Arguments passed to the PApplet.
     */
    public static void main(String[] args) {
        PApplet.main(new String[]{Equalizer.class.getName()});
    }
}

Write controller to depict initial PApplet state


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

import junit.framework.TestCase;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.net.URI;

public class CachedContentFetcherTest extends TestCase {
  private RemoteContentFetcher fetcher
      = new CachedContentFetcher(new BasicRemoteContentFetcher(Integer.MAX_VALUE));

  public void testFetch() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = new RemoteContentRequest(temp.toURI());
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
  }

  public void testDontCache() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = RemoteContentRequest.getRequest(temp.toURI(), true);
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  public void testNotExists() throws Exception {
    RemoteContentRequest request
        = new RemoteContentRequest(new URI("file:///does/not/exist"));
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  // TODO test caching of POST requests, headers, options, etc.
}

Test that nocache is honored by CachedContentFetcher


package com.dyhpoon.fodex;

import android.content.ContentUris;
import android.net.Uri;
import android.test.AndroidTestCase;

import com.dyhpoon.fodex.data.actual.FodexContract;

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

/**
 * Created by darrenpoon on 2/4/15.
 */
public class ContractTest extends AndroidTestCase {

    public void testBuildImageUri() {
        long id = 0;
        Uri uri = FodexContract.ImageEntry.buildImageUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ImageEntry.CONTENT_URI, id), uri);
    }

    public void testBuildTagUri() {
        long id = 0;
        Uri uri = FodexContract.TagEntry.buildTagUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.TagEntry.CONTENT_URI, id), uri);
    }

    public void testSearchTagName() {
        String expected = "hello";
        Uri uri = FodexContract.TagEntry.buildSearchTagName(expected);
        String actual = FodexContract.TagEntry.getSearchTagName(uri);
        assertEquals(expected, actual);
    }

    public void testTagName() {
        String expected = "morning";
        Uri uri = FodexContract.TagEntry.buildTagName(expected);
        String actual = FodexContract.TagEntry.getTagName(uri);
        assertEquals(expected, actual);
    }

    public void testBuildImageTagUri() {
        long id = 0;
        Uri uri = FodexContract.ImageTagEntry.buildImageTagUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ImageTagEntry.CONTENT_URI, id), uri);
    }

    public void testTagNames() {
        List<String> expected = Arrays.asList("hello");
        Uri uri = FodexContract.ImageTagEntry.buildTagNames(expected);
        List<String> actual = FodexContract.ImageTagEntry.getTagNames(uri);
        assertEquals(expected, actual);

        expected = Arrays.asList("hello", "morning");
        uri = FodexContract.ImageTagEntry.buildTagNames(expected);
        actual = FodexContract.ImageTagEntry.getTagNames(uri);
        assertEquals(expected, actual);
    }

    public void testSearchId() {
        long expected = 0;
        Uri uri = FodexContract.ImageTagEntry.buildSearchId(expected);
        long actual = Long.parseLong(FodexContract.ImageTagEntry.getSearchId(uri));
        assertEquals(expected, actual);
    }

    public void testSearchName() {
        String expected = "hello";
        Uri uri = FodexContract.ImageTagEntry.buildSearchName(expected);
        String actual = FodexContract.ImageTagEntry.getSearchName(uri);
        assertEquals(expected, actual);
    }

    public void testBuildShareUri() {
        long id = 0;
        Uri uri = FodexContract.ShareEntry.buildShareUri(id);
        assertEquals(ContentUris.withAppendedId(FodexContract.ShareEntry.CONTENT_URI, id), uri);
    }
}

Add test cases for FodexContract


package to.etc.domui.hibernate.types;

import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import to.etc.util.DateUtil;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;

/**
 * @author Frits Jalvingh
 * Created on 31-10-17.
 */
public class DateNonnullType implements UserType {
	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return null;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		if(value == null)
			return value;
		return new Date(((java.util.Date) value).getTime());
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return null;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if(x != null)
			return x.equals(y);
		else
			return x == y;
	}

	@Override
	public int hashCode(Object arg0) throws HibernateException {
		return arg0.hashCode();
	}

	@Override
	public boolean isMutable() {
		return true;
	}

	@Override
	public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
		if(resultSet == null)
			return null;
		Date v = resultSet.getDate(names[0]);
		if(resultSet.wasNull())
			return null;
		if(DateUtil.getYear(v) >= 9999)
			return null;
		return new java.util.Date(v.getTime());
	}

	@Override
	public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException {
		Date dt = (Date) value;
		if(null == dt) {
			dt = DateUtil.dateFor(9999, 0, 1);
		}
		statement.setDate(index, new java.sql.Date(dt.getTime()));
	}

	@Override
	public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
		return null;
	}

	@Override
	public Class< ? > returnedClass() {
		return Date.class;
	}

	@Override
	public int[] sqlTypes() {
		return new int[]{Types.DATE};
	}
}

Add Hibernate Type to store null Date values as 9999-01-01.


// Copyright (c) 2003 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

/**
 * Helper functions for doing serial arithmetic.  These should be used when
 * setting/checking SOA serial numbers.
 *
 * @author Brian Wellington
 */

public final class Serial {

private static final long MAX32 = 0xFFFFFFFFL;

private
Serial() {
}

/**
 * Compares two numbers using serial arithmetic.  The numbers are assumed
 * to be 32 bit unsigned integers stored in longs.
 * @param serial1 The first integer
 * @param serial2 The second integer
 * @return 0 if the 2 numbers are equal, a positive number if serial1 is greater
 * than serial2, and a negative number if serial2 is greater than serial1.
 * @throws IllegalArgumentException serial1 or serial2 is out of range
 */
public static int
compare(long serial1, long serial2) {
	if (serial1 < 0 || serial1 > MAX32)
		throw new IllegalArgumentException(serial1 + " out of range");
	if (serial2 < 0 || serial2 > MAX32)
		throw new IllegalArgumentException(serial2 + " out of range");
	long diff = serial1 - serial2;
	if (diff >= MAX32)
		diff -= (MAX32 + 1);
	else if (diff < -MAX32)
		diff += (MAX32 + 1);
	return (int)diff;
}

/**
 * Increments a serial number.  The number is assumed to be a 32 bit unsigned
 * integer stored in a long.  This basically adds 1 and resets the value to
 * 0 if it is 2^32.
 * @param val The serial number
 * @return The incremented serial number
 * @throws IllegalArgumentException serial is out of range
 */
public static long
increment(long serial) {
	if (serial < 0 || serial > MAX32)
		throw new IllegalArgumentException(serial + " out of range");
	if (serial == MAX32)
		return 0;
	return serial + 1;
}

}

Add a class for doing serial arithmetic.


import java.util.HashMap;
//3. Longest Substring Without Repeating Characters
/**
 * Given a string, find the length of the longest substring without repeating characters.
 *
 * Examples:
 * Given "abcabcbb", the answer is "abc", which the length is 3.
 * Given "bbbbb", the answer is "b", with the length of 1.
 * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 *
 * Tags: Hash Table, Two Pointers, String
 * Similar Problems: (H) Longest Substring with At Most Two Distinct Characters
 *
 * @author Xinyue Zhang
 *
 */

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        //create a Hashmap, where character is key and index of the character is value
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        //two pointers
        for (int i = 0, j = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i)))
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            map.put(s.charAt(i), i);
            max = Math.max(max, i - j + 1);
        }
        return max;
    }

    public static void main(String args[]) {
        String s = "abba";
        Solution sol = new Solution();
        System.out.println(sol.lengthOfLongestSubstring(s));
    }
}

Add solution for problem 003


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.highgoalshooter.FreeFire;

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

/**
 * ALL VALUES ARE TEMPORARY
 */
public class AutoShootCleat extends CommandGroup {

    public  AutoShootCleat(int defense) {
        addSequential(new MoveToMiddleGoal(defense));
        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 24, 0));
        addSequential(new FreeFire());
    }
}

Add skeleton for auto shoot cleat


package net.the4thdimension.android;

import android.os.Environment;
import android.support.test.runner.AndroidJUnit4;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by jaydeepw on 1/2/17.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FileUtilsInstrumentationTest extends AndroidTestCase {

    @Test
    public void listFilesMultiple() throws Exception {

        File tempFile = new File(Environment.getExternalStorageDirectory().getPath());
        File directory = new File(tempFile, "rajababu");
        boolean isDirCreated = directory.mkdir();
        assertEquals("Directory created", true, isDirCreated);

        File file1 = new File(directory, "f1.txt");
        File file2 = new File(directory, "f2.txt");
        file1.createNewFile();
        file2.createNewFile();

        ArrayList files = new ArrayList();
        FileUtils.listFiles(directory, files);

        assertEquals(2, files.size());

        // clean up
        file1.delete();
        file2.delete();
        directory.delete();
    }

    @Test
    public void listFilesZeroFiles() throws Exception {

        File tempFile = new File(Environment.DIRECTORY_DOWNLOADS);
        File directory = new File(tempFile, "rajababu");
        directory.mkdir();

        ArrayList files = new ArrayList();
        FileUtils.listFiles(directory, files);

        assertEquals(0, files.size());

        // clean up
        directory.delete();
    }

}

Disable allows backup. Creates problem with using this library with other apps.


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

import static com.facebook.buck.jvm.java.JavaCompilationConstants.ANDROID_JAVAC_OPTIONS;

import com.facebook.buck.android.toolchain.AndroidPlatformTarget;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.AbstractNodeBuilder;
import com.facebook.buck.core.toolchain.impl.ToolchainProviderBuilder;
import com.facebook.buck.jvm.java.JavaCompilationConstants;
import com.facebook.buck.jvm.java.toolchain.JavaToolchain;
import com.facebook.buck.jvm.java.toolchain.JavacOptionsProvider;

public class AndroidBuildConfigBuilder
    extends AbstractNodeBuilder<
        AndroidBuildConfigDescriptionArg.Builder,
        AndroidBuildConfigDescriptionArg,
        AndroidBuildConfigDescription,
        AndroidBuildConfig> {

  public AndroidBuildConfigBuilder(BuildTarget target) {
    super(
        new AndroidBuildConfigDescription(
            new ToolchainProviderBuilder()
                .withToolchain(
                    JavacOptionsProvider.DEFAULT_NAME,
                    JavacOptionsProvider.of(ANDROID_JAVAC_OPTIONS))
                .withToolchain(
                    AndroidPlatformTarget.DEFAULT_NAME, TestAndroidPlatformTargetFactory.create())
                .withToolchain(
                    JavaToolchain.DEFAULT_NAME, JavaCompilationConstants.DEFAULT_JAVA_TOOLCHAIN)
                .build()),
        target);
  }

  public AndroidBuildConfigBuilder setPackage(String packageName) {
    getArgForPopulating().setPackage(packageName);
    return this;
  }
}

Add a TargetNode builder for AndroidBuildConfig


package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import picard.sam.markduplicates.MarkDuplicates;

import java.io.File;
import java.util.ArrayList;

public class DuplicateMarker implements Function<File, File> {
    final private ArrayList<String> extraArgs;

    public DuplicateMarker(String extraArgsString) {
        this.extraArgs = Utils.possibleStringToArgs(extraArgsString);
    }

    public File call(File file) throws Exception {
        MarkDuplicates markDuplicates = new MarkDuplicates();

        ArrayList<String> markerArgs = new ArrayList<String>();
        markerArgs.add("INPUT=");
        markerArgs.add(file.getPath());

        String newFileName = Utils.removeExtenstion(file.getPath(), "bam") + "-deduped.bam";
        File outputBamFile = new File(newFileName);

        markerArgs.add("OUTPUT=");
        markerArgs.add(outputBamFile.getPath());

        markerArgs.add("METRICS_FILE=");
        markerArgs.add(file.getPath() + "-metrics.txt");

        if (this.extraArgs != null) {
            markerArgs.addAll(extraArgs);
        }

        markDuplicates.instanceMain(markerArgs.toArray(new String[0]));
        return outputBamFile;
    }
}

Create a class which is used to mark all duplicate reads.


// Write and then read back binary data.
import java.io.*;

class RWData {
	public static void main(String args[]) throws IOException {
		DataOutputStream dataOut;
		DataInputStream dataIn;

		int i = 10;
		double d = 1023.56;
		boolean b = true;

		try {
			dataOut = new DataOutputStream(new FileOutputStream("testdata"));
		}
		catch(IOException exc) {
			System.out.println("Cannot open file.");
			return;
		}

		try {
			System.out.println("Writing " + i);
			dataOut.writeInt(i);

			System.out.println("Writing " + d);
			dataOut.writeDouble(d);

			System.out.println("Writing " + b);
			dataOut.writeBoolean(b);

			System.out.println("Writing " + 12.2 * 7.4);
			dataOut.writeDouble(12.2 * 7.4);
		}
		catch(IOException exc) {
			System.out.println("Write error.");
		}

		dataOut.close();

		System.out.println();

		// Now, read them back.
		try {
			dataIn = new DataInputStream(new FileInputStream("testdata"));
		}
		catch(IOException exc) {
			System.out.println("Cannot open file.");
			return;
		}

		try {
			i = dataIn.readInt();
			System.out.println("Reading " + i);

			d = dataIn.readDouble();
			System.out.println("Reading " + d);

			b = dataIn.readBoolean();
			System.out.println("Reading " + b);

			d = dataIn.readDouble();
			System.out.println("Reading " + d);
		}
		catch(IOException exc) {
			System.out.println("Read error.");
		}

		dataIn.close();
	}
}

Write and then read back binary data


/**
 *
 */
package de.hhu.tbus.applications.testapp;

import com.dcaiti.vsimrti.fed.app.api.interfaces.Application;
import com.dcaiti.vsimrti.fed.app.api.interfaces.ApplicationLayer;
import com.dcaiti.vsimrti.fed.app.api.util.ReceivedV2XMessage;

/**
 * @author bialon
 *
 * Empty dummy application
 */
public class TbusDummyApp implements Application {

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.TimerCall#getMinimalTimerCallInterval()
	 */
	@Override
	public long getMinimalTimerCallInterval() {
		return 0L;
	}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.TimerCall#timerCall(long)
	 */
	@Override
	public void timerCall(long arg0) {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#dispose()
	 */
	@Override
	public void dispose() {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#initialize(com.dcaiti.vsimrti.fed.app.api.interfaces.ApplicationLayer)
	 */
	@Override
	public void initialize(ApplicationLayer arg0) {}

	/**
	 * @see com.dcaiti.vsimrti.fed.app.api.interfaces.Application#receiveMessage(com.dcaiti.vsimrti.fed.app.api.util.ReceivedV2XMessage)
	 */
	@Override
	public void receiveMessage(ReceivedV2XMessage arg0) {}
}

Add Dummy app for VSimRTI with TBUS


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @author tags. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package org.jboss.as.console.client.core;

import com.google.gwt.user.client.rpc.AsyncCallback;
import org.jboss.as.console.client.shared.dispatch.AsyncCommand;
import org.jboss.as.console.client.shared.dispatch.DispatchAsync;
import org.jboss.as.console.client.shared.dispatch.impl.DMRAction;
import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse;
import org.jboss.dmr.client.ModelNode;

import static org.jboss.dmr.client.ModelDescriptionConstants.*;

/**
 * @author Heiko Braun
 * @date 5/19/11
 */
public class BootstrapCmd implements AsyncCommand<Boolean>{

    private BootstrapContext bootstrap;
    private DispatchAsync dispatcher;

    public BootstrapCmd(BootstrapContext bootstrap, DispatchAsync dispatcher) {
        this.bootstrap = bootstrap;
        this.dispatcher = dispatcher;
    }

    @Override
    public void execute(final AsyncCallback<Boolean> callback) {

        final ModelNode operation = new ModelNode();
        operation.get(OP).set(READ_CHILDREN_NAMES_OPERATION);
        operation.get(CHILD_TYPE).set("subsystem");
        operation.get(ADDRESS).setEmptyList();

        dispatcher.execute(new DMRAction(operation), new AsyncCallback<DMRResponse>() {
            @Override
            public void onFailure(Throwable caught) {
                bootstrap.setProperty(BootstrapContext.STANDALONE, "false");
            }

            @Override
            public void onSuccess(DMRResponse result) {

                ModelNode response = ModelNode.fromBase64(result.getResponseText());
                boolean outcome = response.get("outcome").asString().equals("success");
                bootstrap.setProperty(BootstrapContext.STANDALONE, Boolean.valueOf(outcome).toString());

                callback.onSuccess(outcome);

            }
        });

    }
}

Move bootstrap op to custom command


package com.maddenabbott.jenny.test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.hamcrest.Matcher;
import static org.hamcrest.Matchers.is;

/**
 * Test utility to verify multi-line Strings against content in files.
 */
public class OutputMatcher {
  /**
   * Verify that something matches exactly the content of a file. The file name given should be a
   * path relative to a directory called output at the root of the classpath,
   * with no file extension. A file extension of '.txt' will automatically be appended.
   *
   * For example "foo" would be the name of a file at classpath:output/foo.txt whilst "foo/bar"
   * would load the file classpath:output/foo/bar.txt.
   *
   * All of this is necessary because Java has no real way of having multi-line Strings so they
   * must be specified in files instead.
   *
   * @param path the path of the file to load content from
   * @return a Matcher that will verify equality with the contents of the loaded file
   */
  public static Matcher<String> isIn(final String path) {

    URL url = ClassLoader.getSystemResource("output/" + path + ".txt");
    if (url == null) {
      throw new RuntimeException("Unable to load output resource " + path);
    }

    URI uri;
    try {
      uri = url.toURI();
    } catch (URISyntaxException e) {
      throw new RuntimeException("Unable to load output resource " + path);
    }

    try {
      return is(new String(Files.readAllBytes(Paths.get(uri))));
    } catch (IOException e) {
      throw new RuntimeException("Unable to load output resource " + path);
    }
  }
}

Add utility for verifying equality of multiline strings against content in files.


package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.os.pkg.PackageManagerFactory;
import com.github.aureliano.achmed.os.service.IService;
import com.github.aureliano.achmed.os.service.RedHatService;
import com.github.aureliano.achmed.types.OperatingSystemFamily;
import com.github.aureliano.achmed.types.PackageProvider;

public class RedHat extends Linux {

	private IPackageManager packageManager;
	private IService serviceManager;

	public RedHat() {
		this.packageManager = PackageManagerFactory.createPackageManager(PackageProvider.YUM);
		this.serviceManager = new RedHatService();
	}

	public IPackageManager getDefaultPackageManager() {
		return this.packageManager;
	}

	public IService getDefaultServiceManager() {
		return this.serviceManager;
	}

	public OperatingSystemFamily getOperatingSystemFamily() {
		return OperatingSystemFamily.DEBIAN;
	}
}

Create Red Hat operating system.


package leetcode.n_queens;

import java.util.ArrayList;

public class Solution {
	public void dfs(ArrayList<String[]> ans, char[][] board, boolean[] row, boolean[] col, boolean[] diag, boolean[] rdiag, int n, int c){
		if(c == n){
			String[] cur = new String[n];
			for(int i = 0; i < n; i++){
				cur[i] = new String(board[i]);
			}
			ans.add(cur);
		}else{
			for(int r = 0; r < n; r++){
				if(!row[r] && !col[c] && !diag[r + c] && !rdiag[r - c + n - 1]){
					row[r] = col[c] = diag[r + c] = rdiag[r - c + n - 1] = true;
					board[r][c] = 'Q';
					dfs(ans, board, row, col, diag, rdiag, n, c + 1);
					row[r] = col[c] = diag[r + c] = rdiag[r - c + n - 1] = false;
					board[r][c] = '.';
				}
			}
		}
	}

    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> ans = new ArrayList<String[]>();
        if(n == 0){
        	ans.add(new String[0]);
        	return ans;
        }
        boolean[] row = new boolean[n];
        boolean[] col = new boolean[n];
        boolean[] diag = new boolean[2 * n - 1];
        boolean[] rdiag = new boolean[2 * n - 1];
        char[][] board = new char[n][n];
        for(int i = 0; i < n; i++){
        	for(int j = 0; j < n; j++){
        		board[i][j] = '.';
        	}
        }
        dfs(ans, board, row, col, diag, rdiag, n, 0);
        return ans;
    }

    public static void main(String[] args){
    	int cnt = 0;
    	for(String[] row : new Solution().solveNQueens(8)){
    		cnt++;
    		for(String s : row){
    			System.err.println(s);
    		}
    		System.err.println("");
    	}
    	System.err.println("cnt:" + cnt);
    }
}

Add java solution for 51. N-Queens


package net.alexrose.rofretta.detection;

import net.alexrose.rofretta.core.Instrument;
import net.alexrose.rofretta.core.InstrumentString;
import net.alexrose.rofretta.core.Voicing;

import java.util.List;

/**
 * You plucked something on the guitar that sounded good.
 * You saw your idol play something.
 * Your theory isn't hot or you're a bit lazy - what WAS that, probably?
 * <p>
 * The VoicingDetector will attempt to figure out it out for you.
 */
public class VoicingDetector {

    /**
     * Given
     *
     * @return
     */
    public List<Voicing> detect(List<InstrumentString> strings, Instrument tuning) {

    }

    public List<Voicing> detect(String input) {

    }
}

Check in a rough draft of what a detection interface might look like


package org.usergrid.launcher;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class AppleUtils {

	public static void initMacApp() {
		com.apple.eawt.Application macApp = com.apple.eawt.Application
				.getApplication();
		macApp.setDockIconImage(new ImageIcon(App.class
				.getResource("dock_icon.png")).getImage());

		macApp.setAboutHandler(new com.apple.eawt.AboutHandler() {
			@Override
			public void handleAbout(com.apple.eawt.AppEvent.AboutEvent evt) {
				JOptionPane
						.showMessageDialog(
								null,
								"Usergrid Standalone Server Launcher\nCopyright 2011 Ed Anuff & Usergrid",
								"About Usergrid Launcher",
								JOptionPane.INFORMATION_MESSAGE);
			}
		});

	}
}

Move Apple-specific setup code into separate class


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


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


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


/*
* 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;
    }
}

Create charset encoding utility that detects malformed input


/*
 * 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


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.


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


/*******************************************************************************
 * 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


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


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


/*
 * 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


/*
 * 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


/*
 * 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


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


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.'


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;
    }
}

Create charset encoding utility that detects malformed input


/*
 * 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


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


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