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

import com.github.daytron.revworks.authentication.AccessControl;
import com.github.daytron.revworks.ui.AdminLoginPopup;
import com.vaadin.ui.Button;
import com.vaadin.ui.UI;

/**
 * Click listener for webmaster link click event. Opens a modal sub-window for
 * admin login form.
 *
 * @author Ryan Gilera
 */
public class WebmasterLinkButtonListener implements Button.ClickListener {

    private static final long serialVersionUID = 1L;

    private final AccessControl userAccessControl;

    public WebmasterLinkButtonListener(AccessControl uac) {
        this.userAccessControl = uac;
    }

    @Override
    public void buttonClick(Button.ClickEvent event) {
        AdminLoginPopup adminLoginPopup = new AdminLoginPopup(userAccessControl);

        adminLoginPopup.setSizeUndefined();

        adminLoginPopup.center();

        UI.getCurrent().addWindow(adminLoginPopup);
    }

}

Add button click behaviour for webmaster link


package nl.tehdreamteam.se42.data;

/**
 * Defines certain constants for the data layer.
 *
 * @author Lesley
 */
public final class DataConstants {

    /**
     * The persistency-unit name for Hiberbante.
     */
    public static final String HIBERNATE_PERSISTENCY_UNIT_NAME = "manager";

    private DataConstants() {
        throw new UnsupportedOperationException("Should not be instantiated.");
    }

}

Define constants for the data layer.


package ahlers.phantom.embedded;

import de.flapdoodle.embed.process.config.ExecutableProcessConfig;
import de.flapdoodle.embed.process.config.ISupportConfig;
import de.flapdoodle.embed.process.distribution.IVersion;

/**
 * Command line options for PhantomJS.
 *
 * @author [[mailto:michael@ahlers.consulting Michael Ahlers]]
 * @see Command Line Interface
 */
public class PhantomProcessConfig
        extends ExecutableProcessConfig {

    private final Boolean debug;

    protected PhantomProcessConfig(
            final IVersion version,
            final Boolean debug
    ) {
        super(version, new ISupportConfig() {
            @Override
            public String getName() {
                return "phantomjs";
            }

            @Override
            public String getSupportUrl() {
                return "https://github.com/michaelahlers/embedded-phantom/issues";
            }

            @Override
            public String messageOnException(final Class<?> context, final Exception exception) {
                return "";
            }
        });

        this.debug = debug;
    }

    public static class Builder {

        private final IVersion version;

        private Boolean debug;

        public Builder(final IVersion version) {
            this.version = version;
        }

        public void withDebug(final Boolean debug) {
            this.debug = debug;
        }

        public PhantomProcessConfig build() {
            return new PhantomProcessConfig(version, debug);
        }

    }

}

Add initial CLI config. class


package org.concord.otrunk.test;

import java.util.Random;

import junit.framework.TestCase;

import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTrunk;
import org.concord.otrunk.view.OTFolderObject;
import org.concord.otrunk.view.OTViewerHelper;
import org.concord.otrunk.xml.XMLDatabase;

public class OTObjectInternalTest extends TestCase
{
	OTFolderObject folder;
	OTFolderObject item;
	OTChangeListener listener;
	Thread changeObjectThread;
	Thread changeListenersThread;
	boolean noExceptionThrown;

	// run test for 500 ms
    final long endTime = System.currentTimeMillis() + 1000;

    /**
     * If OTObjectInternal believes it has listeners when an otObject is
     * being changed, and another removes the last listener during the
     * change event, OTObjectInternal should handle it gracefully.
     */
	public void testListenersNotNull(){
		OTViewerHelper viewerHelper = new OTViewerHelper();

		// create  an empty database
		XMLDatabase db = new XMLDatabase();

		noExceptionThrown = true;

		try {
	        viewerHelper.loadOTrunk2(null, db);

	        OTrunk otrunk = viewerHelper.getOtrunk();
	        folder = otrunk.createObject(OTFolderObject.class);
	        item = otrunk.createObject(OTFolderObject.class);

	        otrunk.setRoot(folder);

	        changeObjectThread = new Thread(){
	        	public void run(){
	        		while(System.currentTimeMillis() < endTime){
	        			try {
		        			if (folder.getChildCount() == 0){
		        				folder.addChild(item);
		        			} else {
		        				folder.removeAllChildren();
		        			}
	        			} catch (java.lang.NullPointerException e){
	        				noExceptionThrown = false;
	        			}
	        		}
	        	}
	        };

	        changeListenersThread = new Thread(){
	        	public void run(){
	        		listener = new OTChangeListener() {

	    				public void stateChanged(OTChangeEvent e){}
	    			};

	        		boolean added = false;

	        		while(System.currentTimeMillis() < endTime){
	        			if (!added){
	        				folder.addOTChangeListener(listener);
	        				added = true;
	        			} else {
	        				folder.removeOTChangeListener(listener);
	        				added = false;
	        			}
	        		}
	        	}
	        };

	        changeObjectThread.start();
	        changeListenersThread.start();

	        // FIXME we should automatically check if the id is actually saved in the string.

        } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
        }

//        System.out.println(noExceptionThrown);
//        assertTrue(noExceptionThrown);
        while (System.currentTimeMillis() < (endTime)){
        	assertTrue(noExceptionThrown);
        }
	}

}

Add JUnit test which checks that OTObjectInternal gracefully handles the case where another thread removes a listener during a change event.


/**
 *
 */
package eu.aleon.aleoncean.device.remote;

import eu.aleon.aleoncean.packet.radio.userdata.UserDataScaleValueException;
import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;
import eu.aleon.aleoncean.packet.radio.userdata.UserDataEEPA50205;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author Thomas Stezaly (thomas.stezaly@aleuon.eu)
 *
 */
public class RemoteDeviceEEPA50205Test {

    /**
     * @throws java.lang.Exception
     */
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    /**
     * @throws java.lang.Exception
     */
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {

    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetGetTemperature() {

        final double temperatureSet = 20.0;
        final UserDataEEPA50205 userData = new UserDataEEPA50205();

        try {
            userData.setTemperature(temperatureSet);
            userData.setTeachIn(false);
        } catch (UserDataScaleValueException e) {
            fail("Throws exception: UserDataScaleValueException");
        }

        final RadioPacket4BS packet = userData.generateRadioPacket();
        final RemoteDeviceEEPA50205 testDevice = new RemoteDeviceEEPA50205(null, packet.getSenderId(), packet.getDestinationId());

        testDevice.parseRadioPacket(packet);

        double temperatureGet = testDevice.getTemperature();
        double delta = temperatureGet - temperatureSet;

        System.out.println("temperatureSet: "+temperatureSet);
        System.out.println("temperatureGet: "+temperatureGet);

        // We use a delta of 0.2, because one range point fits to 0.15 degree.
        // So is this value acceptable
        assertTrue(delta < 0.2);
    }
}

Add unit test for RD A5-02-05


/*
 Copyright 2006 Paul Zepernick

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for
 the specific language governing permissions and limitations under the License.
 */
package net.sf.pzfilereader.parserutils;

import net.sf.pzfilereader.util.ParserUtils;
import junit.framework.TestCase;

/**
 * Tests the functionality of the left trim in the ParserUtils
 *
 * @author paul zepernick
 */
public class LTrimTest extends TestCase{

    /**
     * Make sure all spaces are properly removed from the front of the String
     *
     */
    public void testTrimLeadingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe";
        assertEquals(true , ParserUtils.lTrim(testS).indexOf(" ") == -1);
    }

    /**
     * Make sure all spaces are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingSpacesWithTrailingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith(" ") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingTabs(){
        final String testS = "\t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testKeepLeadingTabs(){
        final String testS = "     \t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrimKeepTabs(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    public static void main(final String[] args) {
        junit.textui.TestRunner.run(LTrimTest.class);
    }
}

Test cases for lTrim and lTrimKeepTabs


// 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 com.cloud.region;

import java.util.Date;

/**
 *
 */
public interface RegionSync  {

    public long getId();

    public int getRegionId();

	public String getApi();

	Date getCreateDate();
}

Add sync entry to region_sunc table on region api failure


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

package org.jeecqrs.bundle.jcommondomain.sagas;

import java.util.Map;
import org.jeecqrs.common.event.Event;
import org.jeecqrs.sagas.Saga;
import org.jeecqrs.sagas.SagaIdentificationStrategy;

/**
 * A simple saga identification strategy that simply maps a saga to
 * the id of an incomiong event.
 * This obviously means that the corresponding saga may only handle exactly
 * on event.
 */
public class EventIdSagaIdentificationStrategy<S extends Saga<Event>>
    implements SagaIdentificationStrategy<S, Event> {

    @Override
    public String identifySaga(Event event) {
        return event.id().toString();
    }

}

Add a simple saga ident strat by event id


package io.github.ddebree.game.ai.core.strategy;

import javax.annotation.Nonnull;
import java.util.stream.Stream;

/**
 * A basic representation of a player's strategy.
 *
 * At a given state, for a particular player, what is the best possible set of moves
 *
 * @param <S> The class that represents a game state
 * @param <P> The class that represents a player
 * @param <M> The class used to represent a player's move
 *
 * @author Dean de Bree
 */
public interface IStrategy<S, P, M> {

