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

import com.facebook.presto.tests.AbstractTestDistributedQueries;

import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner;
import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession;
import static io.airlift.tpch.TpchTable.getTables;

public class TestHiveDistributedQueries
        extends AbstractTestDistributedQueries
{
    public TestHiveDistributedQueries()
            throws Exception
    {
        super(createQueryRunner(getTables()), createSampledSession());
    }

    @Override
    public void testDelete()
            throws Exception
    {
        // Hive connector currently does not support delete
    }
}

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

import com.facebook.presto.tests.AbstractTestDistributedQueries;

import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner;
import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession;
import static io.airlift.tpch.TpchTable.getTables;

public class TestHiveDistributedQueries
        extends AbstractTestDistributedQueries
{
    public TestHiveDistributedQueries()
            throws Exception
    {
        super(createQueryRunner(getTables()), createSampledSession());
    }

    @Override
    public void testDelete()
            throws Exception
    {
        // Hive connector currently does not support row-by-row delete
    }

    @Override
    public void testAddColumn()
            throws Exception
    {
        // Hive connector currently does not support schema change
    }

    @Override
    public void testRenameColumn()
            throws Exception
    {
        // Hive connector currently does not support schema change
    }

    @Override
    public void testRenameTable()
            throws Exception
    {
        // Hive connector currently does not support table rename
    }
}

Disable schema change tests in Hive distributed test


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

import android.content.Context;
import android.util.Log;

import com.getpebble.android.kit.PebbleKit;

import ca.joshuatacoma.bluesky.BlueSkyConstants;

public class PebbleAckReceiver extends PebbleKit.PebbleAckReceiver
{
    static final String TAG = "BlueSky";

    public PebbleAckReceiver() {
        super(BlueSkyConstants.APP_UUID);
    }

    @Override
    public void receiveAck(
            Context context,
            int transactionId)
    {
        Log.d(TAG, "receiveAck(" + String.valueOf(transactionId) + ")");
        PebbleState.recordNack(context, transactionId);
    }
};

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

import android.content.Context;
import android.util.Log;

import com.getpebble.android.kit.PebbleKit;

import ca.joshuatacoma.bluesky.BlueSkyConstants;

public class PebbleAckReceiver extends PebbleKit.PebbleAckReceiver
{
    static final String TAG = "BlueSky";

    public PebbleAckReceiver() {
        super(BlueSkyConstants.APP_UUID);
    }

    @Override
    public void receiveAck(
            Context context,
            int transactionId)
    {
        Log.d(TAG, "receiveAck(" + String.valueOf(transactionId) + ")");
        PebbleState.recordAck(context, transactionId);
    }
};

