/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.servlet;

import foam.util.SafetyUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.text.StringEscapeUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ResourceImageServlet
  extends ImageServlet
{
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    System.out.println("ResourceImageServlet.service uri: "+req.getRequestURI());
    String request = req.getRequestURI().replaceFirst("/?images/?", "/");
    System.out.println("ResourceImageServlet.service request: "+request);
    // tried a few prefixes, /images, /webapp/images, images/,
    InputStream is = getClass().getResourceAsStream("images/"+request);
    if ( is != null ) {
      String ext = EXTS.get(request.substring(request.lastIndexOf('.') +1));
      try ( BufferedInputStream bis = new BufferedInputStream(is) ) {
        resp.setContentType(!SafetyUtil.isEmpty(ext) ? ext : DEFAULT_EXT);
        resp.setHeader("Content-Disposition", "filename=\"" + StringEscapeUtils.escapeHtml4(request) + "\"");
        //resp.setContentLengthLong(src.length());

        IOUtils.copy(bis, resp.getOutputStream());
        return;
      }
    } else {
      System.out.println("ResourceImageServlet.service is: null");
    }
    resp.sendError(resp.SC_NOT_FOUND);
  }
}

Support loading images from jar resource.


package leetcode;

/**
 * https://leetcode.com/problems/h-index-ii/
 */
public class Problem275 {
    public int hIndex(int[] citations) {
        // TODO:
        return 0;
    }

    public static void main(String[] args) {
        Problem275 prob = new Problem275();
    }
}

Add skeleton for problem 275


package com.japlj.healthydiet.food;

public class FoodParameter {
	public float proteinValue;
	public float carbohydrateValue;
	public float vitaMineValue;
	public float saturation;

	public FoodParameter(float protein, float carbo, float vitamine, float satu) {
		this.proteinValue = protein;
		this.carbohydrateValue = carbo;
		this.vitaMineValue = vitamine;
		this.saturation = satu;
	}

	private float addValue(float v1, float v2) {
		return Math.min(100.0F, v1 + v2);
	}

	public void add(FoodParameter param) {
		proteinValue = addValue(proteinValue, param.proteinValue);
		carbohydrateValue = addValue(carbohydrateValue, param.carbohydrateValue);
		vitaMineValue = addValue(vitaMineValue, param.vitaMineValue);
		saturation = addValue(saturation, param.saturation);
	}
}

Add the class representing nutrition values of a food


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.spec;

import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static prm4j.Util.set;
import static prm4j.Util.tuple;

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

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

import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;

import prm4j.AbstractTest;
import prm4j.Util;
import prm4j.Util.Tuple;
import prm4j.api.BaseEvent;
import prm4j.api.Parameter;
import prm4j.api.fsm.FSMSpec;
import prm4j.spec.FiniteParametricProperty;

public class FiniteParametricPropertyHasNextTest extends AbstractTest {

    FSM_HasNext fsm;
    FiniteParametricProperty fpp;
    @Before
    public void init() {
	fsm = new FSM_HasNext();
	fpp = new FiniteParametricProperty(new FSMSpec(fsm.fsm));
    }

    @Test
    public void getMonitorSetData() throws Exception {
	SetMultimap<Set<Parameter<?>>, Tuple<Set<Parameter<?>>, Boolean>> actual = fpp.getMonitorSetData();
	SetMultimap<Set<Parameter<?>>, Tuple<Set<Parameter<?>>, Boolean>> expected = HashMultimap.create();

	System.out.println(fpp.getMonitorSetData());
	System.out.println(fpp.getChainData());
	System.out.println(fpp.getJoinData());
	System.out.println(fpp.getCreationEvents());

    }

}

Add test for FiniteParametricProperty based on HasNext


package de.lmu.ifi.dbs.elki.visualization.batikutil;

import java.awt.Component;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

/**
 * Class to lazily process canvas resize events by applying a threshold.
 *
 * @author Erich Schubert
 *
 */
public abstract class LazyCanvasResizer extends ComponentAdapter {
  /**
   * Default threshold for resizing.
   */
  public static final double DEFAULT_THRESHOLD = 0.05;

  /**
   * Active threshold
   */
  double threshold;

  /**
   * Last ratio of the Canvas applied
   */
  double activeRatio;

  /**
   * Component the ratio applies to.
   */
  Component component;

  /**
   * Full constructor.
   *
   * @param component Component to track
   * @param threshold Threshold
   */
  public LazyCanvasResizer(Component component, double threshold) {
    super();
    this.threshold = threshold;
    this.component = component;
    this.activeRatio = getCurrentRatio();
  }

  /**
   * Simplified constructor using the default threshold {@link #DEFAULT_THRESHOLD}
   *
   * @param component Component to track.
   */
  public LazyCanvasResizer(Component component) {
    this(component, DEFAULT_THRESHOLD);
  }

  /**
   * React to a component resize event.
   */
  @Override
  public void componentResized(ComponentEvent e) {
    if (e.getComponent() == component) {
      double newRatio = getCurrentRatio();
      if (Math.abs(newRatio - activeRatio) > threshold) {
        activeRatio = newRatio;
        executeResize(newRatio);
      }
    }
  }

  /**
   * Get the components current ratio.
   *
   * @return Current ratio.
   */
  public final double getCurrentRatio() {
    return (double) component.getWidth() / (double) component.getHeight();
  }

  /**
   * Callback function that needs to be overridden with actual implementations.
   *
   * @param newratio New ratio to apply.
   */
  public abstract void executeResize(double newratio);

  /**
   * Get the components last applied ratio.
   *
   * @return Last applied ratio.
   */
  public double getActiveRatio() {
    return activeRatio;
  }
}

Add a utility class to do lazy screen resizing.


package jp.pushmestudio.kcuc.rest;

import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import io.swagger.jaxrs.config.BeanConfig;

@ApplicationPath("/api")
public class KCNoticeApplicationConfig extends Application {

	/**
	 * to be added
	 */
	public KCNoticeApplicationConfig() {
		BeanConfig beanConfig = new BeanConfig();
		beanConfig.setTitle("KCUC");
		beanConfig.setDescription("Knowledge Center Update Checker");
		beanConfig.setVersion("1.0.2");
		beanConfig.setSchemes(new String[] { "http" });
		beanConfig.setHost("localhost:8080");
		beanConfig.setBasePath("/kcuc"); // applicationのルートパスを指定
		beanConfig.setPrettyPrint(true);
		beanConfig.setResourcePackage("io.swagger.resources");
		beanConfig.setScan(true);
	}

	@Override
	public Set<Class<?>> getClasses() {
		Set<Class<?>> resources = new java.util.HashSet<>();
		addRestResourceClasses(resources);

		// enable Swagger
		resources.add(io.swagger.jaxrs.listing.ApiListingResource.class);
		resources.add(io.swagger.jaxrs.listing.SwaggerSerializers.class);

		return resources;
	}

	private void addRestResourceClasses(Set<Class<?>> resources) {
		resources.add(KCNoticeResource.class);
	}
}

Add application config class for swagger app


package org.jbake.app;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;

public class DebugUtilTest
{

    @Test
    public void printMap() throws UnsupportedEncodingException
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintStream ps = new PrintStream(baos, true, "UTF-8")) {
            DebugUtil.printMap(new HashMap<String, Object>() {{
                                       put("stringKey", "stringVal");
                                       put("forNullVal", null);
                                       put(null, "forNullKey");
                                       put("forObject", new Object());
                                       put("forCharset", StandardCharsets.UTF_8);
                                       put("forNonSerializableVal", new Exception("nonSerializableVal"));
                                   }},
                    ps);
        }
        String printed = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        System.out.println(printed);

        Assert.assertTrue(printed.contains("stringKey :: stringVal"));
        Assert.assertTrue(printed.contains("null :: forNullKey"));
        Assert.assertTrue(printed.contains("forNullVal :: null"));
        Assert.assertTrue(printed.contains("forCharset :: UTF-8"));
        Assert.assertTrue(printed.contains("forNonSerializableVal :: java.lang.Exception: nonSerializableVal"));
    }
}

Add a test for DebugUtil