    /**
     * Get the best moves that a player could make at the current game state
     *
     * @param state The current game state
     * @param player The player to determine the best current state for
     * @return A stream of moves that would result in the best outcome for the provided player
     */
    @Nonnull
    Stream<M> getBestMoves(@Nonnull S state, P player);

}

Add the basic strategy interface


/*
 * Copyright (C) 2011 Google 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.google.android.apps.mytracks.services.sensors.ant;

/**
 * A enum which stores static data about ANT sensors.
 *
 * @author Matthew Simmons
 */
public enum AntSensor {
  SENSOR_HEART_RATE (Constants.ANT_DEVICE_TYPE_HRM),
  SENSOR_CADENCE (Constants.ANT_DEVICE_TYPE_CADENCE),
  SENSOR_SPEED (Constants.ANT_DEVICE_TYPE_SPEED),
  SENSOR_POWER (Constants.ANT_DEVICE_TYPE_POWER);

  private static class Constants {
    public static byte ANT_DEVICE_TYPE_POWER = 11;
    public static byte ANT_DEVICE_TYPE_HRM = 120;
    public static byte ANT_DEVICE_TYPE_CADENCE = 122;
    public static byte ANT_DEVICE_TYPE_SPEED = 123;
  };

  private final byte deviceType;

  private AntSensor(byte deviceType) {
    this.deviceType = deviceType;
  }

  public byte getDeviceType() {
    return deviceType;
  }
}

Add an enum which stores static data about ANT sensors.


package flyway.oskari;

import java.sql.Connection;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;

public class V1_54_2__register_3d_camera_controls_bundle implements JdbcMigration {

	private static final String BUNDLE_ID = "camera-controls-3d";

	@Override
	public void migrate(Connection connection) throws Exception {

		// BundleHelper checks if these bundles are already registered
        Bundle bundle = new Bundle();
        bundle.setName(BUNDLE_ID);
        BundleHelper.registerBundle(bundle, connection);
	}
}

Add migration to register camera-controls-3d bundle


package leetcode.binary_tree_level_order_traversal_ii;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import common.TreeNode;

public class Solution {
	public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
		Queue<MyNode> queue = new LinkedList<MyNode>();
		ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
		if(root == null) return ans;
		queue.offer(new MyNode(root, 0));
		while(!queue.isEmpty()){
			MyNode myNode = queue.remove();
			TreeNode tn = myNode.node;
			ArrayList<Integer> lvl = null;
			if(ans.size() <= myNode.level){
				lvl = new ArrayList<Integer>();
				ans.add(lvl);
			}else{
				lvl = ans.get(myNode.level);
			}
			lvl.add(tn.val);
			if(tn.left != null) queue.offer(new MyNode(tn.left, myNode.level + 1));
			if(tn.right != null) queue.offer(new MyNode(tn.right, myNode.level + 1));
		}
		int size = ans.size();
		for(int i = 0; i < size / 2; i++){
			ArrayList<Integer> tmp = ans.get(i);
			ans.set(i, ans.get(size - 1 - i));
			ans.set(size - 1 - i, tmp);
		}
		return ans;
	}
	public static class MyNode{
		TreeNode node;
		int level;
		public MyNode(TreeNode node, int level){
			this.node = node;
			this.level = level;
		}
	}

	public static void main(String[] args){
		final int N = 15;
		final int R = 5;
		ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
		for(int i = 0; i < N; i++){
			nodes.add(new TreeNode(i));
		}
		Random r = new Random();
		for(int i = 0; i < N; i++){
			if(i * 2 + 1 < N){
				nodes.get(i).left = nodes.get(i * 2 + 1);
			}
			if(i * 2 + 2 < N){
				nodes.get(i).right = nodes.get(i * 2 + 2);
			}
		}
		for(int i = 0; i < R; i++){
			int ran = r.nextInt(N);
			System.err.println("ran:" + ran);
			nodes.get(ran).left = null;
		}

		for(ArrayList<Integer> row : new Solution().levelOrderBottom(nodes.get(0))){
			for(int x : row){
				System.err.print(x + ", ");
			}
			System.err.println("");
		}
	}
}

Add java solution for 107. Binary Tree Level Order Traversal II


package io.github.satoshinm.WebSandboxMC.sponge;

import com.google.inject.Inject;
import org.slf4j.Logger;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Plugin;

@Plugin(id = "websandboxmc", name = "WebSandboxMC", version = "1.6.0")
public class WebSandboxSpongePlugin {

    @Inject
    private Logger logger;

    @Listener
    public void onServerStart(GameStartedServerEvent event) {
        logger.info("WebSandboxMC/Sponge starting");
    }
}

Add a skeletal Sponge plugin class


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

/**
 *
 * @author Ryan Gilera
 */
public class ConversionClient {

}

Add a base conversion client class


package com.fasterxml.jackson.failing;

import com.fasterxml.jackson.core.BaseTest;
import com.fasterxml.jackson.core.JsonPointer;

// For https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=51806
// (via databind, but we don't need that)
public class Fuzz51806JsonPointerParseTest extends BaseTest
{
    // Before fix, looks like this is enough to cause StackOverflowError
    private final static int TOO_DEEP_PATH = 6000;

    // Verify that very deep/long (by number of segments) JsonPointer
    // may still be parsed ok
    public void testJsonPointerParseTail() throws Exception
    {
        JsonPointer p = JsonPointer.compile(_generatePath(TOO_DEEP_PATH));
        assertNotNull(p);
    }

    private String _generatePath(int depth) {
        StringBuilder sb = new StringBuilder(4 * depth);
        for (int i = 0; i < depth; ++i) {
            sb.append("/a").append(depth);
        }
        return sb.toString();
    }
}

Add a failing test for JsonParser.compile() and Very Deeply Nested expressions


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

package de.vorb.platon.web.rest;

import de.vorb.platon.persistence.CommentRepository;

import com.google.common.collect.Sets;
import com.google.common.truth.Truth;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RunWith(MockitoJUnitRunner.class)
public class CommentCountResourceTest {

    @Mock
    private CommentRepository commentRepository;

    @InjectMocks
    private CommentCountResource commentCountResource;

    private final Set<String> sampleThreadUrls = Sets.newHashSet("/article-a.html", "/2016/11/article-b.html");

    @Before
    public void setUp() throws Exception {

        Mockito.when(commentRepository.countByThreadUrls(Mockito.eq(sampleThreadUrls)))
                .thenReturn(sampleThreadUrls.stream()
                        .collect(Collectors.toMap(Function.identity(), String::length)));
    }

    @Test
    public void getCommentCounts() throws Exception {
        commentCountResource.getCommentCounts(sampleThreadUrls)
                .getCommentCounts()
                .forEach((threadUrl, count) -> {
                    Truth.assertThat(count).isEqualTo(threadUrl.length());
                });
    }
}

Implement unit test for CommentCountResource


package jp.naist.inet_lab.android.ipv6multicast;

/**
 * Throw if something issue related to networking is occurred.
 *
 * @author yohei-ka
 *
 */
public class MulticastException extends Exception {

    /**
     * Auto-generated serial version UID
     */
    private static final long serialVersionUID = -8561020680607603227L;

    public MulticastException(Throwable cause) {
        super(cause);
    }

}

Implement MutlicastException, which handle the exception related to networking


package com.blankstyle.vertx.php.http;

import org.vertx.java.core.buffer.Buffer;

import com.blankstyle.vertx.php.Handler;
import com.blankstyle.vertx.php.streams.ExceptionSupport;
import com.blankstyle.vertx.php.streams.ReadStream;
import com.caucho.quercus.env.Callback;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.Value;

/**
 * A PHP compatible implementation of the Vert.x HttpClientResponse.
 *
 * @author Jordan Halterman
 */
public class HttpClientResponse implements ReadStream, ExceptionSupport {

  private org.vertx.java.core.http.HttpClientResponse response;

  public HttpClientResponse(org.vertx.java.core.http.HttpClientResponse response) {
    this.response = response;
  }

  public HttpClientResponse(Env env, org.vertx.java.core.http.HttpClientResponse response) {
    this.response = response;
  }

  @Override
  public Value pause(Env env) {
    response.pause();
    return env.wrapJava(this);
  }

  @Override
  public Value resume(Env env) {
    response.resume();
    return env.wrapJava(this);
  }

  public Value cookies(Env env) {
    return env.wrapJava(response.cookies());
  }

  public Value headers(Env env) {
    return env.wrapJava(response.headers());
  }

  public Value trailers(Env env) {
    return env.wrapJava(response.trailers());
  }

  public Value netSocket(Env env) {
    return env.wrapJava(response.netSocket());
  }