Fix bad typo (doesn't fix bug)


package org.buddycloud.channelserver.pubsub.model.impl;

import nl.jqno.equalsverifier.EqualsVerifier;

import org.junit.Test;

public class NodeAffiliationImplTest {

    @Test
    public void testEquals() {
        EqualsVerifier.forClass(NodeAffiliationImpl.class).verify();
    }

}

package org.buddycloud.channelserver.pubsub.model.impl;

import java.util.Date;

import junit.framework.Assert;
import nl.jqno.equalsverifier.EqualsVerifier;

import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.junit.Test;
import org.xmpp.packet.JID;

public class NodeAffiliationImplTest {

  private String node = "/user/test@example.com/posts";
  private JID fullJid = new JID("test@example.com/resource");

  @Test
  public void testEquals() {
    EqualsVerifier.forClass(NodeAffiliationImpl.class).verify();
  }

  @Test
  public void providingFullJidSetsAsAsBareJid() throws Exception {
    NodeAffiliationImpl affiliation =
        new NodeAffiliationImpl(node, fullJid, Affiliations.member, new Date());
    Assert.assertEquals(fullJid.toBareJID(), affiliation.getUser().toString());
  }

}

Increase coverage of NodeAffiliationImpl to 100%


package org.dummy.load;

/**
 * Created by baardl on 26.07.15.
 */
public class LoadThread implements Runnable {

    private final int sleepMillis;

    public LoadThread(int sleepMillis) {
        this.sleepMillis = sleepMillis;
    }

    @Override
    public void run() {
        do {
            System.out.println("Hello You at " + System.currentTimeMillis());
            try {
                Thread.sleep(sleepMillis);
            } catch (InterruptedException e) {
                //sleep interupted
            }
        } while (true);
    }
}

package org.dummy.load;

/**
 * Created by baardl on 26.07.15.
 */
public class LoadThread implements Runnable {

    private final int sleepMillis;

    public LoadThread(int sleepMillis) {
        this.sleepMillis = sleepMillis;
    }

    @Override
    public void run() {
        do {
            performVisibleLoad();
            try {
                Thread.sleep(sleepMillis);
            } catch (InterruptedException e) {
                //sleep interupted
            }
        } while (true);
    }

    public void performVisibleLoad() {
        System.out.println("Hello You at " + System.currentTimeMillis());
    }
}

Load is picked up by Valuereporter-agent.


package org.alien4cloud.secret.services;

import java.util.List;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import alien4cloud.plugin.AbstractPluginLinker;
import alien4cloud.plugin.model.PluginUsage;
import org.alien4cloud.secret.ISecretProvider;

@Component
public class SecretProviderRegistry extends AbstractPluginLinker<ISecretProvider> {

    @Override
    public List<PluginUsage> usage(String pluginId) {
        // TODO how to determine plugin usage
        return null;
    }
}

package org.alien4cloud.secret.services;

import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.model.orchestrators.locations.Location;
import alien4cloud.model.secret.SecretProviderConfiguration;
import alien4cloud.plugin.AbstractPluginLinker;
import alien4cloud.plugin.model.PluginUsage;
import com.google.common.collect.Lists;
import org.alien4cloud.secret.ISecretProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class SecretProviderRegistry extends AbstractPluginLinker<ISecretProvider> {
    @Resource(name = "alien-es-dao")
    private IGenericSearchDAO alienDAO;

    @Override
    public List<PluginUsage> usage(String pluginId) {
        GetMultipleDataResult<Location> locationData = alienDAO.buildQuery(Location.class).prepareSearch().search(0, Integer.MAX_VALUE);

        List<PluginUsage> usages = Lists.newArrayList();
        for (Location location : locationData.getData()) {
            SecretProviderConfiguration locationSecretProviderConfiguration = location.getSecretProviderConfiguration();
            if (locationSecretProviderConfiguration != null && locationSecretProviderConfiguration.getPluginName().equals(pluginId)) {
                usages.add(new PluginUsage(location.getId(), location.getName(), Location.class.getSimpleName()));

            }
        }

        return usages;
    }
}

Check vault plugins usage before delete/disable it


package de.holisticon.util.tracee.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author Daniel Wegener (Holisticon AG)
 */
public final class TraceePropertiesFileLoader {

	public static final String TRACEE_PROPERTIES_FILE = "tracee.properties";

	public Properties loadTraceeProperties() throws IOException {
		final Properties propertiesFromFile = new Properties();
		final ClassLoader loader = Thread.currentThread().getContextClassLoader();

		final Enumeration<URL> traceePropertyFiles = loader.getResources(TRACEE_PROPERTIES_FILE);

		while (traceePropertyFiles.hasMoreElements()) {
			final URL url = traceePropertyFiles.nextElement();
			InputStream stream = null;
			try {
				stream = url.openStream();
				propertiesFromFile.load(stream);
			} catch (IOException e) {
				throw e;
			} finally {
				try {
					if (stream != null)
						stream.close();
				} catch (IOException ignored) {}
			}
		}

		return propertiesFromFile;
	}

}

package de.holisticon.util.tracee.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author Daniel Wegener (Holisticon AG)
 */
public final class TraceePropertiesFileLoader {

	public static final String TRACEE_PROPERTIES_FILE = "tracee.properties";

	public Properties loadTraceeProperties() throws IOException {
		final Properties propertiesFromFile = new Properties();
		final ClassLoader loader = Thread.currentThread().getContextClassLoader();

		final Enumeration<URL> traceePropertyFiles = loader.getResources(TRACEE_PROPERTIES_FILE);

		while (traceePropertyFiles.hasMoreElements()) {
			final URL url = traceePropertyFiles.nextElement();
			InputStream stream = null;
			try {
				stream = url.openStream();
				propertiesFromFile.load(stream);
			} finally {
				try {
					if (stream != null)
						stream.close();
				} catch (IOException ignored) {}
			}
		}

		return propertiesFromFile;
	}

}

Remove not necessary catch-rethrow because exception is not handled


package io.github.web.springtest;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith({ SeleniumExtension.class, SpringExtension.class })
@SpringBootTest(classes = SpringTestDemoApp.class, webEnvironment = RANDOM_PORT)
public class SpringChromeJupiterTest {

    @LocalServerPort
    int serverPort;

    @Test
    public void test(ChromeDriver driver) {
        // Open system under test
        driver.get("http://localhost:" + serverPort);

        // Verify first page title
        String firstPageTitle = driver.getTitle();
        String expectedFirstPageTitle = "Spring Boot Test - Page 1";
        assertEquals(expectedFirstPageTitle, firstPageTitle);

        // Click on link
        driver.findElement(By.linkText("another")).click();

        // Verify second page caption
        String secondPageCaption = driver.findElement(By.id("caption"))
                .getText();
        String expectedSecondPageTitle = "Other page";
        assertEquals(expectedSecondPageTitle, secondPageCaption);
    }

}

package io.github.web.springtest;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith({ SeleniumExtension.class, SpringExtension.class })
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class SpringChromeJupiterTest {

    @LocalServerPort
    int serverPort;

    @Test
    public void test(ChromeDriver driver) {
        // Open system under test
        driver.get("http://localhost:" + serverPort);

        // Verify first page title
        String firstPageTitle = driver.getTitle();
        String expectedFirstPageTitle = "Spring Boot Test - Page 1";
        assertEquals(expectedFirstPageTitle, firstPageTitle);

        // Click on link
        driver.findElement(By.linkText("another")).click();

        // Verify second page caption
        String secondPageCaption = driver.findElement(By.id("caption"))
                .getText();
        String expectedSecondPageTitle = "Other page";
        assertEquals(expectedSecondPageTitle, secondPageCaption);
    }

}

Remove class in SpringBooTest annotation


package lt.inventi.wicket.component.bootstrap.form;

import org.apache.wicket.util.string.AppendingStringBuffer;

abstract class ChoiceUtils {

    public enum InputPosition {
        BEFORE_LABEL, AFTER_LABEL
    }

    private ChoiceUtils() {
        // static utils
    }

    static void moveInputInsideLabel(AppendingStringBuffer buffer, String cssClass, InputPosition position) {
        int inputIdx = buffer.lastIndexOf("<input");
        if (inputIdx == -1) {
            throw new IllegalStateException("Must contain an input!");
        }
        int labelIdx = buffer.indexOf("<label", inputIdx);
        if (labelIdx == -1) {
            throw new IllegalStateException("Must contain a label!");
        }
        int labelEndIdx = buffer.indexOf("", labelIdx);
        if (labelEndIdx == -1) {
            throw new IllegalStateException("Must contain label's end!");
        }

        String label = buffer.substring(labelIdx, labelEndIdx);
        String labelClass = "class=\"" + cssClass + "\" ";
        String labelWithClass = label.substring(0, 7) + labelClass + label.substring(7, label.length());
        String input = buffer.substring(inputIdx, labelIdx);

        buffer.replace(inputIdx, labelEndIdx, position == InputPosition.BEFORE_LABEL ? "
" + input + labelWithClass + "
" : labelWithClass + input);
    }
}

package lt.inventi.wicket.component.bootstrap.form;

import org.apache.wicket.util.string.AppendingStringBuffer;

abstract class ChoiceUtils {

    public enum InputPosition {
        BEFORE_LABEL, AFTER_LABEL
    }

    private ChoiceUtils() {
        // static utils
    }

    static void moveInputInsideLabel(AppendingStringBuffer buffer, String cssClass, InputPosition position) {
        int inputIdx = buffer.lastIndexOf("<input");
        if (inputIdx == -1) {
            throw new IllegalStateException("Must contain an input!");
        }
        int labelIdx = buffer.indexOf("<label", inputIdx);
        if (labelIdx == -1) {
            throw new IllegalStateException("Must contain a label!");
        }
        int labelEndIdx = buffer.indexOf("", labelIdx);
        if (labelEndIdx == -1) {
            throw new IllegalStateException("Must contain label's end!");
        }

        String label = buffer.substring(labelIdx, labelEndIdx);
        String labelClass = "class=\"" + cssClass + "\" ";
        String labelWithClass = label.substring(0, 7) + labelClass + label.substring(7, label.length());
        String input = buffer.substring(inputIdx, labelIdx);

        buffer.replace(inputIdx, labelEndIdx, position == InputPosition.BEFORE_LABEL ? "
" + input + label + "
" : labelWithClass + input);
    }
}

Move cssClass from label to div


package org.jboss.pnc.jenkinsbuilddriver;

import org.jboss.pnc.core.spi.builddriver.BuildDriver;
import org.jboss.pnc.core.spi.repositorymanager.Repository;
import org.jboss.pnc.model.BuildResult;
import org.jboss.pnc.model.BuildType;
import org.jboss.pnc.model.Project;

import java.util.function.Consumer;

/**
 * Created by Matej Lazar on 2014-11-23.
 */
//TODO implement me
public class JenkinsBuildDriver implements BuildDriver {
    @Override
    public String getDriverId() {
        return null;
    }

    @Override
    public void setDeployRepository(Repository deployRepository) {

    }

    @Override
    public void setSourceRepository(Repository repositoryProxy) {

    }

    @Override
    public void buildProject(Project project, Consumer<BuildResult> onBuildComplete) {
        //TODO implement me

        //notify build complete
        onBuildComplete.accept(new BuildResult());
    }

    @Override
    public BuildType getBuildType() {
        return BuildType.JAVA;
    }

}

package org.jboss.pnc.jenkinsbuilddriver;

import org.jboss.pnc.core.spi.builddriver.BuildDriver;
import org.jboss.pnc.core.spi.repositorymanager.Repository;
import org.jboss.pnc.model.BuildResult;
import org.jboss.pnc.model.BuildType;
import org.jboss.pnc.model.Project;

import java.util.function.Consumer;

/**
 * Created by Matej Lazar on 2014-11-23.
 */
//TODO implement me
public class JenkinsBuildDriver implements BuildDriver {
    private Consumer<BuildResult> onBuildComplete;

    @Override
    public String getDriverId() {
        return null;
    }

    @Override
    public void setDeployRepository(Repository deployRepository) {

    }

    @Override
    public void setSourceRepository(Repository repositoryProxy) {

    }

    @Override
    public void buildProject(Project project, Consumer<BuildResult> onBuildComplete) {
        this.onBuildComplete = onBuildComplete;
        //TODO implement me

        return;
    }

    @Override
    public BuildType getBuildType() {
        return BuildType.JAVA;
    }

    //TODO
    private void notifyBuildComplete() {
        //notify build complete

        onBuildComplete.accept(new BuildResult());
    }

}

Move callback notification 'after' return.


package org.sculptor.generator.util;

public abstract class ChainLink<T extends ChainLink<?>> {
	private T nextLink;

	public ChainLink(T next) {
		// TODO check for NULL
		// can be null only when created from templates and extension in generator-core
		nextLink = next;
	}

	public T getNext() {
		return nextLink;
	}
}

package org.sculptor.generator.util;

public abstract class ChainLink<T extends ChainLink<?>> {
	private T nextLink;

	public ChainLink(T next) {
		// TODO check for NULL
		// can be null only when created from templates and extension in generator-core
		nextLink = next;
	}

	public ChainLink() {

	}

	public void setNext(ChainLink<?> next) {
		nextLink = (T) next;
	}

	public T getNext() {
		return nextLink;
	}
}

Add default constructor to generated class


package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer.portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String EXTERNAL_DRIVER_URI = "/external/driver/";
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer.portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

Introduce integration tests using DropWizards ResourceTest. Include ability to return an Invalid Request message when the DLN or EnquiryId are missing.


package com.bbn.bue.common.diff;

import com.bbn.bue.common.evaluation.FMeasureCounts;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class FMeasureTableRendererTest {
    @Test
    public void testFMeasureTableRenderer() {
        final FMeasureTableRenderer renderer = FMeasureTableRenderer.create();

        final Map<String, FMeasureCounts> data = ImmutableMap.of(
                "foo", FMeasureCounts.from(1, 2, 3),
                "bar", FMeasureCounts.from(4, 5, 6));

        final String expected=
                "Name                            TP       FP       FN        P        R       F1\n"+
                "===============================================================================\n"+
                "foo                            1.0      2.0      3.0    33.33    25.00    28.57\n"+
                "bar                            4.0      5.0      6.0    44.44    40.00    42.11\n";
        final String result = renderer.render(data);
        assertEquals(expected, result);
    }
}

package com.bbn.bue.common.diff;

import com.bbn.bue.common.evaluation.FMeasureCounts;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class FMeasureTableRendererTest {
    @Test
    public void testFMeasureTableRenderer() {
        final FMeasureTableRenderer renderer = FMeasureTableRenderer.create();

        final Map<String, FMeasureCounts> data = ImmutableMap.of(
                "foo", FMeasureCounts.from(1, 2, 3),
                "bar", FMeasureCounts.from(4, 5, 6));

        final String expected=
                "Name                            TP       FP       FN        P        R       F1\n"+
                "===============================================================================\n"+
                "bar                            4.0      5.0      6.0    44.44    40.00    42.11\n"+
                "foo                            1.0      2.0      3.0    33.33    25.00    28.57\n";

        final String result = renderer.render(data);
        assertEquals(expected, result);
    }
}

Change test due to change in default sort order.


package lv.ctco.cukesrest.internal.matchers;

import org.hamcrest.*;

import java.math.*;

public class EqualToIgnoringTypeMatcher {

    public static Matcher<String> equalToIgnoringType(final String value) {
        return new BaseMatcher<String>() {

            @Override
            public void describeTo(Description description) {
                description.appendText("equal to ignoring type " + value);
            }

            @Override
            public boolean matches(Object item) {
                String toString = item.toString();
                if (toString.equals(value)) return true;

                if (item instanceof Number) {
                    BigDecimal observedValue = item instanceof BigDecimal ?
                            (BigDecimal) item : new BigDecimal(toString);
                    return new BigDecimal(value).compareTo(observedValue) == 0;
                }

                return false;
            }
        };
    }

    public static Matcher<String> notEqualToIgnoringType(final String value) {
        return new BaseMatcher<String>() {

            @Override
            public void describeTo(Description description) {
                description.appendText("not equal to ignoring type " + value);
            }

            @Override
            public boolean matches(Object item) {
                String toString = item.toString();
                if (!toString.equals(value)) return true;

                if (item instanceof Number) {
                    BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString);
                    return new BigDecimal(value).compareTo(observedValue) != 0;
                }
                return false;
            }
        };
    }
}

package lv.ctco.cukesrest.internal.matchers;

import org.hamcrest.*;

import java.math.*;

public class EqualToIgnoringTypeMatcher {

    public static Matcher<String> equalToIgnoringType(final String value) {
        return new BaseMatcher<String>() {

            @Override
            public void describeTo(Description description) {
                description.appendText("equal to ignoring type " + value);
            }

            @Override
            public boolean matches(Object item) {
                if (item == null) {
                    return value.equalsIgnoreCase("null");
                }

                String toString = item.toString();
                if (toString.equals(value)) return true;

                if (item instanceof Number) {
                    BigDecimal observedValue = item instanceof BigDecimal ?
                            (BigDecimal) item : new BigDecimal(toString);
                    return new BigDecimal(value).compareTo(observedValue) == 0;
                }

                return false;
            }
        };
    }

    public static Matcher<String> notEqualToIgnoringType(final String value) {
        return new BaseMatcher<String>() {

            @Override
            public void describeTo(Description description) {
                description.appendText("not equal to ignoring type " + value);
            }

            @Override
            public boolean matches(Object item) {
                String toString = item.toString();
                if (!toString.equals(value)) return true;

                if (item instanceof Number) {
                    BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString);
                    return new BigDecimal(value).compareTo(observedValue) != 0;
                }
                return false;
            }
        };
    }
}

Support of comparison null values in object properties


package com.github.triceo.splitlog;

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.rules.Timeout;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Base class for all Splitlog tests. Will enforce a default timeout and add
 * some useful test execution logging.
 */
public abstract class AbstractSplitlogTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSplitlogTest.class);

    @Rule
    public Timeout globalTimeout = new Timeout((int) TimeUnit.MINUTES.toMillis(2));

    @Rule
    public TestRule watchman = new TestWatcher() {

        @Override
        protected void finished(final Description d) {
            AbstractSplitlogTest.LOGGER.info("----- Finished test: {}\n", d);
        }

        @Override
        protected void starting(final Description d) {
            AbstractSplitlogTest.LOGGER.info("----- Starting test: {}", d);
        }
    };

}