package sfBugs;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Bug1942828 {
	public int getInt0(ResultSet rs) throws SQLException {
		return rs.getInt(0);
	}

	public int getInt(ResultSet rs, int i) throws SQLException {
		return rs.getInt(i);
	}

	private final int CONST = 7;

	public int getIntCheck(ResultSet rs, int i) throws SQLException {
		return i > 0 ? rs.getInt(i) : CONST;
	}
}

Test case for [ 1942828 ] ResultSet getXXX where index is not zero reported as zero


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.ClientRegistry;
import info.u_team.u_team_test.TestMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.SpriteRenderer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestModels {

	@SubscribeEvent
	public static void register(FMLClientSetupEvent event) {
		ClientRegistry.registerEntityRenderer(TestEntityTypes.BETTER_ENDERPEARL, manager -> new SpriteRenderer<>(manager, Minecraft.getInstance().getItemRenderer()));
	}
}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.ClientRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.SpriteRenderer;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestModels {

	private static void setup(FMLClientSetupEvent event) {
		ClientRegistry.registerEntityRenderer(TestEntityTypes.BETTER_ENDERPEARL, manager -> new SpriteRenderer<>(manager, Minecraft.getInstance().getItemRenderer()));
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestModels::setup);
	}
}

Use the new system now


package io.pcp.parfait.dxm.semantics;

import static org.junit.Assert.assertNotNull;
import static systems.uom.unicode.CLDR.BIT;
import static systems.uom.unicode.CLDR.BYTE;
import static tech.units.indriya.quantity.time.TimeQuantities.MILLISECOND;
import static tech.units.indriya.unit.Units.SECOND;

import javax.measure.MetricPrefix;

import org.junit.Test;
import tech.units.indriya.AbstractUnit;
import tech.units.indriya.unit.Units;

public class UnitMappingTest {

    @Test
    public void getUnitMapping_whenByteAndDerivativeUnitsGiven() {
        UnitMapping byteUnitMapping = UnitMapping.findUnitMapping(BYTE);
        assertNotNull(byteUnitMapping);

        UnitMapping bytePerSecondUnitMapping = UnitMapping.findUnitMapping(BYTE.divide(SECOND));
        assertNotNull(bytePerSecondUnitMapping);

        UnitMapping bytePerMilliSecondUnitMapping = UnitMapping.findUnitMapping(BYTE.divide(SECOND.divide(1000)));
        assertNotNull(bytePerMilliSecondUnitMapping);

        UnitMapping bitUnitMapping = UnitMapping.findUnitMapping(BIT);
        assertNotNull(bitUnitMapping);
    }

    @Test
    public void getUnitMapping_whenTimeAndDerivativeUnitsGiven() {
        UnitMapping milliSeconds = UnitMapping.findUnitMapping(MetricPrefix.MILLI(SECOND));
        assertNotNull(milliSeconds);

        UnitMapping onePerMinute = UnitMapping.findUnitMapping(AbstractUnit.ONE.divide(Units.MINUTE));
        assertNotNull(onePerMinute);

        UnitMapping milliSeconds2 = UnitMapping.findUnitMapping(MILLISECOND);
        assertNotNull(milliSeconds2);
    }
}

Add tests to highlight issue with unit mapping with MetricPrefix


package org.gnucash.android.test.unit.util;

import org.gnucash.android.util.AmountParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Locale;

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

public class AmountParserTest {
    private Locale mPreviousLocale;

    @Before
    public void setUp() throws Exception {
        mPreviousLocale = Locale.getDefault();
        Locale.setDefault(Locale.US);
    }

    @After
    public void tearDown() throws Exception {
        Locale.setDefault(mPreviousLocale);
    }

    @Test
    public void testParseIntegerAmount() throws ParseException {
        assertThat(AmountParser.parse("123")).isEqualTo(new BigDecimal(123));
    }

    @Test
    public void parseDecimalAmount() throws ParseException {
        assertThat(AmountParser.parse("123.45")).isEqualTo(new BigDecimal("123.45"));
    }

    @Test
    public void parseDecimalAmountWithDifferentSeparator() throws ParseException {
        Locale.setDefault(Locale.GERMANY);
        assertThat(AmountParser.parse("123,45")).isEqualTo(new BigDecimal("123.45"));
    }

    @Test(expected = ParseException.class)
    public void withGarbageAtTheBeginning_shouldFailWithException() throws ParseException {
        AmountParser.parse("asdf123.45");
    }

    @Test(expected = ParseException.class)
    public void withGarbageAtTheEnd_shouldFailWithException() throws ParseException {
        AmountParser.parse("123.45asdf");
    }

    @Test(expected = ParseException.class)
    public void emptyString_shouldFailWithException() throws ParseException {
        AmountParser.parse("");
    }
}

Add test case for AmountParser.


package com.ibm.watson.developer_cloud.service;

import com.ibm.watson.developer_cloud.WatsonServiceUnitTest;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.http.RequestBuilder;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.service.model.GenericModel;
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class HeadersTest extends WatsonServiceUnitTest {

  public class TestModel extends GenericModel { }

  public class TestService extends WatsonService {

    private static final String SERVICE_NAME = "test";

    public TestService() {
      super(SERVICE_NAME);
    }

    public ServiceCall<TestModel> testMethod() {
      RequestBuilder builder = RequestBuilder.get(HttpUrl.parse(getEndPoint() + "/v1/test"));
      return createServiceCall(builder.build(), ResponseConverterUtils.getObject(TestModel.class));
    }
  }

  TestService service;

  /*
   * (non-Javadoc)
   *
   * @see com.ibm.watson.developer_cloud.WatsonServiceTest#setUp()
   */
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    service = new TestService();
    service.setApiKey("");
    service.setEndPoint(getMockWebServerUrl());
  }

  @Test
  public void testAddHeader() throws InterruptedException {
    server.enqueue(new MockResponse()
        .addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON)
        .setBody("{\"test_key\": \"test_value\"}"));

    String headerName = "X-Test";
    TestModel response = service.testMethod()
        .addHeader(headerName, "test")
        .execute();
    final RecordedRequest request = server.takeRequest();
    assertTrue(request.getHeader(headerName) != null);
  }
}

Add unit test for adding headers


package sfBugs;

public class Bug1926389 {
	public int avg(int i, int j, int[] elts) {
		int k = (i+j)/2;
		System.out.println(k);
		return elts[k];
	}
}

Test case for [ 1926389 ] Wrong line number printed/highlighted in bug.


/*
 * Copyright 2011 The Netty Project
 *
 * The Netty Project 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.
 */

/**
 * Internal-use-only utilities which is not allowed to be used
 * outside Netty.
 */
package org.jboss.netty.util.internal.jzlib;

Add missing file for checkstyle plugin fix


package com.yammer.stresstime.entities;

import com.yammer.stresstime.managers.AssignableDayManager;
import com.yammer.stresstime.managers.GroupManager;
import com.yammer.stresstime.test.DatabaseTest;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

public class AssignableDayTest extends DatabaseTest {

    private AssignableDayManager mAssignableDayManager;
    private GroupManager mGroupManager;
    private Group mGroup;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        mAssignableDayManager = new AssignableDayManager(getSessionFactory());
        mGroupManager = new GroupManager(getSessionFactory());
        mGroup = mGroupManager.random();
    }

    @Test
    public void testDateFieldEqualityIsTimeAgnostic() {
        AssignableDay day = new AssignableDay();
        day.setDate(new LocalDate(1985, 2, 24));

        assertThat(day.getDate(), equalTo(new LocalDate(1985, 2, 24)));
        assertThat(day.getDate(), equalTo(new LocalDateTime(1985, 2, 24, 2, 30).toLocalDate()));

        day.setGroup(mGroup);
        mAssignableDayManager.save(day);
        refresh(day);

        assertThat(day.getDate(), equalTo(new LocalDate(1985, 2, 24)));
        assertThat(day.getDate(), equalTo(new LocalDateTime(1985, 2, 24, 1, 15).toLocalDate()));

        mAssignableDayManager.delete(day);
    }
}

Add test for AssignableDay entity