  public Value statusCode(Env env) {
    return env.wrapJava(response.statusCode());
  }

  public Value statusMessage(Env env) {
    return env.wrapJava(response.statusMessage());
  }

  @Override
  public Value dataHandler(Env env, Callback handler) {
    response.dataHandler(new Handler<Buffer>(env, handler));
    return env.wrapJava(this);
  }

  public Value bodyHandler(Env env, Callback handler) {
    response.bodyHandler(new Handler<Buffer>(env, handler));
    return env.wrapJava(this);
  }

  @Override
  public Value endHandler(Env env, Callback handler) {
    response.endHandler(new Handler<Void>(env, handler));
    return env.wrapJava(this);
  }

  @Override
  public Value exceptionHandler(Env env, Callback handler) {
    response.exceptionHandler(new Handler<Throwable>(env, handler));
    return env.wrapJava(this);
  }

}

Add HTTP client response handler.


package io.quarkus.runtime;

import java.util.Optional;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 * This configuration class is here to avoid warnings when using {@code -Dquarkus.args=...}.
 */
@ConfigRoot(name = ConfigItem.PARENT, phase = ConfigPhase.RUN_TIME)
public class CommandLineRuntimeConfig {

    /**
     * The arguments passed to the command line.
     * <p>
     * We don't make it a list as the args are separated by a space, not a comma.
     */
    @ConfigItem
    public Optional<String> args;

}

Add a config class to avoid a warning for -Dquarkus.args=...


package uk.ac.ebi.phenotype.dao;

import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import uk.ac.ebi.phenotype.bean.StatisticalResultBean;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-config.xml" })
@TransactionConfiguration
@Transactional
public class StatisticalResultDAOTest {

	@Autowired
	StatisticalResultDAO statisticalResultDAO;

	@Test
	public void testGetPvaluesByAlleleAndPhenotypingCenterAndPipeline() {

		// MGI:4432021?phenotyping_center=HMGU&pipeline_stable_id=ESLIM_001
		String alleleAccession = "MGI:4432021";
		String phenotypingCenter = "HMGU";
		String pipelineStableId = "ESLIM_001";

		Map<String, List<StatisticalResultBean>> results = statisticalResultDAO.getPvaluesByAlleleAndPhenotypingCenterAndPipeline(
				alleleAccession, phenotypingCenter, pipelineStableId);

		for (String key: results.keySet()) {
			System.out.println(key);
			for (StatisticalResultBean bean: results.get(key)) {
				System.out.println(bean.getStatisticalMethod() + "\t" + bean.getpValue() + "\t" + bean.getEffectSize());
			}
		}
	}

}

Test to get all p-values from a line


package eu.nimble.service.dashboard.services;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.apache.marmotta.platform.core.api.config.ConfigurationService;
import org.apache.marmotta.platform.core.events.SystemStartupEvent;

@ApplicationScoped
public class StartupConfigurator {
	@Inject
	ConfigurationService config;

	public StartupConfigurator() {
		// TODO Auto-generated constructor stub
	}
	public void onSystemStartup(@Observes SystemStartupEvent event) {

		String[] databaseVal = new String [] {"database.type","database.url","database.user","database.password" };
		String[] hostVal = new String [] {"kiwi.path","kiwi.context","kiwi.host" };

		if ( processEnvironmentVariables(databaseVal)) {
			config.setBooleanConfiguration("kiwi.setup.database", Boolean.TRUE);
		}
		if ( processEnvironmentVariables(hostVal)) {
			config.setBooleanConfiguration("kiwi.setup.host", Boolean.TRUE);
		}
		/*
			security.enabled
			database.type
			database.url
			database.user
			database.password
			kiwi.setup.database
			kiwi.path
			kiwi.context
			kiwi.host
			kiwi.setup.host
		*/
	}

	private boolean processEnvironmentVariables(String[] variables) {
		boolean variablesPresent = true;
		String[] values = new String[variables.length];

		for ( int i = 0; i < variables.length; i++ ) {
			// try to get from environment
			values[i] = System.getenv(variables[i]);

			if ( values[i]  == null ) {
				values[i] = System.getProperty(variables[i]);
			}

			if ( values[i] == null ) {
				variablesPresent = false;
			}
		}
		if (variablesPresent) {
			for ( int i = 0; i < variables.length; i++) {
				config.setConfiguration(variables[i], values[i]);
			}
			return true;
		}
		return false;
	}

}

Configure Environment Variables for database and host


package net.minecraftforge.test;

import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.BlockEvent.CreateFluidSourceEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.Event.Result;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod(modid = "CreateFluidSourceTest", version = "1.0")
public class CreateFluidSourceTest
{
    public static final boolean ENABLE = false;

    @Mod.EventHandler
    public static void init(FMLInitializationEvent event)
    {
        if (ENABLE)
            MinecraftForge.EVENT_BUS.register(CreateFluidSourceTest.class);
    }

    @SubscribeEvent
    public static void onCreateFluidSource(CreateFluidSourceEvent event)
    {
        // make it work exactly the opposite of how it works by default
        if (event.getState().getBlock() == Blocks.FLOWING_WATER)
            event.setResult(Result.DENY);
        else
            event.setResult(Result.ALLOW);
    }
}

Add a test for CreateFluidSourceEvent


public class Upi {

	public static String getUpi( long id ) {
		String str = Long.toHexString( id ).toUpperCase();
		return "URS0000000000".substring(0, 13 - str.length() ) + str;
	}

	public static void main (String args[]) {
		long l = Long.parseLong(args[0]);
		System.out.println(getUpi(l));
	}
}

Add the java file that calculates the UPI that is executed in the Oracle database


package org.ocpsoft.prettytime.i18n;

import java.util.Date;
import java.util.Locale;

import org.junit.Assert;
import org.junit.Test;
import org.ocpsoft.prettytime.PrettyTime;

public class Resources_hrTest {

	   private static final int MINUTES = 1000 * 60;

	@Test
	   public void testFormatMinute() throws Exception
	   {
	      PrettyTime prettyTime = new PrettyTime(new Locale("hr"));

	      Assert.assertEquals("za 1 minutu", prettyTime.format(new Date(System.currentTimeMillis() + 1*MINUTES)));
	      Assert.assertEquals("za 2 minute", prettyTime.format(new Date(System.currentTimeMillis() + 2*MINUTES)));
	      Assert.assertEquals("za 3 minute", prettyTime.format(new Date(System.currentTimeMillis() + 3*MINUTES)));
	      Assert.assertEquals("za 4 minute", prettyTime.format(new Date(System.currentTimeMillis() + 4*MINUTES)));
	      Assert.assertEquals("za 5 minuta", prettyTime.format(new Date(System.currentTimeMillis() + 5*MINUTES)));
	      Assert.assertEquals("za 6 minuta", prettyTime.format(new Date(System.currentTimeMillis() + 6*MINUTES)));

	      Assert.assertEquals("prije 1 minutu", prettyTime.format(new Date(System.currentTimeMillis() - 1*MINUTES)));
	      Assert.assertEquals("prije 2 minute", prettyTime.format(new Date(System.currentTimeMillis() - 2*MINUTES)));
	      Assert.assertEquals("prije 3 minute", prettyTime.format(new Date(System.currentTimeMillis() - 3*MINUTES)));
	      Assert.assertEquals("prije 4 minute", prettyTime.format(new Date(System.currentTimeMillis() - 4*MINUTES)));
	      Assert.assertEquals("prije 5 minuta", prettyTime.format(new Date(System.currentTimeMillis() - 5*MINUTES)));
	      Assert.assertEquals("prije 6 minuta", prettyTime.format(new Date(System.currentTimeMillis() - 6*MINUTES)));
	   }

}

Fix - updated Croatian translation


package eu.mosaic_cloud.tools.callbacks.core;

import java.lang.reflect.Method;

public interface CallbackFunnelHandler
		extends
			CallbackHandler
{
	public CallbackCompletion<?> executeCallback (final Callbacks Proxy, final Method method, final Object[] arguments);
}

Add callback funnel handler (like `InvocationHandler` from `java.lang.reflect`)


package edu.berkeley.eecs.cfc_tracker.log;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.StreamHandler;

/**
 * Created by shankari on 7/16/15.
 */
public class DatabaseLogHandler extends SQLiteOpenHelper {
    private String TABLE_LOG = "logTable";
    private String KEY_LINE = "log_line";
    private String KEY_ID = "ID";
    private static final int DATABASE_VERSION = 1;

    private Context cachedContext;

    public DatabaseLogHandler(Context context) {
        super(context, "logDB", null, DATABASE_VERSION);
        cachedContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String CREATE_LOG_TABLE = "CREATE TABLE " + TABLE_LOG +" (" +
                KEY_ID + " INTEGER PRIMARY_KEY, "+ KEY_LINE +" TEXT)";
        System.out.println("CREATE_CLIENT_STATS_TABLE = " + CREATE_LOG_TABLE);
        sqLiteDatabase.execSQL(CREATE_LOG_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_LOG);
        onCreate(sqLiteDatabase);
    }