package com.github.triceo.splitlog;

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.rules.Timeout;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Base class for all Splitlog tests. Will enforce a default timeout and add
 * some useful test execution logging.
 */
public abstract class AbstractSplitlogTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSplitlogTest.class);

    @Rule
    public Timeout globalTimeout = new Timeout((int) TimeUnit.MINUTES.toMillis(1));

    @Rule
    public TestRule watchman = new TestWatcher() {

        @Override
        protected void finished(final Description d) {
            AbstractSplitlogTest.LOGGER.info("----- Finished test: {}\n", d);
        }

        @Override
        protected void starting(final Description d) {
            AbstractSplitlogTest.LOGGER.info("----- Starting test: {}", d);
        }
    };

}

Reduce test timeout to 60 seconds


package no.uio.ifi.trackfind.rest.controllers;

import no.uio.ifi.trackfind.services.TrackFindService;
import org.apache.lucene.queryparser.classic.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class TrackFindController {

    private final TrackFindService trackFindService;

    @Autowired
    public TrackFindController(TrackFindService trackFindService) {
        this.trackFindService = trackFindService;
    }

    @GetMapping(path = "/reinit", produces = "application/json")
    public void reinit() throws Exception {
        trackFindService.updateIndex();
    }

    @GetMapping(path = "/metamodel", produces = "application/json")
    public Object getMetamodel() throws IOException, ParseException {
        return trackFindService.getMetamodel().asMap();
    }

    @GetMapping(path = "/search", produces = "application/json")
    public Object search(@RequestParam String query) throws IOException, ParseException {
        return trackFindService.search(query);
    }

}

package no.uio.ifi.trackfind.rest.controllers;

import no.uio.ifi.trackfind.services.TrackFindService;
import org.apache.lucene.queryparser.classic.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class TrackFindController {

    private final TrackFindService trackFindService;

    @Autowired
    public TrackFindController(TrackFindService trackFindService) {
        this.trackFindService = trackFindService;
    }

    @GetMapping(path = "/reinit", produces = "application/json")
    public void reinit() throws Exception {
        trackFindService.updateIndex();
    }

    @GetMapping(path = "/metamodel", produces = "application/json")
    public Object getMetamodel() throws IOException, ParseException {
        return trackFindService.getMetamodel().asMap();
    }

    @GetMapping(path = "/attributes", produces = "application/json")
    public Object getAttributes(@RequestParam(required = false) String expression) throws IOException, ParseException {
        Set<String> attributes = trackFindService.getMetamodel().asMap().keySet();
        if (StringUtils.isEmpty(expression)) {
            return attributes;
        } else {
            return attributes.stream().filter(a -> a.contains(expression)).collect(Collectors.toSet());
        }
    }

    @GetMapping(path = "/values", produces = "application/json")
    public Object getValues(@RequestParam String attribute) throws IOException, ParseException {
        return trackFindService.getMetamodel().get(attribute);
    }

    @GetMapping(path = "/search", produces = "application/json")
    public Object search(@RequestParam String query) throws IOException, ParseException {
        return trackFindService.search(query);
    }

}

Add separate methods for getting attributes and values.


/*
 * * Copyright (C) 2013-2015 Matt Baxter http://kitteh.org
 *
 * 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.
 */
/**
 * Internally used classes, no javadocs.
 */
package org.kitteh.irc.client.library.implementation;

Add missing LICENSE to unnecessary file


package com.alexstyl.specialdates.events;

import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;

import com.alexstyl.specialdates.R;

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

public enum EventType {
    BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red),
    NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue);

    private static final Map<Integer, EventType> map;

    static {
        map = new HashMap<>();
        for (EventType eventType : values()) {
            map.put(eventType.id, eventType);
        }
    }

    private final int id;
    private final int eventNameRes;
    private final int eventColorRes;

    EventType(@EventTypeId int id, @StringRes int nameResId, @ColorRes int colorResId) {
        this.id = id;
        this.eventNameRes = nameResId;
        this.eventColorRes = colorResId;
    }

    @StringRes
    public int nameRes() {
        return eventNameRes;
    }

    @ColorRes
    public int getColorRes() {
        return eventColorRes;
    }

    public static EventType fromId(@EventTypeId int eventTypeId) {
        if (map.containsKey(eventTypeId)) {
            return map.get(eventTypeId);
        }
        throw new IllegalArgumentException("No event type with id " + eventTypeId);
    }
}