//pcckage com.hotye.dchaoxiong.serializabletest;

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;

    public class SerializeBox implements Serializable {
        /**
 *          *
 *                   */
        private static final long serialVersionUID = 1L;
        private int width;
        private int height;
        private String name;

        public static void main(String[] args) {

            try {
                SerializeBox myBox = new SerializeBox();
                myBox.setWidth(50);
                myBox.setHeight(30);
                myBox.setName("雕戈");

                FileOutputStream fs = new FileOutputStream("serializableObject.txt");
                ObjectOutputStream os = new ObjectOutputStream(fs);
                os.writeObject(myBox);
                os.close();
                fs.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            try {
                FileInputStream fis = new FileInputStream("serializableObject.txt");
                ObjectInputStream ois = new ObjectInputStream(fis);
                SerializeBox box = (SerializeBox) ois.readObject();
                System.out.println(box.getWidth());
                System.out.println(box.getHeight());
                System.out.println(box.getName());
                ois.close();
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getHeight() {
            return height;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getWidth() {
            return width;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

    }

Rename the serialization java file name


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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.esoco.process;

import de.esoco.process.step.InteractionFragment;

import java.util.Collection;

import org.obrel.core.RelationType;

/********************************************************************
 * A parameter wrapper with additional functions for enum values.
 *
 * @author eso
 */
public class EnumParameter<E extends Enum<E>>
	extends ParameterBase<E, EnumParameter<E>>
{
	//~ Constructors -----------------------------------------------------------

	/***************************************
	 * {@inheritDoc}
	 */
	public EnumParameter(
		InteractionFragment rFragment,
		RelationType<E>		rParamType)
	{
		super(rFragment, rParamType);
	}

	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * Disables certain values of the parameter enum.
	 *
	 * @param  rDisabledElements The elements to disable
	 *
	 * @return This parameter instance
	 */
	@SuppressWarnings("unchecked")
	public EnumParameter<E> disable(E... rDisabledElements)
	{
		fragment().disableElements(type(), rDisabledElements);

		return this;
	}

	/***************************************
	 * Disables certain values of the parameter enum.
	 *
	 * @param  rDisabledElements A collection of the elements to disable
	 *
	 * @return This parameter instance
	 */
	public EnumParameter<E> disable(Collection<E> rDisabledElements)
	{
		fragment().disableElements(type(), rDisabledElements);

		return this;
	}

	/***************************************
	 * Enables all enum values.
	 *
	 * @return This parameter instance
	 */
	public EnumParameter<E> enableAll()
	{
		return disable();
	}
}

Add support for arbitrary client events


class NewThread implements Runnable {
    public NewThread(String name) {
        this.name = name;
        thread = new Thread(this, this.name);
        System.out.println("New thread: " + thread);
        thread.start();
    }

    // [Runnable] interface implementation
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println(name + ": " + i);
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e) {
            System.out.println(name + " was interrupted.");
        }
        System.out.println(name + " exiting.");
    }

    private String name;
    private Thread thread;
}

class MultiThreadDemo {
    public static void main(String args[]) {
        new NewThread("One");
        new NewThread("Two");
        new NewThread("Three");

        try {
            Thread.sleep(10000);
        }
        catch (InterruptedException e) {
            System.out.println("main thread was interrupted.");
        }
        System.out.println("exiting the main thread.");
    }
}

Add some code about creating multiple threads


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

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

import static org.junit.Assert.assertEquals;

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

  private BitsToTransform bitsToTransform;

  @Before public void setUp() {
    bitsToTransform = new BitsToTransform();
  }

  @Test public void shouldReturnZeroIfBothNumbersAreEquals() {
    int numA = 7;
    int numB = 7;

    int numberOfDifferentBits = bitsToTransform.calculate(numA, numB);

    assertEquals(0, numberOfDifferentBits);
  }

  @Test public void shouldClaculateHappyCase() {
    int numA = 5; // 101
    int numB = 1; // 001

    int numberOfDifferentBits = bitsToTransform.calculate(numA, numB);

    assertEquals(1, numberOfDifferentBits);
  }

  @Test public void shouldReturnTheNumberOfDifferentBitsWhenNumAIsLower() {
    int numA = 78; // 1001110
    int numB = 99; // 1100011

    int numberOfDifferentBits = bitsToTransform.calculate(numA, numB);

    assertEquals(4, numberOfDifferentBits);
  }

  @Test public void shouldReturnTheNumberOfDifferentBitsWhenNumAIsGreater() {
    int numA = 99; // 1100011
    int numB = 78; // 1001110

    int numberOfDifferentBits = bitsToTransform.calculate(numA, numB);

    assertEquals(4, numberOfDifferentBits);
  }
}

Add some tests to problem 69


package test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import P.A2;
import P.B2;

public class AssociationTests {

	@Test
	public void test() {

		A2 a2 = new A2();
		a2.linkB2 = new B2Mock();

		assertEquals(20, a2.getSummationOfVar1andVar2());
	}

	public class B2Mock extends B2 {
		public int getbVar1() {
			return 10;
		}

		public int getbVar2() {
			return 10;
		}
	}

}

Add association's relation test case


package leetcode.excel_sheet_column_title;

public class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while(n > 0){
        	n--;
        	sb.append((char)('A' + (n % 26)));
        	n /= 26;
        }
        return sb.reverse().toString();
    }
    public static void main(String[] args){
    	System.err.println(new Solution().convertToTitle(704));
    }
}

Add java solution for 168. Excel Sheet Column Title


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is 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.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.policy;

import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.policy.ExecutionResult;
import gov.nasa.arc.mct.policy.Policy;
import gov.nasa.arc.mct.policy.PolicyContext;
import gov.nasa.arc.mct.scenario.component.RepositoryCapability;

public class RepositoryRemovalPolicy implements Policy {

	@Override
	public ExecutionResult execute(PolicyContext context) {
		AbstractComponent parentComponent = context.getProperty(
				PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class);

		String message = "";
		boolean allow = true;

		if (parentComponent != null) {
			RepositoryCapability repo = parentComponent.getCapability(RepositoryCapability.class);
			if (repo != null) {
				allow = false;
				message = "Cannot remove objects from repository (can only delete)";
			}
		}

		return new ExecutionResult(context, allow, message);
	}
}

Add policy to prevent Remove from repositories


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 Jeff Nelson, Cinchapi Software Collective
 *
 * 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.cinchapi.concourse.server.storage;

import java.util.Comparator;

import com.google.common.primitives.Longs;

/**
 * A Comparator that sorts Revisions in a block. The sort order is
 * {@code locator} followed by {@code key} followed by {@code version}.
 *
 * @author jnelson
 */
@SuppressWarnings("rawtypes")
public enum BlockSorter implements Comparator<Revision> {
	INSTANCE;

	/**
	 * Sorts by locator followed by key followed by version.
	 */
	@Override
	@SuppressWarnings("unchecked")
	public int compare(Revision o1, Revision o2) {
		int order;
		return (order = o1.getLocator().compareTo(o2.getLocator())) != 0 ? order
				: ((order = o1.getKey().compareTo(o2.getKey())) != 0 ? order
						: (Longs.compare(o1.getVersion(), o2.getVersion())));
	}

}

Make an enum since only one instance should ever exist


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

package alluxio.worker.netty;

import alluxio.network.protocol.databuffer.DataBuffer;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import javax.annotation.concurrent.ThreadSafe;

/**
 * A listener that will release the given resource when the operation completes. This class accepts
 * null resources.
 */
@ThreadSafe
final class ReleasableResourceChannelListener implements ChannelFutureListener {
  private final DataBuffer mResource;

  /**
   * Creates a new instance of {@link alluxio.worker.netty.ReleasableResourceChannelListener}.
   *
   * @param resource the resource to close
   */
  ReleasableResourceChannelListener(DataBuffer resource) {
    mResource = resource;
  }

  @Override
  public void operationComplete(ChannelFuture future) throws Exception {
    if (mResource != null) {
      mResource.release();
    }
  }
}

Add a releasable resource channel listener.


/*
 * Copyright 2019 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;

import javax.annotation.Nonnull;
import javax.inject.Provider;

/**
 * Intercepts dependency {@link Provider} resolving. Can be used to replace real providers with mocks in tests.
 */
