/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010(Year date of delivery) United States Government, as represented by the Secretary of Health and Human Services.  All rights reserved.
 *
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gov.hhs.fha.nhinc.mpi.adapter.component;

import gov.hhs.fha.nhinc.mpilib.Patients;

/**
 *
 * @author rayj
 */
public class CommonChecks {

    public static boolean isSingleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() == 1));
    }

    public static boolean isMultipleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() > 1));
    }

    public static boolean isZeroSearchResult(Patients patients) {
        return ((patients == null) || (patients.size() == 0));
    }

}

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010(Year date of delivery) United States Government, as represented by the Secretary of Health and Human Services.  All rights reserved.
 *
 */
package gov.hhs.fha.nhinc.mpi.adapter.component;

import gov.hhs.fha.nhinc.mpilib.Patients;
import gov.hhs.fha.nhinc.patientdb.model.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author rayj
 */
public class CommonChecks {

    // MPI XML Checks

    public static boolean isSingleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() == 1));
    }

    public static boolean isMultipleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() > 1));
    }

    public static boolean isZeroSearchResult(Patients patients) {
        return ((patients == null) || (patients.size() == 0));
    }

    // MPI DB Checks

    public static boolean isSinglePerAASearchResult(List<Patient> patients) {
        boolean result = true;

        Map testMap = new HashMap();
        if (patients != null) {
            for (Patient patient : patients) {
                if (patient.getIdentifiers() != null &&
                        patient.getIdentifiers().size() > 0 &&
                        patient.getIdentifiers().get(0) != null) {
                    String orgId = patient.getIdentifiers().get(0).getOrganizationId();
                    if (testMap.containsKey(orgId)) {
                        result = false;
                        break;
                    }
                }
            }
        }

        return result;
    }

    public static boolean isZeroPerAASearchResult(List<Patient> patients) {
        return ((patients == null) || (patients.size() == 0));
    }

}

CONNECT MPI Adapter - DB implementation - implemented MPI DB Checks


package io.quarkus.spring.web.test;

import static io.restassured.RestAssured.when;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import io.quarkus.test.QuarkusUnitTest;

public class ResponseStatusAndExceptionHandlerTest {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(ExceptionController.class, RestExceptionHandler.class));

    @Test
    public void testRootResource() {
        when().get("/exception").then().statusCode(400);
    }

    @RestController
    @RequestMapping("/exception")
    public static class ExceptionController {

        @GetMapping
        @ResponseStatus(HttpStatus.OK)
        public String throwException() {
            throw new RuntimeException();
        }
    }

    @RestControllerAdvice
    public static class RestExceptionHandler {

        @ExceptionHandler(RuntimeException.class)
        public ResponseEntity<Object> handleException(Exception ex) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
}

Add test for case where @ResponseStatus is used along with @ExceptionHandler


package org.synyx.urlaubsverwaltung.calendar;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import java.util.Optional;

import static org.hamcrest.Matchers.hasProperty;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

@RunWith(MockitoJUnitRunner.class)
public class CalendarSharingViewControllerTest {

    private CalendarSharingViewController sut;

    @Mock
    private PersonCalendarService personCalendarService;

    @Before
    public void setUp() {
        sut = new CalendarSharingViewController(personCalendarService);
    }

    @Test
    public void index() throws Exception {

        when(personCalendarService.getPersonCalendar(1)).thenReturn(Optional.of(new PersonCalendar()));

        perform(get("/web/persons/1/calendar/share"))
            .andExpect(view().name("calendarsharing/index"))
            .andExpect(status().isOk());
    }

    @Test
    public void indexNoPersonCalendar() throws Exception {

        when(personCalendarService.getPersonCalendar(1)).thenReturn(Optional.empty());

        perform(get("/web/persons/1/calendar/share"))
            .andExpect(view().name("calendarsharing/index"))
            .andExpect(model().attributeExists("privateCalendarShare"))
            .andExpect(status().isOk());
    }

    @Test
    public void linkPrivateCalendar() throws Exception {

        perform(post("/web/persons/1/calendar/share/me"))
            .andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/web/persons/1/calendar/share"));

        verify(personCalendarService).createCalendarForPerson(1);
    }

    @Test
    public void unlinkPrivateCalendar() throws Exception {

        perform(post("/web/persons/1/calendar/share/me").param("unlink", ""))
            .andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/web/persons/1/calendar/share"));

        verify(personCalendarService).deletePersonalCalendarForPerson(1);
    }

    private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception {
        return standaloneSetup(sut).build().perform(builder);
    }
}

Add test for overview share controller


package cmu.core;

public class MatOperation {
	/**
	 * Generalized matrix multiplication
	 * @param src1
	 * @param src2
	 * @return
	 */
	public static<T extends Number> Mat<T> gemm(Mat<T> src1, Mat<T> src2) {
		Mat<T> result = new Mat<T>();
		return result;
	}

	/**
	 * Per-element sum of two matrix
	 * @param src1
	 * @param src2
	 * @return
	 */
	public static<T extends Number> Mat<T> add(Mat<T> src1, Mat<T> src2) {

	}

	/*
	 * Enumerate supported norm operation type
	 */
	private static enum NormType {NORM_L1, NORM_L2};

	/**
	 * Calculates a matrix norm, norm type is specified by NormType
	 * @param src
	 * @param normType
	 * @return
	 */
	public static <T extends Number> double norm(Mat<T> src, NormType normType) {
		return 0.0;
	}
}

Add matrix operation code template. All methods are static.


import java.util.Scanner;

public class Calculator{

	static double result, num1, num2;

	public static double add(double a, double b){
		result = a + b;
		return result;
	}
	public static double subtract(double a, double b){
		result = a - b;
		return result;
	}
	public static double multiply(double a, double b){
		result = a * b;
		return result;
	}
	public static double divide(double a, double b){
		result = a / b;
		return result;
	}
	public static double sqrt(double a, double b){
		result = Math.sqrt(a);
		return result;
	}
	public static double power(double a, double b){
		result = Math.pow(a,b);
		return result;
	}
	public static double mod(double a, double b){
		result = a % b;
		return result;
	}
	public static double average(double a, double b){
		result = (a + b) / 2;
		return result;
	}
	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);

		System.out.println("What would you like to do? \n 1. Add \n 2. Subtract \n 3. Multiply \n 4. Divide \n 5. Square Root \n 6. Power \n 7. Modulus \n 8. Average");

		int operation = input.nextInt();

		while (operation < 1 || operation > 8) {
			System.out.println("Please try again:");
			operation = input.nextInt();
		}

		// If correct operation is entered
		if (operation >=1 && operation <= 8) {
			if (operation == 5) {
				System.out.println("Enter Value");
				num1 = input.nextDouble();
			} else {
				System.out.println("Enter Value 1:");
				num1 = input.nextDouble();
				System.out.println("Enter Value 2:");
				num2 = input.nextDouble();
			}

			switch (operation){
				case 1:
					add(num1, num2);
				break;
				case 2:
					subtract(num1, num2);
				break;
				case 3:
					multiply(num1, num2);
				break;
				case 4:
					divide(num1, num2);
				break;
				case 5:
					sqrt(num1, num2);
				break;
				case 6:
					power(num1, num2);
				break;
				case 7:
					mod(num1, num2);
				break;
				case 8:
					average(num1, num2);
				break;
				default :
	            System.out.println("Wrong Operation!");
			}
			System.out.println("Your solution is: " + result);
		}
		// If wrong operation is entered
		else {
			System.out.println("Wrong Operation!!!");
		}

	}
}

Create a calculator class. Allows users to add, subtract, multiply, divide, square-root, exponent, modulus, and average


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.infn.ct.futuregateway.apiserver.v1;

import javax.persistence.EntityManagerFactory;
import org.junit.Test;

/**
 *
 * @author Marco Fargetta <marco.fargetta@ct.infn.it>
 */
public class InfrastructureServiceTest {

    /**
     * EMF.
     */
    EntityManagerFactory emf;

    /**
     * Build.
     */
    public InfrastructureServiceTest() {
    }

    /**
     * Test of getInfraDetails method, of class InfrastructureService.
     */
    @Test
    public void testGetInfraDetails() {
    }

    /**
     * Test of deleteInfra method, of class InfrastructureService.
     */
    @Test
    public void testDeleteInfra() {
    }

}

Create the skeleton for the first unit test


package leetcode;

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

/**
 * https://leetcode.com/problems/sort-list/
 */
public class Problem148 {
    public static class ListNode {
        int val;
        ListNode next;

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