package com.alexstyl.specialdates.events;

import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;

import com.alexstyl.specialdates.R;

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

public enum EventType {
    BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red),
    NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue);

    private static final Map<Integer, EventType> map;

    private final int eventTypeId;
    private final int eventNameRes;
    private final int eventColorRes;

    static {
        map = new HashMap<>();
        for (EventType eventType : values()) {
            map.put(eventType.eventTypeId, eventType);
        }
    }

    public static EventType fromId(@EventTypeId int eventTypeId) {
        if (map.containsKey(eventTypeId)) {
            return map.get(eventTypeId);
        }
        throw new IllegalArgumentException("No event type with eventTypeId " + eventTypeId);
    }

    EventType(@EventTypeId int eventTypeId, @StringRes int nameResId, @ColorRes int colorResId) {
        this.eventTypeId = eventTypeId;
        this.eventNameRes = nameResId;
        this.eventColorRes = colorResId;
    }

    @StringRes
    public int nameRes() {
        return eventNameRes;
    }

    @ColorRes
    public int getColorRes() {
        return eventColorRes;
    }
}

Move fields to top and give explicit name to id


package jkind;

public enum SolverOption {
	YICES, CVC4, Z3, YICES2, MATHSAT, SMTINTERPOL;

	@Override
	public String toString() {
		return name().toLowerCase();
	}
}

package jkind;

public enum SolverOption {
	SMTINTERPOL, Z3, YICES, YICES2, CVC4, MATHSAT;

	@Override
	public String toString() {
		return name().toLowerCase();
	}
}

Change order of solvers to reflect preference


package hello;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GreetingControllerTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getGreeting() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/greeting").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
	}

}

package hello;

import static org.hamcrest.core.StringContains.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GreetingControllerTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getGreeting() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/greeting").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
		.andExpect(content().string(containsString("Hello, World!")));
	}

	@Test
	public void getGreetingName() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/greeting?name=Rob").accept(MediaType.TEXT_HTML))
				.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, Rob!")));
	}

}

Test view content in greetings test.


package org.wikimedia.wikipedia.data;

import android.content.ContentProviderClient;
import android.net.Uri;
import android.os.RemoteException;

abstract public class ContentPersister<T> {
    private final ContentProviderClient client;
    private final PersistanceHelper<T> persistanceHelper;

    public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) {
        this.client = client;
        this.persistanceHelper = persistanceHelper;
    }

    public void persist(T obj) {
        Uri uri = Uri.parse("content://" +
                        SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) +
                        "/" + persistanceHelper.getTableName());

        try {
            client.insert(uri, persistanceHelper.toContentValues(obj));
        } catch (RemoteException e) {
            // This shouldn't happen
            throw new RuntimeException(e);
        }
    }

    public void deleteAll() {
        Uri uri = persistanceHelper.getBaseContentURI();
        try {
            client.delete(uri, "", new String[] {});
        } catch (RemoteException e) {
            // This also shouldn't happen
            throw new RuntimeException(e);
        }
    }

    public void cleanup() {
        this.client.release();
    }
}

package org.wikimedia.wikipedia.data;

import android.content.ContentProviderClient;
import android.net.Uri;
import android.os.RemoteException;

abstract public class ContentPersister<T> {
    private final ContentProviderClient client;
    private final PersistanceHelper<T> persistanceHelper;

    public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) {
        this.client = client;
        this.persistanceHelper = persistanceHelper;
    }

    public void persist(T obj) {
        Uri uri = Uri.parse("content://" +
                        SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) +
                        "/" + persistanceHelper.getTableName());

        try {
            client.insert(uri, persistanceHelper.toContentValues(obj));
        } catch (RemoteException e) {
            // This shouldn't happen
            throw new RuntimeException(e);
        }
    }

    public void deleteAll() {
        deleteWhere("", new String[] {});
    }

    public void deleteWhere(String selection, String[] selectionArgs) {
        Uri uri = persistanceHelper.getBaseContentURI();
        try {
            client.delete(uri, selection, selectionArgs);
        } catch (RemoteException e) {
            // This also shouldn't happen
            throw new RuntimeException(e);
        }
    }

    public void cleanup() {
        this.client.release();
    }
}

Implement deleteAll as a variant of delete


package com.grunka.random.fortuna;

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

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;

public class PrefetchingSupplierTest {
    private ExecutorService executorService;

    @Before
    public void setUp() {
        executorService = Executors.newFixedThreadPool(2);
    }

    @After
    public void tearDown() {
        executorService.shutdown();
    }

    @Test
    public void shouldGetValues() {
        AtomicInteger number = new AtomicInteger();
        PrefetchingSupplier<String> prefetcher = new PrefetchingSupplier<>(() -> "hello " + number.getAndIncrement(), executorService);
        assertEquals("hello 0", prefetcher.get());
        assertEquals("hello 1", prefetcher.get());
        assertEquals("hello 2", prefetcher.get());
    }
}

package com.grunka.random.fortuna;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;

public class PrefetchingSupplierTest {
    private ExecutorService executorService;
    private List<Integer> sleeps;

    @Before
    public void setUp() {
        sleeps = new ArrayList<>(Arrays.asList(200, 150, 100, 50, 0));
        executorService = Executors.newFixedThreadPool(5);
    }

    @After
    public void tearDown() {
        executorService.shutdown();
    }

    @Test
    public void shouldGetValues() {
        AtomicInteger number = new AtomicInteger();
        PrefetchingSupplier<String> prefetcher = new PrefetchingSupplier<>(() -> "hello " + number.getAndIncrement(), executorService);
        assertEquals("hello 0", prefetcher.get());
        assertEquals("hello 1", prefetcher.get());
        assertEquals("hello 2", prefetcher.get());
    }

    @Test
    public void shouldBeOrderedAndCorrectNumberOfOutputs() throws ExecutionException, InterruptedException {
        AtomicInteger number = new AtomicInteger();
        PrefetchingSupplier<Integer> prefetcher = new PrefetchingSupplier<>(() -> {
            sleep();
            return number.getAndIncrement();
        }, executorService);
        List<Integer> values = new ArrayList<>();
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            futures.add(executorService.submit(() -> values.add(prefetcher.get())));
        }
        for (Future<?> future : futures) {
            future.get();
        }
        assertEquals(Arrays.asList(0, 1, 2, 3, 4), values);
    }

    private void sleep() {
        try {
            Thread.sleep(sleeps.remove(0));
        } catch (InterruptedException e) {
            throw new Error(e);
        }
    }
}

Test verifying that the prefetcher doesn't serve outputs in the wrong order


package com.vladmihalcea.book.hpjp.hibernate.mapping.enums;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 * @author Vlad Mihalcea
 */
public class PostgreSQLEnumType extends org.hibernate.type.EnumType {

    public void nullSafeSet(
            PreparedStatement st,
            Object value,
            int index,
            SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, Types.OTHER);
        } else {
            st.setObject(index, value.toString(), Types.OTHER);
        }
    }
}

package com.vladmihalcea.book.hpjp.hibernate.mapping.enums;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 * @author Vlad Mihalcea
 */
public class PostgreSQLEnumType extends org.hibernate.type.EnumType {

    public void nullSafeSet(
            PreparedStatement st,
            Object value,
            int index,
            SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        st.setObject(
            index,
            value != null ?
                ((Enum) value).name() :
                null,
            Types.OTHER
        );
    }
}

USe the Enum name, not the toString method when binding the parameter value


package io.github.uetoyo.patterns.specification;

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

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

/**
 * The composite specification is composed from zero or more specifications.
 *
 * @param <T> The type of entity for which the specification is defined.
 */
abstract class CompositeSpecification<T> implements Specification<T> {

	private final ArrayList<Specification<T>> specifications;

	protected CompositeSpecification(final ArrayList<Specification<T>> specifications) {
		this.specifications = checkNotNull(specifications);
	}

	/**
	 * Gets the inner specifications.
	 *
	 * @return The inner specifications.
	 */
	public List<Specification<T>> getSpecifications() {
		return specifications;
	}