public interface ProviderInterceptor {
  /**
   * This method is called when the {@link Injector} is requested to resolve a {@link Provider} for the given key.
   *
   * @param chain
   *     An interceptor {@link Chain} that contains provision parameters and can be used to proceed with the default resolution.
   * @param key
   *     The {@link Key} to resolve a {@link Provider} for.
   * @return A {@link Provider} that will be returned for the given key.
   */
  @Nonnull
  Provider<?> intercept(@Nonnull Chain chain, @Nonnull Key<?> key);

  interface Chain {
    /** @return The {@link Injector} used to resolve a {@link Provider}. */
    @Nonnull
    Injector injector();

    /**
     * Proceed with the default {@link Provider} resolution.
     *
     * @param key
     *     The {@link Key} to resolve a {@link Provider} for.
     * @return A {@link Provider} that will be returned for the given key.
     */
    @Nonnull
    Provider<?> proceed(@Nonnull Key<?> key);
  }
}

Add an interface for Provider interception


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

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

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

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

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

}

Create single Karaf feature tests for single components, aws-s3 component


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

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

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

public class OnCompletionFailAndOkTest extends ContextTestSupport {

    @Test
    public void testOk() throws Exception {
        getMockEndpoint("mock:ok").expectedMessageCount(1);
        getMockEndpoint("mock:fail").expectedMessageCount(0);
        getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testFail() throws Exception {
        getMockEndpoint("mock:ok").expectedMessageCount(0);
        getMockEndpoint("mock:fail").expectedMessageCount(1);
        getMockEndpoint("mock:result").expectedMessageCount(0);

        try {
            template.sendBody("direct:start", "Kabom");
            fail("Should throw exception");
        } catch (Exception e) {
            // expected
        }

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testOkAndFail() throws Exception {
        getMockEndpoint("mock:ok").expectedBodiesReceived("Bye World");
        getMockEndpoint("mock:fail").expectedBodiesReceived("Kabom");
        getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");

        template.sendBody("direct:start", "Hello World");
        try {
            template.sendBody("direct:start", "Kabom");
            fail("Should throw exception");
        } catch (Exception e) {
            // expected
        }

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .onCompletion()
                        .choice()
                            .when(e -> e.getProperty(Exchange.EXCEPTION_CAUGHT) != null)
                                .to("log:fail").to("mock:fail")
                            .otherwise()
                                .to("log:ok").to("mock:ok")
                        .end()
                    .end()
                    .process(new OnCompletionTest.MyProcessor())
                    .to("mock:result");
            }
        };
    }

}

Add unit test based on user forum issue


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

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

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

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

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

}

Create single Karaf feature tests for single components, aws-sns test


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

import java.io.IOException;

/**
 * For sharing between the local and remote block reader implementations.
 */
class BlockReaderUtil {

  /* See {@link BlockReader#readAll(byte[], int, int)} */
  public static int readAll(BlockReader reader,
      byte[] buf, int offset, int len) throws IOException {
    int n = 0;
    for (;;) {
      int nread = reader.read(buf, offset + n, len - n);
      if (nread <= 0)
        return (n == 0) ? nread : n;
      n += nread;
      if (n >= len)
        return n;
    }
  }

  /* See {@link BlockReader#readFully(byte[], int, int)} */
  public static void readFully(BlockReader reader,
      byte[] buf, int off, int len) throws IOException {
    int toRead = len;
    while (toRead > 0) {
      int ret = reader.read(buf, off, toRead);
      if (ret < 0) {
        throw new IOException("Premature EOF from inputStream");
      }
      toRead -= ret;
      off += ret;
    }
  }
}

Add missing file to previous commit.


package ru.ifmo.nds.rundb.tests;

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

import ru.ifmo.nds.IdCollection;

public class IdCollectionTests {
    @Test
    public void idCollectionConstructs() {
        Assert.assertTrue(IdCollection.getAllDatasetIds().size() > 0);
    }
}

Add a smoke test for IdCollection.


/*
 * Copyright 2011 Splunk, 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.
 */

// parse
// typeahead
// timeparser
// jobs.create
//  - result kinds
//

package com.splunk;

import com.splunk.http.HTTPException;
import com.splunk.http.ResponseMessage;
import com.splunk.sdk.Command;

import junit.framework.TestCase;
import org.junit.*;

public class SearchTest extends TestCase {
    Command command;

    public SearchTest() {}

    Service connect() {
        return Service.connect(command.opts);
    }

    @Before public void setUp() {
        command = Command.splunk(); // Pick up .splunkrc settings
    }

    @Test public void testParse() {
        Args parseArgs;
        ResponseMessage response;

        Service service = connect();

        String query = "search index=sdk-test * | head 1";

        // Check simple parse.
        response = service.parse(query);
        assertEquals(response.getStatus(), 200);

        // Check parse with parse_only argument.
        parseArgs = new Args("parse_only", true);
        service.parse(query, parseArgs);
        assertEquals(response.getStatus(), 200);

        // Check parse with multiple arguments.
        parseArgs = new Args();
        parseArgs.put("parse_only", false);
        parseArgs.put("output_mode", "json");
        parseArgs.put("enable_lookups", true);
        parseArgs.put("reload_macros", true);
        service.parse(query, parseArgs);
        assertEquals(response.getStatus(), 200);
    }

    @Test public void testParseFail() {
        Service service = connect();

        String query = "syntax-error";

        // Check for parse error.
        try {
            service.parse(query);
            fail("Expected a parse error");
        }
        catch (HTTPException e) {
            assertEquals(e.getStatus(), 400);
        }

        // Check for parse error with args.
        try {
            Args parseArgs = new Args();
            parseArgs.put("parse_only", false);
            parseArgs.put("output_mode", "json");
            parseArgs.put("enable_lookups", true);
            parseArgs.put("reload_macros", true);
            service.parse(query, parseArgs);
            fail("Expected a parse error");
        }
        catch (HTTPException e) {
            assertEquals(e.getStatus(), 400);
        }

        // Check for argument error.
        try {
            Args parseArgs = new Args("babble", 42);
            service.parse(query, parseArgs);
        }
        catch (HTTPException e) {
            assertEquals(e.getStatus(), 400);
        }
    }
}

Add unit tests for Searvice.parse


package org.xtext.example.mydsl.plugin;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

public class NewWizard extends Wizard implements INewWizard {

	public NewWizard() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean performFinish() {
		// TODO Auto-generated method stub
		return false;
	}

}

Add New Wizard (really, this time ...)


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

/* $Id$ */

package org.apache.fop.render.ps;

import java.util.List;

import org.apache.fop.render.gradient.Function;
import org.apache.fop.render.gradient.Function.SubFunctionRenderer;
import org.apache.fop.render.gradient.GradientMaker.DoubleFormatter;
import org.apache.fop.render.gradient.Pattern;
import org.apache.fop.render.gradient.Shading;

/**
 * Helper class to draw gradients in PostScript.
 */
public final class Gradient {

    private Gradient() { }

    public static String outputPattern(Pattern pattern, DoubleFormatter doubleFormatter) {
        StringBuilder p = new StringBuilder(64);
        p.append("/Pattern setcolorspace\n");
        p.append("<< \n/Type /Pattern \n");

        p.append("/PatternType " + pattern.getPatternType() + " \n");

        if (pattern.getShading() != null) {
            p.append("/Shading ");
            outputShading(p, pattern.getShading(), doubleFormatter);
            p.append(" \n");
        }
        p.append(">> \n");
        List<Double> matrix = pattern.getMatrix();
        if (matrix == null) {
            p.append("matrix ");
        } else {
            p.append("[ ");
            for (double m : pattern.getMatrix()) {
                p.append(doubleFormatter.formatDouble(m));
                p.append(" ");
            }
            p.append("] ");
        }
        p.append("makepattern setcolor\n");

        return p.toString();
    }