    public void log(String line) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_LINE, line);
        db.insert(TABLE_LOG, null, cv);
        db.close();
    }

    public void export() {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String ourFileName = Log.getLogBase(cachedContext) + "/dumped_log_file.txt";
            System.out.println("ourFileName = "+ourFileName);
            PrintStream out = new PrintStream(new FileOutputStream(ourFileName, true));
            String queryString = "SELECT * from " + TABLE_LOG;
            Cursor cur = db.rawQuery(queryString, null);
            int resultCount = cur.getCount();
            if (cur.moveToFirst()) {
                for (int i = 0; i < resultCount; i++) {
                    out.println(cur.getString(0));
                }
            }
        } catch (IOException e) {
            Toast.makeText(cachedContext, e.getMessage(), Toast.LENGTH_LONG).show();
            System.err.println();
        }
        db.close();
    }
}

Add a new database oriented logger


package org.realityforge.arez;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

final class TestSpyEventHandler
  implements SpyEventHandler
{
  private final ArrayList<Object> _events = new ArrayList<>();

  @Override
  public void onSpyEvent( @Nonnull final Object event )
  {
    _events.add( event );
  }

  <T> T assertEvent( @Nonnull final Class<T> type, final int index )
  {
    assertTrue( eventCount() > index );
    final Object event = _events.get( index );
    assertTrue( type.isInstance( event ),
                "Expected event at index " + index + " to be of type " + type + " but is " +
                event + " which is of type " + event.getClass() );
    return type.cast( event );
  }

  void assertEventCount( final int count )
  {
    assertEquals( eventCount(), count );
  }

  int eventCount()
  {
    return _events.size();
  }
}

Add SpyEventHandler useful during tests


package lt.dariusl.rxfirebaseandroid;

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

public class TestTest {
    @Test
    public void testTest() throws Exception {
        Assert.assertTrue(true);
    }
}

Add random test to try out drone


package com.rackspacecloud.blueflood.eventemitter;

import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.types.Points;
import com.rackspacecloud.blueflood.types.Rollup;
import com.rackspacecloud.blueflood.types.SimpleNumber;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class RollupEventTest {

    Locator locator;
    Rollup rollup;
    String unit;
    String granularity;
    long timestamp;

    RollupEvent event;

    @Before
    public void setUp() throws IOException {

        locator = Locator.createLocatorFromPathComponents("tenant", "a", "b");
        Points<SimpleNumber> points = new Points<SimpleNumber>();
        rollup = Rollup.BasicFromRaw.compute(points);
        unit = "Some init";
        granularity = "Some granularity";
        timestamp = 1451631661000L;     // 2016-01-01 01:01:01 CST

        event = new RollupEvent(locator, rollup, unit, granularity, timestamp);
    }

    @Test
    public void locatorGetsSetInConstructor() {
        Assert.assertSame(locator, event.getLocator());
    }

    @Test
    public void rollupGetsSetInConstructor() {
        Assert.assertSame(rollup, event.getRollup());
    }

    @Test
    public void unitGetsSetInConstructor() {
        Assert.assertEquals(unit, event.getUnit());
    }

    @Test
    public void granularityGetsSetInConstructor() {
        Assert.assertEquals(granularity, event.getGranularityName());
    }

    @Test
    public void timestampGetsSetInConstructor() {
        Assert.assertEquals(timestamp, event.getTimestamp());
    }

    @Test
    public void setUnitChangesUnit() {
        //given
        String unit2= "Some other unit";
        // when
        event.setUnit(unit2);
        // then
        assertEquals(unit2, event.getUnit());
    }
}

Add a test class for RollupEvent.


package org.thinkinghub.gateway.oauth.exception;

public class OAuthProcessingException extends GatewayException {

	private static final long serialVersionUID = -253028809896546433L;

	public OAuthProcessingException(String errCode, String errMsg) {
		super(errMsg);
	}

	protected String getErrorCode() {
		return "GW100";
	}

}

Add exception class for oauth processing


/*
 * Copyright 2013 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html
 */
package io.liveoak.git;

import io.liveoak.spi.Config;
import io.liveoak.spi.resource.RootResource;
import io.liveoak.testtools.AbstractHTTPResourceTestCase;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Test;

import java.io.File;

import static org.fest.assertions.Assertions.assertThat;

/**
 * @author Ken Finnigan
 */
public class HTTPGitResourceTest extends AbstractHTTPResourceTestCase {
    @Override
    public RootResource createRootResource() {
        return new GitRepoResource( "git" );
    }

    @Override
    public Config createConfig() {
        File repoDir = new File(this.projectRoot, "/target/repo_http");
        if (!repoDir.exists()) {
            repoDir.mkdirs();
        }

        Config config = super.createConfig();
        config.put("repoPath", repoDir.getAbsolutePath());
        return config;
    }

    @Test
    public void enumerateRoot() throws Exception {
        HttpGet get = new HttpGet( "http://localhost:8080/git" );
        get.addHeader( "Accept", "application/json" );

        try {
            System.out.println( "DO GET" );
            CloseableHttpResponse result = httpClient.execute( get );
            System.out.println( "=============>>>" );
            System.out.println( result );

            HttpEntity entity = result.getEntity();
            if ( entity.getContentLength() > 0 ) {
                entity.writeTo( System.out );
            }
            System.out.println( "\n<<<=============" );
            assertThat( result.getStatusLine().getStatusCode() ).isEqualTo( 200 );
        } finally {
            httpClient.close();
        }
    }
}

Add HTTP test for git resource


package org.robolectric.res;

import org.junit.Before;
import org.junit.Test;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import java.io.StringReader;

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

public class StaxValueLoaderTest {

  private PackageResourceTable resourceTable;
  private NodeHandler topLevelNodeHandler;
  private StaxDocumentLoader staxDocumentLoader;

  @Before
  public void setUp() throws Exception {
    resourceTable = new PackageResourceTable("pkg");

    topLevelNodeHandler = new NodeHandler();
    staxDocumentLoader = new StaxDocumentLoader("pkg", null, topLevelNodeHandler);
  }

  @Test
  public void ignoresXliffTags() throws Exception {
    topLevelNodeHandler.addHandler("resources", new NodeHandler()
        .addHandler("string", new StaxValueLoader(resourceTable, "string", ResType.CHAR_SEQUENCE))
    );

    parse("<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">" +
        "<string name=\"preposition_for_date\">on <xliff:g id=\"date\" example=\"May 29\">%s</xliff:g></string>" +
        "</resources>");

    assertThat(resourceTable.getValue(new ResName("pkg:string/preposition_for_date"), "").getData())
        .isEqualTo("on %s");
  }

  @Test
  public void ignoresBTags() throws Exception {
    topLevelNodeHandler.addHandler("resources", new NodeHandler()
        .addHandler("item[@type='string']", new StaxValueLoader(resourceTable, "string", ResType.CHAR_SEQUENCE))
    );

    parse("<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">" +
        "<item type=\"string\" name=\"sms_short_code_details\">This <b>may cause charges</b> on your mobile account.</item>" +
        "</resources>");

    assertThat(resourceTable.getValue(new ResName("pkg:string/sms_short_code_details"), "").getData())
        .isEqualTo("This may cause charges on your mobile account.");
  }

  private void parse(String xml) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(new StringReader(xml));
    staxDocumentLoader.doParse(xmlStreamReader, new XmlContext("pkg", Fs.fileFromPath("/tmp/fake.txt")));
  }
}

Add test for StaxValueLoader of strings.


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

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipalLookupService;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestUserPrincipalLookupService {

	private static MiniDFSCluster cluster;
    private static URI clusterUri;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        cluster = startMini(TestFileSystem.class.getName());
        clusterUri = cluster.getFileSystem().getUri();
    }

    @AfterClass
    public static void teardownClass() throws Exception {
        if (cluster != null)
        {
            cluster.shutdown();
        }
    }

    private static MiniDFSCluster startMini(String testName) throws IOException {
        File baseDir = new File("./target/hdfs/" + testName).getAbsoluteFile();
        FileUtil.fullyDelete(baseDir);
        Configuration conf = new Configuration();
        conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
        MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
        MiniDFSCluster hdfsCluster = builder.clusterId(testName).build();
        hdfsCluster.waitActive();
        return hdfsCluster;
    }

    /**
     * Test UserPrincipalLookupService support.
     *
     * @throws IOException
     */
    @Test
    public void testGetPosixViewSetOwner() throws IOException {
        Path rootPath = Paths.get(clusterUri);

        UserPrincipalLookupService lus = rootPath.getFileSystem().getUserPrincipalLookupService();
        assertNotNull(lus);
    }
}

Add unit test for UserPrincipalLookupService


package org.jenkinsci.plugins.relution_publisher.unittest.mocks;

import org.jenkinsci.plugins.relution_publisher.logging.Log;