	/**
	 * Gets the inner unsatisfied specifications.
	 *
	 * @return The inner unsatisfied specifications.
	 */
	Set<Specification<T>> getUnsatisfiedSpecificationsFor(final T candidate) {

		Set<Specification<T>> unsatisfied = new HashSet<>();
		for (Specification<T> specification : getSpecifications()) {
			if (!specification.isSatisfiedBy(candidate)) {
				unsatisfied.add(specification);
			}
		}
		return Collections.unmodifiableSet(unsatisfied);
	}

}

package io.github.uetoyo.patterns.specification;

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

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

/**
 * The composite specification is composed from zero or more specifications.
 *
 * @param <T> The type of entity for which the specification is defined.
 */
abstract class CompositeSpecification<T> implements Specification<T> {

	private final ArrayList<Specification<T>> specifications;

	protected CompositeSpecification(final ArrayList<Specification<T>> specifications) {
		this.specifications = checkNotNull(specifications);
	}

	/**
	 * Gets the inner specifications.
	 *
	 * @return The inner specifications.
	 */
	public List<Specification<T>> getSpecifications() {
		return specifications;
	}

	/**
	 * Gets the inner unsatisfied specifications.
	 *
	 * @return The inner unsatisfied specifications.
	 */
	public Set<Specification<T>> getUnsatisfiedSpecificationsFor(final T candidate) {

		Set<Specification<T>> unsatisfied = new HashSet<>();
		for (Specification<T> specification : getSpecifications()) {
			if (!specification.isSatisfiedBy(candidate)) {
				unsatisfied.add(specification);
			}
		}
		return Collections.unmodifiableSet(unsatisfied);
	}

}

Use explicit scoping instead of the default package private level


package de.retest.recheck.ui.descriptors;

import java.awt.Rectangle;

public class AttributeUtil {

	public static Rectangle getOutline( final IdentifyingAttributes attributes ) {
		final OutlineAttribute outlineAttribute =
				(OutlineAttribute) attributes.getAttribute( OutlineAttribute.RELATIVE_OUTLINE );
		if ( outlineAttribute == null ) {
			return null;
		}
		return outlineAttribute.getValue();
	}

	public static Rectangle getAbsoluteOutline( final IdentifyingAttributes attributes ) {
		final OutlineAttribute outlineAttribute =
				(OutlineAttribute) attributes.getAttribute( OutlineAttribute.ABSOLUTE_OUTLINE );
		if ( outlineAttribute == null ) {
			return null;
		}
		return outlineAttribute.getValue();
	}
}

package de.retest.recheck.ui.descriptors;

import java.awt.Rectangle;
import java.util.List;

import de.retest.recheck.ui.diff.AttributeDifference;
import de.retest.recheck.ui.diff.ElementDifference;
import de.retest.recheck.ui.diff.IdentifyingAttributesDifference;

public class AttributeUtil {

	public static Rectangle getActualOutline( final ElementDifference difference ) {
		final Rectangle actualRelative = getActualOutline( difference, OutlineAttribute.RELATIVE_OUTLINE );

		if ( actualRelative != null ) {
			return actualRelative;
		}
		return getOutline( difference.getIdentifyingAttributes() );
	}

	public static Rectangle getActualAbsoluteOutline( final ElementDifference difference ) {
		final Rectangle actualAbsolute = getActualOutline( difference, OutlineAttribute.ABSOLUTE_OUTLINE );

		if ( actualAbsolute != null ) {
			return actualAbsolute;
		}
		return getAbsoluteOutline( difference.getIdentifyingAttributes() );
	}

	public static Rectangle getOutline( final IdentifyingAttributes attributes ) {
		final OutlineAttribute outlineAttribute =
				(OutlineAttribute) attributes.getAttribute( OutlineAttribute.RELATIVE_OUTLINE );
		if ( outlineAttribute == null ) {
			return null;
		}
		return outlineAttribute.getValue();
	}

	public static Rectangle getAbsoluteOutline( final IdentifyingAttributes attributes ) {
		final OutlineAttribute outlineAttribute =
				(OutlineAttribute) attributes.getAttribute( OutlineAttribute.ABSOLUTE_OUTLINE );
		if ( outlineAttribute == null ) {
			return null;
		}
		return outlineAttribute.getValue();
	}

	private static Rectangle getActualOutline( final ElementDifference difference, final String type ) {
		final IdentifyingAttributesDifference identifyingAttributesDifference =
				(IdentifyingAttributesDifference) difference.getIdentifyingAttributesDifference();

		if ( identifyingAttributesDifference != null ) {

			final List<AttributeDifference> attributeDifferences =
					identifyingAttributesDifference.getAttributeDifferences();

			if ( attributeDifferences != null ) {
				for ( final AttributeDifference aDiff : attributeDifferences ) {
					if ( aDiff.getKey().equals( type ) ) {
						return ((Rectangle) aDiff.getActual());
					}
				}
			}
		}
		return null;
	}

}

Add methods for actual outline


package org.ingrahamrobotics.robottables;

public class TimeConstants {

    /**
     * Time to wait from when publishing a table to sending updates for it.
     */
    public static final long PUBLISH_WAIT_TIME = 200l;

    /**
     * Time between full updates sent.
     */
    public static final long UPDATE_INTERVAL = 5000l;

    /**
     * How long we should wait between update messages during a table update before we assume the update is finished. If
     * this many ms have passed after the last update during a table update, the update is considered finished.
     */
    public static final long MAX_INTERVAL_DURING_UPDATE = 100l;
}

package org.ingrahamrobotics.robottables;

public class TimeConstants {

    /**
     * Time to wait from when publishing a table to sending updates for it.
     */
    public static final long PUBLISH_WAIT_TIME = 400l;

    /**
     * Time between full updates sent.
     */
    public static final long UPDATE_INTERVAL = 15000l;

    /**
     * How long we should wait between update messages during a table update before we assume the update is finished. If
     * this many ms have passed after the last update during a table update, the update is considered finished.
     */
    public static final long MAX_INTERVAL_DURING_UPDATE = 200l;
}

Change default time constants to be a bit longer, as the current values don't seem to work well with the amount of data that we are sending back and forth.


package software.committed.rejux.utils;

import java.util.List;

import software.committed.rejux.interfaces.Dispatcher;
import software.committed.rejux.interfaces.Middleware;
import software.committed.rejux.interfaces.State;

public final class MiddlewareUtils {

  private MiddlewareUtils() {
    // Singleton
  }

  public static <S> Dispatcher createChain(final Dispatcher firstDispatcher, final S store,
      final List<Middleware<? super S>> middlewares, final Dispatcher lastDispatcher) {
    Dispatcher dispatcher = lastDispatcher;

    if (middlewares != null && !middlewares.isEmpty()) {
      for (int i = middlewares.size() - 1; i >= 0; i--) {
        final Middleware<? super S> m = middlewares.get(i);
        final Dispatcher previous = dispatcher;
        dispatcher = (action) -> m.apply(firstDispatcher, store, action, previous);
      }
    }

    return dispatcher;
  }

  public static <S> Dispatcher createChain(final Dispatcher firstDispatcher, final State<S> holder,
      final List<Middleware<? super S>> middlewares, final Dispatcher lastDispatcher) {
    Dispatcher dispatcher = lastDispatcher;

    if (middlewares != null && !middlewares.isEmpty()) {
      for (int i = middlewares.size() - 1; i >= 0; i--) {
        final Middleware<? super S> m = middlewares.get(i);
        final Dispatcher previous = dispatcher;
        dispatcher = (action) -> m.apply(firstDispatcher, holder.get(), action, previous);
      }
    }

    return dispatcher;
  }

}

package software.committed.rejux.utils;

import java.util.List;
import java.util.function.Supplier;

import software.committed.rejux.interfaces.Dispatcher;
import software.committed.rejux.interfaces.Middleware;

public final class MiddlewareUtils {

  private MiddlewareUtils() {
    // Singleton
  }

  public static <S> Dispatcher createChain(final Dispatcher firstDispatcher, final S store,
      final List<Middleware<? super S>> middlewares, final Dispatcher lastDispatcher) {
    Supplier<S> supplier = () -> store;
    return createChain(firstDispatcher, supplier, middlewares, lastDispatcher);
  }

