package tree;

/**
 * https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
 * <p/>
 * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
 */
public class ConvertSortedListBinarySearchTree {
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    private static class TreeNode {
        TreeNode(int val) {
            this.val = val;
        }

        int val;
        TreeNode left;
        TreeNode right;
    }

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        ListNode[] nodes = new ListNode[1];
        nodes[0] = head;
        return constructBinarySearchTree(nodes, 0, count - 1);
    }

    private TreeNode constructBinarySearchTree(ListNode[] nodes, int start, int end) {
        if (start > end) return null;

        int mid = start + (end - start) / 2;
        TreeNode left = constructBinarySearchTree(nodes, start, mid - 1);
        TreeNode root = new TreeNode(nodes[0].val);
        root.left = left;
        nodes[0] = nodes[0].next;
        root.right = constructBinarySearchTree(nodes, mid + 1, end);
        return root;
    }
}

Convert Sorted List to Binary Search Tree


/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.9
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.opensim.modeling;

public class SubcomponentsWithDuplicateName extends OpenSimException {
  private transient long swigCPtr;

  public SubcomponentsWithDuplicateName(long cPtr, boolean cMemoryOwn) {
    super(opensimCommonJNI.SubcomponentsWithDuplicateName_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  public static long getCPtr(SubcomponentsWithDuplicateName obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        opensimCommonJNI.delete_SubcomponentsWithDuplicateName(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public SubcomponentsWithDuplicateName(String file, long line, String func, String thisName, String duplicateName) {
    this(opensimCommonJNI.new_SubcomponentsWithDuplicateName(file, line, func, thisName, duplicateName), true);
  }

}

Add newly generated SWIG file


package com.thoughtworks.xstream.converters.reflection;

import junit.framework.TestCase;

import java.util.Iterator;
import java.lang.reflect.Field;

public class FieldDictionaryTest extends TestCase {

    private FieldDictionary fieldDictionary;

    protected void setUp() throws Exception {
        super.setUp();
        fieldDictionary = new FieldDictionary();
    }

    class SomeClass {
        private String a;
        private String c;
        private String b;
    }

    public void testListsFieldsInClassInDefinitionOrder() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SomeClass.class);
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }

    class SpecialClass extends SomeClass {
        private String brilliant;
    }

    public void testIncludesFieldsInSuperClasses() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SpecialClass.class);
        assertEquals("brilliant", ((Field)fields.next()).getName());
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }
}

Test that fields come out in same order they are defined.


package org.orangeflamingo.namesandsongs.controller;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MainControllerTest {

    private MainController mainController = new MainController();

    @Test
    public void testDummy() throws Exception {
        assertEquals("Zanger", mainController.dummySong().getArtist());
        assertEquals("Voornaam in titel", mainController.dummySong().getTitle());
    }

}

Add coverage for testing sonarqube/travis settings.


package org.hl7.fhir.dstu3.model;

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.*;

public class HumanNameDstu3Test {
	@Ignore("Issue #865")
	@Test
	public void hasGivenFindsParameter() {
		HumanName humanName = new HumanName().addGiven("test");
		assertTrue(humanName.hasGiven("test"));
	}

	@Ignore("Issue #865")
	@Test
	public void hasPrefixFindsParameter() {
		HumanName humanName = new HumanName().addPrefix("test");
		assertTrue(humanName.hasPrefix("test"));
	}

	@Ignore("Issue #865")
	@Test
	public void hasSuffixFindsParameter() {
		HumanName humanName = new HumanName().addSuffix("test");
		assertTrue(humanName.hasSuffix("test"));
	}
}

Add unit tests for HumanName has(String) methods


package com.jakewharton.rxbinding.view;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.UiThreadTest;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;

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

@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
  @Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

  private final Context context = InstrumentationRegistry.getTargetContext();
  private final LinearLayout parent = new LinearLayout(context);
  private final View child = new View(context);

  @Test @UiThreadTest public void childViewEvents() {
    RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
    Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    parent.addView(child);
    assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));

    parent.removeView(child);
    assertThat(o.takeNext()).isEqualTo(
        ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));

    subscription.unsubscribe();

    parent.addView(child);
    o.assertNoMoreEvents();
  }
}

package com.jakewharton.rxbinding.view;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;

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

@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
  @Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

  private final Context context = InstrumentationRegistry.getTargetContext();
  private final LinearLayout parent = new LinearLayout(context);
  private final View child = new View(context);

  @Test @UiThreadTest public void childViewEvents() {
    RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
    Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    parent.addView(child);
    assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));

    parent.removeView(child);
    assertThat(o.takeNext()).isEqualTo(
        ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));

    subscription.unsubscribe();

    parent.addView(child);
    o.assertNoMoreEvents();
  }
}

Use the right UiThreadTest annotation.


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

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {

  public int calculate(int n1, int n2) {
    return 0;
  }

}

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

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {

  /**
   * Iterative solution to this problem. This algorithm is based on the multiplication definition
   * as
   * a consecutive sum. The complexity order of this algorithm in time terms is O(N) where N is
   * equals to n1 parameter. In space terms the complexity order of this algorithm is O(1) because
   * we are not using any additional data structure related to the input size.
   */
  public int calculate(int n1, int n2) {
    int result = 0;
    boolean negative = n1 < 0;
    n1 = Math.abs(n1);
    for (int i = 0; i < n1; i++) {
      result += n2;
    }

    if (negative) {
      result *= -1;
    }
    return result;
  }
}

Add solution to problem 20


package org.realityforge.arez.processor;

import javax.annotation.Nonnull;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic;

class ArezProcessorException
  extends Exception
{
  private final Element _element;

  ArezProcessorException( @Nonnull final String message, @Nonnull final Element element )
  {
    super( message );
    _element = element;
  }

  void print( @Nonnull final Messager messager )
  {
    if ( null != _element )
    {
      messager.printMessage( Diagnostic.Kind.ERROR, getMessage(), _element );
    }
    else
    {
      messager.printMessage( Diagnostic.Kind.ERROR, getMessage() );
    }
  }
}

Add exception that can be thrown during generation process


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public int maxDepth(TreeNode root) {

        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;

    }

}

Create : 104 Maximum Depth of Binary Tree


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

// https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
public class JumpingOnTheClouds {

    private static final String SPACE = " ";
    private static final int SENTINEL = -1;
    private static final int CUMULUS = 0;

    private static int[] readClouds() throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            reader.readLine(); // ignore first line
            String[] split = reader.readLine().split(SPACE);
            int[] clouds = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
            return clouds;
        }
    }

    private static int jumpClouds(int index, int jumps, int[] clouds) {
        int updatedIndex = index + jumps;
        if (updatedIndex >= clouds.length) {
            return SENTINEL;
        }
        int cloud = clouds[updatedIndex];
        return (cloud == CUMULUS) ? updatedIndex : SENTINEL;
    }

    private static int getMinStepsToLastCloud(int[] clouds) {
        int steps = 0;
        int i = 0;
        while (i < clouds.length) {
            if (i == clouds.length - 1) {
                return steps;
            }
            int cloud = clouds[i];
            if (cloud == 1) {
                throw new IllegalStateException("Current cloud could not be 1. Index is: " + i);
            }
            int updatedIndex = jumpClouds(i, 2, clouds);
            i = (updatedIndex != SENTINEL) ? updatedIndex : jumpClouds(i, 1, clouds);
            steps += 1;
        }
        return steps;
    }

    public static void main(String[] args) throws IOException {
        int[] clouds = readClouds();
        int minSteps = getMinStepsToLastCloud(clouds);
        System.out.println(minSteps);
    }
}

Add solution for Jumping on the clouds problem.


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

import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Test;

import java.util.Collections;

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

public class TestAntlrUtils {

    @Test
    public void testEdges() {
        ParserRuleContext context = new ParserRuleContext(null, 42);

        ParseTree content = new RuleContext() {
            @Override
            public String getText() {
                return "Content";
            }
        };
        context.children = Collections.singletonList(content);

        Token start = new CommonToken(1, "Start");
        Token stop = new CommonToken(2, "Stop");

        context.start = null;
        context.stop = null;
        assertEquals("Content", AntlrUtils.getSourceText(context));

        context.start = start;
        context.stop = null;
        assertEquals("Content", AntlrUtils.getSourceText(context));

        context.start = null;
        context.stop = stop;
        assertEquals("Content", AntlrUtils.getSourceText(context));
    }

}