    private static void outputShading(StringBuilder out, Shading shading, final DoubleFormatter doubleFormatter) {
        final Function function = shading.getFunction();
        Shading.FunctionRenderer functionRenderer = new Shading.FunctionRenderer() {

            public void outputFunction(StringBuilder out) {
                SubFunctionRenderer subFunctionRenderer = new Function.SubFunctionRenderer() {

                    public void outputFunction(StringBuilder out, int functionIndex) {
                        Function subFunction = function.getFunctions().get(functionIndex);
                        assert subFunction.getFunctions().isEmpty();
                        subFunction.output(out, doubleFormatter, null);
                    }
                };
                function.output(out, doubleFormatter, subFunctionRenderer);
            }
        };
        shading.output(out, doubleFormatter, functionRenderer);
    }

}

Support PDF shading to PS


/*
 * Copyright (c) 2015 Inocybe and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.neutron.spi.NeutronSubnet;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;

/**
 * Unit test fort {@link SubnetHandler}
 */
@RunWith(MockitoJUnitRunner.class)
public class SubnetHandlerTest {

    @InjectMocks private SubnetHandler subnetHandler;

    @Mock NeutronL3Adapter neutronl3Adapter;

    @Test
    public void testCanCreateSubnet() {
        assertEquals("Error, canCreateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canCreateSubnet(mock(NeutronSubnet.class)));
    }

    @Test
    public void testCanUpdateSubnet() {
        assertEquals("Error, canUpdateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canUpdateSubnet(mock(NeutronSubnet.class), mock(NeutronSubnet.class)));
    }

    @Test
    public void testCanDeleteSubnet() {
        assertEquals("Error, canDeleteSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canDeleteSubnet(mock(NeutronSubnet.class)));
    }

    @Test
    public void testProcessEvent() {
        NorthboundEvent ev = mock(NorthboundEvent.class);
        when(ev.getSubnet()).thenReturn(mock(NeutronSubnet.class));

        when(ev.getAction()).thenReturn(Action.ADD);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.DELETE);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.UPDATE);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;
    }
}

Add JUnit testing for SubnetHandler class.


package arez.integration.dagger.codegen;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.InjectMode;
import arez.annotations.PerInstance;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import org.testng.annotations.Test;

public class ReactComponentIntegrationTest
  extends AbstractCodegenIntegrationTest
{
  static class MyDependency
  {
    @Inject
    MyDependency()
    {
    }
  }

  static abstract class Component
  {
  }

  static abstract class BasicReactComponent
    extends Component
  {
    @Inject
    String someParam;
  }

  @ArezComponent( disposeTrackable = Feature.DISABLE, allowEmpty = true, inject = InjectMode.CONSUME, dagger = Feature.ENABLE )
  static abstract class React4j_BasicReactComponent
    extends BasicReactComponent
  {
    React4j_BasicReactComponent( @Nonnull @PerInstance final String someValue )
    {
    }
  }

  @Test
  public void scenario()
    throws Exception
  {
    assertClassPresent( "ReactComponentIntegrationTest_Arez_React4j_BasicReactComponent" );
    assertClassNotPresent( "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerModule" );
    assertClassNotPresent( "ReactComponentIntegrationTest_Arez_React4j_BasicReactComponent$Enhancer" );
    assertClassPresent( "ReactComponentIntegrationTest_Arez_React4j_BasicReactComponent$Factory" );
    assertClassPresent( "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerComponentExtension" );
    assertClassPresent(
      "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerComponentExtension$InjectSupport" );
    assertClassNotPresent(
      "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerComponentExtension$DaggerModule" );
    assertClassNotPresent(
      "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerComponentExtension$EnhancerDaggerModule" );
    assertClassPresent(
      "ReactComponentIntegrationTest_React4j_BasicReactComponentDaggerComponentExtension$DaggerSubcomponent" );
  }
}

Add test that covers failing scenario present react project


package de.springbootbuch.reactive.watchednow;

import java.util.concurrent.CountDownLatch;
import static org.springframework.http.HttpMethod.GET;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.HandlerFunction;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.server.HttpServer;

/**
 * Part of springbootbuch.de.
 *
 * @author Michael J. Simons
 * @author @rotnroll666
 */
public class DemoFunctionalProgrammingModel {
	public static void main(String...a) {

		HandlerFunction<ServerResponse> helloWorld =
			request -> ServerResponse.ok().body(
				Mono.just("Hello, World"), String.class
			);

		RouterFunction<ServerResponse> helloSpringRoute =
			request ->  {
				if(request.method() == GET &&
					request.path().equals("/hellospring")
				) {
					return Mono.just(r ->
						ok().body(
							Mono.just("Functional Spring"),
							String.class
						)
					);
				} else {
					return Mono.empty();
				}
			};

		RouterFunction<ServerResponse> helloWorldRoute =
			RouterFunctions.route(
				GET("/helloworld"), helloWorld);

		RouterFunction routes = helloSpringRoute
			.and(helloWorldRoute);

		HttpHandler httpHandler = RouterFunctions
			.toHttpHandler(routes);
		HttpServer.create(8080)
			.newHandler(new ReactorHttpHandlerAdapter(httpHandler))
			.block();

		CountDownLatch latch = new CountDownLatch(1);
		Thread awaitThread = new Thread(() -> {
			try {
				latch.await();
			} catch (InterruptedException ex) {
			}

		});
		awaitThread.setDaemon(false);
		awaitThread.start();
	}
}

Add introduction to funcitonal model


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

/**
 *
 * @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
 */
public enum WMSServerType {
    CARMENTA_SERVER("carmentaserver"), GEOSERVER("geoserver"),
    MAPSERVER("mapserver"), QGIS("qgis"), UNKNOWN("unknown");

    private final String _value;

    private WMSServerType(String value) {
        _value = value;
    }

    public static WMSServerType fromString(String string) {
        if (CARMENTA_SERVER.toString().equalsIgnoreCase(string)) {
            return CARMENTA_SERVER;
        }
        else if (GEOSERVER.toString().equalsIgnoreCase(string)) {
            return GEOSERVER;
        }
        else if (MAPSERVER.toString().equalsIgnoreCase(string)) {
            return MAPSERVER;
        }
        else if (QGIS.toString().equalsIgnoreCase(string)) {
            return QGIS;
        } else {
            return UNKNOWN;
        }
    }

    @Override
    public String toString() {
        return _value;
    }
}

Add wms server type enumiration.


/**
 *
 */
package mathsquared.resultswizard2;

import org.junit.Test;

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

    /**
     * Test method for {@link mathsquared.resultswizard2.ConnectionDetailsFrame#ConnectionDetailsFrame()}.
     */
    @Test
    public void testConnectionDetailsFrame () {
        ConnectionDetailsFrame cdf = new ConnectionDetailsFrame();
        cdf.call();
    }

}

Add a test harness for ConnectionDetailsFrame (runs and waits)


package org.lodder.subtools.sublibrary.control;

import static org.junit.Assert.assertEquals;

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

public class RomanTest {

  @Before
  public void setUp() throws Exception {}

  @Test
  public void testDecode() {
    assertEquals(Roman.decode("M"), 1000);
    assertEquals(Roman.decode("D"), 500);
    assertEquals(Roman.decode("C"), 100);
    assertEquals(Roman.decode("L"), 50);
    assertEquals(Roman.decode("X"), 10);
    assertEquals(Roman.decode("I"), 1);

    assertEquals(Roman.decode("MI"), 1001);
    assertEquals(Roman.decode("VI"), 6);
    assertEquals(Roman.decode("IV"), 4);
  }

}

Add test for roman class


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("/static/**")
           .addResourceLocations("classpath:/static/")
           .setCacheControl(CacheControl
                   .maxAge(10, TimeUnit.MINUTES)
                   .cachePrivate());
}

Enable cache in http header


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.toscana.model.dao.implementations;

import com.toscana.model.dao.interfaces.ReceiptCashOutDAO;
import com.toscana.model.reports.ReceiptCashOut;

public class ReceiptCashOutDAOImplementation extends GenericDAOImplementation<ReceiptCashOut, Integer> implements ReceiptCashOutDAO {

}

Create DAOS interfaces and implementations


import cloudsimulator.clustersimulator.ClusterManager;
import cloudsimulator.clustersimulator.dto.Cluster;
import org.junit.Test;

public class TestClusterManager {