  public static <S> Dispatcher createChain(final Dispatcher firstDispatcher,
      final Supplier<S> store, final List<Middleware<? super S>> middlewares,
      final Dispatcher lastDispatcher) {
    Dispatcher dispatcher = lastDispatcher;

    if (middlewares != null && !middlewares.isEmpty()) {
      for (int i = middlewares.size() - 1; i >= 0; i--) {
        final Middleware<? super S> m = middlewares.get(i);
        final Dispatcher previous = dispatcher;
        dispatcher = (action) -> m.apply(firstDispatcher, store.get(), action, previous);
      }
    }

    return dispatcher;
  }

}

Reimplement middleware utils as common code


package org.elasticsearch.rest.action.readonlyrest.acl.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.google.common.base.Charsets;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestRequest.Method;
import org.elasticsearch.rest.action.readonlyrest.acl.ACL;
import org.elasticsearch.rest.action.readonlyrest.acl.ACLRequest;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class MarvelPassThroughACL {
    private static ACL acl;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/marvel_passthrough.yml"));
            String str = Charsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
            Settings s = Settings.builder().loadFromSource(str).build();
            acl = new ACL(ESLoggerFactory.getLogger(ACL.class.getName()), s);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public final void testInternalMethods(){
        Assert.assertNull(acl.check( new ACLRequest(".marvel-2015.11.10/_search", "127.0.0.1", "", "", 0, Method.POST, null)));
    }

}

package org.elasticsearch.rest.action.readonlyrest.acl.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.google.common.base.Charsets;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestRequest.Method;
import org.elasticsearch.rest.action.readonlyrest.acl.ACL;
import org.elasticsearch.rest.action.readonlyrest.acl.ACLRequest;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class MarvelPassthroughACL {
    private static ACL acl;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/marvel_passthrough.yml"));
            String str = Charsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
            Settings s = Settings.builder().loadFromSource(str).build();
            acl = new ACL(ESLoggerFactory.getLogger(ACL.class.getName()), s);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public final void testInternalMethods(){
        Assert.assertNull(acl.check( new ACLRequest(".marvel-2015.11.10/_search", "127.0.0.1", "", "", 0, Method.POST, null)));
    }

}

Fix typo preventing build to proceed


package org.spoofax.jsglr2.inputstack;

import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.Position;

public class LayoutSensitiveInputStack extends InputStack {

    private static final int TAB_SIZE = 8;

    private int currentLine = 1;
    private int currentColumn = 1;
    public Position previousPosition = new Position(-1, 1, 0);

    public LayoutSensitiveInputStack(String inputString) {
        super(inputString);
    }

    public Position currentPosition() {
        return new Position(currentOffset, currentLine, currentColumn);
    }

    @Override public void next() {
        super.next();

        previousPosition = currentPosition();

        if(currentOffset < inputLength) {
            if(CharacterClassFactory.isNewLine(currentChar)) {
                currentLine++;
                currentColumn = 0;
            } else if(CharacterClassFactory.isCarriageReturn(currentChar)) {

            } else if(CharacterClassFactory.isTab(currentChar)) {
                currentColumn = (currentColumn / TAB_SIZE + 1) * TAB_SIZE;
            } else {
                currentColumn++;
            }
        }
        if(currentOffset == inputLength)
            currentColumn++;
    }

}

package org.spoofax.jsglr2.inputstack;

import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.Position;

public class LayoutSensitiveInputStack extends InputStack {

    private static final int TAB_SIZE = 8;

    private int currentLine;
    private int currentColumn;
    public Position previousPosition;

    public LayoutSensitiveInputStack(String inputString) {
        super(inputString);

        this.currentLine = 1;
        this.currentColumn = CharacterClassFactory.isNewLine(currentChar) ? 0 : 1;
        this.previousPosition = new Position(-1, currentLine, currentColumn - 1);
    }

    public Position currentPosition() {
        return new Position(currentOffset, currentLine, currentColumn);
    }

    @Override public void next() {
        super.next();

        previousPosition = currentPosition();

        if(currentOffset < inputLength) {
            if(CharacterClassFactory.isNewLine(currentChar)) {
                currentLine++;
                currentColumn = 0;
            } else if(CharacterClassFactory.isCarriageReturn(currentChar)) {

            } else if(CharacterClassFactory.isTab(currentChar)) {
                currentColumn = (currentColumn / TAB_SIZE + 1) * TAB_SIZE;
            } else {
                currentColumn++;
            }
        }
        if(currentOffset == inputLength)
            currentColumn++;
    }

}

Fix position calculation of second character when first character is a newline


package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiErrorType;

import java.util.UUID;

import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;

/**
 * Created by izumin on 9/17/15.
 */
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {

    protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
        super(service, uuid);
    }

    @Override
    public boolean execute(BluetoothGattWrapper gattWrapper) {
        if (getCharacteristic() != null) {
            rejectIfParamsAreInvalid(KonashiErrorType.UNSUPPORTED_OPERATION);
            return false;
        }
        BletiaErrorType errorType = validate();
        if (errorType == KonashiErrorType.NO_ERROR) {
            setValue();
            return super.execute(gattWrapper);
        } else {
            rejectIfParamsAreInvalid(errorType);
            return false;
        }
    }

    protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
        getDeferred().reject(new BletiaException(this, errorType));
    }

    protected abstract void setValue();
    protected abstract BletiaErrorType validate();
}

package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiErrorType;

import java.util.UUID;

import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;

/**
 * Created by izumin on 9/17/15.
 */
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {

    protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
        super(service, uuid);
    }

    @Override
    public boolean execute(BluetoothGattWrapper gattWrapper) {
        if (getCharacteristic() == null) {
            rejectIfParamsAreInvalid(KonashiErrorType.UNSUPPORTED_OPERATION);
            return false;
        }
        BletiaErrorType errorType = validate();
        if (errorType == KonashiErrorType.NO_ERROR) {
            setValue();
            return super.execute(gattWrapper);
        } else {
            rejectIfParamsAreInvalid(errorType);
            return false;
        }
    }

    protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
        getDeferred().reject(new BletiaException(this, errorType));
    }

    protected abstract void setValue();
    protected abstract BletiaErrorType validate();
}

Fix decision unsupported operation on execute


package info.u_team.u_team_core.util.registry;

import java.util.function.Consumer;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

public class BusRegistry {

	public static void registerMod(Consumer<IEventBus> consumer) {
		register(FMLJavaModLoadingContext.get().getModEventBus(), consumer);
	}

	public static void registerForge(Consumer<IEventBus> consumer) {
		register(MinecraftForge.EVENT_BUS, consumer);
	}

	public static void register(IEventBus bus, Consumer<IEventBus> consumer) {
		consumer.accept(bus);
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Consumer;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

public class BusRegistry {

	public static void registerMod(Consumer<IEventBus> consumer) {
		register(FMLJavaModLoadingContext.get().getModEventBus(), consumer);
	}

	public static void registerForge(Consumer<IEventBus> consumer) {
		register(MinecraftForge.EVENT_BUS, consumer);
	}

	public static void registerForge(Bus bus, Consumer<IEventBus> consumer) {
		register(bus.bus().get(), consumer);
	}

	public static void register(IEventBus bus, Consumer<IEventBus> consumer) {
		consumer.accept(bus);
	}

}

Add util method for the bus enum


package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.0";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "alpha 1";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.0";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

Set version to 0.5.0 final.


/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2017 Adobe
 * %%
 * 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.
 * #L%
 */
@Version("3.10.0")
package com.adobe.acs.commons.mcp.util;

import aQute.bnd.annotation.Version;

/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2017 Adobe
 * %%
 * 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.
 * #L%
 */
@Version("3.11.0")
package com.adobe.acs.commons.mcp.util;

import aQute.bnd.annotation.Version;

Increment MCP Util package version


import java.util.concurrent.locks.*;

class JSR166 {
	Lock l = new ReentrantLock();
	int x;

	void l() {
		l.lock();
		}

	void foo() {
		l.lock();
		x++;
		if (x >= 0)
			l.unlock();
		}

	void increment() {
		l.lock();
		x++;
		l.unlock();
		}

	void decrement() {
		l.lock();
		try {
		  x++;
		} finally {
		  l.unlock();
		  }
		}
	}

import java.util.concurrent.locks.*;

class JSR166 {
	Lock l = new ReentrantLock();
	int x;

	void l() {
		l.lock();
		}

	void foo() {
		l.lock();
		x++;
		if (x >= 0)
			l.unlock();
		}

	void increment() {
		l.lock();
		x++;
		l.unlock();
		}

	void decrement() {
		l.lock();
		try {
		  x++;
		} finally {
		  l.unlock();
		  }
		}

	void waitOnCondition(Condition cond) throws InterruptedException {
		while (x == 0) {
		cond.wait();
		cond.wait(1000L);
		cond.wait(1000L, 10);
		}
	}
	}

Call wait() on a Condition.


package de.tse.simplerestfacade;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import de.tse.simplerestfacade.marshalling.Unmarshaller;

public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> {

    private final Unmarshaller unmarshaller;
    private final Class<T> returnType;

    public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) {
        this.unmarshaller = unmarshaller;
        this.returnType = returnType;
    }

    @Override
    public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {

        validateStatusCode(response);

        final String content = EntityUtils.toString(response.getEntity());

        return unmarshaller.unmarshall(content, returnType);
    }

    private void validateStatusCode(final HttpResponse response) {
        final StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new RestClientException(statusLine.toString());
        }
    }
}