Test edges of the AntlrUtils.getSourceText


package com.google.step.coffee.data;

import com.google.step.coffee.TestHelper;
import com.google.step.coffee.entity.Event;
import com.google.step.coffee.entity.Group;
import org.junit.Test;

import java.time.Duration;
import java.time.Instant;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class EventStoreTest extends TestHelper {
  private EventStore eventStore = new EventStore();
  private GroupStore groupStore = new GroupStore();

  @Test
  public void testInsertSetsId() throws Exception {
    Group group = groupStore.create("test group");

    Event event = Event.builder()
        .setDescription("bla bla bla")
        .setDuration(Duration.ofMinutes(30))
        .setStart(Instant.ofEpochSecond(1_600_000_000))
        .setGroupId(group.id())
        .build();

    assertThat(eventStore.put(event).id(), notNullValue());
  }

  @Test
  public void testFutureEventsReturned() throws Exception {
    Group group = groupStore.create("test group");
    Group anotherGroup = groupStore.create("unrelated group");

    // round to the nearest second
    Instant now = Instant.ofEpochSecond(Instant.now().getEpochSecond());

    Event eventPast = Event.builder()
        .setDescription("past")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.minusSeconds(100000))
        .setGroupId(group.id())
        .build();

    Event eventFuture = Event.builder()
        .setDescription("future")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.plusSeconds(100000))
        .setGroupId(group.id())
        .build();

    Event eventFutureOtherGroup = Event.builder()
        .setDescription("future other group")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.plusSeconds(100000))
        .setGroupId(anotherGroup.id())
        .build();

    eventPast = eventStore.put(eventPast);
    eventFuture = eventStore.put(eventFuture);
    eventFutureOtherGroup = eventStore.put(eventFutureOtherGroup);

    assertThat(eventStore.getUpcomingEventsForGroup(group), contains(
        eventFuture
    ));
  }
}

Add tests for event store


package ds.arrays;

import java.util.Arrays;

/**
 * Copy/merge array1 of size 'm' to an array2 of size 'm+n'
 * Array1 : contains only m elements
 * array2 : contains n elements stored in array of size 'm+n'
 *
 * O/p : sorted arr2 with copies contents of array1
 *
 * array1 : 1,3,4,6  (m=4)
 * array2 : 4, -1, 5,-8, -1, -1, -1 (m+n = 7), -1 indicates empty place holders
 *
 *
 * Note : assuming arrays have positive integers only, no dups
 *
 * @author bboggaramrama
 *
 */
public class ArrayMerger {

	public static void main(String args[]) {
		ArrayMerger driver = new ArrayMerger();
		driver.copyArrays(new int[] {5,7,9,25},new int[] {2,8,-1,-1,-1,13,-1,15,20});

		// Tests
	}

	/**
	 * 1. Move all the elements in array2 to end
	 * 2. Then start merge step from array1 and array2 (from end), Keep adding the smallest to start of array2. thats it !!
	 */
	public void copyArrays(int[] arr1, int[] arr2) {

		// Move all the elements in array2 to end. Keep two pointers i and j, Start decrementing them over copying on non -1's
		int m = arr1.length;
		int n = arr2.length;
		int i = n-1, j = n-1;
		while(i >= 0) {
			if(arr2[i] != -1) {
				arr2[j] = arr2[i];
				i--;
				j--;
			} else {
				i--;
			}
		}

	// Lets start the  merge step and comparing, copying resply
	 i = 0; // Start of first array
	 j = n - m -1 ; // start of second array
	 int k = 0;
		while (k < n-1 && j<n ) {
			int element1 = arr1[i];
			int element2 = arr2[j];

			if (element1 > element2) {
				arr2[k] = element2;
				j++;
			} else {
				arr2[k] = element1;
				i++;
			}

			k++; // Increment the k to keep track of where we are at copying the
					// arr2
		}
		System.out.println(Arrays.toString(arr2));
	}

}

Copy contents from one array (m size) to another array (m+n size)


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.IsZeroMin;
import net.imglib2.Interval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.IsZeroMin.class, name = ViewOps.IsZeroMin.NAME)
public class DefaultIsZeroMin extends AbstractView<Interval, Boolean> implements
		IsZeroMin<Interval, Boolean> {

	@Override
	public Boolean compute(Interval input) {
		return Views.isZeroMin(input);
	}

}

Add default implementation of IsZeroMin interface.


package uk.ac.ebi.quickgo.common;

import java.util.stream.Stream;

/**
 * Defines which fields are facetable for a given {@link QuickGODocument}.
 * @author Ricardo Antunes
 */
public interface FacetableField {
    /**
     * Indicates whether the provided {@param field} is facetable or not.
     *
     * @param field the field to check
     * @return true if the field is facetable, false otherwise
     */
    boolean isFacetable(String field);

    /**
     * Returns all facetable fields of a concrete implementation of {@link QuickGODocument}.
     *
     * @return an {@link Stream} of all fields that are facetable for a specific implementation of
     * {@link QuickGODocument}
     */
    Stream<String> facetableFields();
}

Create an interface that indicates which fields are facetable.


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

package org.apache.jmeter.util;

import junit.framework.TestCase;

public class PackageTest extends TestCase {

	public PackageTest() {
		super();
	}

	public PackageTest(String arg0) {
		super(arg0);
	}

	public void testServer() throws Exception {
		BeanShellServer bshs = new BeanShellServer(9876, "");
		assertNotNull(bshs);
		// Not sure we can test anything else here
	}
	public void testSub1() throws Exception {
		String input = "http://jakarta.apache.org/jmeter/index.html";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("http://${server}/jmeter/index.html", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub2() throws Exception {
		String input = "arg1=param1;param1";
		String pattern = "param1";
		String sub = "${value}";
		assertEquals("arg1=${value};${value}", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub3() throws Exception {
		String input = "jakarta.apache.org";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("${server}", StringUtilities.substitute(input, pattern, sub));
	}

}

Move more tests to test tree


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

import javax.annotation.Nonnull;

/**
 * Exception for {@link GroovyFileGlobalVariable} management.
 * @author Oleg Nenashev
 */
class GroovyFileGlobalVariableException extends Exception {

    private static final long serialVersionUID = 1L;

    private final String variableName;

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull String message) {
        super(message);
        this.variableName = variableName;
    }

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull Throwable cause) {
        super(cause);
        this.variableName = variableName;
    }

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull String message, @Nonnull Throwable cause) {
        super(message, cause);
        this.variableName = variableName;
    }

    @Override
    public String getMessage() {
        return "[" + variableName + "] - " + super.getMessage();
    }

}

Add an exception class for the future use


package com.uwetrottmann.shopr.context.algorithm;

import com.uwetrottmann.shopr.algorithm.model.Item;

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

/**
 * Created by yannick on 17.02.15.
 *
 * In this class the post-filtering of the recommended cases is done. We will retrieve several different
 * items from the recommendation algorithm. Based on the current active context and the contexts in which these items
 * were selected, there is going to be a re-ordered list of the top x items.
 */
public class ContextualPostFiltering {

    /**
     * This method shall postFilter the provided item set of the case base in order to return better recommendations.
     * Therefore it takes a list of current preferred items by the algorithm and searches for contexts in which this item
     * was selected. It then checks these contexts with the current context and compares them based on the context's distance metric.
     *
     * @param currentRecommendation the current recommendations as set by the algorithm
     * @param numberOfRecommendations the number of recommendations that should be outputted
     * @return an updated list with only the number of items that should be outputted.
     */
    public static List<Item> postFilterItems(List<Item> currentRecommendation, int numberOfRecommendations){
        List<Item> updatedRecommendation = new ArrayList<Item>();

        for (Item item : currentRecommendation){
            if (updatedRecommendation.size() < numberOfRecommendations) {
                updatedRecommendation.add(item);
            } else {
                break;
            }
        }

        return updatedRecommendation;
    }
}

Build skeleton of context-algorithm for post-filtering


package com.github.aureliano.achmed.exception;

public class UnsupportedOperatingSystemException extends RuntimeException {

	private static final long serialVersionUID = 4654066489822139408L;