    public ListNode sortList(ListNode head) {
        // I know this is cheating
        if (head == null) {
            return head;
        }
        List<ListNode> nodes = new ArrayList<>();
        for (ListNode n = head; n != null; n = n.next) {
            nodes.add(n);
        }
        Collections.sort(nodes, (a, b) -> Integer.valueOf(a.val).compareTo(Integer .valueOf(b.val)));
        ListNode newHead = null;
        ListNode node = null;
        nodes.get(nodes.size()-1).next = null;
        for (int i = 0; i < nodes.size(); i++) {
            if (i == 0) {
                newHead = nodes.get(i);
                node = newHead;
            } else {
                node.next = nodes.get(i);
                node = node.next;
            }
        }
        return newHead;
    }
}

Solve problem 148 with O(N) space


package com.bloatit.framework.exceptions.lowlevel;

public class MalformedArgumentException extends IllegalArgumentException {
    private static final long serialVersionUID = -316403949660231531L;

    public MalformedArgumentException() {
        super();
    }

    public MalformedArgumentException(final String s) {
        super(s);
    }

    public MalformedArgumentException(final Throwable cause) {
        super(cause);
    }

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

}

Add the forgotten file for malformed exception


package com.workshop.wilqor.testing.bonus.examples;

import org.junit.Test;

import java.io.IOException;

/**
 * Example demonstrating basic behavior of exceptions in JUnit
 * and serving as a base for discussing exception handling in tests.
 *
 * @author wilqor
 */
public class ExceptionsExampleTest {
    @Test
    public void uncheckedExceptionThrown() {
        // does not need to be caught, handled properly
        throw new NullPointerException();
        // does the test pass?
    }

    @Test
    public void checkedExceptionThrownAndCaught() {
        try {
            throw new IOException("Network connection timeout");
        } catch (IOException e) {
            System.err.println("Caught exception: " + e);
        }
        // does the test pass? was this behavior correct?
    }

    @Test
    public void checkedExceptionAddedToSignature() throws IOException {
        throw new IOException("Network connection timeout");
        // does the test pass?
    }

    @Test
    public void genericExceptionSignature() throws Exception {
        throw new CustomException("Custom exception with message");
        // what does it give us?
    }

    @Test(expected = CustomException.class)
    public void checkedExceptionExpected() throws Exception {
        throw new CustomException("Custom exception with message");
        // when should we use this method?
    }

    private static class CustomException extends Exception {
        CustomException(String message) {
            super(message);
        }
    }
}

Add bonus content related to exceptions in test


package com.antew.redditinpictures.library.json;

import android.content.Intent;
import android.os.Bundle;

import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.library.service.RequestCode;

public abstract class JsonResult {
    private Bundle      mExtraData;
    private RequestCode mRequestCode;
    private int         mHttpStatusCode;
    private String      mJson;

    public JsonResult(Intent result) {
        mExtraData = result.getBundleExtra(RedditService.EXTRA_PASS_THROUGH);

        Bundle args = result.getBundleExtra(RedditService.EXTRA_BUNDLE);
        mRequestCode = (RequestCode) args.getSerializable(RedditService.EXTRA_REQUEST_CODE);
        mHttpStatusCode = args.getInt(RedditService.EXTRA_STATUS_CODE);
        mJson = args.getString(RedditService.REST_RESULT);
    }

    public Bundle getExtraData() {
        return mExtraData;
    }

    public RequestCode getRequestCode() {
        return mRequestCode;
    }

    public int getHttpStatusCode() {
        return mHttpStatusCode;
    }

    public String getJson() {
        return mJson;
    }

}

Add generic class for Json results from the service.


package com.epam.itweek.boosenger.controller;

import java.util.Collections;
import java.util.concurrent.Callable;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class BoosengerController {

    @RequestMapping("/{username}")
    public Callable<String> createMessage(@PathVariable("username") String username, Model model) {
        return () -> {
            model.addAttribute("username", username);

            model.addAttribute("messages", Collections.EMPTY_LIST);
            return "messaging/messages";
        };
    }

    @RequestMapping(value = "/{username}", method = RequestMethod.POST)
    public Callable<String> posMessage(@PathVariable("username") String username,
                                       @RequestParam("message") String postedMessage) {
        return () -> {
            log.info("Is about to post message '{}' for username: '{}'", postedMessage, username);
            return "redirect:/" + username;
        };
    }
}

Add MVC controller to create messages


package keymix;

import java.util.HashMap;
import javafx.scene.input.KeyCode;
import java.io.File;

/**
 * HashMap to map keycodes to the corresponding sound they should produce.
 */
public class SoundMap {

    /* Maps keycodes to string containing the file name of the sound byte. */
    HashMap<KeyCode, String> sounds = new HashMap<KeyCode, String>();

    /* KeyCodes for all valid keys. */
    KeyCode[] codes = new KeyCode[]{KeyCode.A, KeyCode.B, KeyCode.C, KeyCode.D, KeyCode.E, KeyCode.F, KeyCode.G,
            KeyCode.H, KeyCode.I, KeyCode.J, KeyCode.K, KeyCode.L, KeyCode.M, KeyCode.N, KeyCode.O, KeyCode.P,
            KeyCode.Q, KeyCode.R, KeyCode.S, KeyCode.T, KeyCode.U, KeyCode.V, KeyCode.W, KeyCode.X, KeyCode.Y, KeyCode.Z,
            KeyCode.DIGIT0, KeyCode.DIGIT1, KeyCode.DIGIT2, KeyCode.DIGIT3, KeyCode.DIGIT4, KeyCode.DIGIT5,
            KeyCode.DIGIT6, KeyCode.DIGIT7, KeyCode.DIGIT8, KeyCode.DIGIT9,
            KeyCode.SPACE, KeyCode.SHIFT, KeyCode.CONTROL, KeyCode.BACK_SPACE};

    /* Filepaths for all sound bytes to be available. */
    String[] filepaths = new String[]{
        // Insert filepaths as Strings
    };

    /* Given a filepath as a String, return the name of the file. */
    public static String name(String filepath) {
        File f = new File(filepath);
        return f.getName();
    }

    public static HashMap<KeyCode, String> map(KeyCode[] c, String[] fp, HashMap<KeyCode, String> m) {
        for(int i = 0; i < c.length; i += 1) {
            m.put(c[i], name(fp[i]));
        }
        return m;
    }
}

Create sound HashMap for KeyCode to file name


package com.intellij.debugger.streams.ui;

import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
  PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
    super(project, value);
  }

  @Override
  public String calcValueName() {
    final Value value = getValue();
    if (value instanceof ObjectReference) {
      return super.calcValueName();
    }

    return value.type().name();
  }

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

  @Override
  public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
    final Value value = getValue();
    if (value instanceof ObjectReference) {
      return super.getDescriptorEvaluation(debuggerContext);
    }

    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
    return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
  }
}

package com.intellij.debugger.streams.ui;

import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
  PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
    super(project, value);
  }

  @Override
  public String calcValueName() {
    final Value value = getValue();
    if (value instanceof ObjectReference) {
      return super.calcValueName();
    }

    return value.type().name();
  }

  @Override
  public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
    final Value value = getValue();
    if (value instanceof ObjectReference) {
      return super.getDescriptorEvaluation(debuggerContext);
    }

    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
    return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
  }
}

Remove a duplicated label from the collection view


package de.uni_stuttgart.vis.vowl.owl2vowl.parser.helper;

import org.junit.Test;

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

public class ComparisonHelperTest {

	@Test
	public void testExtractBaseIRI() throws Exception {
		String resultIri = "http://test.de/working";

		String testIri1 = "http://test.de/working#worker";
		assertThat(ComparisonHelper.extractBaseIRI(testIri1), is(resultIri));

		String testIri2 = "http://test.de/working/worker/";
		assertThat(ComparisonHelper.extractBaseIRI(testIri2), is(resultIri));

		String testIri3 = "http://test.de/working/worker";
		assertThat(ComparisonHelper.extractBaseIRI(testIri3), is(resultIri));

		String testIri4 = "http://test.de/working#";
		assertThat(ComparisonHelper.extractBaseIRI(testIri4), is(resultIri));
	}
}

Add test for baseIri extraction.


package org.beanmaker.util;

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

public class Names {

    public static <B extends NamedDbBean> List<String> getList(final List<B> beans) {
        final List<String> names = new ArrayList<String>();

        for (B bean: beans)
            names.add(bean.getDisplayName());

        return names;
    }

    public static <B extends NamedDbBean> List<String> getSortedList(final List<B> beans) {
        final List<String> names = getList(beans);
        Collections.sort(names);
        return names;
    }

    public static <B extends MultiLingualNamedDbBean> List<String> getList(
            final List<B> beans,
            final DbBeanLanguage dbBeanLanguage)
    {
        final List<String> names = new ArrayList<String>();

        for (B bean: beans)
            names.add(bean.getDisplayName(dbBeanLanguage));

        return names;
    }

    public static <B extends MultiLingualNamedDbBean> List<String> getSortedList(
            final List<B> beans,
            final DbBeanLanguage dbBeanLanguage)
    {
        final List<String> names = getList(beans, dbBeanLanguage);
        Collections.sort(names);
        return names;
    }