import java.io.PrintWriter;
import java.io.StringWriter;

public class MockLog implements Log {

    private static final long serialVersionUID = 1L;

    private static String valueOf(final Throwable t) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);

        t.printStackTrace(pw);

        return sw.toString();
    }

    @Override
    public void write() {
        // Do nothing
    }

    @Override
    public void write(final Class<?> source, final String format, final Object... args) {
        System.out.format(format, args);
        System.out.println();
    }

    @Override
    public void write(final Object source, final String format, final Object... args) {
        System.out.format(format, args);
        System.out.println();
    }

    @Override
    public void write(final Object source, final String format, final Throwable t) {
        System.out.format(format, valueOf(t));
        System.out.println();
    }
}

Add mock log implementation for unit tests


package arez.integration;

import arez.ArezContext;
import arez.annotations.ArezComponent;
import arez.annotations.ContextRef;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ContextRefReferencedInCtorTest
  extends AbstractIntegrationTest
{
  @ArezComponent( allowEmpty = true )
  static abstract class TestComponent
  {
    TestComponent()
    {
      getContext();
    }

    @ContextRef
    abstract ArezContext getContext();
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, ContextRefReferencedInCtorTest_Arez_TestComponent::new );
    assertEquals( exception.getMessage(), "Method invoked on uninitialized component of type 'TestComponent'" );
  }
}

Add integration test to verify that invariant is correctly generated


package arez.integration.observe;

import arez.Arez;
import arez.ArezContext;
import arez.Environment;
import arez.Function;
import arez.SafeFunction;
import arez.annotations.ArezComponent;
import arez.annotations.Executor;
import arez.annotations.Observe;
import arez.annotations.OnDepsChanged;
import arez.integration.AbstractArezIntegrationTest;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TrackInEnvironmentTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    private final ArrayList<String> _steps;

    TestComponent1( final ArrayList<String> steps )
    {
      _steps = steps;
    }

    @Observe( executor = Executor.APPLICATION, requireEnvironment = true )
    public void render()
    {
      _steps.add( "render1" );
      observeADependency();
    }

    @OnDepsChanged
    final void onRenderDepsChanged()
    {
    }

    @Observe( executor = Executor.APPLICATION, requireEnvironment = false )
    public void render2()
    {
      _steps.add( "render2" );
      observeADependency();
    }

    @OnDepsChanged
    final void onRender2DepsChanged()
    {
    }
  }

  @Test
  public void scenario()
  {
    final ArezContext context = Arez.context();

    // Scheduler paused otherwise reactions will run in environment and upset our environment call count
    context.pauseScheduler();

    final ArrayList<String> steps = new ArrayList<>();
    context.setEnvironment( new Environment()
    {
      @Override
      public <T> T run( @Nonnull final SafeFunction<T> function )
      {
        try
        {
          steps.add( "EnvironmentStart" );
          return function.call();
        }
        finally
        {
          steps.add( "EnvironmentEnd" );
        }
      }

      @Override
      public <T> T run( @Nonnull final Function<T> function )
        throws Throwable
      {
        try
        {
          steps.add( "EnvironmentStart" );
          return function.call();
        }
        finally
        {
          steps.add( "EnvironmentEnd" );
        }
      }
    } );

    final TestComponent1 component = new TrackInEnvironmentTest_Arez_TestComponent1( steps );

    component.render();

    assertEquals( steps, Arrays.asList( "EnvironmentStart", "render1", "EnvironmentEnd" ) );

    component.render2();

    assertEquals( steps, Arrays.asList( "EnvironmentStart", "render1", "EnvironmentEnd", "render2" ) );
  }
}

Add integration test for tracking observer


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

package org.apache.commons.lang3.function;

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

import org.junit.jupiter.api.Test;

/**
 * Tests {@link ToBooleanBiFunction}.
 */
public class ToBooleanBiFunctionTest {

    @Test
    public void test() {
        final ToBooleanBiFunction<String, Integer> func = (t, u) -> Integer.valueOf(t).equals(u);
        assertTrue(func.applyAsBoolean("1", 1));
    }
}

Add standalone test for ToBooleanBiFunction.


package org.hyperledger.indy.sdk.demo;

import org.hyperledger.indy.sdk.IndyIntegrationTest;
import org.hyperledger.indy.sdk.agent.Agent;
import org.hyperledger.indy.sdk.agent.AgentResults;
import org.hyperledger.indy.sdk.crypto.Crypto;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.junit.Assert;
import org.junit.Test;

public class AgentDemoTest extends IndyIntegrationTest {

	@Test
	public void testAgentDemo() throws Exception {
		// 1. Create and open wallets for Alice and Bob
		Wallet.createWallet("no pool", "alice_wallet", null, null, null).get();
		Wallet aliceWallet = Wallet.openWallet("alice_wallet", null, null).get();
		Wallet.createWallet("no pool", "bob_wallet", null, null, null).get();
		Wallet bobWallet = Wallet.openWallet("bob_wallet", null, null).get();

		// 2. Create keys for Alice and Bob
		String aliceKey = Crypto.createKey(aliceWallet, "{}").get();
		String bobKey = Crypto.createKey(bobWallet, "{}").get();

		// 3. Prepare authenticated message from Alice to Bob
		byte[] encryptedAuthMsg = Agent.prepMsg(aliceWallet, aliceKey, bobKey, MESSAGE).get();

		// 4. Parse authenticated message on Bob's side
		{
			AgentResults.ParseMsgResult decryptedAuth = Agent.parseMsg(bobWallet, bobKey, encryptedAuthMsg).get();
			Assert.assertEquals(aliceKey, decryptedAuth.getSenderKey());
			Assert.assertArrayEquals(MESSAGE, decryptedAuth.getMessage());
		}

		// 5. Prepare anonymous message from Bob to Alice
		byte[] encryptedAnonMsg = Agent.prepAnonymousMsg(aliceKey, MESSAGE).get();

		// 6. Parse anonymous message on Alice's side
		{
			AgentResults.ParseMsgResult decryptedAnon = Agent.parseMsg(aliceWallet, aliceKey, encryptedAnonMsg).get();
			Assert.assertNull(decryptedAnon.getSenderKey());
			Assert.assertArrayEquals(MESSAGE, decryptedAnon.getMessage());
		}
	}
}

Add Agent Demo for java wrapper.


package edu.harvard.iq.dataverse.engine.command.impl;

import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException;

/**
 * Deletes a data set.
 * @author michael
 */
@RequiredPermissions( Permission.DeleteDatasetDraft )
public class DeleteDatasetCommand extends DestroyDatasetCommand {

	private final Dataset doomed;

	public DeleteDatasetCommand(Dataset doomed, User aUser) {
		super(doomed, aUser);
		this.doomed = doomed;
	}

	@Override
	protected void executeImpl(CommandContext ctxt) throws CommandException {
		if ( doomed.isReleased() ) {
			throw new IllegalCommandException("Cannot delete a released dataset", this);
		}
		super.executeImpl(ctxt);
	}

}

package edu.harvard.iq.dataverse.engine.command.impl;

import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.engine.command.AbstractVoidCommand;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;

/**
 * Deletes a data set.
 *
 * @author michael
 */
@RequiredPermissions(Permission.DeleteDatasetDraft)
public class DeleteDatasetCommand extends AbstractVoidCommand {

    private final Dataset doomed;

    public DeleteDatasetCommand(User aUser, Dataset dataset) {
        super(aUser, dataset);
        this.doomed = dataset;
    }

    public DeleteDatasetCommand(Dataset dataset, User aUser) {
        super(aUser, dataset);
        this.doomed = dataset;
    }

    @Override
    protected void executeImpl(CommandContext ctxt) throws CommandException {
        // TODO: REMOVE THIS COMMAND
        // for now it just calls DeleteDatasetVersion
        ctxt.engine().submit(new DeleteDatasetVersionCommand(getUser(), doomed));
    }

}

REMOVE THIS COMMAND for now it just calls DeleteDatasetVersion


// Copyright 2013 Daniel de Kok
//
// 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 eu.danieldk.dictomaton.collections;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import eu.danieldk.dictomaton.DictionaryBuilderException;
import eu.danieldk.dictomaton.Util;
import eu.danieldk.dictomaton.categories.Benchmarks;

@Category(Benchmarks.class)
public class ImmutableStringIntMapBenchmark extends AbstractBenchmark
{
	private static SortedSet<String> d_words;
	private ImmutableStringIntMap map;

	@BeforeClass
	public static void initializeExpensive() throws DictionaryBuilderException, IOException
	{
		d_words = Util.loadWordList("eu/danieldk/dictomaton/web2-1");
	}

	@Before
	public void initialize() throws DictionaryBuilderException
	{
		ImmutableStringIntMap.Builder builder = new ImmutableStringIntMap.Builder();

		int i = 0;
		for (String word : d_words)
		{
			builder.put(word, i++);
		}

		map = builder.build();
	}