	public UnsupportedOperatingSystemException() {
		super();
	}

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

	public UnsupportedOperatingSystemException(Throwable throwable) {
		super(throwable);
	}

	public UnsupportedOperatingSystemException(String message, Throwable throwable) {
		super(message, throwable);
	}
}

Create unsupported operating system exception.


package Person.test.mock;

import Person.PersonAgent;
import Person.PersonAgent.PersonState;
import junit.framework.*;
public class PersonTest2 extends TestCase{

		PersonAgent pa;
		PersonAgent pa2;

		public void setUp() throws Exception{
			super.setUp();
			pa = new PersonAgent("TestPerson1");
			pa2= new PersonAgent("TestPerson2");
		}
		public void testInitialization() {
			assertTrue("State of customer initially be Idle", pa.state==PersonState.Idle);
			System.out.println("Testing all the transactions which involve money/loans and if the SSN algorithm works correctly");
    	    assertEquals("The person should have 100 dollars initially",pa.getMoney(),100.00);
    	    pa.setMoney(150);
    	    assertEquals("The person should have 150 dollars now as I set that as the money",pa.getMoney(),150.00);
    	    pa.setLoan(1000);
    	    assertEquals("The person should have a loan of 1000 dollars",pa.getLoan(),1000.00);
    	    pa.msgReceiveSalary(1000);
    	    assertEquals("The person should have 150+1000 dollars now",pa.getMoney(),1150.00);
    	    pa.msgPayBackLoanUrgently();
    	    assertTrue("State of customer should be PayLoanNow", pa.state==PersonState.PayLoanNow);
    	    pa.msgPayBackRentUrgently();
    	    assertTrue("State of customer should be PayLoanNow", pa.state==PersonState.PayRentNow);
    	    //checking SSNs
    	    assertTrue("SSN of person 1 should be 0", pa.getSSN()==0);
    	    assertTrue("SSN of person 2 should be 1", pa2.getSSN()==1);

    	    pa.msgINeedMoney(100);
    	    assertTrue("State of customer should be NeedsMoney", pa.state==PersonState.NeedsMoney);
    	    assertEquals("The person should need 100 dollars now",pa.getMoneyNeeded(),100.00);

		}

	}

Test for the monetary transactions and the SSN algorithm


package replicant.messages;

import java.util.Objects;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

/**
 * The message that represents a set of changes to subscriptions and entities that should be applied atomically.
 */
@SuppressWarnings( "NullableProblems" )
@SuppressFBWarnings( "EI_EXPOSE_REP" )
@JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "Object" )
public class SessionCreatedMessage
  extends ServerToClientMessage
{
  @JsOverlay
  public static final String TYPE = "session-created";
  @Nonnull
  private String sessionId;

  @GwtIncompatible
  @Nonnull
  public static SessionCreatedMessage create( @Nonnull final String sessionId )
  {
    final SessionCreatedMessage changeSet = new SessionCreatedMessage();
    changeSet.type = TYPE;
    changeSet.requestId = null;
    changeSet.sessionId = Objects.requireNonNull( sessionId );
    return changeSet;
  }

  @JsOverlay
  @Nonnull
  public final String getSessionId()
  {
    return sessionId;
  }
}

Add message received to initiate session


package com.elytradev.teckle.common.tile.inv;

import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

/**
 * Created by darkevilmac on 5/4/17.
 */
public class ItemStream {

    public static Stream<ItemStack> createItemStream(IItemHandler handler) {
        AtomicInteger i = new AtomicInteger(0);
        return Stream.generate(() -> handler.getStackInSlot(i.getAndIncrement())).limit(handler.getSlots());
    }

}

Add utility method to create streams out of IItemHandlers.


package fi.nls.oskari;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Support for link redirects. Configuration in linkredirect.properties
 *
 * @see fi.nls.oskari.spring.SpringConfig
 */
@Controller
public class FriendlyURLHandler {

    @Value("${ortophoto.url}")
    private String ortophotoUrl;

    @RequestMapping("/historiallisetilmakuvat")
    public ModelAndView finnish(HttpServletRequest request) throws Exception {
        return ortophotos("fi", request);
    }

    @RequestMapping("/sv/historiskaflygbilder")
    public ModelAndView swedish(HttpServletRequest request) throws Exception {
        return ortophotos("sv", request);
    }

    @RequestMapping("/en/historicalorthophotos")
    public ModelAndView english(HttpServletRequest request) throws Exception {
        return ortophotos("en", request);
    }

    public ModelAndView ortophotos(String lang, HttpServletRequest request) throws Exception {
        String url = attachQuery(ortophotoUrl, "lang=" + lang);
        return new ModelAndView("redirect:" + attachQuery(url, request.getQueryString()));
    }

    private String attachQuery(String path, String query) {
        if (query == null) {
            return path;
        }
        if (path.indexOf('?') == -1) {
            return path + "?" + query;
        }
        if (path.endsWith("?")) {
            return path + query;
        }
        return path + "&" + query;

    }
}

Add handler for ortophoto friendly url


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

package com.github.rconner.anansi;

import org.junit.Test;

import java.util.NoSuchElementException;

public class TraversalMoveTest {

    // This test class is exercising TraversalMove.rootIterator(T).next() when the iterator is exhausted.
    // The classes which use the package-private TraversalMove never call next() without having tested hasNext()
    // first, so this logic is not otherwise executed.

    @Test
    public void rootIteratorNotExhausted() {
        TraversalMove<String, String> move = TraversalMove.start( "A" );
        move.iterator.next();
    }

    @Test( expected = NoSuchElementException.class )
    public void rootIteratorExhausted() {
        TraversalMove<String, String> move = TraversalMove.start( "A" );
        move.iterator.next();
        move.iterator.next();
    }
}

Add a test to exhaust a root-node traversal iterator.


package uk.co.benjiweber.expressions;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static uk.co.benjiweber.expressions.Exceptions.unchecked;

public class ExceptionsTest {
    @Test
    public void checked_to_unchecked() {
        String foo = unchecked(() -> Example.methodThatThrowsCheckedException(DO_NOT_THROW));
        assertEquals("foo", foo);
    }

    @Test
    public void checked_to_unchecked_method_reference() {
        unchecked(Example::methodThatThrowsCheckedExceptionNoParams);
    }

    @Test
    public void checked_to_unchecked_void() {
        unchecked(() -> Example.voidMethodThatThrowsACheckedException(DO_NOT_THROW));
    }

    @Test(expected = RuntimeException.class)
    public void checked_to_unchecked_should_wrap_in_runtime_exception() {
        String foo = unchecked(() -> Example.methodThatThrowsCheckedException(THROW));
    }

    @Test(expected = RuntimeException.class)
    public void checked_to_unchecked_void_should_wrap_in_runtime_exception() {
        unchecked(() -> Example.voidMethodThatThrowsACheckedException(THROW));
    }

    static class ACheckedExceptionIDontHaveAGoodWayToDealWith extends Exception {

    }

    static boolean THROW = true;
    static boolean DO_NOT_THROW = false;

    static class Example {
        public static String methodThatThrowsCheckedException(boolean throwPlease) throws ACheckedExceptionIDontHaveAGoodWayToDealWith {
            if (throwPlease) throw new ACheckedExceptionIDontHaveAGoodWayToDealWith();
            return "foo";
        }

        public static void voidMethodThatThrowsACheckedException(boolean throwPlease) throws ACheckedExceptionIDontHaveAGoodWayToDealWith {
            if (throwPlease) throw new ACheckedExceptionIDontHaveAGoodWayToDealWith();
        }

        public static void methodThatThrowsCheckedExceptionNoParams() throws ACheckedExceptionIDontHaveAGoodWayToDealWith {

        }
    }

}

Add test to illustrate exception wrapping


package com.github.aureliano.damihilogs.config.output;

public enum OutputConfigTypes {

	ELASTIC_SEARCH,
	FILE_OUTPUT,
	STANDARD_OUTPUT,
	JDBC_OUTPUT,
	TWITTER_OUTPUT;
}

Create output config types enum.


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

package tachyon.worker.block.allocator;

import com.google.common.base.Optional;

import tachyon.worker.block.meta.BlockMeta;

/**
 * Interface for the allocation policy of Tachyon managed data.
 */