    public static <B extends DbBeanMultilingual> List<String> getListFromMultilingualBeans(
            final List<B> beans,
            final DbBeanLanguage dbBeanLanguage)
    {
        final List<String> names = new ArrayList<String>();

        for (B bean: beans)
            names.add(bean.getLabel(dbBeanLanguage));

        return names;
    }

    public static <B extends DbBeanMultilingual> List<String> getSortedListFromMultilingualBeans(
            final List<B> beans,
            final DbBeanLanguage dbBeanLanguage)
    {
        final List<String> names = getListFromMultilingualBeans(beans, dbBeanLanguage);
        Collections.sort(names);
        return names;
    }
}

Add utility class to create list of names from bean


package forBiic;

import bdv.util.Bdv;
import bdv.util.BdvFunctions;
import ij.IJ;
import ij.ImagePlus;
import net.imglib2.FinalInterval;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

/**
 *
 * Visualize current nicest brain and vnc templates for biic conference.
 *
 * Manually oriented the brain and vnc relative to one another, saved the settings here:
 *	/groups/saalfeld/public/fly-template/joint-brain-vnc-2.xml
 *
 * TODO - incorporate that transformation into this script
 */
public class VisWithVNC
{

	public static void main( String[] args )
	{
		String brainTemplate = "/groups/saalfeld/public/fly-template/template.tif";
		String vncTemplate = "/nrs/saalfeld/john/projects/flyChemStainAtlas/VNC_take6/all-flip-r1p5-affineCC/hiResRenders/VNC-template.tif";

		ImagePlus brainIp = IJ.openImage( brainTemplate );
		ImagePlus vncIp = IJ.openImage( vncTemplate );

		Img< FloatType > brainimg = ImageJFunctions.convertFloat( brainIp );
		Img< FloatType > vncimg = ImageJFunctions.convertFloat( vncIp );

		FinalInterval unionInterval = Intervals.union( brainimg, vncimg );

//		IntervalView< FloatType > both = Views.permute(
//				Views.addDimension(
//						Views.stack( brainimg, vncimg ), 0, 1),
//				4, 3);

		IntervalView< FloatType > brainpad = Views.interval( Views.extendZero( brainimg ), unionInterval );
		IntervalView< FloatType > vncpad = Views.interval( Views.extendZero( vncimg ), unionInterval );

		IntervalView< FloatType > bothpad = Views.permute(
				Views.addDimension(
						Views.stack( brainpad, vncpad ), 0, 1),
				4, 3);

		Bdv bdv = BdvFunctions.show( bothpad, "Brain and VNC" );
		bdv.getBdvHandle().getSetupAssignments().getMinMaxGroups().get( 0 ).setRange( 0, 1000 );
	}

}

Add script to create visualization for biic2017


package org.fundacionjala.automation.framework.utils.common;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class UIActions {

	public static void waitFor(String locatorString ) {
		By locator = By.xpath(locatorString);
		(new WebDriverWait(BrowserManager.getDriver(), 10))
		.until(ExpectedConditions.presenceOfElementLocated(locator));
	}

	public static void clickAt(WebElement element) {
		element.click();
		LogManager.info("Button has been clicked");
	}

	public static void typeOn(WebElement element, String message) {
		element.clear();
		element.sendKeys(message);
		LogManager.info("'" + message + " has been set up in " + element.getText());
	}
}

Delete Resource Scenario Implemented and Fixed


package fgis.server.services;

import fgis.server.entity.fgis.Resource;
import fgis.server.entity.fgis.ResourceTrack;
import fgis.server.entity.fgis.dao.ResourceRepository;
import fgis.server.entity.fgis.dao.ResourceTrackRepository;
import java.util.Date;
import java.util.Random;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import org.geolatte.geom.DimensionalFlag;
import org.geolatte.geom.Point;
import org.geolatte.geom.PointSequenceBuilder;
import org.geolatte.geom.PointSequenceBuilders;
import org.geolatte.geom.crs.CrsId;

@javax.ejb.Local
@Stateless
public class DataGeneratorEJB
{
  @EJB
  private ResourceRepository _resourceService;

  @EJB
  private ResourceTrackRepository _resourceTrackRepository;

  @Schedule( second = "*/5", minute = "*", hour = "*", persistent = false )
  public void insertData()
  {
    final String resourceName = "Peter";
    Resource resource = _resourceService.findByName( resourceName );
    if ( null == resource )
    {
      resource = new Resource( resourceName );
      _resourceService.persist( resource );
    }
    final Random random = new Random();

    final PointSequenceBuilder builder =
      PointSequenceBuilders.variableSized( DimensionalFlag.d2D, CrsId.UNDEFINED );
    final double latPosition = 144.92978643046 + random.nextDouble() / 1;
    final double longPosition = 37.794939500455+ random.nextDouble() / 1;
    builder.add( latPosition , longPosition );

    System.out.println( "Generating point " + latPosition + ", " + longPosition +
                        " for resource " + resource.getName() );

    final Point point = new Point( builder.toPointSequence() );
    _resourceTrackRepository.persist( new ResourceTrack( resource, new Date(), point ) );
  }
}

Add simple service that generates points for a person over time


package de.gurkenlabs.litiengine.graphics;

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

public class CameraTests {

  @Test
  public void testInit() {
    Camera cam = new Camera();
    Assert.assertEquals(cam.getZoom(), 1, 0.0001);
  }

  @Test
  public void testSimpleZoom() {
    Camera cam = new Camera();
    cam.setZoom(5, 0);

    Assert.assertEquals(cam.getZoom(), 5, 0.0001);
  }
}

Add simple init and zoom test for the camera.


package org.deeplearning4j.earlystopping.termination;

/**
 * Created by Sadat Anwar on 3/26/16.
 *
 * Stop the training once we achieved an expected score. Normally this will stop if the current score is lower than
 * the initialized score. If you want to stop the training once the score increases the defined score set the
 * lesserBetter flag to false (feel free to give the flag a better name)
 */
public class BestScoreEpochTerminationCondition  implements EpochTerminationCondition{
    private final double bestExpectedScore;
    private boolean lesserBetter = true;

    public BestScoreEpochTerminationCondition(double bestExpectedScore){
        this.bestExpectedScore = bestExpectedScore;
    }

    public BestScoreEpochTerminationCondition(double bestExpectedScore, boolean lesserBetter){
        this(bestExpectedScore);
        this.lesserBetter = lesserBetter;
    }

    @Override
    public void initialize() {
        /* No OP */
    }

    @Override
    public boolean terminate(int epochNum, double score) {
        if (lesserBetter) {
            return score < bestExpectedScore;
        } else{
            return bestExpectedScore < score;
        }
    }

    @Override
    public String toString(){
        return "BestScoreEpochTerminationCondition("+bestExpectedScore+")";
    }
}

Stop the training once we achieved an expected score. Normally this will stop if the current score is lower than the initialized score. If you want to stop the training once the score increases the defined score set the lesserBetter flag to false (feel free to give the flag a better name). Useful specially in debugging cases when you dont want to finish the training. Also can be used in cases where you are okay with a certain level of error.


package io.quarkus.websockets.client.runtime;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.graalvm.nativeimage.hosted.Feature;

import com.oracle.svm.core.annotate.AutomaticFeature;

/**
 * Disables logging during the analysis phase
 */
@AutomaticFeature
public class DisableLoggingAutoFeature implements Feature {

    private static final String[] CATEGORIES = {
            "io.undertow.websockets",
    };

    private final Map<String, Level> categoryMap = new HashMap<>(CATEGORIES.length);

    @Override
    public void beforeAnalysis(BeforeAnalysisAccess access) {
        for (String category : CATEGORIES) {
            Logger logger = Logger.getLogger(category);
            categoryMap.put(category, logger.getLevel());
            logger.setLevel(Level.WARNING);
        }
    }

    @Override
    public void afterAnalysis(AfterAnalysisAccess access) {
        for (String category : CATEGORIES) {
            Level level = categoryMap.remove(category);
            if (level != null) {
                Logger logger = Logger.getLogger(category);
                logger.setLevel(level);
            }
        }
    }
}

Disable Websockets logging during native image build


package leetcode.rotate_list;

import common.ListNode;

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
    	if(head == null) return head;
    	int length = 0;
    	ListNode cur = head;
    	ListNode tail = null;
    	while(cur != null){
    		length++;
    		tail = cur;
    		cur = cur.next;
    	}
    	int shift = (length - (n % length)) % length;
    	ListNode nHead = head;
    	ListNode prev = null;
    	while(shift > 0){
    		prev = nHead;
    		nHead = nHead.next;
    		shift--;
    	}
    	if(prev != null){
    		 tail.next = head;
    		 prev.next = null;
    		 head = nHead;
    	}
    	return head;
    }

    public static void dump(ListNode cur){
    	while(cur != null){
    		System.err.print(cur.val + "->");
    		cur = cur.next;
    	}
    	System.err.println("null");
    }

    public static void main(String args[]){
    	final int N = 1;
    	dump(new Solution().rotateRight(null, 10));
    	for(int shift = 0; shift < 12; shift++){
    		ListNode[] list = new ListNode[N];
    		for(int i = 0; i < N; i++){
    			list[i] = new ListNode(i);
    			if(i > 0) list[i - 1].next = list[i];
    		}
    		dump(new Solution().rotateRight(list[0], shift));
    	}
    }
}