package de.tse.simplerestfacade;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import de.tse.simplerestfacade.marshalling.Unmarshaller;

public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> {

    private final Unmarshaller unmarshaller;
    private final Class<T> returnType;

    public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) {
        this.unmarshaller = unmarshaller;
        this.returnType = returnType;
    }

    @Override
    public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {

        validateStatusCode(response);

        Object result = null;

        if (response.getEntity() != null) {

            final String content = EntityUtils.toString(response.getEntity());
            result = unmarshaller.unmarshall(content, returnType);
        }

        return result;
    }

    private void validateStatusCode(final HttpResponse response) {
        final StatusLine statusLine = response.getStatusLine();
        if (!requestWasSuccessful(statusLine.getStatusCode())) {
            throw new RestClientException(statusLine.toString());
        }
    }

    private boolean requestWasSuccessful(final int statusCode) {
        return statusCode >= HttpStatus.SC_OK || statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
    }
}

Throw Exception only if StatusCode is out of 2xx Range; Unmarshal Response only, if ResponseEntity exist.


package org.gbif.registry;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

@TestConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"org.gbif.ws.server.interceptor",
    "org.gbif.ws.server.filter", "org.gbif.ws.security", "org.gbif.query", "org.gbif.registry"})
@PropertySource("classpath:application-test.yml")
public class RegistryIntegrationTestsConfiguration {
}

package org.gbif.registry;

import org.gbif.registry.mail.EmailSender;
import org.gbif.registry.mail.InMemoryEmailSender;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

@TestConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"org.gbif.ws.server.interceptor",
  "org.gbif.ws.server.filter", "org.gbif.ws.security", "org.gbif.query", "org.gbif.registry"})
@PropertySource("classpath:application-test.yml")
public class RegistryIntegrationTestsConfiguration {

  // use InMemoryEmailSender if devemail is disabled
  @Bean
  @ConditionalOnProperty(value = "mail.devemail.enabled", havingValue = "false")
  public EmailSender emailSender() {
    return new InMemoryEmailSender();
  }
}

Add condition on EmailSender bean creation


package com.navigation.reactnative;

import android.content.Context;
import android.view.ViewGroup;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.facebook.react.uimanager.PixelUtil;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

public class BottomSheetView extends ViewGroup {
    public BottomSheetView(Context context) {
        super(context);
        CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.setBehavior(new BottomSheetBehavior());
        setLayoutParams(params);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        BottomSheetBehavior.from(this).setPeekHeight((int) PixelUtil.toPixelFromDIP(200));
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
    }
}

package com.navigation.reactnative;

import android.content.Context;
import android.view.ViewGroup;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.facebook.react.uimanager.PixelUtil;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

public class BottomSheetView extends ViewGroup {
    public BottomSheetView(Context context) {
        super(context);
        CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        BottomSheetBehavior bottomSheetBehavior = new BottomSheetBehavior();
        bottomSheetBehavior.setPeekHeight((int) PixelUtil.toPixelFromDIP(200));
        params.setBehavior(bottomSheetBehavior);
        setLayoutParams(params);
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
    }
}

Set behavior prop before added to window


package info.schleichardt.training.java8.lecture2;

public class P2_FunctionalInterfacesFirstClassMembers {

    //show also Automatic-Resource-Management
}

package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

    @FunctionalInterface
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;

        //return type, works also in classes
        static HashFunction ofAlgorithm(final String algorithm) {
            return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
        }
    }

    //member in a class
    public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
    //field
    private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());

    //input parameter
    public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
        return function.hash(input);
    }

    public static void demoForReturnType() throws Exception {
        final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
        final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
    }

    //example method that is not at all related to the interface HashFunction
    //but still has the same signature of taking a String as input and returning a byte array
    public static byte[] md5(final String input) throws Exception {
        return MessageDigest.getInstance("MD5").digest(input.getBytes());
    }

    //method reference
    public static void demoForMethodReference() throws Exception {
        final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
    }
}

Add description how closures can be first class members.


package com.github.ayltai.newspaper.data;

import android.content.Context;
import android.support.annotation.NonNull;

import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
import io.realm.RealmConfiguration;

@Module
public final class DataModule {
    private static final int SCHEMA_VERSION = 1;

    private static boolean isInitialized;

    private final Context context;

    public DataModule(@NonNull final Context context) {
        this.context = context.getApplicationContext();
    }

    @NonNull
    @Provides
    Context provideContext() {
        return this.context;
    }

    @NonNull
    @Provides
    Realm provideRealm() {
        if (!DataModule.isInitialized) {
            Realm.init(this.context);
            Realm.setDefaultConfiguration(new RealmConfiguration.Builder().schemaVersion(DataModule.SCHEMA_VERSION).build());

            DataModule.isInitialized = true;
        }

        return Realm.getDefaultInstance();
    }
}

package com.github.ayltai.newspaper.data;

import android.content.Context;
import android.support.annotation.NonNull;

import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
import io.realm.RealmConfiguration;

@Module
public final class DataModule {
    private static final int SCHEMA_VERSION = 1;

    private static boolean isInitialized;

    private final Context context;

    public DataModule(@NonNull final Context context) {
        this.context = context.getApplicationContext();
    }

    @NonNull
    @Provides
    Context provideContext() {
        return this.context;
    }

    @NonNull
    @Provides
    Realm provideRealm() {
        if (!DataModule.isInitialized) {
            Realm.init(this.context);
            Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
                .schemaVersion(DataModule.SCHEMA_VERSION)
                .deleteRealmIfMigrationNeeded()
                .compactOnLaunch()
                .build());

            DataModule.isInitialized = true;
        }

        return Realm.getDefaultInstance();
    }
}

Fix app crash due to Realm database migration


package org.jimmutable.platform_test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
    		try{
    			App.main(null);
    			assertTrue( true );
    		} catch (Exception e) {
    			assert(false);
    		}
    }
}

package org.jimmutable.platform_test;

import static org.junit.Assert.*;

import org.junit.Test;

public class AppTest extends App
{

//	@Test
	public void testMain()
	{
		try{
			App.main(null);
			assertTrue( true );
		} catch (Exception e) {
			e.printStackTrace();
			assert(false);
		}
	}

}

Update to platform_test test class