public interface Allocator {
  Optional<BlockMeta> allocateBlock(long userId, long blockId, long blockSize, int tierHint);
}

Add allocator interface which tells BlockStore how to allocate


package water.nbhm;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

public class NonBlockingHashMapLongZeroKeyConcurrentGetPutIfAbsentTest extends TestCase {
    private static final int N_THREADS = 4;
    private static final int ITERATIONS = 1000000;
    private ExecutorService service;

    protected void setUp() {
        service = Executors.newFixedThreadPool(N_THREADS);
    }

    protected void tearDown() throws Exception {
        service.shutdownNow();
        service.awaitTermination(1, TimeUnit.HOURS);
    }

    public void test_empty_map_key_0() throws Exception {
        empty_map_test(0);
    }

    public void test_empty_map_key_123() throws Exception {
        empty_map_test(123);
    }

    private void empty_map_test(long key) throws Exception {
        for (int i = 0; i < ITERATIONS; i++) {
            Set<String> results = runIteration(new NonBlockingHashMapLong<String>(), key);
            assertEquals(results.toString(), 1, results.size());
        }
    }

    private Set<String> runIteration(NonBlockingHashMapLong<String> map, long key) throws Exception {
        List<Callable<String>> tasks = new ArrayList<Callable<String>>(N_THREADS);
        for (int i = 1; i <= N_THREADS; i++) {
            tasks.add(new PutIfAbsent(map, key, "worker #" + i));
        }

        List<String> results = executeTasks(tasks);

        return new HashSet<String>(results);
    }

    private List<String> executeTasks(List<Callable<String>> tasks) throws Exception {
        List<Future<String>> futures = new ArrayList<Future<String>>(N_THREADS);
        final CountDownLatch startLatch = new CountDownLatch(N_THREADS + 1);
        for (Callable<String> t : tasks) {
            final Callable<String> task = t;
            Future<String> future = service.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    startLatch.countDown();
                    startLatch.await();
                    return task.call();
                }
            });
            futures.add(future);
        }

        startLatch.countDown();

        List<String> results = new ArrayList<String>(N_THREADS);
        for (Future<String> f : futures) {
            results.add(f.get());
        }
        return results;
    }

    private static class PutIfAbsent implements Callable<String> {
        private final NonBlockingHashMapLong<String> map;
        private final String newValue;
        private final long key;

        public PutIfAbsent(NonBlockingHashMapLong<String> map, long key, String newValue) {
            this.map = map;
            this.newValue = newValue;
            this.key = key;
        }

        @Override
        public String call() throws Exception {
            String value = map.get(key);
            if (value == null) {
                value = newValue;
                String tmp = map.putIfAbsent(key, value);
                if (tmp != null) {
                    return tmp;
                }
            }
            return value;
        }
    }
}

Test that case for NonBlockingHashMapLong for zero and non-zero key on putIfAbsent atomicity


/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.timeseries.snapshot;

import java.util.List;

import com.google.common.collect.ImmutableList;

/**
 * Empty black list of values
 */
public final class EmptyBlackList implements BlackList {

  /**
   * Singleton instance
   */
  public static final EmptyBlackList INSTANCE = new EmptyBlackList();

  private String _name;

  private List<String> _blackList;

  private EmptyBlackList() {
    _name = "EMPTY";
    _blackList = ImmutableList.of();
  }

  @Override
  public String getName() {
    return _name;
  }

  @Override
  public List<String> getBlackList() {
    return _blackList;
  }

}

Create empty black list to use when empty one is needed


/**
 * Copyright 2017 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.timelock.paxos;

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

import org.junit.Test;

import com.palantir.atlasdb.timelock.config.TimeLockServerConfiguration;

public class PaxosTimeLockConstantsTest {
    @Test
    public void internalNamespaceShouldNotBeParsableAsClient() {
        assertThat(PaxosTimeLockConstants.INTERNAL_NAMESPACE.matches(TimeLockServerConfiguration.CLIENT_NAME_REGEX))
                .isFalse();
    }
}

Add test verifying that the internal namespace is not a possible client name


/**
 *
 */
package mathsquared.resultswizard2;

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

/**
 * @author MathSquared
 *
 */
public class SyntaxParserTest {

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseQuotedSyntax(java.lang.String)}.
     *
     * Tests the String <code>"a" "b" "c""d"</code>.
     */
    @Test
    public void testParseQuotedSyntax () {
        String[] parsed = SyntaxParser.parseQuotedSyntax("\"a\" \"b\" \"c\"\"d\"");
        assertTrue("quoted syntax: space-separated with one quote escape", Arrays.equals(parsed, new String[] {"a", "b", "c\"d"}));
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#createPairwiseMap(T[])}.
     */
    @Test
    public void testCreatePairwiseMap () {
        Map<Integer, Integer> pairs = SyntaxParser.createPairwiseMap(new Integer[] {1, 2, 3, 4, 5});
        Map<Integer, Integer> expected = new HashMap<Integer, Integer>();
        expected.put(1, 2);
        expected.put(3, 4);
        assertTrue("pairwise: five integers", pairs.equals(expected));
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseIntegerList(java.lang.String)}.
     */
    @Test
    public void testParseIntegerList () {
        int[] parsed = SyntaxParser.parseIntegerList("1 2,3 4.5$");
        assertTrue("integer list: five integers, various separators, trailing", Arrays.equals(parsed, new int[] {1, 2, 3, 4, 5}));
    }

}

Add JUnit test folder and test cases for SyntaxParser


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

package io.marmot.laboratory.algorithm;

import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;

import java.util.Comparator;

public class TopKTest {

  @Before
  public void setUp() {
  }

  @Test
  public void testQuickSelect() {
    Integer[] array = {45, 42, 13, 87, 36, 55, 67, 13, 90, 54, 51, 9};

    Integer i0 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 1 - 1);
    Assert.assertEquals((Integer) 9, i0);

    Integer i1 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 9 - 1);
    Assert.assertEquals((Integer) 55, i1);

    Integer i2 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 5 - 1);
    Assert.assertEquals((Integer) 42, i2);
  }

  @After
  public void tearDown() {
  }
}

Add test for median of medians.


/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.app.console.shared.model;

import java.io.Serializable;

public class GwtMessage extends KapuaBaseModel implements Serializable {
    private static final long serialVersionUID = 5344433827767946887L;

    public GwtMessage() {
    }
}

/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.app.console.shared.model;

import java.io.Serializable;

public class GwtMessage extends KapuaBaseModel implements Serializable {
    private static final long serialVersionUID = 5344433827767946887L;

    public GwtMessage() {
        setAllowNestedValues(false);
    }
}

Fix NPE in Data View for metrics containing . in name


package org.apache.solr.handler.dataimport;

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

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies;
import org.apache.solr.SolrTestCaseJ4;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@ThreadLeakAction({ThreadLeakAction.Action.WARN})
@ThreadLeakLingering(linger = 0)
@ThreadLeakZombies(ThreadLeakZombies.Consequence.CONTINUE)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class TestJdbcDataSourceConvertType extends AbstractDataImportHandlerTestCase {
  public void testConvertType() throws Throwable {
    // ironically convertType=false causes BigDecimal to String conversion
    convertTypeTest("false", String.class);

    // convertType=true uses the "long" conversion (see mapping of some_i to "long")
    convertTypeTest("true", Long.class);
  }

  private void convertTypeTest(String convertType, Class resultClass) throws Throwable {
    JdbcDataSource dataSource = new JdbcDataSource();
    Properties p = new Properties();
    p.put("driver", "org.apache.derby.jdbc.EmbeddedDriver");
    p.put("url", "jdbc:derby:memory:tempDB;create=true");
    p.put("convertType", convertType);

    List<Map<String, String>> flds = new ArrayList<>();
    Map<String, String> f = new HashMap<>();
    f.put("column", "some_i");
    f.put("type", "long");
    flds.add(f);

    Context c = getContext(null, null,
        dataSource, Context.FULL_DUMP, flds, null);
    dataSource.init(c, p);
    Iterator<Map<String, Object>> i = dataSource
        .getData("select 1 as id, CAST(9999 AS DECIMAL) as \"some_i\" from sysibm.sysdummy1");
    assertTrue(i.hasNext());
    Map<String, Object> map = i.next();
    Object val = map.get("some_i");
    assertEquals(resultClass, val.getClass());

    dataSource.close();
  }
}