	@Test
	public void getBenchmark()
	{
        int i = 0;
		for (String word : d_words)
            Assert.assertEquals(i++, (int) map.get(word));
	}
}

Add a benchmark for ImmutableStringIntMap.get().


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.smoketest;

import org.elasticsearch.test.ESIntegTestCase;

public class PreventFailingBuildIT extends ESIntegTestCase {

    public void testSoThatTestsDoNotFail() {
        // Noop

        // This is required because if tests are not enable no
        // tests will be run in the entire project and all tests will fail.
    }
}

Add noop test to prevent test failures


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

package net.imagej.ops.deconvolve;

import net.imagej.ops.AbstractNamespaceTest;
import net.imagej.ops.DeconvolveOps.RichardsonLucy;

import org.junit.Test;

/**
 * Tests that the ops of the math namespace have corresponding type-safe Java
 * method signatures declared in the {@link DeconvolveNamespace} class.
 *
 * @author Alison Walter
 */
public class DeconvolveNamespaceTest extends AbstractNamespaceTest {

	/** Tests for {@link RichardsonLucy} method convergence. */
	@Test
	public void testRichardsonLucy() {
		assertComplete("deconvolve", DeconvolveNamespace.class, RichardsonLucy.NAME);
	}

}

Add tests for DeconvolveNamespace built-ins


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

package net.uncontended.precipice.samples;

import net.uncontended.precipice.Failable;
import net.uncontended.precipice.GuardRail;
import net.uncontended.precipice.GuardRailBuilder;
import net.uncontended.precipice.concurrent.CompletionContext;
import net.uncontended.precipice.factories.CompletableFactory;
import net.uncontended.precipice.metrics.CountMetrics;
import net.uncontended.precipice.metrics.MetricCounter;
import net.uncontended.precipice.semaphore.UnlimitedSemaphore;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class GuardRailWithFactory {

    public static void main(String[] args) {
        CountMetrics<Result> resultMetrics = new MetricCounter<>(Result.class);
        CountMetrics<RejectedReason> rejectedMetrics = new MetricCounter<>(RejectedReason.class);

        GuardRailBuilder<Result, RejectedReason> builder = new GuardRailBuilder<>();
        builder.name("Example")
                .resultMetrics(resultMetrics)
                .rejectedMetrics(rejectedMetrics)
                .addBackPressure(new UnlimitedSemaphore<>(RejectedReason.MAX_CONCURRENCY));

        GuardRail<Result, RejectedReason> guardRail = builder.build();

        CompletionContext<Result, String> completable = CompletableFactory.acquirePermitsAndGetCompletable(guardRail, 1L);

        try {
            URL url = new URL("http://www.google.com");
            URLConnection urlConnection = url.openConnection();
            completable.complete(Result.SUCCESS, readToString(urlConnection.getInputStream()));
        } catch (Exception ex) {
            completable.completeExceptionally(Result.EXCEPTION, ex);
        }
    }

    private static String readToString(InputStream inputStream) {
        return "Http Response";
    }

    public enum Result implements Failable {
        SUCCESS,
        EXCEPTION;

        @Override
        public boolean isFailure() {
            return this == EXCEPTION;
        }

        @Override
        public boolean isSuccess() {
            return this == SUCCESS;
        }
    }

    public enum RejectedReason {
        MAX_CONCURRENCY
    }
}

Add example with usage of factory


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

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.objectweb.asm.Type;

import java.util.Map;

public class AnnotationDescriptor {
    private final Type type;
    private final Map<String, Object> values;
    private final boolean resolved;

    AnnotationDescriptor(final Type type, final Map<String, Object> values, final boolean resolved) {
        this.type = type;
        this.values = values;
        this.resolved = resolved;
    }

    public Type getType() {
        return type;
    }

    public Map<String, Object> getValues() {
        return values;
    }

    public boolean isResolved() {
        return resolved;
    }

    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final AnnotationDescriptor that = (AnnotationDescriptor) object;
        final EqualsBuilder equalsBuilder = new EqualsBuilder()
                .append(type, that.type)
                .append(values.size(), that.values.size());
        if (!equalsBuilder.isEquals()) {
            return false;
        }

        for (final Map.Entry<String, Object> entry : values.entrySet()) {
            equalsBuilder
                    .append(true, that.getValues().containsKey(entry.getKey()))
                    .append(entry.getValue(), that.getValues().get(entry.getKey()));
            if (!equalsBuilder.isEquals()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        final HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(17, 37)
                .append(type);
        final HashCodeBuilder mapHashCodeBuilder = new HashCodeBuilder(1, 1);
        for (final Map.Entry<String, Object> entry : values.entrySet()) {
            mapHashCodeBuilder.append(entry.getValue());
        }
        return hashCodeBuilder
                .append(mapHashCodeBuilder.build())
                .build();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("type", type)
                .append("values", values)
                .toString();
    }
}

Add a descriptor class for annotations


package com.coding4people.mosquitoreport.api.models;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;

@DynamoDBTable(tableName = "passwordresettoken")
public class PasswordResetToken {
    @DynamoDBHashKey
    private String token;

    @DynamoDBAttribute
    private String expires;

    @DynamoDBAttribute
    private String email;

    @DynamoDBAttribute
    private String userguid;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getExpires() {
        return expires;
    }

    public void setExpires(String expires) {
        this.expires = expires;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUserguid() {
        return userguid;
    }

    public void setUserguid(String userguid) {
        this.userguid = userguid;
    }
}

Create password reset token model


package org.deeplearning4j.spark.data;

import org.apache.spark.api.java.JavaRDD;
import org.deeplearning4j.spark.BaseSparkTest;
import org.deeplearning4j.spark.util.SparkUtils;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;

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

import static org.junit.Assert.assertEquals;

/**
 * Created by Alex on 06/01/2017.
 */
public class TestShuffleExamples extends BaseSparkTest {

    @Test
    public void testShuffle(){
        List<DataSet> list = new ArrayList<>();
        for( int i=0; i<10; i++ ){
            INDArray f = Nd4j.valueArrayOf(new int[]{10,1}, i);
            INDArray l = f.dup();

            DataSet ds = new DataSet(f,l);
            list.add(ds);
        }

        JavaRDD<DataSet> rdd = sc.parallelize(list);

        JavaRDD<DataSet> shuffled = SparkUtils.shuffleExamples(rdd, 10, 10);

        List<DataSet> shuffledList = shuffled.collect();

        int totalExampleCount = 0;
        for(DataSet ds : shuffledList){
            totalExampleCount += ds.getFeatures().length();
            System.out.println(Arrays.toString(ds.getFeatures().data().asFloat()));

            assertEquals(ds.getFeatures(), ds.getLabels());
        }

        assertEquals(100, totalExampleCount);
    }

}

Add test for spark shuffling


package org.lumongo.test.storage;

import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.lucene.store.BaseDirectoryWrapper;
import org.apache.lucene.util.LuceneTestCase;
import org.lumongo.storage.lucene.DistributedDirectory;
import org.lumongo.storage.lucene.MongoDirectory;
import org.lumongo.util.TestHelper;

import com.mongodb.MongoClient;
import com.mongodb.MongoException;

public class LumongoTestCase extends LuceneTestCase {

	private static int indexNameCounter = 0;

	@Override
	public void setUp() throws Exception {
		MongoClient mongo = TestHelper.getMongo();
		mongo.dropDatabase(TestHelper.TEST_DATABASE_NAME);
		mongo.close();
		super.setUp();
	}

	public static BaseDirectoryWrapper newDirectory() {

		try {
			final MongoClient mongo = TestHelper.getMongo();
			return new BaseDirectoryWrapper(new DistributedDirectory(new MongoDirectory(mongo, TestHelper.TEST_DATABASE_NAME, "index" + indexNameCounter++,
							false, false) {
				@Override
				public void close() {
					mongo.close();
				}
			}));
		}
		catch (UnknownHostException e) {
			throw new RuntimeException(e);
		}
		catch (MongoException e) {
			throw new RuntimeException(e);
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

}

Add lumongo test case that extends lucene test case


package nu.studer.teamcity.buildscan;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public final class SlackInvocation {

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            throw new IllegalArgumentException("Webhook URL must be specified.");
        }

        Map<String, String> params = new HashMap<>();
        params.put("teamcity.buildConfName", "My Configuration");
        params.put("teamcity.serverUrl", "http://ci.company.org");
        params.put("teamcity.build.id", "23");

        BuildScanReferences buildScanReferences = BuildScanReferences.of(Arrays.asList(
            new BuildScanReference("myId", "http://www.myUrl.org/s/abcde"),
            new BuildScanReference("myOtherId", "http://www.myOtherUrl.org/efghi")));

        SlackIntegration slackIntegration = SlackIntegration.forWebhook(new URL(args[0]));
        slackIntegration.notify(buildScanReferences, params);
    }

}

Add main method to easily verify the webhook invocation


/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2012 Regents of the University of Minnesota and contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
/**
 * Similarity functions over vectors.
 */
package org.grouplens.lenskit.vectors.similarity;

Add package docs for vector similarity.


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.data.float64.real.Float64VectorMember;

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

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();