    @Test
    public void createClusterManager() {
        ClusterManager clusterManager = new ClusterManager();
        Cluster cluster = clusterManager.getCluster();
    }

    @Test
    public void readMaxRps() {
        ClusterManager clusterManager = new ClusterManager();
        long maxRps = clusterManager.computeMaxRps();
        System.out.println("Max rps: " + maxRps);
    }

}

Add unit tests for ClusterManager.


/*
 * 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.beam.sdk.testing;

import org.apache.beam.sdk.transforms.ParDo;

/**
 * Category tag for validation tests which utilize stateful {@link ParDo}.
 */
public interface UsesStatefulParDo {}

Add JUnit category for stateful ParDo tests


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

import com.vladmihalcea.book.hpjp.util.AbstractTest;
import org.junit.Test;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.assertNotNull;

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

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

    @Test
    public void test() {
        doInJPA(entityManager -> {
            for (int i = 0; i < 3; i++) {
                Post post = new Post(String.format("Post nr. %d", i));
                post.setDetails(new PostDetails("Excellent!"));

                entityManager.persist(post);
            }
        });

        doInJPA(entityManager -> {
            List<Post> posts = entityManager.createQuery(
                "select p from Post p " +
                "where p.title like 'Post nr.%'", Post.class)
            .getResultList();
        });
    }

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

        @Id
        @GeneratedValue
        private Long id;

        private String title;

        @OneToOne(mappedBy = "post", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        private PostDetails details;

        public Post() {}

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

        public Long getId() {
            return id;
        }

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

        public String getTitle() {
            return title;
        }

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

        public PostDetails getDetails() {
            return details;
        }

        public void setDetails(PostDetails details) {
            this.details = details;
            details.setPost(this);
        }
    }

    @Entity(name = "PostDetails")
    @Table(name = "post_details")
    public static class PostDetails {

        @Id
        @GeneratedValue
        private Long id;

        @Column(name = "created_on")
        private Date createdOn;

        @Column(name = "created_by")
        private String createdBy;

        @OneToOne(fetch = FetchType.LAZY)
        @MapsId
        private Post post;

        public PostDetails() {}

        public PostDetails(String createdBy) {
            createdOn = new Date();
            this.createdBy = createdBy;
        }

        public Long getId() {
            return id;
        }

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

        public Date getCreatedOn() {
            return createdOn;
        }

        public String getCreatedBy() {
            return createdBy;
        }

        public Post getPost() {
            return post;
        }

        public void setPost(Post post) {
            this.post = post;
        }
    }
}

Add @OneToOne N+1 query issue test


package com.epam.cdp.jee.todo.servlet.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import lombok.extern.slf4j.Slf4j;

@WebListener
@Slf4j
public class RequestsListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(final ServletRequestEvent servletRequestEvent) {
        log.info("Request was destroyed {}", servletRequestEvent.getServletRequest().getParameterMap());
    }

    @Override
    public void requestInitialized(final ServletRequestEvent servletRequestEvent) {
        log.info("Request initialised {}", servletRequestEvent.getServletRequest().getParameterMap());
    }
}

Add basic implementation for ServletListener


package com.example.georgekaraolanis.project7_booklistingapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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

public class BookAdapter extends ArrayAdapter<Book> {

    /*Constructor*/
    public BookAdapter(Context context,List<Book> books){
        super(context,0,books);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        /*Get view and check if it is being reused*/
        View listItemView = convertView;
        if (listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(
            R.layout.list_item,parent,false);
        }

        /*Get book at specified position*/
        Book currentBook = getItem(position);

        /*Get references to views*/
        ImageView thumbnail = (ImageView) listItemView.findViewById(R.id.thumbnail);
        TextView titleTextView = (TextView) listItemView.findViewById(R.id.title);
        TextView authorsTextView = (TextView) listItemView.findViewById(R.id.authors);

        /*Set data in those views*/
        thumbnail.setImageBitmap(currentBook.getThumbnail());
        titleTextView.setText(currentBook.getTitle());

        /*Because a book can have multiple authors, they will be separated with commas*/
        ArrayList<String> authors = currentBook.getAuthors();
        int numAuthors = authors.size();

        /*If there is one author display his name, else process their names*/
        if(numAuthors == 1){
            authorsTextView.setText(authors.get(0));
        }
        else{

            /*First author name is used to initialize StringBuilder*/
            StringBuilder authorsText = new StringBuilder(authors.get(0));

            /*Start from second author*/
            for(int i = 1; i < numAuthors; i++){
                authorsText.append(", " + authors.get(i));
            }

            /*When finished set text in TextView*/
            authorsTextView.setText(authorsText.toString());

        }

        return listItemView;
    }

}

Add ArrayAdapter for Book objects


/**
 * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.mockwire.guice2;

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

import net.stickycode.mockwire.MockwireTck;

@RunWith(Suite.class)
@SuiteClasses({
  MockwireTck.class
})
public class MockwireTckTest {

}

/**
 * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.mockwire.guice2;

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

import net.stickycode.mockwire.MockwireTck;
import net.stickycode.mockwire.direct.MockwireDirectTck;
import net.stickycode.mockwire.junit4.MockwireRunnerTck;

@RunWith(Suite.class)
@SuiteClasses({
  MockwireTck.class,
  MockwireDirectTck.class,
  MockwireRunnerTck.class
})
public class MockwireTckTest {

}

Add two more test suites, pending containment and configuration.


package colector.co.com.collector.listeners;

import android.widget.LinearLayout;

import colector.co.com.collector.views.PhotoItemView;
import colector.co.com.collector.views.PhotoItemViewContainer;
import colector.co.com.collector.views.SignatureItemViewContainer;

/**
 * @author Gabriel Rodriguez
 * @version 1.0
 */

public interface OnAddSignatureListener {

    void onAddSignatureClicked(SignatureItemViewContainer container);
}

Add listener to notify when the button to add a signature has been pressed


import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.OnTimer;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static com.sun.btrace.BTraceUtils.Atomic.incrementAndGet;
import static com.sun.btrace.BTraceUtils.Atomic.newAtomicInteger;
import static com.sun.btrace.BTraceUtils.Collections.*;
import static com.sun.btrace.BTraceUtils.jstackStr;
import static com.sun.btrace.BTraceUtils.printNumberMap;

@BTrace
public class PatternSetCreation {
    private static Map<String, AtomicInteger> histo = newHashMap();

    @OnMethod(
            clazz = "org.gradle.api.tasks.util.PatternSet",
            method = "<init>"
    )
    public static void onPatternSetInit() {
        String stackTrace = jstackStr(6);
        AtomicInteger counter = get(histo, stackTrace);
        if (counter == null) {
            counter = newAtomicInteger(1);
            put(histo, stackTrace, counter);
        } else {
            incrementAndGet(counter);
        }
    }

    @OnTimer(5000)
    public static void print() {
        if (size(histo) != 0) {
            printNumberMap("\n\nStacktrace Histogram for 'new PatternSet()'", histo);
        }
    }
}

Add probe for PatternSet creation


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

package tachyon.client.keyvalue;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

import tachyon.Constants;

/**
 * Writer to create a KeyValue file.
 */
public final class KeyValueFileReaderImpl implements KeyValueFileReader {
  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);

  public KeyValueFileReaderImpl(List<Long> blockIds) {
    // For now, only 1 block is allowed.
    Preconditions.checkArgument(blockIds.size() == 1);

  }

  /**
   * {@inheritDoc}
   */
  @Override
  public byte[] get(byte[] key) {
    LOG.trace("get key");

    return null;
  }
}

Add an incomplete impl of KeyValueFileReader


package classes.test;

/*
 * Verify that calling wait() does not cause other threads to wake up without
 * receiving notify().
 */
class WaitTest {

  static Object obj = new Object();

  static class Foo implements Runnable {
    Thread thread;

    Foo() {
      thread = new Thread(this);
      thread.start();
    }

    public void run() {
      synchronized(obj) {
        try {
          obj.wait();
        }
        catch (InterruptedException e) {
          System.out.println("Interrupted");
          return;
        }
        System.out.println("Not interrupted");
      }
    }
  }