Add tests for convertType and BigDecimal implicit conversion


package uk.org.taverna.scufl2.rdfxml;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static uk.org.taverna.scufl2.rdfxml.TestRDFXMLWriter.APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE;

import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.io.WorkflowBundleIO;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage;

public class TestResourcesInZip {

	protected WorkflowBundleIO bundleIO = new WorkflowBundleIO();
	protected ExampleWorkflow exampleWorkflow = new ExampleWorkflow();
	protected WorkflowBundle originalBundle;

	@Before
	public void makeBundle() {
		originalBundle = exampleWorkflow.makeWorkflowBundle();
	}

	@Test
	public void singleFile() throws Exception {
		UCFPackage resources = originalBundle.getResources();
		resources.addResource("Hello there", "hello.txt", "text/plain");
		File bundleFile = tempFile();
		bundleIO.writeBundle(originalBundle, bundleFile, APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE);

		ZipFile zipFile = new ZipFile(bundleFile);
		ZipEntry hello = zipFile.getEntry("hello.txt");
		assertEquals("hello.txt", hello.getName());
		assertEquals("Hello there",
				IOUtils.toString(zipFile.getInputStream(hello), "ASCII"));

	}

	public File tempFile() throws IOException {
		File bundleFile = File.createTempFile("test", ".scufl2");
		bundleFile.deleteOnExit();
		//System.out.println(bundleFile);
		return bundleFile;
	}
}

Test writing of added source


/*
 * Copyright 2018, 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.server.aggregate.given.importado;

import io.spine.server.aggregate.given.importado.command.Move;
import io.spine.server.aggregate.given.importado.command.MoveVBuilder;
import io.spine.server.aggregate.given.importado.event.Moved;
import io.spine.server.aggregate.given.importado.event.MovedVBuilder;

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

/**
 * Static utilities for movement DSL.
 *
 * @author Alexander Yevsyukov
 */
public class MoveMessages {

    /** Prevents instantiation of this utility class. */
    private MoveMessages() {
    }

    /**
     * Creates a command to move the passed object into the given direction.
     */
    public static Move move(ObjectId object, Direction direction) {
        checkNotNull(object);
        checkNotNull(direction);
        return MoveVBuilder
                .newBuilder()
                .setObject(object)
                .setDirection(direction)
                .build();
    }

    /**
     * Creates an event on the fact that the object moved into the passed direction.
     */
    public static Moved moved(ObjectId object, Direction direction) {
        checkNotNull(object);
        checkNotNull(direction);
        return MovedVBuilder
                .newBuilder()
                .setObject(object)
                .setDirection(direction)
                .build();
    }
}

Add test env. message utility


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

import com.github.daytron.twaattin.service.TwitterService;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Component;
import com.vaadin.ui.HasComponents;
import com.vaadin.ui.Table;
import java.util.List;
import twitter4j.Status;
import twitter4j.TwitterException;

/**
 *
 * @author Ryan Gilera
 */
@SuppressWarnings("serial")
public class TweetRefresherBehaviour implements HasComponents.ComponentAttachListener {

    @Override
    public void componentAttachedToContainer(HasComponents.ComponentAttachEvent event) {
        Component component = event.getAttachedComponent();

        if (component instanceof Table) {
            Table table = (Table) component;

            try {
                List<Status> statuses =
                        TwitterService.get().getTwitter().getUserTimeline();

                BeanItemContainer<Status> container =
                        new BeanItemContainer<>(Status.class);

                container.addAll(statuses);
                table.setContainerDataSource(container);
            } catch (TwitterException | IllegalArgumentException e) {
                throw new RuntimeException("TweetRefresher error: " + e.getMessage());
            }
        }
    }

}

Add a concrete component attach listener whenever user update the time, new tweets are added to the bean list


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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.ac.ebi.spot.goci.curation.model.mail.CurationSystemEmail;
import uk.ac.ebi.spot.goci.curation.model.mail.CurationSystemEmailToCurator;

import static org.junit.Assert.assertEquals;

/**
 * Created by emma on 09/03/2016.
 *
 * @author emma
 *         <p>
 *         Test for uk/ac/ebi/spot/goci/curation/model/mail/CurationSystemEmail.java
 */
@RunWith(MockitoJUnitRunner.class)
public class TestCurationSystemEmail {

    private CurationSystemEmail email;

    @Before
    public void setUp() throws Exception {
        email = new CurationSystemEmailToCurator();
        email.setBody("This is a test.");
    }

    @Test
    public void testAddBody() {
        String newTextToAdd = " Will this test pass?";
        email.addToBody(newTextToAdd);
        assertEquals("This is a test. Will this test pass?", email.getBody());
    }
}

Test for new abstract email class method


/*
 * Copyright 2016-2018 Talsma ICT
 *
 * 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 nl.talsmasoftware.context.functions;

import nl.talsmasoftware.context.Context;
import nl.talsmasoftware.context.ContextManagers;
import nl.talsmasoftware.context.ContextSnapshot;
import nl.talsmasoftware.context.DummyContextManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * @author Sjoerd Talsma
 */
public class BooleanSupplierWithContextTest {

    private ExecutorService unawareThreadpool;

    @Before
    @After
    public void clearDummyContext() {
        DummyContextManager.clear();
    }

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() {
        unawareThreadpool = Executors.newCachedThreadPool();
    }

    @After
    public void tearDown() throws InterruptedException {
        unawareThreadpool.shutdown();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException {
        DummyContextManager.setCurrentValue("true");
        final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1];

        BooleanSupplier supplier = new BooleanSupplierWithContext(ContextManagers.createContextSnapshot(), () -> {
            try {
                return Boolean.parseBoolean(DummyContextManager.currentValue().get());
            } finally {
                DummyContextManager.setCurrentValue("false");
            }
        }, s -> snapshotHolder[0] = s);

        Future<Boolean> future = unawareThreadpool.submit(supplier::getAsBoolean);
        assertThat(future.get(), is(true));

        assertThat(DummyContextManager.currentValue(), is(Optional.of("true")));
        try (Context<Void> reactivation = snapshotHolder[0].reactivate()) {
            assertThat(DummyContextManager.currentValue(), is(Optional.of("false")));
        }
        assertThat(DummyContextManager.currentValue(), is(Optional.of("true")));
    }

}

Add unit test for `BooleanSupplierWithContext`


package com.sensia.tools.client.swetools.editors.sensorml.panels.base.attribute.edit;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.sensia.relaxNG.RNGAttribute;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;

public class EditAttributeCodeSpacePanel extends EditAttributePanel {

	public EditAttributeCodeSpacePanel(RNGAttribute tag) {
		super(tag);
		container = new HorizontalPanel();
	}

	protected AbstractPanel<RNGAttribute> newInstance() {
		// TODO Auto-generated method stub
		return null;
	}

}

Add codespace edit attribute panel to remove codeSpace label


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

/**
 * Deprecated auto-configuration for Elasticsearch client, superseded by classes in
 * {@code org.springframework.boot.autoconfigure.elasticsearch}.
 */
package org.springframework.boot.autoconfigure.elasticsearch.rest;

Add package info to o.s.b.autoconfigure.elasticsearch.rest