		Float64VectorMember vec = new Float64VectorMember(new double[] {1,2,3});

		RModuleReshape.compute(G.DBL_VEC, G.DBL, 4, vec);

		assertEquals(4, vec.length());
		vec.v(0, value);
		assertEquals(1, value.v(), 0);
		vec.v(1, value);
		assertEquals(2, value.v(), 0);
		vec.v(2, value);
		assertEquals(3, value.v(), 0);
		vec.v(3, value);
		assertEquals(0, value.v(), 0);

		RModuleReshape.compute(G.DBL_VEC, G.DBL, 2, vec);

		assertEquals(2, vec.length());
		vec.v(0, value);
		assertEquals(1, value.v(), 0);
		vec.v(1, value);
		assertEquals(2, value.v(), 0);
	}
}

Define a test for the RModuleReshape algorithm


/*
 * 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-10-01
 * Site       : https://www.acmicpc.net/problem/2675
 */

public class Boj2675 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        for(int i=0; i<t; i++){
            int r = br.read()-48;
            br.read();
            while(true) {
                char tmp = (char)br.read();
                if(tmp=='\n'){
                    break;
                }
                for(int j=0; j<r; j++){
                    System.out.print(tmp);
                }
            }
            System.out.println();
        }
    }

}

Solve No.2675 from Baekjoon Online Judge


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

import org.destinationsol.game.Console;
import org.destinationsol.game.Hero;
import org.destinationsol.game.SolGame;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

import static org.junit.Assert.*;

public class RespawnCommandHandlerTest {

    private RespawnCommandHandler commandHandler;
    private SolGame game;
    private Hero hero;
    private Console console;

    @Before
    public void init() {
        game = Mockito.mock(SolGame.class);
        hero = Mockito.mock(Hero.class);
        commandHandler = new RespawnCommandHandler(hero, game);
        console = Mockito.mock(Console.class);
    }

    @Test
    public void shouldRespawnWhenDead() {
        Mockito.when(hero.isAlive()).thenReturn(false);
        commandHandler.handle("respawn", console);
        Mockito.verify(game, Mockito.times(1)).respawn();
    }

    @Test
    public void shouldNotRespawnWhenAlive() {
        Mockito.when(hero.isAlive()).thenReturn(true);
        commandHandler.handle("respawn", console);
        Mockito.verify(game, Mockito.never()).respawn();
    }
}

Create unit test for 'respawn' command


package io.searchbox.core.search.aggregation;

import static org.junit.Assert.*;
import io.searchbox.core.BulkResult;
import io.searchbox.core.search.aggregation.TermsAggregation.Entry;

import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class TermsAggregationTermTest {

	private static String EXPECTED_KEY_VALUE = "someKeyValue";
	private static String EXPECTED_KEY_AS_STRING_VALUE = "someKeyAsStringValue";
	private static long EXPECTED_DOC_COUNT_VALUE = 100L;

	static String termObjectWithKeyAsStringField = "{\n" +
			"    \"key\": \"" + EXPECTED_KEY_VALUE + "\",\n" +
			"    \"key_as_string\": \"" + EXPECTED_KEY_AS_STRING_VALUE + "\",\n" +
			"    \"doc_count\": " + EXPECTED_DOC_COUNT_VALUE + "\n" +
			"}";

	static String termObjectWithoutKeyAsStringField = "{\n" +
			"    \"key\": \"" + EXPECTED_KEY_VALUE + "\",\n" +
			"    \"doc_count\": " + EXPECTED_DOC_COUNT_VALUE + "\n" +
			"}";

	static String termsAggregationContent = "{\n" +
			"    \"doc_count_error_upper_bound\":0,\n" +
			"    \"sum_other_doc_count\":0,\n" +
			"    \"buckets\": [\n" +
				termObjectWithKeyAsStringField +
			"    ,\n" +
				termObjectWithoutKeyAsStringField +
			"    ]\n" +
			"}";

	@Test
	public void testParseBuckets() {

		JsonObject termsAggregationJson = new Gson().fromJson(termsAggregationContent, JsonObject.class);
		TermsAggregation termsAggregation = new TermsAggregation("termsAggregation", termsAggregationJson);
		List<Entry> buckets = termsAggregation.getBuckets();
		assertNotNull(buckets);
		assertEquals(2, buckets.size());
		// Test for entry *with* key_as_value present
		Entry entryWithKeyAsString = buckets.get(0);
		assertEquals(EXPECTED_KEY_VALUE, entryWithKeyAsString.getKey());
		assertEquals(EXPECTED_KEY_AS_STRING_VALUE, entryWithKeyAsString.getKeyAsString());
		assertTrue(EXPECTED_DOC_COUNT_VALUE == entryWithKeyAsString.getCount());
		// Test for entry *without* key_as_value present
		Entry entryWithoutKeyAsString = buckets.get(1);
		assertEquals(EXPECTED_KEY_VALUE, entryWithoutKeyAsString.getKey());
		// If key_as_string wasn't populated, return key value
		assertEquals(EXPECTED_KEY_VALUE, entryWithoutKeyAsString.getKeyAsString());
		assertTrue(EXPECTED_DOC_COUNT_VALUE == entryWithoutKeyAsString.getCount());

	}

}

Add unit test to verify newly added getKeyAsString method


/*
 * 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.
 *
 */
@NonNullApi
package com.google.android.exoplayer2.text.webvtt;

import com.google.android.exoplayer2.util.NonNullApi;

Annotate webvtt package with @NonNullApi


package uk.gov.register.presentation.functional;

import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.isEmptyOrNullString;

public class VerifiableLogResourceFunctionalTest extends FunctionalTestBase {

    private final String proofIdentifier = "merkle:sha-256";

    @Before
    public void publishTestMessages() throws Throwable {
        mintItems("{\"address\":\"1111\",\"street\":\"elvis\"}",
                "{\"address\":\"2222\",\"street\":\"presley\"}",
                "{\"address\":\"3333\",\"street\":\"ellis\"}",
                "{\"address\":\"4444\",\"street\":\"pretzel\"}",
                "{\"address\":\"5555\",\"street\":\"elfsley\"}");
    }

    @Test
    public void getRegisterProof() {
        Response response = getRequest("/proof/register/" + proofIdentifier);

        assertThat(response.getStatus(), equalTo(200));

        Map<?,?> responseData = response.readEntity(Map.class);
        assertThat(responseData.get("proof-identifier").toString(), equalTo(proofIdentifier));
        assertThat(responseData.get("root-hash").toString(), not(isEmptyOrNullString()));
    }

    @Test
    public void getEntryProof() {
        Response response = getRequest("/proof/entry/1/5/" + proofIdentifier);

        assertThat(response.getStatus(), equalTo(200));

        Map<?,?> responseData = response.readEntity(Map.class);
        assertThat(responseData.get("proof-identifier").toString(), equalTo(proofIdentifier));
        assertThat(responseData.get("entry-number").toString(), equalTo("1"));

        List<?> auditPath = (List)(responseData.get("merkle-audit-path"));
        assertThat(auditPath, hasSize(3));
    }

    @Test
    public void getConsistencyProof() {
        Response response = getRequest("/proof/consistency/2/5/" + proofIdentifier);

        assertThat(response.getStatus(), equalTo(200));

        Map<?,?> responseData = response.readEntity(Map.class);
        assertThat(responseData.get("proof-identifier").toString(), equalTo(proofIdentifier));

        List<?> auditPath = (List)(responseData.get("merkle-consistency-nodes"));
        assertThat(auditPath, hasSize(2));
    }
}

Add functional test for Verifiable log resource


package com.evolveum.midpoint.testing.selenium;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.evolveum.midpoint.api.logging.Trace;
import com.evolveum.midpoint.logging.TraceManager;

public class Test004UserPassword {
	WebDriverBackedSelenium se;
	static String baseUrl="http://localhost:8080/idm";

	private static final transient Trace logger = TraceManager.getTrace(Test004UserPassword.class);

	@Before
	public void start() {
		WebDriver driver = new FirefoxDriver();
		se = new WebDriverBackedSelenium(driver, baseUrl);
		se.open("/");
		se.waitForPageToLoad("10000");
	}

	@After
	public void stop() {
		se.stop();
	}

	@Test
	public void test010positiveAdminLoginTest() {
		se.type("loginForm:userName", "administrator");
		se.type("loginForm:password", "secret");
		se.click("loginForm:loginButton");
		se.waitForPageToLoad("10000");
		assertEquals(baseUrl+"/index.iface", se.getLocation());
	}

	@Test
	public void test011positiveUserLoginTest() {
		se.type("loginForm:userName", "jack");
		se.type("loginForm:password", "deadmentellnotales");
		se.click("loginForm:loginButton");
		se.waitForPageToLoad("10000");
		assertEquals(baseUrl+"/index.iface", se.getLocation());
	}