  public static void main(String[] args) {
    Foo a = new Foo();
    Foo b = new Foo();
    try {
      Thread.currentThread().sleep(100);
    }
    catch (InterruptedException e) {}
    if (a.thread.isAlive()) a.thread.interrupt();
    if (b.thread.isAlive()) b.thread.interrupt();
  }

}

Add failing test for wait().


package net.restlesscoder.sandbox;

public class TriLambda {

	@FunctionalInterface
	public interface TernaryFunction {
		String apply(String a, String b, String c);
	}

	public static void main(final String... args) throws Exception {
		process((a, b, c) -> a + " " + b + " " + c);
		process((a, b, c) -> a + "|" + b + "|" + c);
	}

	private static void process(TernaryFunction f) {
		final String[][] args = {
			{"happy", "birthday", "!"},
			{"good", "night", "moon"}
		};
		for (final String[] arg : args) {
			System.out.println(f.apply(arg[0], arg[1], arg[2]));
		}
	}
}

Add a quick test of three-argument lambda


/*
Copyright 2010 WebDriver committers
Copyright 2010 Google Inc.
Portions copyright 2011 Software Freedom Conservatory

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.openqa.selenium.android.environment;

import org.openqa.selenium.environment.TestEnvironment;
import org.openqa.selenium.environment.webserver.AppServer;
import org.openqa.selenium.environment.webserver.Jetty7AppServer;

public class AndroidTestEnvironment implements TestEnvironment {
  private AppServer appServer;

  public AndroidTestEnvironment() {
    appServer = new Jetty7AppServer("10.0.2.2");
    appServer.start();
  }

  public AppServer getAppServer() {
    return appServer;
  }

  public void stop() {
    appServer.stop();
  }

  public static void main(String[] args) {
    new AndroidTestEnvironment();
  }
}

/*
Copyright 2010 WebDriver committers
Copyright 2010 Google Inc.
Portions copyright 2011 Software Freedom Conservatory

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.openqa.selenium.android.environment;

import org.openqa.selenium.environment.TestEnvironment;
import org.openqa.selenium.environment.webserver.AppServer;
import org.openqa.selenium.environment.webserver.Jetty7AppServer;

public class AndroidTestEnvironment implements TestEnvironment {
  private AppServer appServer;
  // In order to run the tests on a real device, the device and the host
  // running the tests must be on the same network. This variable should
  // contain the externally-visible IP of the host.
  private static String ANDROID_HOST_IP = "ANDROID_HTTP_HOST";

  public AndroidTestEnvironment() {
    String servingHost = System.getenv(ANDROID_HOST_IP);
    if (servingHost == null) {
      servingHost = "10.0.2.2";
    }
    appServer = new Jetty7AppServer(servingHost);
    appServer.start();
  }

  public AppServer getAppServer() {
    return appServer;
  }

  public void stop() {
    appServer.stop();
  }

  public static void main(String[] args) {
    new AndroidTestEnvironment();
  }
}

Allow running the Android tests on a real device by specifying the external IP of the in-process test server.


package voldemort.utils;

import voldemort.annotations.concurrency.Threadsafe;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;

@Threadsafe
public class CachedCallable<T> implements Callable<T> {

    private final Callable<T> inner;
    private final long ttlMs;
    private final AtomicReference<T> valueRef;

    private volatile long lastCalledMs;

    public CachedCallable(Callable<T> inner,
                          long ttlMs) {
        this.inner = inner;
        this.ttlMs = ttlMs;
        valueRef = new AtomicReference<T>();
    }

    public T call() throws Exception {
        T value = valueRef.get();
        long now = System.currentTimeMillis();
        if(value == null || now - lastCalledMs > ttlMs) {
            T newValue = inner.call();
            if(valueRef.compareAndSet(value, newValue)) {
                lastCalledMs = now;
                return newValue;
            }
        }
        return valueRef.get();
    }
}

Create a cached callable for caching expensive stats


/*
 * #%L
 * SciJava UI components for Java Swing.
 * %%
 * Copyright (C) 2010 - 2017 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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 org.scijava.ui.swing;

import org.scijava.Context;
import org.scijava.ui.UIService;

/**
 * Shows the SciJava Swing UI.
 *
 * @author Curtis Rueden
 */
public class Main {

	public static void main(String[] args) {
		final Context context = new Context();
		context.service(UIService.class).showUI(SwingUI.NAME);
	}
}

Add a main method to launch the SciJava Swing UI


/****************************************************************
 * 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.james.transport.camel;

import org.apache.camel.Header;

/**
 * Delayer which use a Header called NEXT_DELIVERY which contains a long value which represent the Date
 * in milliseconds till which the processing of the next Processor should be delayed
 *
 *
 */
public class MailDeliveryDelayer {

    /**
     * Header to use for storing the date till the processing should be delayed (in milliseconds)
     */
    public final static String NEXT_DELIVERY ="NEXT_DELIVERY";

    /**
     * Return the time in milliseconds which should the execution of the next processor get delayed
     *
     * @param nextDelivery
     * @return millisToSleep
     */
    public long delay(@Header(NEXT_DELIVERY) long nextDelivery) {
        long sleepTime = nextDelivery - System.currentTimeMillis();

        // check if we should trigger the next processor now
        if (sleepTime < 0) {
            sleepTime = 0;
        }
        return sleepTime;
    }

}

Add delayer for computing the time to sleep before try to deliver the message again. See JAMES-977


package com.orgsync.api.integration;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.AfterClass;
import org.junit.Test;

import com.orgsync.api.MembershipLogsResource;
import com.orgsync.api.Resources;
import com.orgsync.api.model.membership_logs.MembershipLogEntry;
import com.orgsync.api.model.membership_logs.MembershipLogEntryRequest;
import com.typesafe.config.Config;

public class MembershipLogsIntergrationTest extends BaseIntegrationTest<MembershipLogsResource> {

    public MembershipLogsIntergrationTest() {
        super(Resources.MEMBERSHIP_LOGS);
    }

    @AfterClass
    public static void cleanup() {
        BaseIntegrationTest.cleanup(Resources.MEMBERSHIP_LOGS);
    }

    @Test
    public void testGetMembershipLogEntries() throws Exception {
        List<MembershipLogEntry> result = getResult(getResource().getLogEntries(new MembershipLogEntryRequest()));

        assertEquals(2, result.size());
    }

    @Test
    public void testGetMembershipLogForAcount() throws Exception {
        Config userConfig = DbTemplate.getList("users").get(0);
        Config portalConfig = DbTemplate.getList("portals").get(0);

        List<MembershipLogEntry> result = getResult(getResource().getLogEntries(
                new MembershipLogEntryRequest().setAccountId(userConfig.getInt("id"))));

        assertEquals(1, result.size());

        MembershipLogEntry entry = result.get(0);
        assertEquals("Join", entry.getAction());
        assertEquals(userConfig.getInt("id"), entry.getAccountId());
        assertEquals(portalConfig.getInt("id"), entry.getOrgId());
    }

}

Add integration tests for the org membership log entries.


package org.apache.helix.integration.task;

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

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

public class TestRetrieveWorkflows extends TaskTestBase {
  @Test
  public void testGetAllWorkflows() throws Exception {
    List<Workflow> workflowList = new ArrayList<Workflow>();
    for (int i = 0; i < 4; i++) {
      Workflow workflow = WorkflowGenerator.generateDefaultRepeatedJobWorkflowBuilder(TestHelper.getTestMethodName() + i).build();
      _driver.start(workflow);
      workflowList.add(workflow);
    }

    for (Workflow workflow : workflowList) {
      //TaskTestUtil.pollForWorkflowState(_driver, workflow.getName(), TaskState.COMPLETED);
    }

    _manager = HelixManagerFactory
        .getZKHelixManager("ESPRESSO_TEST_NUAGE", "Admin", InstanceType.ADMINISTRATOR, "zk-ei1-espresso.stg.linkedin.com:12913");
    _manager.connect();
    TaskDriver taskDriver = new TaskDriver(_manager);

    Map<String, WorkflowConfig> workflowConfigMap = taskDriver.getWorkflows();
    Assert.assertEquals(workflowConfigMap.size(), workflowList.size());

    for(Map.Entry<String, WorkflowConfig> workflow :  workflowConfigMap.entrySet()) {
      WorkflowConfig workflowConfig = workflow.getValue();
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflow.getKey());
      Assert.assertNotNull(workflowContext);

      for(String job : workflowConfig.getJobDag().getAllNodes()) {
        JobConfig jobConfig = _driver.getJobConfig(job);
        JobContext jobContext = _driver.getJobContext(job);

        Assert.assertNotNull(jobConfig);
        Assert.assertNotNull(jobContext);
      }
    }
  }
}