/*
 * Copyright 2019 Immutables Authors and Contributors
 *
 * 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.immutables.criteria.elasticsearch;

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

import static org.immutables.check.Checkers.check;

class VersionTest {

  @Test
  void version() {
    check(Version.of("1.2.3").major).is(1);
    check(Version.of("2.2.3").major).is(2);
    check(Version.of("7").major).is(7);
    check(Version.of("7.1").major).is(7);
    check(Version.of("7.1.2").major).is(7);
    check(Version.of("7.1-pre").major).is(7);
    check(Version.of("3-beta").major).is(3);
    check(Version.of("200-ea").major).is(200);
    check(Version.of("2014.12.12").major).is(2014);

    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(""));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("aa"));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("a.b"));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("."));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(".."));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(".2"));
  }
}

Add tests for elastic version parsing


package com.github.dakusui.actionunit.ut.actions;

import com.github.dakusui.actionunit.Action;
import org.junit.Test;

import static com.github.dakusui.actionunit.Actions.nop;
import static com.github.dakusui.actionunit.Actions.tag;
import static junit.framework.TestCase.assertFalse;

public class TagTest {
  @Test
  public void givenNonTagAction$whenEquals$thenFalse() {
    Action action = tag(0);
    assertFalse(action.equals(nop()));
  }

  @Test
  public void givenTagActionWithDifferentIndex$whenEquals$thenFalse() {
    Action action = tag(0);
    assertFalse(action.equals(tag(1)));
  }

  @Test(expected = IllegalArgumentException.class)
  public void givenNegativeInteger$whenInstantiate$thenIllegalArgumentThrown() {
    tag(-1);
  }
}

Add tests for tag action.


package fibonacci;

public class FirstWithNDigits
{
  public static long firstWithNDigits(long n) throws IllegalArgumentException
  {
    if (n <= 0)
      throw new IllegalArgumentException("Must use a positive integer greater than 0");

    long x = 0,
         result = 0,
         digits = 1;

    while (digits < n)
    {
      result = Fibonacci.fibonacci(++x);
      digits = (long)Math.log10(result) + 1;
    }

    return result;
  }

  public static void main(String[] args)
  {
    if (args.length > 0)
    {
      try
      {
        long n = Long.parseLong(args[0]);
        System.out.printf("First with %d digits: %d\n", n, firstWithNDigits(n));
      }
      catch (NumberFormatException e)
      {
        System.err.println("Arguments must be numbers!");
      }
      catch (IllegalArgumentException e)
      {
        System.err.println(e.getMessage());
      }
    }
  }
}

Implement a program that returns the first number in the fibonacci sequence with given number of digits.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops;

import net.imagej.ops.OpService;
import net.imagej.ops.Ops.CreateImg;

import org.junit.Test;

/**
 * Tests that the ops of the global namespace have corresponding type-safe Java
 * method signatures declared in the {@link OpService} class.
 *
 * @author Curtis Rueden
 */
public class GlobalNamespaceTest extends AbstractNamespaceTest {

	/** Tests for {@link CreateImg} method convergence. */
	@Test
	public void testCreateImg() {
		assertComplete(null, OpService.class, CreateImg.NAME);
	}

}

Add a test for createimg op method convergence


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops.coloc.icq;

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

import org.junit.Test;

import net.imagej.ops.AbstractOpTest;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.util.IterablePair;
import net.imglib2.util.Pair;

/**
 * Tests {@link net.imagej.ops.Ops.Coloc.ICQ}.
 *
 * @author Curtis Rueden
 */
public class LiICQTest extends AbstractOpTest {

	@Test
	public void testICQ() {
		final Img<ByteType> img1 = generateByteArrayTestImg(true, 10, 15, 20);
		final Img<ByteType> img2 = generateByteArrayTestImg(true, 10, 15, 20);

		final DoubleType mean1 = ops.stats().mean(new DoubleType(), img1);
		final DoubleType mean2 = ops.stats().mean(new DoubleType(), img2);

		Iterable<Pair<ByteType, ByteType>> pairs = new IterablePair<ByteType, ByteType>(img1, img2);

		final Object icqValue =
			ops.run(LiICQ.class, pairs, mean1.get(), mean2.get());

		assertTrue(icqValue instanceof Double);
		assertEquals(0.5, (Double) icqValue, 0.0);
	}
}

Add a unit test for LiICQ


package org.elasql.migration;

import java.util.List;

import org.elasql.storage.metadata.PartitionPlan;

public class DummyMigrationComponentFactory extends MigrationComponentFactory {

	private String message;

	public DummyMigrationComponentFactory(String message) {
		this.message = message;
	}

	@Override
	public List<MigrationRange> generateMigrationRanges(PartitionPlan oldPlan, PartitionPlan newPlan) {
		throw new RuntimeException(message);
	}

	@Override
	public PartitionPlan newPartitionPlan() {
		throw new RuntimeException(message);
	}

}

Add a dummy migration factory


package com.codingbat.test;

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

import com.codingbat.array1.Array1Test;
import com.codingbat.array2.Array2Test;
import com.codingbat.string1.String1Test;
import com.codingbat.string2.String2Test;
import com.codingbat.warmup1.Warmup1Test;
import com.codingbat.warmup2.Warmup2Test;

@RunWith(Suite.class)
@SuiteClasses({Warmup1Test.class, Warmup2Test.class, Array1Test.class, Array2Test.class,
    String1Test.class, String2Test.class})
public class AllTests {

}

Create test suite to run 6 test cases at once.


/*
 * Copyright 2014-2019 Real Logic 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 org.agrona.concurrent;

import org.junit.Test;

import static org.junit.Assert.*;

public class HighResolutionTimerTest
{
    @Test
    public void shouldEnableHighResolutionTimers()
    {
        assertFalse(HighResolutionTimer.isEnabled());

        HighResolutionTimer.enable();
        assertTrue(HighResolutionTimer.isEnabled());

        HighResolutionTimer.disable();
        assertFalse(HighResolutionTimer.isEnabled());
    }
}

Add test for high resolution timers.


package org.opencb.biodata.models.variant;

import org.opencb.biodata.models.variant.stats.VariantStats;

/**
 * @author Alejandro Aleman Ramos <aaleman@cipf.es>
 * @author Cristina Yenyxe Gonzalez Garcia <cyenyxe@ebi.ac.uk>
 */
public class VariantAggregatedVcfFactory extends VariantVcfFactory {

    @Override
    protected void setOtherFields(Variant variant, VariantSource source, String id, float quality, String filter, String info, String format, int numAllele, String[] alternateAlleles) {
        // Fields not affected by the structure of REF and ALT fields
        variant.setId(id);
        if (quality > -1) {
            variant.getFile(source.getFileId(), source.getStudyId()).addAttribute("QUAL", String.valueOf(quality));
        }
        if (!filter.isEmpty()) {
            variant.getFile(source.getFileId(), source.getStudyId()).addAttribute("FILTER", filter);
        }
        if (!info.isEmpty()) {
            parseInfo(variant, source.getFileId(), source.getStudyId(), info);
        }
        variant.getFile(source.getFileId(), source.getStudyId()).setFormat(format);

        addStats(variant, source, numAllele, alternateAlleles);
    }

    private void addStats(Variant variant, VariantSource source, int numAllele, String[] alternateAlleles) {

        ArchivedVariantFile file = variant.getFile(source.getFileId(), source.getStudyId());

        if (file.hasAttribute("AN") && file.hasAttribute("AC")) {
            int total = Integer.parseInt(file.getAttribute("AN"));
            String[] alleleCountString = file.getAttribute("AC").split(",");

            if (alleleCountString.length != alternateAlleles.length) {
                return;
            }

            int[] alleleCount = new int[alleleCountString.length];

            String mafAllele = variant.getReference();
            int referenceCount = total;

            for (int i = 0; i < alleleCountString.length; i++) {
                alleleCount[i] = Integer.parseInt(alleleCountString[i]);
                referenceCount -= alleleCount[i];
            }

            float maf = (float) referenceCount / total;

            for (int i = 0; i < alleleCount.length; i++) {
                float auxMaf = (float) alleleCount[i] / total;
                if (auxMaf < maf) {
                    maf = auxMaf;
                    mafAllele = alternateAlleles[i];
                }
            }

            VariantStats vs = new VariantStats();

            vs.setMaf(maf);
            vs.setMafAllele(mafAllele);

            file.setStats(vs);
        }

    }

}

Create new VariantAggregatedFactory for aggregated Vcfs. This factory loads Maf/AlleleMAf (from attributes) into stats


package peergos.server;

import peergos.server.util.*;
import peergos.shared.*;
import peergos.shared.cbor.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.cid.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.user.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;

/** This utility check that all of a users mutable pointers and blocks are present as far as the network can tell
 *
 */
public class ValidateUser {