Add java solution for 61. Rotate List


package com.gruppe27.fellesprosjekt.common.serializers;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.time.LocalDateTime;

public class LocalDateTimeSerializer extends Serializer<LocalDateTime> {
    public void write(Kryo kryo, Output output, LocalDateTime dateTime) {
        output.writeString(dateTime.toString());
    }

    public LocalDateTime read(Kryo kryo, Input input, Class<LocalDateTime> type) {
        return LocalDateTime.parse(input.readString());
    }
}

Add a serializer for LocalDateTime-


/*
 * Copyright 2010 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kfs.module.endow.businessobject.defaultvalue;

import org.kuali.kfs.module.endow.EndowConstants;
import org.kuali.kfs.module.endow.businessobject.AutomatedCashInvestmentModel;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.kns.lookup.valueFinder.ValueFinder;
import org.kuali.rice.kns.service.SequenceAccessorService;

public class NextACIModelIDFinder implements ValueFinder {

    /**
     * @see org.kuali.rice.kns.lookup.valueFinder.ValueFinder#getValue()
     */
    public String getValue() {
        return getLongValue().toString();

    }

    /**
     * Gets the next sequence number as a long.
     *
     * @return next sequence number as a long
     */
    public static Long getLongValue() {

        SequenceAccessorService sequenceAccessorService = SpringContext.getBean(SequenceAccessorService.class);
        return sequenceAccessorService.getNextAvailableSequenceNumber(EndowConstants.Sequences.END_ACI_SEQ, AutomatedCashInvestmentModel.class);
    }

}

Use SequenceAccessorService to get the next sequence number for the ACI Model ID field.


package org.apache.beam.runners.spark.structuredstreaming.translation.batch;

import java.io.Serializable;
import org.apache.beam.runners.spark.structuredstreaming.SparkPipelineOptions;
import org.apache.beam.runners.spark.structuredstreaming.SparkRunner;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Test class for beam to spark {@link org.apache.beam.sdk.transforms.Combine} translation. */
@RunWith(JUnit4.class)
public class CombineTest implements Serializable {
  private static Pipeline pipeline;

  @BeforeClass
  public static void beforeClass() {
    PipelineOptions options = PipelineOptionsFactory.create().as(SparkPipelineOptions.class);
    options.setRunner(SparkRunner.class);
    pipeline = Pipeline.create(options);
  }

  @Test
  public void testCombine() {
    PCollection<Integer> input = pipeline.apply(Create.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    input.apply(Combine.globally(new Combine.CombineFn<Integer, Integer, Integer>() {

      @Override public Integer createAccumulator() {
        return 0;
      }

      @Override public Integer addInput(Integer accumulator, Integer input) {
        return accumulator + input;
      }

      @Override public Integer mergeAccumulators(Iterable<Integer> accumulators) {
        Integer result = 0;
        for (Integer value : accumulators){
          result += value;
        }
        return result;
      }

      @Override public Integer extractOutput(Integer accumulator) {
        return accumulator;
      }
    }));
    pipeline.run();
  }
}

Add a test for the most simple possible Combine


package moulder.moulds;

import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;

import java.io.StringReader;
import java.util.Arrays;
import java.util.List;

import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;

public class ForEachTest extends BaseMoulderTest {

    @Test
    public void test() throws Exception {
        List<Integer> list = Arrays.asList(4, 2);
        final SimpleBox<Integer> sb = new SimpleBox<Integer>();
        ForEach<Integer> f = new ForEach<Integer>(sb, new SeqValue<Integer>(list), new Moulder() {
            public List<Node> process(Element element) {
                return Arrays.asList(parseNode("ohai n" + sb.get() + ""));
            }
        });
        Document document = Jsoup
                .parseBodyFragment("<tag>text</tag>");
        Element element = document.getElementsByTag("tag").first();

        List<Node> processed = f.process(element);

        // check for correct repetition of html
        assertXMLEqual(new StringReader("" + "ohai n4ohai n2" + ""), new StringReader(
                html(processed)));
    }

}

Add test for ForEach moulder


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.opensim.view;

import org.opensim.modeling.*;
import vtk.*;

/**
 *
 * @author ayman
 */
public abstract class ObjectDisplayer extends vtkActor {
    protected OpenSimObject obj;

    public ObjectDisplayer(OpenSimObject object) {
        obj = object;
    }

    /**
     * Apply user display preference (None, wireframe, shading)
     */
    protected void applyDisplayPrefs(OpenSimObject object) {
        AbstractProperty ap = obj.getPropertyByName("display_preference");
        int prefInt = PropertyHelper.getValueInt(ap);
        DisplayGeometry.DisplayPreference pref = DisplayGeometry.DisplayPreference.swigToEnum(prefInt);
        // Show vs. HideDisplayGeometry
        if (pref == DisplayGeometry.DisplayPreference.None) {
            SetVisibility(0);
            return;
        }
        SetVisibility(1);
        if (pref == DisplayGeometry.DisplayPreference.WireFrame) {
            GetProperty().SetRepresentationToWireframe();
        } else {
            GetProperty().SetRepresentationToSurface();
            if (pref == DisplayGeometry.DisplayPreference.FlatShaded) {
                GetProperty().SetInterpolationToFlat();
            } else {
                GetProperty().SetInterpolationToGouraud();
            }
        }
    }

    abstract void updateFromProperties();

    protected void updatePropertiesForPolyData(vtkPolyData polyData) {
        addPolyDataToActorApplyProperties(polyData, obj.getDisplayer());
        // Color/shading
        if (obj.hasProperty("color")) {
            AbstractProperty ap = obj.getPropertyByName("color");
            double[] dColor = new double[]{PropertyHelper.getValueDouble(ap, 0), PropertyHelper.getValueDouble(ap, 1), PropertyHelper.getValueDouble(ap, 2)};
            GetProperty().SetColor(dColor);
        } else {
            GetProperty().SetColor(new double[]{0.0, 1.0, 1.0});
        }
        applyDisplayPrefs(obj);
        Modified();
    }

    protected void addPolyDataToActorApplyProperties(final vtkPolyData meshPoly, final VisibleObject visibleObject) {
        // Move rep to proper location
        vtkTransformPolyDataFilter mover = new vtkTransformPolyDataFilter();
        vtkTransform moverTransform = new vtkTransform();
        double[] matRows = new double[16];
        visibleObject.getTransformAsDouble16(matRows);
        moverTransform.SetMatrix(SingleModelVisuals.convertTransformToVtkMatrix4x4(matRows));
        mover.SetInput(meshPoly);
        mover.SetTransform(moverTransform);
        // Mapper
        vtkPolyDataMapper mapper = new vtkPolyDataMapper();
        mapper.SetInput(mover.GetOutput());
        SetMapper(mapper);
    }

}

Add new file missing from last commit.


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

import javax.servlet.http.HttpServletRequest;

import com.ajah.util.FromStringable;
import com.ajah.util.ToStringable;

/**
 * @author Eric F. Savage, code@efsavage.com.
 *
 */
public class UserAgent implements FromStringable, ToStringable {

	private String raw;

	private UserAgent(String raw) {
		this.raw = raw;
	}

	public static UserAgent from(HttpServletRequest request) {
		return new UserAgent(request.getHeader("User-Agent"));
	}

	@Override
	public String toString() {
		return this.raw;
	}
}

Add User Agent header wrapper


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

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;

import model.job.Job;

/**
 * Represents the response that the Gateway returns to the user when the user
 * has requested to see the information on a list of Jobs currently held by the
 * Piazza Job Manager.
 *
 * @author Patrick.Doody
 *
 */
@ApiModel("JobResults")
public class JobListResponse extends PiazzaResponse {

	@ApiModelProperty(value = "The array of Job results.")
	public List<Job> data;

	@ApiModelProperty(value = "The pagination metadata for this query.")
	public Pagination pagination;

	public JobListResponse() {

	}

	public JobListResponse(List<Job> jobs) {
		this.data = jobs;
	}

	public JobListResponse(List<Job> deployments, Pagination pagination) {
		this(deployments);
		this.pagination = pagination;
	}

	/**
	 * Returns the list of Jobs held by this response object
	 *
	 * @return The list
	 */
	public List<Job> getData() {
		return data;
	}

	public Pagination getPagination() {
		return pagination;
	}
}

Standardize JobList response with a Model object


public class Solution {