/*
 * WireSpider
 *
 * Copyright (c) 2015 kazyx
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

package net.kazyx.wirespider.sampleapp;

import android.app.Application;
import android.util.Log;

public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        net.kazyx.wirespider.Log.writer(new net.kazyx.wirespider.Log.Writer() {
            @Override
            public void v(String tag, String message) {
                Log.v(tag, message);
            }

            @Override
            public void d(String tag, String message) {
                Log.d(tag, message);
            }

            @Override
            public void e(String tag, String message) {
                Log.e(tag, message);
            }

            @Override
            public void printStackTrace(String tag, Throwable th) {
                Log.wtf(tag, th);
            }
        });
        net.kazyx.wirespider.Log.logLevel(net.kazyx.wirespider.Log.Level.VERBOSE);
    }
}

/*
 * WireSpider
 *
 * Copyright (c) 2015 kazyx
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

package net.kazyx.wirespider.sampleapp;

import android.app.Application;
import android.util.Log;

public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        net.kazyx.wirespider.Log.writer(new net.kazyx.wirespider.Log.Writer() {
            @Override
            public void v(String tag, String message) {
                Log.v(tag, message);
            }

            @Override
            public void d(String tag, String message) {
                Log.d(tag, message);
            }

            @Override
            public void e(String tag, String message) {
                Log.e(tag, message);
            }

            @Override
            public void printStackTrace(String tag, Throwable th) {
                Log.wtf(tag, th);
            }
        });
        net.kazyx.wirespider.Log.logLevel(net.kazyx.wirespider.Log.Level.DEBUG);
    }
}

Set debug level DEBUG in sample application


package info.u_team.u_team_core.container;

import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;

public class FluidSlot {

	private final IFluidHandlerModifiable fluidHandler;
	private final int index;
	private final int x;
	private final int y;

	public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
		this.fluidHandler = fluidHandler;
		this.index = index;
		this.x = x;
		this.y = y;
	}

	public boolean isFluidValid(FluidStack stack) {
		if (stack.isEmpty()) {
			return false;
		}
		return fluidHandler.isFluidValid(index, stack);
	}

	public FluidStack getStack() {
		return fluidHandler.getFluidInTank(index);
	}

	public void putStack(FluidStack stack) {
		fluidHandler.setFluidInTank(index, stack);
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public boolean isEnabled() {
		return true;
	}
}

package info.u_team.u_team_core.container;

import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;

public class FluidSlot {

	private final IFluidHandlerModifiable fluidHandler;
	private final int index;
	private final int x;
	private final int y;

	public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
		this.fluidHandler = fluidHandler;
		this.index = index;
		this.x = x;
		this.y = y;
	}

	public boolean isFluidValid(FluidStack stack) {
		if (stack.isEmpty()) {
			return false;
		}
		return fluidHandler.isFluidValid(index, stack);
	}

	public FluidStack getStack() {
		return fluidHandler.getFluidInTank(index);
	}

	public void putStack(FluidStack stack) {
		fluidHandler.setFluidInTank(index, stack);
	}

	public int getSlotCapacity() {
		return fluidHandler.getTankCapacity(index);
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public boolean isEnabled() {
		return true;
	}
}

Add getSlotCapacity method in fluid slot


package com.pqbyte.coherence;

public final class Constants {
  private static final boolean DEBUG = true;

  public static boolean isDebug() {
    return DEBUG;
  }

  public static final int WORLD_WIDTH = 100;
  public static final int WORLD_HEIGHT = 100;

  /* Mask flags for Box2D filters. */
  public static final short PLAYER_ENTITY = 0x1;
  public static final short BULLET_ENTITY = 0x2;
  public static final short WORLD_ENTITY = 0x3;
}

package com.pqbyte.coherence;

public final class Constants {
  private static final boolean DEBUG = false;

  public static boolean isDebug() {
    return DEBUG;
  }

  public static final int WORLD_WIDTH = 100;
  public static final int WORLD_HEIGHT = 100;

  /* Mask flags for Box2D filters. */
  public static final short PLAYER_ENTITY = 0x1;
  public static final short BULLET_ENTITY = 0x2;
  public static final short WORLD_ENTITY = 0x3;
}

Set debug field to false as default


<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see http://www.jhipster.tech/
 for more information.

 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 <%=packageName%>.service.mapper;

import java.util.List;

/**
 * Contract for a generic dto to entity mapper.
 *
 * @param <D> - DTO type parameter.
 * @param <E> - Entity type parameter.
 */

public interface EntityMapper <D, E> {

    E toEntity(D dto);

    D toDto(E entity);

    List <E> toEntity(List<D> dtoList);

    List <D> toDto(List<E> entityList);
}

<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see http://www.jhipster.tech/
 for more information.

 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 <%=packageName%>.service.mapper;

import java.util.List;

/**
 * Contract for a generic dto to entity mapper.
 *
 * @param <DTO> - DTO type parameter.
 * @param <ENTITY> - Entity type parameter.
 */

public interface EntityMapper <DTO, ENTITY> {

    ENTITY toEntity(DTO dto);

    DTO toDto(ENTITY entity);

    List <ENTITY> toEntity(List<DTO> dtoList);

    List <DTO> toDto(List<ENTITY> entityList);
}

Revert "Rename generic names to single letter"


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

import org.xwiki.stability.Unstable;

/**
 * Expose various logging related configurations.
 *
 * @version $Id$
 * @since 12.0RC1
 * @see 11.10.2
 */
@Unstable
public interface LoggerConfiguration
{
    /**
     * @return true if logging about use of deprecated APIs or features is enabled
     */
    boolean isDeprecatedLogEnabled();
}

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

import org.xwiki.stability.Unstable;

/**
 * Expose various logging related configurations.
 *
 * @version $Id$
 * @since 12.0RC1
 */
@Unstable
public interface LoggerConfiguration
{
    /**
     * @return true if logging about use of deprecated APIs or features is enabled
     */
    boolean isDeprecatedLogEnabled();
}

Make easier to disable deprecated log


package com.nullprogram.maze;

import java.awt.Dimension;

import javax.swing.JApplet;

public class MazeApplet extends JApplet {

    private static final long serialVersionUID = 7742407602430714892L;

    private int cellSize = 15;
    private int speed    = 10;
    private Maze maze;
    private MazeDisplay display;
    private MazeSolve solution;

    public void init() {
        Dimension size = getSize();
        maze = new Maze((int) (size.getWidth() / cellSize),
                        (int) (size.getHeight() / cellSize));
        display = new MazeDisplay(maze, cellSize);
        add(display);
        solution = new MazeSolve(maze, display, speed);
    }
}

package com.nullprogram.maze;

import java.awt.Dimension;

import javax.swing.JApplet;

public class MazeApplet extends JApplet {

    private static final long serialVersionUID = 7742407602430714892L;

    private int cellSize = 15;
    private int speed    = 10;
    private Maze maze;
    private MazeDisplay display;
    private MazeSolve solution;

    public void init() {
        Dimension size = getSize();
        maze = new Maze((int) (size.getWidth() / cellSize),
                        (int) (size.getHeight() / cellSize));
        display = new MazeDisplay(maze, cellSize);
        add(display);
        solution = new MazeSolve(maze, display, speed);
    }

    public void start() {
        solution.start();
    }

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

    public void destroy() {
        stop();
    }
}

Use start/stop in the applet.


package problems;

public class ContainerWithMostWater {
    public int maxArea(int[] height) {
        if (height.length <= 1)
            return 0;

        int a = 0, b = height.length - 1;
        int max = 0;
        while (b > a) {
            int volumn = Math.min(height[a], height[b]) * (b - a);
            if (volumn > max)
                max = volumn;
            if (height[a] <= height[b])
                a++;
            else
                b--;
        }
        return max;
    }

    public static void main(String[] args) {
        ContainerWithMostWater cw = new ContainerWithMostWater();
        int[] height = {1, 3, 2, 5, 3};
        System.out.println(cw.maxArea(height));
    }
}

package problems;

public class ContainerWithMostWater {
    public int maxArea(int[] height) {
        if (height.length <= 1)
            return 0;

        int a = 0, b = height.length - 1;
        int max = 0;
        while (b > a) {
            int volumn = Math.min(height[a], height[b]) * (b - a);
            if (volumn > max)
                max = volumn;
            if (height[a] <= height[b])
                a++;
            else
                b--;
        }
        return max;
    }

    public static void main(String[] args) {
        ContainerWithMostWater cw = new ContainerWithMostWater();
        int[] height = { 1, 3, 2, 5, 3 };
        System.out.println(cw.maxArea(height));
    }
}

Add Container with Most Water


package de.blogspot.wrongtracks.example;

import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.extension.osgi.application.OSGiProcessApplication;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.container.BlueprintContainer;

@ProcessApplication(name="MyProcessApplication")
public class ExampleProcessApplication extends OSGiProcessApplication {

  public ExampleProcessApplication(BundleContext ctx, BlueprintContainer blueprintContainer) {
    super(ctx.getBundle(), blueprintContainer);
  }
}

package de.blogspot.wrongtracks.example;

import org.camunda.bpm.application.PostDeploy;
import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.extension.osgi.application.OSGiProcessApplication;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.container.BlueprintContainer;

@ProcessApplication(name="MyProcessApplication")
public class ExampleProcessApplication extends OSGiProcessApplication {

  public ExampleProcessApplication(BundleContext ctx, BlueprintContainer blueprintContainer) {
    super(ctx.getBundle(), blueprintContainer);
  }

  @PostDeploy
  public void executeProcess(ProcessEngine processEngine){
    processEngine.getRuntimeService().startProcessInstanceByKey("Process_1");
  }
}

Add method for starting the process after deploying it