    public static void main(String[] args) throws Exception {
        Crypto crypto = Main.initCrypto();
        NetworkAccess network = NetworkAccess.buildJava(new URL("https://alpha.peergos.net"), true).get();
        String username = args[0];
        Optional<PublicKeyHash> identity = network.coreNode.getPublicKeyHash(username).join();
        Set<PublicKeyHash> ownedKeys = WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable,
                network.dhtClient, network.hasher).join();
        for (PublicKeyHash ownedKey : ownedKeys) {
            validateWriter(identity.get(), ownedKey, network);
        }
    }

    private static void validateWriter(PublicKeyHash owner, PublicKeyHash writer, NetworkAccess network) {
        MaybeMultihash target = network.mutable.getPointerTarget(owner, writer, network.dhtClient).join();
        if (! target.isPresent()) {
            Logging.LOG().log(Level.WARNING, "Skipping unretrievable mutable pointer for: " + writer);
            return;
        }

        validateBlock(target.get(), network);
    }

    private static void validateBlock(Multihash target, NetworkAccess network) {
        Optional<CborObject> block = network.dhtClient.get(target).join();
        if (! block.isPresent())
            throw new IllegalStateException("Couldn't retrieve " + target);

        List<Multihash> links = block.get().links();
        for (Multihash link : links) {
            if (link instanceof Cid && ((Cid) link).codec == Cid.Codec.Raw)
                network.dhtClient.getSize(link).join();
            else
                validateBlock(link, network);
        }
    }
}

Add util to validate a user


package tachyon.worker.keyvalue;

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

/**
 * Unit tests of {@link LinearProbingIndex}.
 */
public class LinearProbingIndexTest {
  private static final byte[] KEY1 = "key1".getBytes();
  private static final byte[] KEY2 = "key2_foo".getBytes();

  @Test
  public void putBasicTest() throws Exception {
    LinearProbingIndex index = LinearProbingIndex.createEmptyIndex();
    Assert.assertEquals(0, index.keyCount());
    Assert.assertTrue(index.put(KEY1, 0));
    Assert.assertEquals(1, index.keyCount());
    Assert.assertTrue(index.put(KEY2, 1));
    Assert.assertEquals(2, index.keyCount());
  }

  @Test
  public void putDuplicatedKeyTest() throws Exception {
    LinearProbingIndex index = LinearProbingIndex.createEmptyIndex();
    // TODO(binfan): change constant 50 to be LinearProbingIndex.MAX_PROBES
    for (int i = 0; i < 50; i ++) {
      Assert.assertEquals(i, index.keyCount());
      Assert.assertTrue(index.put(KEY1, 0));
    }
    Assert.assertFalse(index.put(KEY1, 0));
  }

  @Test
  public void getInsertedKeysTest() throws Exception {
    // Initialize a batch of key-value pairs
    int test_keys = 100;
    byte[][] keys = new byte[test_keys][];
    byte[][] values = new byte[test_keys][];
    for (int i = 0; i < test_keys; i ++) {
      keys[i] = String.format("test-key:%d", i).getBytes();
      values[i] = String.format("test-val:%d", i).getBytes();
    }

    LinearProbingIndex index = LinearProbingIndex.createEmptyIndex();

    // Insert this batch of key-value pairs
    Utils.MockOutputStream mockOutput = new Utils.MockOutputStream(10000);
    PayloadWriter payloadWriter = new PayloadWriter(mockOutput);
    for (int i = 0; i < test_keys; i ++) {
      int offset = mockOutput.getCount();
      payloadWriter.addKeyAndValue(keys[i], values[i]);
      payloadWriter.flush();
      Assert.assertTrue(index.put(keys[i], offset));
      Assert.assertEquals(i + 1, index.keyCount());
    }
    payloadWriter.close();

    // Read all keys back, expect same value as inserted
    PayloadReader payloadReader = new PayloadReader(mockOutput.toByteArray());
    for (int i = 0; i < test_keys; i ++) {
      byte[] value = index.get(keys[i], payloadReader);
      Assert.assertArrayEquals(values[i], value);
    }
  }

  @Test
  public void getNonExistentKeyTest() throws Exception {
    LinearProbingIndex index = LinearProbingIndex.createEmptyIndex();
    PayloadReader payloadReaderNotUsed = new PayloadReader(new byte[] {});
    byte[] nonExistentKey = "NotInserted".getBytes();
    Assert.assertNull(index.get(nonExistentKey, payloadReaderNotUsed));
  }
}

Add unit tests of LinearProbingIndex


package osgi.enroute.trains.hw.provider;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Promise;

import osgi.enroute.trains.controller.api.RFIDSegmentController;

@Designate(ocd=RFIDSegmentImpl.Config.class, factory=true)
@Component(name = "osgi.enroute.trains.hw.rfid", property="service.exported.interfaces=*", configurationPolicy=ConfigurationPolicy.REQUIRE)
public class RFIDSegmentImpl implements RFIDSegmentController {

	private Config config;

	private String lastRFID = null;
	private Deferred<String> nextRFID = new Deferred<String>();

	@ObjectClassDefinition
	@interface Config {
		int controller();

		// TODO also specify which hardware pins/port RFID reader to read out in config
	}

	@Activate
	void activate(Config config) {
		this.config = config;

		// TODO initialize reading out the RFID reader - call trigger each time RFID is detected
	}

	@Override
	public String lastRFID() {
		return lastRFID;
	}

	@Override
	public synchronized Promise<String> nextRFID() {
		return nextRFID.getPromise();
	}

	// This method is called when an RFID tag detected
	private synchronized void trigger(String rfid){
		Deferred<String> toResolve = nextRFID;
		nextRFID = new Deferred<String>();
		toResolve.resolve(rfid);
		this.lastRFID = rfid;
	}
}

Add placeholder for the RFID segment controller


 	private String readFromStream(HttpURLConnection httpConnect) throws Exception{
		InputStream contentStream = httpConnect.getInputStream();
		BufferedReader contentReader = new BufferedReader(new InputStreamReader(contentStream,"UTF-8"));
		String content = "",tmp = "";
		while((tmp=contentReader.readLine()) !=null){
			content = tmp.concat(tmp);
		}
		contentReader.close();
		contentStream.close();
		return content;
	}

Configure response inpustream encode for chinese


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

/**
 * Given a Binary Search Tree, can you write a method to obtain the nTH min element?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindMinNumberAtPosition {
}

Add statement to problem 44


package seedu.doist.model.util;

import org.apache.commons.lang.StringUtils;

public class StringMatchUtil {

    /**
     * Method that uses third party library to compute
     * how close the 'target' string is to the 'query' string, alpha-numerically
     * @param target
     * @param query
     * @return integer between 0 to 1 representing the closeness, 1 being a full match
     */
    private static double nearMatch(String target, String query) {
        return org.apache.commons.lang3.StringUtils.getJaroWinklerDistance(target, query);
    }

    /**
     * Method that returns 1 if 'query' contains 'target', 0 otherwise
     * @param target
     * @param query
     * @return an integer
     */
    private static double stringContain(String target, String query) {
        assert query != null;
        return StringUtils.containsIgnoreCase(target, query) ? 1.0 : 0.0;
    }

    public static double matchValue(String target, String query) {
        return nearMatch(target, query) + stringContain(target, query);
    }

    /**
     * Method that returns a boolean if 'target' and 'query' are close enough
     * alpha-numerically, using the threshold
     * @param target
     * @param query
     * @param threshold
     * @return true if they are close enough, else false
     */
    public static boolean isNearMatch(String target, String query, double threshold) {
        System.out.println(matchValue(target, query) + "  --" + target + "-- " + query);
        return threshold < matchValue(target, query);
    }
}

Create new class to encapsulate all string matching heuristics


package maintest;

import static org.junit.Assert.*;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.junit.*;

import typecheck.Symboles;
import typecheck.TypeChecker;
import antlr.QLangLexer;
import antlr.QLangParser;
import ast.ASTNode;
import ast.visitors.BaseVisitor;

public class TypeCheckerTest {

	@Test
	public void test(boolean expected, String str){
		System.out.println("Input String: " + str);
		ANTLRInputStream input = new ANTLRInputStream(str);
		QLangLexer lexer = new QLangLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		QLangParser parser = new QLangParser(tokens);
		ASTNode tree = parser.form().result;
		BaseVisitor visitor = new BaseVisitor();
		System.out.println(tree.accept(visitor));

		Symboles symb = new Symboles();
		TypeChecker checker = new TypeChecker(symb);
		boolean result = checker.check_symb(tree, symb);
		assertEquals(expected, result);

	}

	@Test
	public void testSymboles(){
		System.out.println("start test");
		test(true, "form Box1HouseOwning { hasSoldHouse: \"Did you sell a house in 2010?\" boolean }");
	}

}