    public boolean containsDuplicate(int[] nums) {

        Arrays.sort(nums);

        for (int i = 1; i < nums.length; i++) {

            if (nums[i] == nums[i - 1]) {
                return true;
            }

        }

        return false;

    }

}

Create : 217 Contains Duplicate


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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.legacy;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.SwingUtilities;

import net.imagej.ui.swing.script.TextEditor;

import org.scijava.Context;

/**
 * Interactive test for the script editor in legacy mode.
 *
 * @author Johannes Schindelin
 */
public class LegacyEditorTestDrive {
	public static void main(String[] args) throws Exception {
		final Context context = new Context();
		final TextEditor editor = new TextEditor(context);
		editor.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(final WindowEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						context.dispose();
					}
				});
			}
		});
		editor.setVisible(true);
	}
}

Add a TestDrive for the editor in legacy mode


package org.aspectj.aspect;

import com.google.gson.GsonBuilder;
import org.aspectj.configuration.model.Artifact;
import org.aspectj.configuration.model.ClassRef;
import org.aspectj.configuration.model.ResourceRef;
import org.aspectj.util.MavenLoader;
import org.aspectj.util.task.MvelTimerTask;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

import java.util.HashMap;
import java.util.Timer;

public class ExecuteTimerTaskTest {

    public static final int TIMER_DELAY = 500;

    private static String jsonResult = null;

    public static void setJsonResult(String jsonResult) {
        ExecuteTimerTaskTest.jsonResult = jsonResult;
    }

    @org.junit.Test
    public void mvelScheduler() throws Exception{
        Timer timer = new Timer();
        MapVariableResolverFactory variableResolverFactory = new MapVariableResolverFactory();
        ClassRef[] classRefs = {new ClassRef("org.github.suhorukov.SigarCollect", "SigarCollect")};
        ResourceRef[] resourceRefs = new ResourceRef[0];
        Artifact[] artifacts = {new Artifact("com.github.igor-suhorukov:jvm-metrics:1.1", classRefs, resourceRefs)};
        MavenLoader.loadArtifact(artifacts, variableResolverFactory);
        String mvelScript = "java.lang.String metrics = new SigarCollect().getJsonFullInfo();" +
                            "org.aspectj.aspect.ExecuteTimerTaskTest.setJsonResult(metrics);";
        timer.schedule(new MvelTimerTask(mvelScript, variableResolverFactory), TIMER_DELAY);
        Thread.sleep(TIMER_DELAY*5);
        HashMap metrics = new GsonBuilder().create().fromJson(jsonResult, HashMap.class);
        assertNotNull(jsonResult);
        assertTrue(metrics.containsKey("ProcCpu"));
        assertTrue(metrics.containsKey("Pid"));
        assertTrue(metrics.containsKey("Mem"));
    }
}

Test TimerTask with Mvel expression


package arez.integration.observed;

import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Observed;
import arez.annotations.ObserverRef;
import arez.integration.AbstractArezIntegrationTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservedArezDependenciesOnlyTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    int _renderCallCount;

    @Observed
    void render()
    {
      getValue();
      _renderCallCount++;
    }

    @ObserverRef
    abstract Observer getRenderObserver();

    @SuppressWarnings( "UnusedReturnValue" )
    @Observable
    abstract long getValue();

    abstract void setValue( long value );
  }

  @Test
  public void scenario()
    throws Exception
  {
    final TestComponent1 component = new ObservedArezDependenciesOnlyTest_Arez_TestComponent1();

    assertEquals( component._renderCallCount, 1 );

    // reportStale should result in exception
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class,
                    () -> safeAction( () -> component.getRenderObserver().reportStale() ) );

    assertEquals( exception.getMessage(),
                  "Arez-0199: Observer.reportStale() invoked on observer named 'TestComponent1.0.render' but arezOnlyDependencies = true." );

    assertEquals( component._renderCallCount, 1 );
  }
}

Add integration test for arez dependencies only and calling reportStale


package io.dmitryivanov.crdt.helpers;

import java.util.*;

public final class Operations {
    private Operations() {
        // No instances
    }

    public static <E> Set<E> diff(Set<E> firstSet, final Set<E> secondSet) {
        return filtered(firstSet, new Predicate<E>() {
            @Override
            public boolean call(E element) {
                return !secondSet.contains(element);
            }
        });
    }

    public static <E> Set<E> union(Set<E> firstSet, final Set<E> secondSet) {
        return filtered(firstSet, new Predicate<E>() {
            @Override
            public boolean call(E element) {
                return secondSet.contains(element);
            }
        });
    }

    public static <E> Set<E> filtered(Set<E> set, Predicate<E> predicate) {
        final Set<E> newSet = new HashSet<>();
        for (E element : set) {
            if (predicate.call(element)) {
                newSet.add(element);
            }
        }
        return newSet;
    }

    public static <E, R> Set<R> filteredAndMapped(Set<E> set, Predicate<E> predicate,
            Mapper<E, R> mapper) {
        final Set<R> newSet = new HashSet<>();
        for (E element : set) {
            if (predicate.call(element)) {
                newSet.add(mapper.call(element));
            }
        }
        return newSet;
    }

    public static <E> E select(Set<E> set, Predicate2<E, E> predicate) {
        if (set.isEmpty()) {
            throw new IllegalArgumentException("Empty set for select operation");
        }
        E winner = set.iterator().next();
        for (E element : set) {
            if (predicate.call(winner, element)) {
                winner = element;
            }
        }
        return winner;
    }

    public static <K, V> Map<K, Collection<V>> toListMap(Set<V> map, Mapper<V, K> mapper) {
        final Map<K, Collection<V>> newMap = new HashMap<>(map.size());
        for (V element : map) {
            K key = mapper.call(element);
            Collection<V> list = newMap.get(key);
            if (null == list) {
                list = new ArrayList<>();
            }
            list.add(element);
            newMap.put(key, list);
        }
        return newMap;
    }

    public static <K, V, R> Map<K, R> mapValues(Map<K, V> map, Mapper<V, R> mapper) {
        final Map<K, R> newMap = new HashMap<>(map.size());
        for (Map.Entry<K, V> entry : map.entrySet()) {
            newMap.put(entry.getKey(), mapper.call(entry.getValue()));
        }
        return newMap;
    }

    public interface Predicate<E> {
        boolean call(E element);
    }

    public interface Predicate2<E, F> {
        boolean call(E first, F second);
    }

    public interface Mapper<E, R> {
        R call(E element);
    }
}

Add Operation helpers to replace Java 8 Streams, and Guava's utils


package net.interfax.rest.client.util;

public class ArrayUtil {

    public static byte[][] chunkArray(byte[] array, int chunkSize) {
        int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
        byte[][] output = new byte[numOfChunks][];

        for(int i = 0; i < numOfChunks; ++i) {
            int start = i * chunkSize;
            int length = Math.min(array.length - start, chunkSize);

            byte[] temp = new byte[length];
            System.arraycopy(array, start, temp, 0, length);
            output[i] = temp;
        }

        return output;
    }
}

Add utility to split byte arrary into chunks


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

import processing.core.PApplet;

public class FlipHFilter
extends BaseFilter {

	public static FlipHFilter instance;

	public FlipHFilter(PApplet p) {
		super(p, "shaders/filters/flip-h.glsl");
	}

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

}

Add flip horizontal shader wrapper class


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

package io.michaelrocks.lightsaber.processor.commons;

import org.junit.Test;

import static org.mockito.Mockito.*;

public class CompositeVisitorHelperTest {
    @Test
    public void testAddNullVisitor() throws Exception {
        // noinspection unchecked
        final CompositeVisitor<Object> compositeVisitor = mock(CompositeVisitor.class);
        CompositeVisitorHelper.addVisitor(compositeVisitor, null);
        verifyZeroInteractions(compositeVisitor);
    }

    @Test
    public void testAddNonNullVisitor() throws Exception {
        // noinspection unchecked
        final CompositeVisitor<Object> compositeVisitor = mock(CompositeVisitor.class);
        final Object visitor = new Object();
        CompositeVisitorHelper.addVisitor(compositeVisitor, visitor);
        verify(compositeVisitor, only()).addVisitor(visitor);
    }
}

Add unit tests for CompositeVisitorHelper


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

package tests.api.java.io;

import java.io.NotSerializableException;

public class NotSerializableExceptionTest extends junit.framework.TestCase {

	/**
	 * @tests java.io.NotSerializableException#NotSerializableException()
	 */
	public void test_Constructor() {
        NotSerializableException nse = new NotSerializableException();
        assertNull(nse.getMessage());
	}

	/**
	 * @tests java.io.NotSerializableException#NotSerializableException(java.lang.String)
	 */
	public void test_ConstructorLjava_lang_String() {
		// Test for method java.io.NotSerializableException(java.lang.String)
        String message = "Test message";
        NotSerializableException nse = new NotSerializableException(message);
        assertSame(message, nse.getMessage());
	}