	@Test
	public void test020adminChangeUserPassword() {
		se.type("loginForm:userName", "administrator");
		se.type("loginForm:password", "secret");
		se.click("loginForm:loginButton");
		se.waitForPageToLoad("10000");
		assertEquals(baseUrl+"/index.iface", se.getLocation());
	}

	@Test
	public void test020userChangeOwnPassword() {
	}

	@Test
	public void test030adminResetUserPassword() {
		//TODO
	}

	@Test
	public void test040adminChangeOwnPassword() {
	}
}

Add new test based on user password


/*
 * Copyright 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
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.material.ripple;

import android.graphics.Canvas;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;

/**
 * A compat {@link android.graphics.drawable.Drawable} to be used pre-Lollipop for drawing an
 * overlay on top of a background for pressed, focused, and hovered states.
 *
 *
This Drawable is a {@link MaterialShapeDrawable} so that it can be shaped to match a
 * MaterialShapeDrawable background.
 *
 *
Unlike the framework {@link android.graphics.drawable.RippleDrawable}, this will not
 * apply different alphas for pressed, focused, and hovered states and it does not provide a ripple
 * animation for the pressed state.
 */
@RestrictTo(Scope.LIBRARY_GROUP)
public class RippleDrawableCompat extends MaterialShapeDrawable {

  /**
   * Whether this compat ripple should be drawn. True when enabled and (pressed, focused, or
   * enabled).
   */
  private boolean shouldDrawRipple = false;

  /**
   * Creates a {@link RippleDrawableCompat} with the given shape.
   *
   * @param shapeAppearanceModel the {@link ShapeAppearanceModel} containing the path that will be
   *     rendered in this drawable.
   */
  public RippleDrawableCompat(ShapeAppearanceModel shapeAppearanceModel) {
    super(shapeAppearanceModel);
  }

  @Override
  public void draw(Canvas canvas) {
    if (shouldDrawRipple) {
      super.draw(canvas);
    }
  }

  @Override
  protected boolean onStateChange(int[] stateSet) {
    final boolean changed = super.onStateChange(stateSet);
    boolean enabled = false;
    boolean pressed = false;
    boolean focused = false;
    boolean hovered = false;

    for (int state : stateSet) {
      if (state == android.R.attr.state_enabled) {
        enabled = true;
      } else if (state == android.R.attr.state_focused) {
        focused = true;
      } else if (state == android.R.attr.state_pressed) {
        pressed = true;
      } else if (state == android.R.attr.state_hovered) {
        hovered = true;
      }
    }
    shouldDrawRipple = enabled && (pressed || focused || hovered);
    return changed;
  }
}

Create compat ripples that are based on MaterialShapeDrawable and only draw when enabled and in the pressed, focused, or hovered states.


package net.ttsui.junit.rules.pending;

import static org.junit.Assert.fail;

import org.junit.Rule;
import org.junit.Test;

public class SupportJUnitExpectedExceptionTest {
    @Rule public PendingRule pendingRule = new PendingRule();

    @Test public void
    passingTest() {

    }

    @PendingImplementation
    @Test(expected=NullPointerException.class) public void
    unexpectedSuccessTest() {
        throw new NullPointerException();
    }

    @Test public void
    failingTest() {
        fail("test");
    }
}

Add test for bug interacting with JUnit expected exception handler.


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctc.c2.util.LinkedListUtil;
import com.sunny.grokkingalgorithms.ctc.c2.util.Node;
import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by sundas on 6/9/2018.
 */
public class CreateLinkedListAtEachLevelOfBinarySearchTree {

  /*
  Create a linked list at each level of binary search tree
   */

  /**
   *
   * @param root
   * @return
   */
  public static List<Node> createLinkedListAtEachLevel(BinaryTreeNode root){
    if(root == null){
      return null;
    }
    /*
    Using level order traversal
     */
    Queue<BinaryTreeNode> queue = new LinkedList<>();
    List<Node> linkedLists = new ArrayList<>();
    queue.add(root);
    BinaryTreeNode levelMarker = new BinaryTreeNode();
    queue.add(levelMarker);
    Node currentLevelHead = null;
    Node previous = null;
    while(!queue.isEmpty()){
      BinaryTreeNode current = queue.poll();
      /*
      Level end logic
       */
      if(current == levelMarker){
        /*
        End of level, means we have the linked list
         */
        if(currentLevelHead != null){
          linkedLists.add(currentLevelHead);
        }
        /*
        Reset
         */
        currentLevelHead = null;
        previous = null;
        /*
        Prepare for next level
         */
        if(!queue.isEmpty()){
          queue.add(levelMarker);
        }
      }
      else{
        /*
        Normal processing
         */
        Node node = new Node();
        node.data = current.data;
        if(currentLevelHead == null){
          currentLevelHead = node;
        }
        if(previous != null){
          previous.next = node;
        }
        previous = node;
        /*
        Normal level order traversal
         */
        if(current.left != null){
          queue.add(current.left);
        }
        if(current.right != null){
          queue.add(current.right);
        }
      }
    }
    return linkedLists;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("##################");
    List<Node> linkedLists = createLinkedListAtEachLevel(root);
    for(Node head : linkedLists){
      LinkedListUtil.printLinkedList(head);
    }
  }

}

Convert nodes at each level of a binary tree to linked lists using level order traversal. O(n) time and O(n) space.


package eic.beike.projectx.eicapi;

import com.google.gson.annotations.SerializedName;

/**
 * Created by alex on 9/22/15.
 */
public class ResponseEntry implements Comparable<ResponseEntry>{
    @SerializedName("resourceSpec")
    String resource;

    @SerializedName("timestamp")
    Integer timestamp;

    @SerializedName("value")
    String value;

    @SerializedName("gatewayId")
    String busVin;

    @Override
    public int compareTo(ResponseEntry other){
        return this.timestamp - other.timestamp;
    }
}

Add class for gson to fill.


package org.jenkinsci.plugins.ghprb;

import hudson.Extension;
import hudson.security.csrf.CrumbExclusion;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Excludes {@link GhprbRootAction} from the CSRF protection.
 * @since 1.28
 */
@Extension
public class GhprbCrumbExclusion extends CrumbExclusion {

    @Override
    public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        final String pathInfo = req.getPathInfo();
        if (pathInfo != null && pathInfo.startsWith(getExclusionPath())) {
            chain.doFilter(req, resp);
            return true;
        }
        return false;
    }

    public String getExclusionPath() {
        return "/" + GhprbRootAction.URL + "/";
    }
}

Allow to work with CSR protection


// RobotBuilder Version: 0.0.2
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java.commands;
import edu.wpi.first.wpilibj.command.AutoSpreadsheetCommand;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc330.Beachbot2013Java.Robot;
/*
 * $Log: PickupFrisbeesOn.java,v $
 * Revision 1.8  2013-03-15 02:58:07  echan
 * robotbuilder update
 *
 * Revision 1.7  2013-03-15 02:51:09  echan
 * added cvs log comments
 *
 */
/**
 *
 */
public class  PickupFrisbeesOnBatteryCompensated extends Command implements AutoSpreadsheetCommand {
    public PickupFrisbeesOnBatteryCompensated() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);

        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
        requires(Robot.frisbeePickup);
    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
    }
    // Called just before this Command runs the first time
    protected void initialize() {
    }
    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.frisbeePickup.setFrisbeePickupMotorPickupBatteryCompensated();
    }
    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }
    // Called once after isFinished returns true
    protected void end() {
        Robot.frisbeePickup.setFrisbeePickupMotorStop();
    }
    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        end();
    }
    public void setParam1(double param1) {
    }
    public void setParam2(double param2) {
    }
    public void setParam3(double param3) {
    }
    public void setStopAtEnd(boolean stopAtEnd) {
    }
    public Command copy() {
        return new PickupFrisbeesOnBatteryCompensated();
    }
}

Create new command for adjusting pickup speed based on linear scaling of battery voltage


package com.jajinba.android.utils;

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

public class EqualUtilsUnitTest {

  @Test
  public void isEqual_Array_isCorrect() throws Exception {
    // null
    Assert.assertTrue(EqualUtils.isEqual(null, null));
    Assert.assertEquals(false, EqualUtils.isEqual(1, null));
    Assert.assertEquals(false, EqualUtils.isEqual("string", null));

    // char and String
    Assert.assertEquals(false, EqualUtils.isEqual('a', "a"));
    Assert.assertEquals(false, EqualUtils.isEqual("a", "abc"));
    Assert.assertTrue(EqualUtils.isEqual("a", "a"));
    Assert.assertTrue(EqualUtils.isEqual("abc", "abc"));

    // numbers
    Assert.assertEquals(false, EqualUtils.isEqual(0, 0f));
    Assert.assertTrue(EqualUtils.isEqual(0, 0));
    Assert.assertTrue(EqualUtils.isEqual(-0, 0));
  }
}

Add EqualsUtils unit test cases