Test Typechecker added but still unable to run


/*******************************************************************************
 *  Copyright (c) 2014 Mentor Graphics and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *     Mentor Graphics - initial API and implementation
 *******************************************************************************/
package com.codesourcery.installer.actions;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.equinox.p2.core.IProvisioningAgent;

import com.codesourcery.installer.IInstallMode;
import com.codesourcery.installer.IInstallPlatform;
import com.codesourcery.installer.IInstallProduct;
import com.codesourcery.installer.Installer;

/**
 * This action will install digitally signed Windows drivers using the
 * Microsoft Driver Package Installer (DPInst).
 * This action will require administrative privileges to run on Windows.
 */
public class DriverAction extends AbstractInstallAction {
	/** Action identifier */
	public static final String ID = "com.codesourcery.installer.DriverAction";
	/** Directory containing drivers files */
	private IPath driverPath;

	/**
	 * Constructor
	 */
	protected DriverAction() {
		super(ID);
	}

	@Override
	public boolean isSupported(String platform, String arch) {
		// Only supported on Windows platforms
		return isWindows(platform);
	}

	/**
	 * Constructor
	 *
	 * @param driverPath Path to driver directory
	 */
	protected DriverAction(IPath driverPath) {
		super(ID);
	}

	/**
	 * Returns the path to the driver directory.
	 *
	 * @return Driver path
	 */
	public IPath getDriverPath() {
		return driverPath;
	}

	@Override
	public void run(IProvisioningAgent agent, IInstallProduct product,
			IInstallMode mode, IProgressMonitor monitor) throws CoreException {
		if (mode.isInstall()) {
			IInstallPlatform installPlatform = Installer.getDefault().getInstallPlatform();
			// If Vista or greater, install signed drivers
			installPlatform.installWindowsDriver(getDriverPath().toOSString());
		}
	}
}

Add general action to install Windows digitaly signed drivers.


package fi.nls.oskari.spring.session;

import fi.nls.oskari.cache.JedisManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@Profile(RedisSessionsConfigElasticCache.PROFILE)
public class RedisSessionsConfigElasticCache  extends WebMvcConfigurerAdapter {
    public static final String PROFILE = "redis-aws";

    @Bean
    @Profile(JedisManager.CLUSTERED_ENV_PROFILE)
    ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }
}

Configure NO_OP configuration to redis-session profile


package com.jmlb0003.jokes.gradlejokesproject;

import android.os.AsyncTask;

import com.example.jose.myapplication.backend.jokeApi.JokeApi;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;

import java.io.IOException;

public final class JokeAsyncTask
        extends AsyncTask<Void, Void, String> {

    private final static String LOCAL_SERVER_ROOT = "http://10.0.2.2:8080/";
    private final static String API_ENDPOINT = "_ah/api/";
    private static JokeApi myApiService = null;
    private final JokeAsyncTaskListener asyncTaskListener;

    public JokeAsyncTask(final JokeAsyncTaskListener listener) {
        asyncTaskListener = listener;
    }

    @Override
    protected String doInBackground(Void... params) {
        if (myApiService == null) {  // Only do this once
            final JokeApi.Builder builder = new JokeApi
                    .Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                    // options for running against local devappserver
                    // - 10.0.2.2 is localhost's IP address in Android emulator
                    // - turn off compression when running against local devappserver
                    .setRootUrl(LOCAL_SERVER_ROOT + API_ENDPOINT)
                    .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {

                        @Override
                        public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) {
                            abstractGoogleClientRequest.setDisableGZipContent(true);
                        }

                    });
            // end options for devappserver

            myApiService = builder.build();
        }

        try {
            return myApiService.getJoke().execute().getData();
        } catch (IOException e) {
            asyncTaskListener.thereIsNoJokes();
            return null;
        }
    }

    @Override
    protected void onPostExecute(final String joke) {
        asyncTaskListener.showAJoke(joke);
    }

    interface JokeAsyncTaskListener {

        void showAJoke(String joke);

        void thereIsNoJokes();

    }

}

Create the asynctask to fetch jokes from the gce endpoint


package de.philipphager.disclosure.api.adapters;

import com.google.gson.TypeAdapterFactory;
import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory;

@GsonTypeAdapterFactory
public abstract class AutoValueTypeAdapterFactory implements TypeAdapterFactory {
  public static TypeAdapterFactory create() {
    return new AutoValueGson_AutoValueTypeAdapterFactory();
  }
}

Add a TypeAdapterFactoy for AutoValue models


/*
 * Copyright 2015 The ISTLab. Use of this source code is governed by a GNU AFFERO GPL 3.0 license
 * that can be found in the LICENSE file.
 */

package gr.aueb.dmst.istlab.unixtools.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class SettingsFileUtil {

  public static InputStream createInputStream(String filename) throws IOException {
    File inputFile = new File(filename);

    if (!inputFile.exists()) {
      inputFile.createNewFile();
    }

    InputStream in = new FileInputStream(inputFile);

    return in;
  }

  public static OutputStream createOutputstream(String filename) throws IOException {
    File outputFile = new File(filename);

    if (!outputFile.exists()) {
      outputFile.createNewFile();
    }

    OutputStream out = new FileOutputStream(outputFile);

    return out;
  }

}

Add utility class to create input-output streams


package innovimax.mixthem.utils;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;

public class StreamUtils {

	static public <T, E extends Exception>
    		Consumer<T> consume(ConsumerWithException<T, E> ce) {
        		return arg -> {
            			try {
                			ce.apply(arg);
            			} catch (Exception e) {
                			throw new RuntimeException(e);
            			}
        		};
	}

	static public <T, E extends Exception>
    		Predicate<T> test(PredicateWithException<T, E> pe) {
        		return arg -> {
            			try {
                			return pe.test(arg);
            			} catch (Exception e) {
                			throw new RuntimeException(e);
            			}
        		};
	}

	static public <T, R, E extends Exception>
    		Function<T, R> apply(FunctionWithException<T, R, E> fe) {
        		return arg -> {
            			try {
                			return fe.apply(arg);
            			} catch (Exception e) {
                			throw new RuntimeException(e);
            			}
        		};
	}

	static public <T, E extends Exception>
    		ToIntFunction<T> applyAsInt(ToIntFunctionWithException<T, E> tife) {
        		return arg -> {
            			try {
                			return tife.applyAsInt(arg);
            			} catch (Exception e) {
                			throw new RuntimeException(e);
            			}
        		};
	}

}

Add stream utils to use new functionnal interfaces


package cz.cuni.mff.d3s.spl.core.data;

public interface SampleBasedDataSource extends DataSource {
	void newSample(long sample, long clock);
	void addSubSource(SampleBasedDataSource subSource);
}

Add data source handling samples by itself


/*
 * Copyright 2016 Timothy Brooks
 *
 * 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 net.uncontended.precipice.metrics.experimental;

import net.uncontended.precipice.metrics.Allocator;
import net.uncontended.precipice.metrics.CircularBuffer;
import net.uncontended.precipice.metrics.IntervalIterator;
import net.uncontended.precipice.time.Clock;

public class NewRoller<T> implements NewMetrics<T> {

    private final Allocator<T> allocator;
    private final Clock clock;
    private final T total;
    private final CircularBuffer<T> buffer;

    public NewRoller(T total, Allocator<T> allocator, CircularBuffer<T> buffer, Clock clock) {
        this.total = total;
        this.buffer = buffer;
        this.clock = clock;
        this.allocator = allocator;
    }

    @Override
    public T current() {
        return buffer.getSlot(clock.nanoTime());
    }

    @Override
    public T current(long nanoTime) {
        T current = buffer.getSlot(nanoTime);
        if (current == null) {
            T newCurrent = allocator.allocateNew();
            // TODO: Consider whether null is the correct return value
            buffer.putOrGet(nanoTime, newCurrent);
            current = allocator.allocateNew();
        }
        return current;
    }

    @Override
    public T total() {
        return total;
    }

    public IntervalIterator<T> intervals() {
        return intervals(clock.nanoTime());
    }

    public IntervalIterator<T> intervals(long nanoTime) {
        return buffer.intervals(nanoTime, null);
    }
}

Work on implementing possible new roller