	/**
	 * Sets up the fixture, for example, open a network connection. This method
	 * is called before a test is executed.
	 */
	protected void setUp() {
	}

	/**
	 * Tears down the fixture, for example, close a network connection. This
	 * method is called after a test is executed.
	 */
	protected void tearDown() {
	}
}

Apply patch for HARMONY-3388([classlib][luni] Refactor the default constuctor of NotSerializableException)


package no.cantara.jau.eventextraction;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

public class MDCEventsFilter extends AbstractMatcherFilter<ILoggingEvent> {
    private static final Logger log = LoggerFactory.getLogger(MDCEventsFilter.class);
    private String mdcEventsToMatch = null;
    @Override
    public void start() {
        if (null != this.mdcEventsToMatch)
            super.start();
        else
            addError("No MDC events to match to yet.");
    }
    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (event.getLevel() == Level.ERROR) {
            return onMatch;
        }

        log.info("Events to match: " + mdcEventsToMatch);
        Set<String> mdcKeys = event.getMDCPropertyMap().keySet();

        for (String mdc : mdcKeys) {
            if (mdcEventsToMatch.contains(mdc)) {
                log.info("A match!!");
                return onMatch;
            }
        }
        return onMismatch;
    }
    public void setMdcEvents(String markerStr) {
        if(null != markerStr)
            mdcEventsToMatch = markerStr;
    }

}

Add log filter for filtering events based on MDC


package com.udinic.accounts_authenticator_example.authentication;

import android.os.Bundle;
import android.support.annotation.NonNull;

import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GetTokenResult;

import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.accounts.AccountManager.KEY_AUTHTOKEN;
import static android.accounts.AccountManager.KEY_PASSWORD;
import static com.google.common.base.Preconditions.checkNotNull;

public class SignInTask implements Continuation<Bundle, Task<Bundle>> {

    private Bundle mAuthData;

    @Override
    public Task<Bundle> then(@NonNull Task<Bundle> task) throws Exception {
        mAuthData = checkNotNull(task.getResult());
        return signUp().continueWithTask(getAuthToken()).continueWith(getResult());
    }

    private Task<AuthResult> signUp() {
        return FirebaseAuth.getInstance().signInWithEmailAndPassword(
                checkNotNull(mAuthData.getString(KEY_ACCOUNT_NAME)),
                checkNotNull(mAuthData.getString(KEY_PASSWORD))
        );
    }

    private Continuation<AuthResult, Task<GetTokenResult>> getAuthToken() {
        return new Continuation<AuthResult, Task<GetTokenResult>>() {
            @Override
            public Task<GetTokenResult> then(@NonNull Task<AuthResult> task) throws Exception {
                return task.getResult().getUser().getToken(true);
            }
        };
    }

    private Continuation<GetTokenResult, Bundle> getResult() {
        return new Continuation<GetTokenResult, Bundle> () {
            @Override
            public Bundle then(@NonNull Task<GetTokenResult> task) throws Exception {
                mAuthData.putString(KEY_AUTHTOKEN, task.getResult().getToken());
                return mAuthData;
            }
        };
    }

}

Create Firebase sign in task


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

package org.apache.flink.table.types.utils;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.types.AtomicDataType;
import org.apache.flink.table.types.CollectionDataType;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.DataTypeVisitor;
import org.apache.flink.table.types.FieldsDataType;
import org.apache.flink.table.types.KeyValueDataType;

/**
 * Implementation of {@link DataTypeVisitor} that redirects all calls to
 * {@link DataTypeDefaultVisitor#defaultMethod(DataType)}.
 */
@Internal
public abstract class DataTypeDefaultVisitor<R> implements DataTypeVisitor<R>{

	@Override
	public R visit(AtomicDataType atomicDataType) {
		return defaultMethod(atomicDataType);
	}

	@Override
	public R visit(CollectionDataType collectionDataType) {
		return defaultMethod(collectionDataType);
	}

	@Override
	public R visit(FieldsDataType fieldsDataType) {
		return defaultMethod(fieldsDataType);
	}

	@Override
	public R visit(KeyValueDataType keyValueDataType) {
		return defaultMethod(keyValueDataType);
	}

	protected abstract R defaultMethod(DataType dataType);
}

Add a default data type visitor


/**
 * Copyright © 2011-2012 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.pojo;

import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@PrimaryKeyJoinColumn(name="id")
@Table(name = "image_record_observation")
public class ImageRecordObservation extends Observation {

	//@OneToOne
	//@JoinColumn(name = "image_record_id")
	//private ImageRecord imageRecord;

}

Move PhenotypeArchive to trunk Copyright notice changed Observation classes added Biological sample and model added.


package org.apereo.cas;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

/**
 * This is {@link CasConfigurationServerServletInitializer}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class CasConfigurationServerServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) {
        return builder
                .sources(CasConfigurationServerWebApplication.class)
                .banner(new CasConfigurationServerBanner())
                .logStartupInfo(true);
    }
}

Add initializer for the config server


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.lesscss.internal.lessjs;

import java.io.FileInputStream;
import java.io.StringWriter;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.xwiki.test.mockito.MockitoComponentMockingRule;

import static org.junit.Assert.assertEquals;

/**
 * Test class for {@link org.xwiki.lesscss.internal.lessjs.JavaScriptLESSCompiler}.
 *
 * @since 6.1M1
 * @version $Id$
 */
public class JavaScriptLESSCompilerTest
{
    @Rule
    public MockitoComponentMockingRule<JavaScriptLESSCompiler> mocker =
            new MockitoComponentMockingRule<>(JavaScriptLESSCompiler.class);

    @Test
    public void compile() throws Exception
    {
        // Get an example
        StringWriter source = new StringWriter();
        IOUtils.copy(new FileInputStream(getClass().getResource("/style.less").getFile()), source);

        // Compile
        String result = mocker.getComponentUnderTest().compile(source.toString());

        // Get the expected result
        StringWriter expectedResult = new StringWriter();
        IOUtils.copy(new FileInputStream(getClass().getResource("/style.css").getFile()), expectedResult);

        // Compare
        assertEquals(expectedResult.toString(), result);
    }

    @Test
    public void compileWithImports() throws Exception
    {
        // Get an example
        StringWriter source = new StringWriter();
        IOUtils.copy(new FileInputStream(getClass().getResource("/styleWithImports.less").getFile()), source);

        // Compile
        Path[] paths = {Paths.get(getClass().getResource("/").getPath())};
        String result = mocker.getComponentUnderTest().compile(source.toString(), paths);

        // Get the expected result
        StringWriter expectedResult = new StringWriter();
        IOUtils.copy(new FileInputStream(getClass().getResource("/styleWithImports.css").getFile()), expectedResult);

        // Compare
        assertEquals(expectedResult.toString(), result);
    }
}

Use LESS4J for the implementation of LESSCompiler.


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

import org.junit.Test;

import static org.junit.Assert.assertSame;

public class TestFormats {

  @Test
  public void testFromStringForValidFormats() {
    assertSame(Formats.AVRO, Formats.fromString("avro"));
    assertSame(Formats.PARQUET, Formats.fromString("parquet"));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testFromStringForInvalidFormats() {
    Formats.fromString("bogus");
  }

}

Add unit test for CDK-207: Formats should support a fromString() method


package leetcode.reverse_linked_list;

import common.ListNode;

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev, cur;
        cur = head;
        prev = null;
        while(cur != null){
            ListNode tmp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }
}

Add java solution for 206. Reverse Linked List


package com.box.l10n.mojito.immutables;

import org.immutables.value.Value;

@Value.Style(
        allParameters = true,
        of = "new",
        defaults = @Value.Immutable(builder = false),
        // Avoid annoying auto-complete and useless copies when working with Immutable collection
        // Could be nice to have for test syntax
        builtinContainerAttributes = false,
        // No prefix or suffix for generated immutable type
        typeImmutable = "*"
)
public @interface JpaDTO {
}

Add Immutable style for Jpa DTOs


package com.formulasearchengine.mathmlquerygenerator;

/**
 * Created by Moritz on 08.11.2014.
 */
public class NtcirPattern {
	private final String num;
	private final String formulaID;
	private final String xQueryExpression;

	public NtcirPattern (String num, String formulaID, String xQueryExpression) {
		this.num = num;
		this.formulaID = formulaID;
		this.xQueryExpression = xQueryExpression;
	}

	public String getNum () {
		return num;
	}

	public String getFormulaID () {
		return formulaID;
	}

	public String getxQueryExpression () {
		return xQueryExpression;
	}
}

Add support for NTCIR topic format


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2017 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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;

import static org.junit.Assert.assertNotNull;

import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.view.Views;

import org.junit.Test;
import org.scijava.Context;

/**
 * Unit tests for {@link DefaultDatasetService}.
 *
 * @author Curtis Rueden
 */
public class DatasetServiceTest {