Add unit test to retrieve workflow and job configurations.


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

import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.assertNull;

@Ignore
public class UpdateLimitTest {

    @Rule
    public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();

    private DocumentNodeStore ns;
    private DocumentStore store;
    private String testId;

    @Before
    public void before() {
        ns = builderProvider.newBuilder().getNodeStore();
        store = ns.getDocumentStore();
        testId = Utils.getIdFromPath("/test");
    }

    @Test
    public void rebase() throws Exception {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.rebase(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    @Test
    public void reset() {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.reset(builder);
            someChanges(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    private NodeBuilder someChanges(NodeBuilder root) {
        NodeBuilder test = root.child("test");
        for (int i = 0; i < 23; i++) {
            test.child("node-" + i);
        }
        return root;
    }
}

Update count increases with rebase


package binarytrees;

import common.Pair;

/**
 * Given a binary tree, convert it into a singly linked list. The "next" pointer
 * in each node of the list is defined using the "right" pointer in the binary
 * tree. The order of nodes in the linked list is the same order that occurs in
 * the inorder representation of the binary tree. Also the solution must set all
 * "left" pointers in each node to null.
 */
public class TreeConvertToSinglyLinkedList {
	public static TreeNode<Integer> convertToSinglyLinkedList(
			TreeNode<Integer> root) {
		return doConnectInorder(root).getFirst();
	}

	private static Pair<TreeNode<Integer>, TreeNode<Integer>> doConnectInorder(
			TreeNode<Integer> root) {
		if (root == null) {
			return null;
		}

		Pair<TreeNode<Integer>, TreeNode<Integer>> toReturn = new Pair<TreeNode<Integer>, TreeNode<Integer>>();
		Pair<TreeNode<Integer>, TreeNode<Integer>> leftPair = doConnectInorder(root
				.getLeft());
		if (leftPair != null) {
			leftPair.getSecond().setRight(root);
			toReturn.setFirst(leftPair.getFirst());
		} else {
			toReturn.setFirst(root);
		}

		Pair<TreeNode<Integer>, TreeNode<Integer>> rightPair = doConnectInorder(root
				.getRight());
		if (rightPair != null) {
			root.setRight(rightPair.getFirst());
			toReturn.setSecond(rightPair.getSecond());
		} else {
			toReturn.setSecond(root);
		}

		root.setLeft(null);

		return toReturn;
	}

	public static void main(String[] args) {
		TreeNode<Integer> rootLeftLeft = new TreeNode<Integer>(3);
		TreeNode<Integer> rootLeftRight = new TreeNode<Integer>(5);

		TreeNode<Integer> rootLeft = new TreeNode<Integer>(4);
		rootLeft.setLeft(rootLeftLeft);
		rootLeft.setRight(rootLeftRight);

		TreeNode<Integer> rootRightLeft = new TreeNode<Integer>(7);
		TreeNode<Integer> rootRightRight = new TreeNode<Integer>(9);

		TreeNode<Integer> rootRight = new TreeNode<Integer>(8);
		rootRight.setLeft(rootRightLeft);
		rootRight.setRight(rootRightRight);

		TreeNode<Integer> root = new TreeNode<Integer>(6);
		root.setLeft(rootLeft);
		root.setRight(rootRight);

		root = convertToSinglyLinkedList(root);

		while (root != null) {
			System.out.println(root);
			System.out.println(root.getLeft());
			root = root.getRight();
		}
	}
}

Convert binary tree to singly linked list.


package database;

/**
 * A simple class that calls the database.
 *
 * Created by alex on 9/18/15.
 */

import java.sql.*;
import java.util.ArrayList;

public class Database {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/ProjectX";

    //  Database credentials
    static final String USER = "root";
    static final String PASS = "root";

    //Replace with connection pool if needed.
    private Connection conn;
    private Statement stmt;

    public Database() {
        Connection conn = null;
        Statement stmt = null;
        try {
            //Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //Open a connection
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        }

    }

    /**
     * @return A string with a to tep scoreboard.
     */
    public String getGolbalTopTen() {
        try {
            ResultSet rs = stmt.executeQuery("CALL getGlobalTopTen;");
            StringBuilder sb = new StringBuilder();
            for (int i = 1; rs.next(); i++) {
                sb.append(i + ". ");
                sb.append(rs.getString("nickname"));
                sb.append(" ");
                sb.append(rs.getInt("score"));
                sb.append("\n");
            }
            //Close the statement. TODO: Check if really needed.
            rs.close();
            stmt.close();
            return sb.toString();

        } catch (SQLException e) {
            e.printStackTrace();
            //Well this is not best practices...
            return "";
        }
    }

    public void closeConnection() {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
}

Add small database interface class.


package org.apache.pig.tools.grunt;

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

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.tools.grunt.GruntParser.ExplainState;
import org.junit.Before;
import org.junit.Test;

public class TestGruntParser {
    private GruntParser parser;
    static PigServer pig;

    @Before
    public void setup() throws IOException {
        pig = new PigServer(ExecType.LOCAL);
    }

    @Test
    public void testProcessRemove() throws IOException {
        File tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        String dummyScript = "";
        parser = new GruntParser(new ByteArrayInputStream(dummyScript.getBytes()));
        parser.setParams(pig);

        //Delete existing file and check that it doesn't exist
        parser.processRemove(tmpFile.getAbsolutePath(), "");
        assertFalse(tmpFile.exists());

        //Delete non-existing file and check for exception
        try {
            parser.processRemove(tmpFile.getAbsolutePath(), "");
            fail("processRemove should throw exception when deleting missing file.");
        } catch (IOException e) {
            //Yay
        }

        //Delete non-existing file with force, no exception
        parser.processRemove(tmpFile.getAbsolutePath(), "force");

        //Ensure that remove isn't processed when in explain mode
        tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        parser.setExplainState(new ExplainState("","","",false,""));
        parser.processRemove(tmpFile.getAbsolutePath(), "force");
        assertTrue(tmpFile.exists());
    }
}

Add support for removing s3 files


package fullcodes.session.camelCase;

/**
 * Created by dotcom on 7/7/17.
 */

//Pascal case
public class FootBall {

    private double BallWeight;

    //Pascal case
    public FootBall(double ballWeight) {
        this.BallWeight = ballWeight;
    }

    public void playBallToMe(){
        String ballName = "Black n White";
        System.out.println(ballName);
    }

    //kick The Ball to the net
    public void tickTheBallToTheNet(){

    }

}

Implement of Camel case in IJava


package leetcode._3sum;

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

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
       	Arrays.sort(num);
       	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	int length = num.length;
    	for(int i = 0; i < length; i++){
    		if(i > 0 && num[i] == num[i - 1]) continue;
    		int head = i + 1, tail = length - 1;
    		while(head < tail){
    			int sum = num[i] + num[head] + num[tail];
    			if(sum < 0){
    				head++;
    				while(head < tail && num[head] == num[head - 1]) head++;
    			}else if(sum > 0){
    				tail--;
    				while(head < tail && num[tail] == num[tail + 1]) tail--;
    			}else{
    				ans.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{num[i], num[head], num[tail]})));
    				head++;
    				tail--;
    				while(head < tail && num[head] == num[head - 1]) head++;
    				while(head < tail && num[tail] == num[tail + 1]) tail--;
    			}
    		}
    	}
    	return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> row : new Solution().threeSum(new int[]{-1, -1, -1, -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, -4, -4, -4 , 0, 1, 2, -1, -4,})){
    		for(int x : row){
    			System.err.print(x + " ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 15. 3Sum