	@Test
	public void testCreateFromRAI() {
		final Context ctx = new Context(DatasetService.class);
		final DatasetService datasetService = ctx.service(DatasetService.class);

		final Img<UnsignedByteType> img = ArrayImgs.unsignedBytes(5, 7);

		// NB: We use Views to create a RAI that is not an Img.
		final RandomAccessibleInterval<UnsignedByteType> rai = Views.interval(img, img);

		// Wrap the RAI in a Dataset.
		final Dataset dataset = datasetService.create(rai);

		// Ensure we can successfully make a copy. This is a
		// regression test for 6156a14da88daf110b1366282a7c3ffc02190270.
		final Img<?> copy = dataset.copy();
		assertNotNull(copy);

		ctx.dispose();
	}
}

Add regression test verifying the previous commit


import org.junit.Test;
import java.util.Arrays;

public class InsertionSortTest {

    @Test
    public void test() {
        int list[] = { -5, 8, 0, 12, 55, 1, -66, 35, 3 };
        InsertionSort insertionSort = new InsertionSort();
        insertionSort.sort(list);
        for (int i = 0; i < list.length - 1; i++) {
            assert (list[i] <= list[i + 1]);
        }
    }

    @Test
    public void nullList(){
        int list[] = {};
        int expectedList[] = {};
        InsertionSort insertionSort = new InsertionSort();
        insertionSort.sort(list);
        assert (Arrays.equals(list, expectedList));
    }
}

Add insertion sort test for Java implementation


/*
 * Copyright (C) 2014-present  The   openSourcLibrary-2015  Authors
 *
 * https://github.com/sdcuike
 *
 * 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.doctor.java8;

import java.util.Arrays;
import java.util.stream.Stream;

/**
 * Convert Stream to Array in Java 8
 *
 * @author doctor
 *
 * @see http://www.programcreek.com/2014/01/convert-stream-to-array-in-java-8/
 *
 * @time 2015年8月5日 上午10:38:41
 *
 */
public class ConvertStreamToArrayInJava8 {

	public static void main(String[] args) {
		String[] strings = {"hello","doctor","who are you"};
		String[] array = Stream.of(strings).toArray(String[]::new);
		System.out.println(Arrays.toString(array));

		String[] array2 = Stream.of(strings).toArray(size -> new String[size]);
		System.out.println(Arrays.toString(array2));

	}

}

Convert Stream to Array in Java 8


/**
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
 * <p>
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
 * graphic logo is a trademark of OpenMRS Inc.
 */
package org.openmrs.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

@Component
public class WebComponentRegistrar implements ServletContextAware {

    @Override
    public void setServletContext(ServletContext servletContext) {
        ServletRegistration openmrsServletReg = servletContext.getServletRegistration("openmrs");
        addMappings(openmrsServletReg, "*.htm", "*.form", "*.list", "*.json", "*.field", "*.portlet");
    }

    private void addMappings(ServletRegistration reg, String... mappings) {
        for (String mapping : mappings) {
            reg.addMapping(mapping);
        }
    }

}

Move mappings for the dispatcher servlet - LUI-40


package com.vladmihalcea.book.hpjp.hibernate.batch;

import com.vladmihalcea.book.hpjp.util.AbstractTest;
import com.vladmihalcea.book.hpjp.util.exception.ExceptionUtil;
import com.vladmihalcea.book.hpjp.util.providers.Database;
import org.hibernate.StaleStateException;
import org.junit.Test;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import static org.junit.Assert.assertTrue;

/**
 * @author Vlad Mihalcea
 */
public class BatchingOptimisticLockingTest extends AbstractTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[]{
            Post.class
        };
    }

    @Override
    protected Database database() {
        return Database.POSTGRESQL;
    }

    @Override
    protected void additionalProperties(Properties properties) {
        properties.put("hibernate.jdbc.batch_size", "5");
        properties.put("hibernate.order_inserts", "true");
        properties.put("hibernate.order_updates", "true");
    }

    @Test
    public void testOptimsticLOcking() {
        doInJPA(entityManager -> {
            for (int i = 1; i <= 3; i++) {
                entityManager.persist(
                    new Post()
                        .setTitle(String.format("Post no. %d", i))
                );
            }
        });

        try {
            doInJPA(entityManager -> {
                List<Post> posts = entityManager.createQuery("""
                    select p
                    from Post p
                    """, Post.class)
                .getResultList();

                posts.forEach(post -> post.setTitle(post.getTitle() + " - 2nd edition"));

                executeSync(
                    () -> doInJPA(_entityManager -> {
                        Post post = _entityManager.createQuery("""
                            select p
                            from Post p
                            order by p.id
                            """, Post.class)
                        .setMaxResults(1)
                        .getSingleResult();

                        post.setTitle(post.getTitle() + " - corrected");
                    })
                );
            });
        } catch (Exception e) {
            assertTrue(
                ExceptionUtil.rootCause(e).getMessage()
                    .startsWith(
                        "Batch update returned unexpected row count from update [0]; " +
                        "actual row count: 0; " +
                        "expected: 1; " +
                        "statement executed:"
                    )
            );
        }
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        private Long id;

        private String title;

        @Version
        private short version;

        public Long getId() {
            return id;
        }

        public Post setId(Long id) {
            this.id = id;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Post setTitle(String title) {
            this.title = title;
            return this;
        }

        public short getVersion() {
            return version;
        }
    }
}

Add test case that shows how the optimistic locking failure occurs when using JDBC batching


package com.philliphsu.bottomsheetpickers;

import android.support.test.espresso.Espresso;
import android.support.test.espresso.ViewAssertion;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import com.example.bottomsheetpickers.R;
import com.example.bottomsheetpickers.TextSwitcherActivity;

import org.hamcrest.Matcher;
import org.hamcrest.core.StringContains;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class NumberPadTimePickerDialogTest {
    private static final String TIME_PICKER_VIEW_CLASS_NAME = "NumberPadTimePicker";

    /**
     * {@link ActivityTestRule} is a JUnit {@link Rule @Rule} to launch your activity under test.
     *
     *

     * Rules are interceptors which are executed for each test method and are important building
     * blocks of Junit tests.
     *
     *

     * The annotated Activity will be launched before each annotated @Test and before any annotated
     * {@link Before @Before} methods. The Activity is automatically terminated after the test is
     * completed and all {@link After @After} methods are finished.
     */
    @Rule
    public ActivityTestRule<TextSwitcherActivity> mActivityTestRule =
            new ActivityTestRule<>(TextSwitcherActivity.class);

    @Test
    public void clickButton_opensTimePickerDialog() {
        // Specifies a view with the given id that we want to interact with.
        ViewInteraction viewInteraction = Espresso.onView(ViewMatchers.withId(R.id.button3));
        // Interact with the view by performing a ViewAction.
        viewInteraction.perform(ViewActions.click());

        // Obtain a Matcher that will allow us to determine if a string being examined contains
        // the specified string. Where does the string being examined come from? Espresso handles
        // that for us when we intend to search for this specified string.
        Matcher<String> classNameMatcher = StringContains.containsString(TIME_PICKER_VIEW_CLASS_NAME);
        // Specifies a view with the given class name that we want to interact with.
        viewInteraction = Espresso.onView(ViewMatchers.withClassName(classNameMatcher));
        // Specifies an assertion we want to test. Here, we convert a ViewMatcher that determines if
        // a view is displayed into a ViewAssertion.
        ViewAssertion assertion = ViewAssertions.matches(ViewMatchers.isDisplayed());
        // Interact with the view by checking the assertion.
        viewInteraction.check(assertion);
    }
}

Create test to check that time picker opens.


package arez.integration.references;

import arez.Arez;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Reference;
import arez.annotations.ReferenceId;
import arez.annotations.Repository;
import arez.component.Identifiable;
import arez.component.TypeBasedLocator;
import arez.integration.AbstractArezIntegrationTest;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ReferenceNotFoundIntegrationTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void scenario()
    throws Throwable
  {
    final ReferenceNotFoundIntegrationTest_Model2Repository repository =
      ReferenceNotFoundIntegrationTest_Model2Repository.newRepository();

    final TypeBasedLocator locator = new TypeBasedLocator();
    Arez.context().registerLocator( locator );

    final Model2 model2 = repository.create();
    final Object model2Id = Objects.requireNonNull( Identifiable.getArezId( model2 ) );

    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> safeAction( () -> Model1.create( model2Id ) ) );

    assertEquals( exception.getMessage(),
                  "Reference method named 'getModel2' invoked on component named 'Model1.0' is unable to resolve entity of type arez.integration.references.ReferenceNotFoundIntegrationTest.Model2 and id = 0" );
  }

  @ArezComponent
  static abstract class Model1
  {
    @Nonnull
    private Object _model2Id;

    static Model1 create( @Nonnull final Object model2Id )
    {
      return new ReferenceNotFoundIntegrationTest_Arez_Model1( model2Id );
    }

    Model1( @Nonnull final Object model2Id )
    {
      _model2Id = model2Id;
    }

    @Reference
    abstract Model2 getModel2();

    @ReferenceId
    @Observable
    @Nonnull
    Object getModel2Id()
    {
      return _model2Id;
    }

    void setModel2Id( @Nonnull Object model2Id )
    {
      _model2Id = model2Id;
    }
  }

  @Repository
  @ArezComponent
  static abstract class Model2
  {
    @Action
    void doStuff()
    {
    }
  }
}

Add integration test that verifies the exception


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

package org.xwiki.extension.repository.xwiki.internal;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.xwiki.component.annotation.Component;
import org.xwiki.query.QueryException;

import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;

/**
 * @version $Id$
 * @since 3.1M2
 */
@Component("org.xwiki.extension.repository.xwiki.internal.ExtensionFileRESTResource")
@Path("/extension/{extensionId}/{extensionVersion}/file")
public class ExtensionFileRESTResource extends AbstractExtensionRESTResource
{
    @GET
    public Response downloadExtension(@PathParam("extensionId") String extensionId,
        @PathParam("extensionVersion") String extensionVersion) throws XWikiException, QueryException
    {
        Document extensionDocument = getExtensionDocument(extensionId);

        if (extensionDocument.isNew()) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }

        com.xpn.xwiki.api.Object extensionVersionObject =
            getExtensionVersionObject(extensionDocument, extensionVersion);

        com.xpn.xwiki.api.Attachment xwikiAttachment =
            extensionDocument.getAttachment(extensionId + "-" + extensionVersion + "."
                + extensionVersionObject.getProperty("type").getValue());
        if (xwikiAttachment == null) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }

        return Response.ok().type(xwikiAttachment.getMimeType()).entity(xwikiAttachment.getContent()).build();
    }
}

Add XWiki extensions repository Forgot to commit a file


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

import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.visitors.AbstractExprVisitor;
import parquet.filter2.predicate.FilterPredicate;

public class DrillParquetFilterGenerator extends
        AbstractExprVisitor<FilterPredicate, Void, RuntimeException> {
    private LogicalExpression le;

    public DrillParquetFilterGenerator(LogicalExpression conditionExp) {
        this.le = conditionExp;
    }

    public FilterPredicate parseTree() {
        return le.accept(this, null);
    }
}

Add a generator/builder for Parquet filters


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

package algorithm.boj;

import java.io.*;

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

public class Boj9498 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int score = Integer.parseInt(br.readLine());
        if(score >= 90){
            System.out.print("A");
        }else if(score >= 80){
            System.out.print("B");
        }else if(score >= 70){
            System.out.print("C");
        }else if(score >= 60){
            System.out.print("D");
        }else{
            System.out.print("F");
        }
    }

}

Solve No.9498 from Baekjoon Online Judge


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

package com.google.gerrit.server.account;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import com.google.gerrit.extensions.client.GeneralPreferencesInfo;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.git.ValidationError;
import org.eclipse.jgit.lib.Config;
import org.junit.Test;
import org.mockito.Mockito;

/** Tests for parsing user preferences from Git. */
public class PreferencesTest {

  enum Unknown {
    STATE
  }

  @Test
  public void ignoreUnknownAccountPreferencesWhenParsing() {
    ValidationError.Sink errorSink = Mockito.mock(ValidationError.Sink.class);
    Preferences preferences =
        new Preferences(Account.id(1), configWithUnknownEntries(), new Config(), errorSink);
    GeneralPreferencesInfo parsedPreferences = preferences.getGeneralPreferences();

    assertThat(parsedPreferences).isNotNull();
    assertThat(parsedPreferences.expandInlineDiffs).isTrue();
    verifyNoMoreInteractions(errorSink);
  }

  @Test
  public void ignoreUnknownDefaultAccountPreferencesWhenParsing() {
    ValidationError.Sink errorSink = Mockito.mock(ValidationError.Sink.class);
    Preferences preferences =
        new Preferences(Account.id(1), new Config(), configWithUnknownEntries(), errorSink);
    GeneralPreferencesInfo parsedPreferences = preferences.getGeneralPreferences();

    assertThat(parsedPreferences).isNotNull();
    assertThat(parsedPreferences.expandInlineDiffs).isTrue();
    verifyNoMoreInteractions(errorSink);
  }

  private static Config configWithUnknownEntries() {
    Config cfg = new Config();
    cfg.setBoolean("general", null, "expandInlineDiffs", true);
    cfg.setBoolean("general", null, "unknown", true);
    cfg.setEnum("general", null, "unknownenum", Unknown.STATE);
    cfg.setString("general", null, "unknownstring", "bla");
    return cfg;
  }
}

Add test to ensure that unkown user preferences are just ignored


package com.sb.elsinore.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PhSensorType {
    String model();
}

Add a new Annotation to identify Ph Models


package jeranvier.math.dsp;

public class Entropy {

	public static double computeApproximateEntropy(int m, double r, double[] t){
		return computePhi(m, r, t) - computePhi(m+1, r ,t);
	}

	private static double computePhi(int m, double r, double[] t){
		int N = t.length;

		//Step 3
		double[][] x = new double[N-m+1][m];
		for(int i = 0; i<=N-m; i++){
			for(int j=0; j<m; j++){
				x[i][j] = t[i+j];
			}
		}

		//Step 4
		double[] C = new double[N-m+1];
		for(int i=0; i<=N-m; i++){
			C[i] = computeCim(i, x, m, r, N);
		}

		//step5
		double phi =0.0;
		for(int i =0; i<= N-m; i++){
			phi += Math.log(C[i]);
		}
		phi = phi/(N-m+1);
		return phi;
	}

	private static double computeCim(int i, double[][] x, int m, double r, int N) {
		double count = 0;
		for(int j=0; j<x.length; j++){
			if(d(x[i], x[j])<=r){
				count++;
			}
		}
		return count/(N-m+1);
	}

	private static double d(double[] x, double[] y){
		double d = 0.0;
		for(int i = 0; i< x.length; i++){
			d = Math.max(d, Math.abs(x[i]-y[i]));
		}
		return d;
	}

	public static void main(String arg[]){
		double[] t = new double[]{85, 80, 89, 85, 80, 89, 85, 80, 89, 85,
								  80, 89, 85, 80, 89, 85, 80, 89, 85, 80,
								  89, 85, 80, 89, 85, 80, 89, 85, 80, 89,
								  85, 80, 89, 85, 80, 89, 85, 80, 89, 85,
								  80, 89, 85, 80, 89, 85, 80, 89, 85, 80,
								  89};
		System.out.println(computeApproximateEntropy(2, 3, t));
	}

}

ADD approximate entropy measurment for a signal


package seedu.taskmanager.logic.commands;

import java.io.IOException;
import java.util.Optional;

import seedu.taskmanager.commons.core.Config;
import seedu.taskmanager.commons.exceptions.DataConversionException;
import seedu.taskmanager.commons.util.ConfigUtil;
import seedu.taskmanager.commons.util.StringUtil;
import seedu.taskmanager.logic.commands.exceptions.CommandException;

/**
 * @@author A0114269E
 * Move the directory of taskmanager.xml file to user-specified path to allow cloud service sync.
 * Overwrite the given file path if a file with same name exists. Old XML file is not deleted.
 * Path matching is case sensitive.
 */
public class MoveCommand extends Command {
    public static final String COMMAND_WORD = "mv";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Move the directory of the taskmanager."
            + "xml file to allow user to sync with cloud services. Overwrite will occur for same file name.\n"
            + "Parameters: PATH...\n"
            + "Example: " + COMMAND_WORD + " /User/admin/Documents/taskmanager.xml";

    public static final String MESSAGE_SUCCESS = "TaskManager directory moved to : ";
    public static final String MESSAGE_ERROR_BUILDCONFIG = "Failed to build new config";
    public static final String MESSAGE_ERROR_SAVECONFIG = "Failed to save config file : '%1$s'";

    private final String newPath;

    public MoveCommand(String path) {
        this.newPath = path;
    }

    @Override
    public CommandResult execute() throws CommandException {
        Config newConfig;
        String configFilePathUsed;

        configFilePathUsed = Config.DEFAULT_CONFIG_FILE;

        try {
            Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
            newConfig = configOptional.orElse(new Config());
        } catch (DataConversionException e) {
            throw new CommandException(MESSAGE_ERROR_BUILDCONFIG);
        }

        newConfig.setTaskManagerFilePath(this.newPath);
        storage.updateTaskManagerStorageDirectory(this.newPath, newConfig);

        try {
            ConfigUtil.saveConfig(newConfig, configFilePathUsed);
        } catch (IOException e) {
            throw new CommandException(MESSAGE_ERROR_SAVECONFIG + StringUtil.getDetails(e));
        }

        return new CommandResult(MESSAGE_SUCCESS + this.newPath);
    }
}

Add new move command, a variant of change directory that overwrites given file path