package liquibase.integration.ant;

import liquibase.resource.FileSystemResourceAccessor;
import liquibase.util.StringUtil;
import org.apache.tools.ant.AntClassLoader;

import java.io.File;

public class AntResourceAccessor extends FileSystemResourceAccessor {

    public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) {

        if (changeLogDirectory == null) {
            this.addRootPath(new File(".").getAbsoluteFile().toPath());
        } else {
            this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath());
        }

        final String classpath = StringUtil.trimToNull(classLoader.getClasspath());
        if (classpath != null) {
            for (String path : classpath.split(System.getProperty("path.separator"))) {
                this.addRootPath(new File(path).toPath());
            }
        }
    }

}

package liquibase.integration.ant;

import liquibase.resource.FileSystemResourceAccessor;
import liquibase.util.StringUtil;
import org.apache.tools.ant.AntClassLoader;

import java.io.File;

public class AntResourceAccessor extends FileSystemResourceAccessor {

    public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) {

        if (changeLogDirectory != null) {
            changeLogDirectory = changeLogDirectory.replace("\\", "/");
        }

        if (changeLogDirectory == null) {
            this.addRootPath(new File("").getAbsoluteFile().toPath());
            this.addRootPath(new File("/").getAbsoluteFile().toPath());
        } else {
            this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath());
        }

        final String classpath = StringUtil.trimToNull(classLoader.getClasspath());
        if (classpath != null) {
            for (String path : classpath.split(System.getProperty("path.separator"))) {
                this.addRootPath(new File(path).toPath());
            }
        }
    }

}

Handle path separator differences in AntLoader DAT-4036


package data;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;

import com.darwinsys.todo.model.Task;

/**
 * This is a basic DAO-like interface for use by JSF or EJB.
 * Methods are implemented for us by Apache DeltaSpike Data.
 * The methods in the inherited interface suffice for many apps!
 * @author Ian Darwin
 */
@Named("todoList") @Default
@SessionScoped
@Repository
public interface TodoList extends Serializable, EntityRepository<Task, Long> {

	// The ordering of Priority is 0=Top..3=Lowest, so sort by prio asc is correct here
	@Query(value="select t from Task t where t.status < 3 order by t.priority asc, t.name asc")
	List<Task> findAll();
}

package data;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;

import com.darwinsys.todo.model.Task;

/**
 * This is a basic DAO-like interface for use by JSF or EJB.
 * Methods are implemented for us by Apache DeltaSpike Data.
 * The methods in the inherited interface suffice for many apps!
 * @author Ian Darwin
 */
@Named("todoList") @Default
@SessionScoped
@Repository
public interface TodoList extends Serializable, EntityRepository<Task, Long> {

	// The ordering of Priority is 0=Top..3=Lowest, so sort by prio asc is correct here
	@Query(value="select t from Task t where t.status < 3 order by t.priority asc, lower(t.name) asc")
	List<Task> findAll();
}

Order by prio then lower(name)


import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AcronymTest {

    @Test
    public void fromTitleCasedPhrases() {
        final String phrase = "Portable Network Graphics";
        final String expected = "PNG";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherTitleCasedPhrases() {
        final String phrase = "Ruby on Rails";
        final String expected = "ROR";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromInconsistentlyCasedPhrases() {
        final String phrase = "HyperText Markup Language";
        final String expected = "HTML";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuation() {
        final String phrase = "First In, First Out";
        final String expected = "FIFO";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherPhrasesWithPunctuation() {
        final String phrase = "PHP: Hypertext Preprocessor";
        final String expected = "PHP";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuationAndSentenceCasing() {
        final String phrase = "Complementary metal-oxide semiconductor";
        final String expected = "CMOS";
        assertEquals(expected, Acronym.generate(phrase));
    }

}

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AcronymTest {

    @Test
    public void fromTitleCasedPhrases() {
        final String phrase = "Portable Network Graphics";
        final String expected = "PNG";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherTitleCasedPhrases() {
        final String phrase = "Ruby on Rails";
        final String expected = "ROR";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromInconsistentlyCasedPhrases() {
        final String phrase = "HyperText Markup Language";
        final String expected = "HTML";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuation() {
        final String phrase = "First In, First Out";
        final String expected = "FIFO";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherPhrasesWithPunctuation() {
        final String phrase = "PHP: Hypertext Preprocessor";
        final String expected = "PHP";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuationAndSentenceCasing() {
        final String phrase = "Complementary metal-oxide semiconductor";
        final String expected = "CMOS";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhraseWithSingleLetterWord() {
        final String phrase = "Cat in a Hat";
        final String expected = "CIAH";
        assertEquals(expected, Acronym.generate(phrase));
    }

}

Add testcase to Acronym test for single letter word


package net.simpvp.NoSpam;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {

	public CommandListener(NoSpam plugin) {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}

	@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
	public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {

		Player player = event.getPlayer();

		String message = event.getMessage().toLowerCase();

		/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
		if (message.startsWith("/tell ")
				|| message.startsWith("/me ")
				|| message.startsWith("/msg ")
				|| message.startsWith("/w ")
				|| message.startsWith("/op ")
				|| message.equals("/op")) {

			boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam

			if ( cancel ) event.setCancelled(true);

		}

	}

}

package net.simpvp.NoSpam;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {

	public CommandListener(NoSpam plugin) {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}

	@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
	public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {

		Player player = event.getPlayer();

		String message = event.getMessage().toLowerCase();

		/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
		if (message.startsWith("/tell ")
				|| message.startsWith("/me ")
				|| message.startsWith("/msg ")
				|| message.startsWith("/w ")
				|| message.startsWith("/op ")
				|| message.startsWith("/r ")
				|| message.startsWith("/m ")
				|| message.equals("/op")) {

			boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam

			if ( cancel ) event.setCancelled(true);

		}

	}

}

Add /r and /m to muted commands


package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testGetIndex() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }
}

package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testThymeleaf() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }

    @Test
    public void testJavascript() throws InterruptedException {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        Thread.sleep(1000); // There's probably a better way to wait for $(document).ready
        assertThat(pageSource()).contains("Hello from javascript!");
    }
}

Test confirming spring boot test runner loads external JARs


package com.github.mobile.android.core.repo;

import static org.eclipse.egit.github.core.event.Event.TYPE_FORK;

import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventPayload;
import org.eclipse.egit.github.core.event.ForkPayload;

/**
 * Helper to find a {@link RepositoryEventMatcher} to open for an event
 */
public class RepositoryEventMatcher {

    /**
     * Get {@link Repository} from event
     *
     * @param event
     * @return gist or null if event doesn't apply
     */
    public Repository getRepository(final Event event) {
        if (event == null)
            return null;
        EventPayload payload = event.getPayload();
        if (payload == null)
            return null;
        String type = event.getType();
        if (TYPE_FORK.equals(type))
            return ((ForkPayload) payload).getForkee();
        else
            return null;
    }
}

package com.github.mobile.android.core.repo;

import static org.eclipse.egit.github.core.event.Event.TYPE_CREATE;
import static org.eclipse.egit.github.core.event.Event.TYPE_FORK;

import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventPayload;
import org.eclipse.egit.github.core.event.EventRepository;
import org.eclipse.egit.github.core.event.ForkPayload;

/**
 * Helper to find a {@link RepositoryEventMatcher} to open for an event
 */
public class RepositoryEventMatcher {

    /**
     * Get {@link Repository} from event
     *
     * @param event
     * @return gist or null if event doesn't apply
     */
    public Repository getRepository(final Event event) {
        if (event == null)
            return null;
        EventPayload payload = event.getPayload();
        if (payload == null)
            return null;
        String type = event.getType();
        if (TYPE_FORK.equals(type))
            return ((ForkPayload) payload).getForkee();
        else if (TYPE_CREATE.equals(type)) {
            EventRepository repo = event.getRepo();
            if (repo != null) {
                String id = repo.getName();
                int slash = id.indexOf('/');
                if (slash > 0 && slash + 1 < id.length()) {
                    Repository full = new Repository();
                    full.setName(id.substring(slash + 1));
                    String login = id.substring(0, slash);
                    // Use actor if it matches login parsed from repository id
                    if (event.getActor() != null && login.equals(event.getActor().getLogin()))
                        full.setOwner(event.getActor());
                    else
                        full.setOwner(new User().setLogin(id.substring(0, slash)));
                    return full;
                }
            }
        }
        return null;
    }
}

Support opening repositories from create events


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

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

/** TestSuite for all of GWT's emul suites. */
public class AllTests {

  public static Test suite() {
    TestSuite suite = new TestSuite("All Emul tests");
    suite.addTest(BigDecimalSuite.suite());
    suite.addTest(BigIntegerSuite.suite());
    suite.addTest(CollectionsSuite.suite());
    suite.addTest(EmulSuite.suite());
    suite.addTest(EmulJava8Suite.suite());
    suite.addTest(TreeMapSuiteSub.suite());
    suite.addTest(TreeSetSuiteSub.suite());
    return suite;
  }
}

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

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

/** TestSuite for all of GWT's emul suites. */
@RunWith(Suite.class)
@SuiteClasses({
  BigDecimalSuite.class,
  BigIntegerSuite.class,
  CollectionsSuite.class,
  EmulSuite.class,
  EmulJava8Suite.class,
})
public class AllTests {}

Use @RunWith(Suite.class) for emul test suites.


package me.gowdru.notes.sort;

import java.util.Comparator;

/**
 * Defines contract for Sorter algorithm implementations
 */
public interface Sorter<T> {

    /**
     * sorts {@code items}i in an array by comparing them using {@code comparator}
     * @param items items to be sorted
     * @param comparator comparison assistant
     */
    public void sort(T[] items, Comparator<T> comparator);

}

package me.gowdru.notes.sort;

import java.util.Comparator;

/**
 * Defines contract for Sorter algorithm implementations
 */
public interface Sorter<T> {

    /**
     * sorts {@code items}i in an array by comparing them using {@code comparator}
     * @param items items to be sorted
     * @param comparator comparison assistant
     */
    public void sort(T[] items, Comparator<T> comparator);

    /**
     * swaps a pair of elements in array
     * @param array - array of items
     * @param pos1 position of an item to be swapped to/with
     * @param pos2 position of another item to be swapped to/with
     */
    public default void swap(T[] array, int pos1, int pos2){
        T tmp = array[pos1];
        array[pos1] = array[pos2];
        array[pos2] = tmp;
    }
}

Add swap method to base class


package uk.ac.ox.ndm.grails.utils.validator;

import com.google.common.base.Strings;

/**
 * @since 14/08/2015
 */
public class NhsNumberValidator implements Validator<String> {

    public Object isValid(String nhsNumberStr) {
        if (!Strings.isNullOrEmpty(nhsNumberStr)) {

            nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
            if (nhsNumberStr.length() != 10) {
                return "validation.nhsnumber.wronglength";
            }
            try {
                int checkDigit = 0;
                int[] nhsNumber = new int[nhsNumberStr.length()];
                for (int i = 0; i < nhsNumberStr.length(); i++) {
                    nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
                }
                if (nhsNumber.length == 10) {
                    for (int i = 0; i <= 8; i++) {
                        checkDigit += nhsNumber[i] * (10 - i);
                    }
                    checkDigit = (11 - (checkDigit % 11));
                    if (checkDigit == 11) checkDigit = 0;
                    if (checkDigit != 10) return checkDigit == nhsNumber[9];
                }
            } catch (NumberFormatException ignored) {
                // Just ignore this as we will return false
            }
        }
        return "validation.empty";
    }
}

package uk.ac.ox.ndm.grails.utils.validator;

import com.google.common.base.Strings;

/**
 * @since 14/08/2015
 */
public class NhsNumberValidator implements Validator<String> {

    public Object isValid(String nhsNumberStr) {
        if (!Strings.isNullOrEmpty(nhsNumberStr)) {

            nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
            if (nhsNumberStr.length() != 10) {
                return "validation.nhsnumber.wronglength";
            }
            try {
                int checkDigit = 0;
                int[] nhsNumber = new int[nhsNumberStr.length()];
                for (int i = 0; i < nhsNumberStr.length(); i++) {
                    nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
                }
                if (nhsNumber.length == 10) {
                    for (int i = 0; i <= 8; i++) {
                        checkDigit += nhsNumber[i] * (10 - i);
                    }
                    checkDigit = (11 - (checkDigit % 11));
                    if (checkDigit == 11) checkDigit = 0;
                    if (checkDigit != 10)
                        return checkDigit == nhsNumber[9] ? true : "validation.nhsnumber.invalid";
                }
            } catch (NumberFormatException ignored) {
                return "validation.nhsnumber.not.numeric";
            }
        }
        return "validation.empty";
    }
}

Add error return strings to the NHS number validator


package example;

import ethanjones.cubes.block.Block;

public class MyBlock extends Block {

  public MyBlock() {
    super("MyMod:block/texture.png");
  }
}

package example;

import ethanjones.cubes.block.Block;

public class MyBlock extends Block {

  public MyBlock() {
    super("MyMod:block/texture");
  }
}

Remove .png (automatically added now)


package com.volumetricpixels.vitals.main;

import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;

import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;

public class Vitals extends CommonPlugin {

        private VitalsConfiguration config;

        @Override
        public void onDisable() {
                getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
        }

        @Override
        public void onEnable() {
                config = new VitalsConfiguration(getDataFolder());

		// Register commands.
                AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
                getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);

                getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
        }

        public VitalsConfiguration getConfig() {
                return config;
        }

}

package com.volumetricpixels.vitals.main;

import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;

import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.commands.ProtectionCommands;
import com.volumetricpixels.vitals.main.commands.WorldCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;

public class Vitals extends CommonPlugin {

        private VitalsConfiguration config;

        @Override
        public void onDisable() {
                getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
        }

        @Override
        public void onEnable() {
                config = new VitalsConfiguration(getDataFolder());

		// Register commands.
                AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
                getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, ProtectionCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, WorldCommands.class, commandRegistration);

                getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
        }

        public VitalsConfiguration getConfig() {
                return config;
        }

}

Add registration of world + protection cmds


package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Default. Returns enough info to match locally. */
    DEFAULT_MIN("min"),
    /** Complete info for an item. */
    FULL("full"),
    /** Only works with sync watchedShows. */
    NOSEASONS("noseasons"),
    /** Only works with seasons/summary */
    EPISODES("episodes"),
    /** Only works with seasons/summary */
    FULLEPISODES("full,episodes");

    private final String value;

    Extended(String value) {
        this.value = value;
    }

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

package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Complete info for an item. */
    FULL("full"),
    /** Only works with sync watchedShows. */
    NOSEASONS("noseasons"),
    /** Only works with seasons/summary */
    EPISODES("episodes"),
    /** Only works with seasons/summary */
    FULLEPISODES("full,episodes");

    private final String value;

    Extended(String value) {
        this.value = value;
    }

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

Remove extended default value, should pass null instead.


package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

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

public class GeneratedCodeTest {

    private Class<?> genClass;

    @Before
    public void setUp() throws ClassNotFoundException {
        genClass = Class.forName("net.folab.fo.runtime._");
    }

    @Test
    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", "1");
        test("_b", "2");
        test("_c", "3");
        test("_d", "4");
        test("_e", "5");
        test("_f", "false");
        test("_t", "true");

    }

    public void test(String name, String string) throws NoSuchFieldException,
            IllegalAccessException {
        Field field = genClass.getField(name);
        Evaluable<?> value = (Evaluable<?>) field.get(null);
        assertThat(value.evaluate().toString(), is(string));
    }

}

package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

import net.folab.fo.runtime._fo._lang.Boolean;
import net.folab.fo.runtime._fo._lang.Integer;

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

public class GeneratedCodeTest {

    private Class<?> genClass;

    @Before
    public void setUp() throws ClassNotFoundException {
        genClass = Class.forName("net.folab.fo.runtime._");
    }

    @Test
    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", Integer.valueOf(1));
        test("_b", Integer.valueOf(2));
        test("_c", Integer.valueOf(3));
        test("_d", Integer.valueOf(4));
        test("_e", Integer.valueOf(5));
        test("_f", Boolean.FALSE);
        test("_t", Boolean.TRUE);

    }

    public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = genClass.getField(name);
        @SuppressWarnings("unchecked")
        Evaluable<T> value = (Evaluable<T>) field.get(null);
        assertThat(value.evaluate(), is(expected));
    }

}

Update test code to compare with real type rather than string value.


package org.scribe.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.junit.Test;

import static org.junit.Assert.*;

public class StreamUtilsTest
{

  @Test
  public void shouldCorrectlyDecodeAStream()
  {
    String value = "expected";
    InputStream is = new ByteArrayInputStream(value.getBytes());
    String decoded = StreamUtils.getStreamContents(is);
    assertEquals("expected", decoded);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldFailForNullParameter()
  {
    InputStream is = null;
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }
}

package org.scribe.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import static org.junit.Assert.*;

public class StreamUtilsTest
{

  @Test
  public void shouldCorrectlyDecodeAStream()
  {
    String value = "expected";
    InputStream is = new ByteArrayInputStream(value.getBytes());
    String decoded = StreamUtils.getStreamContents(is);
    assertEquals("expected", decoded);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldFailForNullParameter()
  {
    InputStream is = null;
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }

  @Test(expected = IllegalStateException.class)
  public void shouldFailWithBrokenStream()
  {
    // This object simulates problems with input stream.
    final InputStream is = new InputStream()
    {
      @Override
      public int read() throws IOException
      {
        throw new IOException();
      }
    };
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }

}

Add negative test for StreamUtils.getStreamContents


package edu.northwestern.bioinformatics.studycalendar.domain.auditing;

import java.util.Date;

/**
 * Subclass of core-commons' DataAuditInfo that aliases the "on" property as "time".
 * This is so that it can be used in HQL queries ("on" is apparently a reserved word).
 *
 * @author Rhett Sutphin
 */
public class DataAuditInfo extends edu.nwu.bioinformatics.commons.DataAuditInfo {
    public DataAuditInfo() { }

    public DataAuditInfo(String by, String ip) {
        super(by, ip);
    }

    public DataAuditInfo(String by, String ip, Date on) {
        super(by, ip, on);
    }

    public static DataAuditInfo copy(edu.nwu.bioinformatics.commons.DataAuditInfo source) {
        return new DataAuditInfo(
            source.getBy(), source.getIp(), source.getOn()
        );
    }

    public Date getTime() {
        return getOn();
    }

    public void setTime(Date on) {
        setOn(on);
    }

    /* Have to duplicate other accessors so that it will work with annotations without
       annotating the superclass. */
    public String getUsername() { return super.getBy(); }
    public void setUsername(String by) { super.setBy(by); }
    public String getIp() { return super.getIp(); }
    public void setIp(String ip) { super.setIp(ip); }
}

package edu.northwestern.bioinformatics.studycalendar.domain.auditing;

import org.hibernate.annotations.Type;

import java.util.Date;
import java.sql.Timestamp;

/**
 * Subclass of core-commons' DataAuditInfo that aliases the "on" property as "time".
 * This is so that it can be used in HQL queries ("on" is apparently a reserved word).
 *
 * @author Rhett Sutphin
 */
public class DataAuditInfo extends edu.nwu.bioinformatics.commons.DataAuditInfo {
    public DataAuditInfo() { }

    public DataAuditInfo(String by, String ip) {
        super(by, ip);
    }

    public DataAuditInfo(String by, String ip, Date on) {
        super(by, ip, on);
    }

    public static DataAuditInfo copy(edu.nwu.bioinformatics.commons.DataAuditInfo source) {
        return new DataAuditInfo(
            source.getBy(), source.getIp(), source.getOn()
        );
    }

    @Type(type = "timestamp")
    public Date getTime() {
        return getOn();
    }

    public void setTime(Date on) {
        setOn(on);
    }

    /* Have to duplicate other accessors so that it will work with annotations without
       annotating the superclass. */
    public String getUsername() { return super.getBy(); }
    public void setUsername(String by) { super.setBy(by); }
    public String getIp() { return super.getIp(); }
    public void setIp(String ip) { super.setIp(ip); }
}

Add timestamp type to time property for oracle


/*
 * Copyright 2014 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.jboss.forge.plugin.idea.ui.component;

import org.jboss.forge.addon.ui.input.InputComponent;

/**
 * A factory for {@link ComponentBuilder} instances.
 *
 * @author George Gastaldi
 */
public enum ComponentBuilderRegistry
{
    INSTANCE;

    private ComponentBuilder[] componentBuilders = {
            new CheckboxComponentBuilder(),
            new ComboComponentBuilder(),
            new RadioComponentBuilder(),
            new FileChooserComponentBuilder(),
            new DirectoryChooserComponentBuilder(),
            new JavaClassChooserComponentBuilder(),
            new JavaPackageChooserComponentBuilder(),
            new TextBoxComponentBuilder(),
            new PasswordComponentBuilder(),
            new TextAreaComponentBuilder(),
            new FallbackTextBoxComponentBuilder()};

    public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
    {
        for (ComponentBuilder builder : componentBuilders)
        {
            if (builder.handles(input))
            {
                return builder;
            }
        }
        throw new IllegalArgumentException(
                "No UI component found for input type of "
                        + input.getValueType()
        );
    }
}

/*
 * Copyright 2014 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.jboss.forge.plugin.idea.ui.component;

import org.jboss.forge.addon.ui.input.InputComponent;

/**
 * A factory for {@link ComponentBuilder} instances.
 *
 * @author George Gastaldi
 */
public enum ComponentBuilderRegistry
{
    INSTANCE;

    private ComponentBuilder[] componentBuilders = {
            new CheckboxComponentBuilder(),
            new ComboComponentBuilder(),
            new RadioComponentBuilder(),
            new TextBoxComponentBuilder(),
            new PasswordComponentBuilder(),
            new TextAreaComponentBuilder(),
            new FileChooserComponentBuilder(),
            new DirectoryChooserComponentBuilder(),
            new JavaClassChooserComponentBuilder(),
            new JavaPackageChooserComponentBuilder(),
            new FallbackTextBoxComponentBuilder()};

    public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
    {
        for (ComponentBuilder builder : componentBuilders)
        {
            if (builder.handles(input))
            {
                return builder;
            }
        }
        throw new IllegalArgumentException(
                "No UI component found for input type of "
                        + input.getValueType()
        );
    }
}

Fix ComponentBuilder order in registry


package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    RaceManager(0),
    WorkerBoat(1),
    Buoy(2),
    FlagBuoy(3),
    TomatoBuoy(4),
    TriangleBuoy(5),
    StartLine(6),
    FinishLine(7),
    StartFinishLine(8),
    Gate(9),
    ReferencePoint(10),
    Other(11);

    private int value;

    ObjectTypes(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    WorkerBoat,
    FlagBuoy,
    TomatoBuoy,
    TriangleBuoy,
    StartLine,
    FinishLine,
    StartFinishLine,

    RaceManager,  //from here, the relevant ObjectTypes:
    Buoy,
    Gate,
    Satellite,
    ReferencePoint,
    Other
}

Revert "Updated object types in Dev"


package com.seaglasslookandfeel.demo;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class TestScrollBars {

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL);
                scrollBar.setPreferredSize(new Dimension(15, 300));

                JPanel panel = new JPanel();
                panel.add(scrollBar, BorderLayout.CENTER);

                JFrame frame = new JFrame();
                frame.add(panel, BorderLayout.CENTER);
                frame.setSize(275, 125);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}

package com.seaglasslookandfeel.demo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class TestScrollBars {

    public static void main(String[] args) {
        if (true) {
            try {
                UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                JPanel panel = new JPanel();
                panel.setPreferredSize(new Dimension(500, 500));
                panel.setBackground(Color.WHITE);

                JScrollPane scrollPane = new JScrollPane(panel);

                JFrame frame = new JFrame();
                frame.add(scrollPane, BorderLayout.CENTER);
                frame.setSize(275, 125);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}

Use a scroll pane for the scroll bar test.


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

package org.openkilda.northbound.dto.flows;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

@Value
public class VerificationInput {
    @JsonProperty("timeout")
    private int timeoutMillis;

    @JsonCreator
    public VerificationInput(
            @JsonProperty("timeout") int timeoutMillis) {
        this.timeoutMillis = timeoutMillis;
    }
}

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

package org.openkilda.northbound.dto.flows;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

import java.util.Optional;

@Value
public class VerificationInput {
    public static final int DEFAULT_TIMEOUT = 2000;

    @JsonProperty("timeout")
    private int timeoutMillis;

    @JsonCreator
    public VerificationInput(
            @JsonProperty("timeout") Integer timeoutMillis) {
        this.timeoutMillis = Optional.ofNullable(timeoutMillis).orElse(DEFAULT_TIMEOUT);
    }
}

Make timeout value optional in flow verification request


package net.izenith.Commands;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;

import net.izenith.Main.Util;
import net.md_5.bungee.api.ChatColor;

public class PlayTime implements HubCommand{

	@Override
	public String getName() {
		return "playtime";
	}

	@Override
	public String[] getAliases() {
		return new String[]{"play","givemearimjobandbitemyear"};
	}

	@Override
	public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
		Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0]));
		Double timeHours = new Double(time)/(1000*60*60);
		sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + timeHours + " hours");
	}

	@Override
	public boolean onlyPlayers() {
		return false;
	}

	@Override
	public boolean hasPermission() {
		return false;
	}

	@Override
	public Permission getPermission() {
		return null;
	}

}

package net.izenith.Commands;

import java.text.DecimalFormat;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;

import net.izenith.Main.Util;
import net.md_5.bungee.api.ChatColor;

public class PlayTime implements HubCommand{

	@Override
	public String getName() {
		return "playtime";
	}

	@Override
	public String[] getAliases() {
		return new String[]{"play","givemearimjobandbitemyear"};
	}

	@Override
	public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
		Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0]));
		Double timeHours = new Double(time)/(1000*60*60);
		DecimalFormat df = new DecimalFormat("#.##");
		String shortTime = df.format(timeHours);
		sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + shortTime + " hours");
	}

	@Override
	public boolean onlyPlayers() {
		return false;
	}

	@Override
	public boolean hasPermission() {
		return false;
	}

	@Override
	public Permission getPermission() {
		return null;
	}

}

Fix to long decimal places


package sfBugsNew;

import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1219 {

    interface A {
    }

    interface B {
    }
    interface C {
    }
    interface D {
    }
    static class CC implements C {}
    static class DC implements D {}

    A objectA;

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public boolean compare(B objectB) {
        return (objectA == objectB);
    }

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
      public boolean compare(C objectC) {
        return (objectA == objectC);
    }

    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public static boolean compare(C objectC, D objectD) {
      return (objectC == objectD);
  }
}

package sfBugsNew;

import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1219 {

    interface A {
    }

    interface B {
    }
    interface C {
    }
    interface D {
    }
    static class CC implements C {}
    static class DC implements D {}

    A objectA;

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
    public boolean compare(B objectB) {
        return (objectA == objectB);
    }

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
      public boolean compare(C objectC) {
        return (objectA == objectC);
    }

    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public static boolean compare(C objectC, D objectD) {
      return (objectC == objectD);
  }
}

Make sure we don't miss "low" confidence warnings


package ceylon;

public final class Boolean extends Object {
    private final boolean value;

    private Boolean(boolean b) {
        value = b;
    }

    public static ceylon.Boolean instance(boolean b) {
        return new ceylon.Boolean(b);
    }

    @Extension
    public ceylon.String string() {
        return ceylon.String.instance(java.lang.Boolean.toString(value));
    }

    public boolean booleanValue() {
        return value;
    }
}

package ceylon;

public final class Boolean extends Object {
    private final boolean value;

    private Boolean(boolean b) {
        value = b;
    }

    public static ceylon.Boolean instance(boolean b) {
        return new ceylon.Boolean(b);
    }

    @Extension
    public ceylon.String string() {
        return ceylon.String.instance(java.lang.Boolean.toString(value));
    }

    @Extension
    public boolean booleanValue() {
        return value;
    }
}

Allow extension to primitive Java types


package com.sb.elsinore.html;

import java.io.IOException;

import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;

import com.sb.elsinore.LaunchControl;

import static org.rendersnake.HtmlAttributesFactory.*;

/**
 * Create a top bar for the web page.
 * @author Doug Edey
 */
public class TopBar implements Renderable {

    @Override
    public final void renderOn(HtmlCanvas htmlCanvas) throws IOException {
        htmlCanvas.div(id("topbar").class_("col-md-12"))
            .div(id("breweryTitle").class_("left  col-md-2"))
                .h1(class_("breweryNameHeader").onClick("editBreweryName()"))
                    .div(id("breweryName")).write("Elsinore")._div()
                    .small()
                        .a(href(LaunchControl.RepoURL))
                            .content("StrangeBrew Elsinore")
                    ._small()
                ._h1()
            ._div()
            .div(class_("center-left col-md-4"))._div()
            .div(class_("center-right col-md-4"))._div()
        ._div()
        .div(id("messages").style("display:none"))
            .div(class_("panel panel-warning"))
                .div(id("messages-title").class_("title panel-heading"))._div()
                .div(id("messages-body").class_("panel-body"))._div()
            ._div()
        ._div();
    }

}

package com.sb.elsinore.html;

import java.io.IOException;

import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;

import com.sb.elsinore.LaunchControl;

import static org.rendersnake.HtmlAttributesFactory.*;

/**
 * Create a top bar for the web page.
 * @author Doug Edey
 */
public class TopBar implements Renderable {

    @Override
    public final void renderOn(HtmlCanvas htmlCanvas) throws IOException {
        htmlCanvas.div(id("topbar").class_("row"))
            .div(id("breweryTitle").class_("left col-md-2"))
                .h1(class_("breweryNameHeader").onClick("editBreweryName()"))
                    .div(id("breweryName")).write("Elsinore")._div()
                    .small()
                        .a(href(LaunchControl.RepoURL))
                            .content("StrangeBrew Elsinore")
                    ._small()
                ._h1()
            ._div()
            .div(class_("center-left col-md-4"))._div()
            .div(class_("center-right col-md-4"))._div()
        ._div()
        .div(id("messages").class_("row").style("display:none"))
            .div(class_("panel panel-warning"))
                .div(id("messages-title").class_("title panel-heading"))._div()
                .div(id("messages-body").class_("panel-body"))._div()
            ._div()
        ._div();
    }

}

Improve the top bar for the error messages.


package fr.minepod.bootstrap;

import java.awt.HeadlessException;
import java.io.IOException;

public class CrashReport {
	public static String DebugFilePath = Config.DebugFilePath;

	public static void SendReport(String exception, String when) {
		try {
			if(Config.Logger != null)
				Config.Logger.severe(exception);
			javax.swing.JOptionPane.showMessageDialog(null, exception + "\n" +  Langage.WHEN.toString() + when + "\n\n\n" + Langage.DEBUGINFORMATIONS.toString() + ":\n\n" + fr.minepod.Utils.Files.ReadFile(DebugFilePath), Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (HeadlessException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		}
        System.exit(0);
	}
}

package fr.minepod.bootstrap;

import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;

public class CrashReport {
	public static void SendReport(String exception, String when) {
		try {
			if(Config.Logger != null)
				Config.Logger.severe(exception);

			String debugMsg = "";

			if(new File(Config.DebugFilePath).exists())
				debugMsg = fr.minepod.Utils.Files.ReadFile(Config.DebugFilePath);

			javax.swing.JOptionPane.showMessageDialog(null, exception + "\n" +  Langage.WHEN.toString() + when + "\n\n\n" + Langage.DEBUGINFORMATIONS.toString() + ":\n\n" + debugMsg, Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (HeadlessException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		}
        System.exit(0);
	}
}

Check if debug file exists


package sizebay.catalog.client.model;

import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;

@Getter
@Setter
public class Modeling   {

  private Long id;
  private String name;

  private Gender gender;
  private String gMerchantBrandName;
  private String gMerchantAgeGroup;
  private String gMerchantSizeType;

  private TypeEnum type;
  private Long brandId;
  private Long categoryId;
  private List<ModelingSizeMeasures> measures = new ArrayList<>();

  private Integer strongCategoryTypeId;
  private String strongCategoryTypeName;

  private int isShoe;

  @Getter
  @RequiredArgsConstructor
  public enum TypeEnum {
    PRODUCT("product"),
    BODY("body");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }

  @Getter
  @RequiredArgsConstructor
  public enum Gender {
    M("M"), F("F"), U("U");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }
}

package sizebay.catalog.client.model;

import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;

@Getter
@Setter
public class Modeling   {

  private Long id;
  private String name;

  private Gender gender;
  private String gMerchantBrandName;
  private String gMerchantAgeGroup;
  private String gMerchantSizeType;
  private String observation;

  private TypeEnum type;
  private Long brandId;
  private Long categoryId;
  private List<ModelingSizeMeasures> measures = new ArrayList<>();

  private Integer strongCategoryTypeId;
  private String strongCategoryTypeName;

  private int isShoe;

  @Getter
  @RequiredArgsConstructor
  public enum TypeEnum {
    PRODUCT("product"),
    BODY("body");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }

  @Getter
  @RequiredArgsConstructor
  public enum Gender {
    M("M"), F("F"), U("U");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }
}

Add attribute observation in measures table


public class item55_optimize_judiciously {
    public static void main(String[] args) {
        System.out.println("do not strive to write fast programs—strive to write good ones; speed will follow.");
    }
}

Add to item55 with a quote from the book


package com.nelsonjrodrigues.pchud;

import java.io.IOException;

import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PcHud {

    public static void main(String[] args) {

        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            log.error("Uncaught thread exception, exiting", t.getName(), e);
            System.exit(-1);
        });

        Worlds worlds = new Worlds();
        worlds.addPropertyChangeListener(evt -> {
            log.debug("{}", worlds);
        });

        try {
            NetThread netThread = new NetThread();
            netThread.addMessageListener(new LogMessageListener());
            netThread.addMessageListener(worlds);
            netThread.start();

            netThread.join();
        }
        catch (IOException | InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        log.debug("Exiting");

    }

    @Slf4j
    private static class LogMessageListener implements MessageListener {

        @Override
        public void onMessage(PcMessage message) {
            log.debug("OnMessage {}", message);
        }

        @Override
        public void onTimeout() {
            log.debug("OnTimeout");
        }

    }

}

package com.nelsonjrodrigues.pchud;

import java.io.IOException;

import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PcHud {

    public static void main(String[] args) {

        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            log.error("Uncaught thread exception, exiting", e);
            System.exit(-1);
        });

        Worlds worlds = new Worlds();
        worlds.addPropertyChangeListener(evt -> {
            log.debug("{}", worlds);
        });

        try {
            NetThread netThread = new NetThread();
            netThread.addMessageListener(new LogMessageListener());
            netThread.addMessageListener(worlds);
            netThread.start();

            netThread.join();
        }
        catch (IOException | InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        log.debug("Exiting");

    }

    @Slf4j
    private static class LogMessageListener implements MessageListener {

        @Override
        public void onMessage(PcMessage message) {
            log.debug("OnMessage {}", message);
        }

        @Override
        public void onTimeout() {
            log.debug("OnTimeout");
        }

    }

}

Remove unused log message param


package com.padakeji.android.ui.autowraplayoutmanager.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * Created by atanl on 2016/3/5.
 */
public class MyScrollView extends ScrollView {

    private int downX;
    private int downY;
    private int mTouchSlop;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) e.getRawX();
                downY = (int) e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) e.getRawY();
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
        }
        return super.onInterceptTouchEvent(e);
    }
}

package com.padakeji.android.ui.autowraplayoutmanager.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ScrollView;

/**
 * 继承于ScrollView，禁止了滑动事件向下传递。
 *
 * Created by atanl on 2015/10/20.
 */
public class MyScrollView extends ScrollView {

    public interface OnScrollListener {
        void onScroll();
    }

    private int downX;
    private int downY;
    private int mTouchSlop;

    public MyScrollView(Context context) {
        super(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) e.getRawX();
                downY = (int) e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) e.getRawY();
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
        }
        return super.onInterceptTouchEvent(e);
    }
}

Change the example module fixing scroll problem.


package uk.gov.register.core;

import uk.gov.register.core.Entry;
import uk.gov.mint.Item;

public class FatEntry {
    public final Entry entry;
    public final Item item;

    public FatEntry(Entry entry, Item item) {
        this.entry = entry;
        this.item = item;
    }
}

package uk.gov.register.core;

import uk.gov.mint.Item;

public class FatEntry {
    public final Entry entry;
    public final Item item;

    public FatEntry(Entry entry, Item item) {
        this.entry = entry;
        this.item = item;
    }
}

Remove unused Entry from mint import


/**
 * Part of Employ
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DashboardFrame extends CommonFrame implements ActionListener {

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    JButton buttonAddData = new JButton("Add");
    buttonAddData.addActionListener(this);
    add(buttonAddData);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    getContentPane().setBackground(Color.white);
    repaint();
  }

}

/**
 * Part of Employ
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textNumber = new JTextField(10);
  JTextField textOutput = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textNumber.addActionListener(this);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textNumber);
    add(textOutput);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    String inputNumber = textNumber.getText();
    textOutput.setText(inputNumber);

    if (event.getActionCommand().equals("addData"))
      getContentPane().setBackground(Color.white);
    else if (event.getActionCommand().equals("deleteData"))
      getContentPane().setBackground(Color.darkGray);
    else
      getContentPane().setBackground(Color.black);

    repaint();
  }

}

Add label and text field with application code


/**
 * Part of Employ
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textNumber = new JTextField(10);
  JTextField textOutput = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textNumber.addActionListener(this);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textNumber);
    add(textOutput);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    String inputNumber = textNumber.getText();
    textOutput.setText(inputNumber);

    if (event.getActionCommand().equals("addData"))
      getContentPane().setBackground(Color.white);
    else if (event.getActionCommand().equals("deleteData"))
      getContentPane().setBackground(Color.darkGray);
    else
      getContentPane().setBackground(Color.black);

    repaint();
  }

}

/**
 * Part of Employ
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textInputNumber = new JTextField(10);
  JTextField textOutputNumber = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textInputNumber.addActionListener(this);
    textOutputNumber.setEditable(false);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textInputNumber);
    add(textOutputNumber);
  }

  // get input number in text input
  void getTextInput() {
    String inputNumber = textInputNumber.getText();
    textOutputNumber.setText(inputNumber);
  }

  // clear input number in text input
  void clearInputNumber() {
    textOutputNumber.setText("");
  }

  // define listener action when button is clicked
  public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("addData"))
      getTextInput();
    else if (event.getActionCommand().equals("deleteData"))
      clearInputNumber();
    else
      getContentPane().setBackground(Color.white);

    repaint();
  }

}

Create button event with method


//
// $Id: SafeScrollPane.java,v 1.3 2002/07/09 21:13:20 ray Exp $

package com.threerings.media;

import java.awt.Component;

import javax.swing.JScrollPane;
import javax.swing.JViewport;

/**
 * A scroll pane that is safe to use in frame managed views.
 */
public class SafeScrollPane extends JScrollPane
{
    public SafeScrollPane (Component view)
    {
        super(view);
    }

    protected JViewport createViewport ()
    {
        JViewport vp = new JViewport();
        vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        return vp;
    }
}

//
// $Id: SafeScrollPane.java,v 1.4 2002/10/06 20:57:36 mdb Exp $

package com.threerings.media;

import java.awt.Component;

import javax.swing.JScrollPane;
import javax.swing.JViewport;

/**
 * A scroll pane that is safe to use in frame managed views.
 */
public class SafeScrollPane extends JScrollPane
{
    public SafeScrollPane ()
    {
    }

    public SafeScrollPane (Component view)
    {
        super(view);
    }

    protected JViewport createViewport ()
    {
        JViewport vp = new JViewport();
        vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        return vp;
    }
}

Allow a safe scroll pane to be constructed without its viewport view (which should be set later via setViewportView()).


/*******************************************************************************
 * Copyright (c) 2010, 2013 Sonatype, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Stuart McCulloch (Sonatype, Inc.) - initial API and implementation
 *******************************************************************************/
package org.sonatype.guice.bean.binders;

import java.util.List;

import com.google.inject.Module;

@Deprecated
public class WireModule
    extends org.eclipse.sisu.wire.WireModule
{
    public WireModule( final Module... modules )
    {
        super( modules );
    }

    public WireModule( final List<Module> modules )
    {
        super( modules );
    }
}

/*******************************************************************************
 * Copyright (c) 2010, 2013 Sonatype, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Stuart McCulloch (Sonatype, Inc.) - initial API and implementation
 *******************************************************************************/
package org.sonatype.guice.bean.binders;

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

import com.google.inject.Binder;
import com.google.inject.Module;

@Deprecated
public class WireModule
    implements Module
{
    private final Module delegate;

    public WireModule( final Module... modules )
    {
        this( Arrays.asList( modules ) );
    }

    public WireModule( final List<Module> modules )
    {
        delegate = new org.eclipse.sisu.wire.WireModule( modules );
    }

    public void configure( final Binder binder )
    {
        delegate.configure( binder );
    }
}

Update to use new strategy pattern


package com.mick88.dittimetable;

import java.util.List;

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

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;
	private static final String TAG = "SQLite";

	public DatabaseHelper(Context context) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

	public Timetable getTimetable(String course, int year, String weeks)
	{
		List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
				new String[]{course, String.valueOf(year), weeks},
				null, "1");
		if (timetables.isEmpty()) return null;
		Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
		return timetables.get(0);
	}

	public void saveTimetable(Timetable timetable)
	{
		replace(timetable);
		Log.d(TAG, "Timetable saved: "+timetable.describe());
	}
}

package com.mick88.dittimetable;

import java.util.List;

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

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;
	private static final String TAG = "SQLite";

	public DatabaseHelper(Context context) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

	public Timetable getTimetable(String course, int year, String weeks)
	{
		List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
				new String[]{course, String.valueOf(year), weeks},
				null, "1");
		if (timetables.isEmpty()) return null;
		Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
		return timetables.get(0);
	}

	public void saveTimetable(Timetable timetable)
	{
		replace(timetable);
		Log.d(TAG, "Timetable saved: "+timetable.describe());
	}

	/**
	 * returns all timetables saved in database
	 * @return
	 */
	public List<Timetable> getSavedTimetables()
	{
		return selectAll(Timetable.class);
	}
}

Add method to get all saved timetables


package net.runelite.cache;

public enum IndexType
{
	TWO(2),
	SPRITE(8);

	private int id;

	IndexType(int id)
	{
		this.id = id;
	}

	public int getNumber()
	{
		return id;
	}
}

package net.runelite.cache;

public enum IndexType
{
	TWO(2),
	MODELS(7),
	SPRITE(8);

	private int id;

	IndexType(int id)
	{
		this.id = id;
	}

	public int getNumber()
	{
		return id;
	}
}

Index 7 appears to be models. Am able to view them in rsmv.


package com.infinityraider.agricraft.plugins.industrialforegoing;

import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

import java.util.List;

public class AgriPlantRecollectable extends PlantRecollectable {
    protected AgriPlantRecollectable() {
        super(AgriCraft.instance.getModId());
    }

    @Override
    public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
        return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
    }

    @Override
    public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
        List<ItemStack> drops = Lists.newArrayList();
        AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
        return drops;
    }

    @Override
    public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
        return true;
    }
}

package com.infinityraider.agricraft.plugins.industrialforegoing;

import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

import java.util.List;

public class AgriPlantRecollectable extends PlantRecollectable {
    protected AgriPlantRecollectable() {
        super(AgriCraft.instance.getModId());
        this.setRegistryName(AgriCraft.instance.getModId(), "plant_recollectable");
    }

    @Override
    public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
        return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
    }

    @Override
    public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
        List<ItemStack> drops = Lists.newArrayList();
        AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
        return drops;
    }

    @Override
    public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
        return true;
    }
}

Fix Industrial Foregoing Compat crash


package net.earthcomputer.easyeditors.api;

import java.util.regex.Pattern;

/**
 * A class containing a number of {@link Pattern}s useful to Easy Editors.
 *
 * <b>This class is a member of the Easy Editors API</b>
 *
 * @author Earthcomputer
 *
 */
public class Patterns {

	public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");

	public static final Pattern playerName = Pattern.compile("\\w{1,32}");

	public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");

	public static final Pattern partialUUID = Pattern
			.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");

	public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w=,!-]*)\\])?");

	public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");

	public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");

}

package net.earthcomputer.easyeditors.api;

import java.util.regex.Pattern;

/**
 * A class containing a number of {@link Pattern}s useful to Easy Editors.
 *
 * <b>This class is a member of the Easy Editors API</b>
 *
 * @author Earthcomputer
 *
 */
public class Patterns {

	public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");

	public static final Pattern playerName = Pattern.compile("\\w{1,32}");

	public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");

	public static final Pattern partialUUID = Pattern
			.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");

	public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w\\.=,!-]*)\\])?");

	public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");

	public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");

}

Allow entities with dots in their names in the player selector pattern


/* NEST (New Scala Test)
 * Copyright 2007-2013 LAMP/EPFL
 * @author Grzegorz Kossakowski
 */

package scala.tools.partest.javaagent;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

/**
 * Profiling agent that instruments byte-code to insert calls to
 * {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
 * by using ASM library for byte-code manipulation.
 */
public class ProfilingAgent {
	public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
	  // NOTE: we are adding transformer that won't be applied to classes that are already loaded
	  // This should be ok because premain should be executed before main is executed so Scala library
	  // and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
	  // not depend on Scala library. In case our assumptions are wrong we can always insert call to
	  // inst.retransformClasses.
		inst.addTransformer(new ASMTransformer(), true);
	}
}

/* NEST (New Scala Test)
 * Copyright 2007-2013 LAMP/EPFL
 * @author Grzegorz Kossakowski
 */

package scala.tools.partest.javaagent;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

/**
 * Profiling agent that instruments byte-code to insert calls to
 * {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
 * by using ASM library for byte-code manipulation.
 */
public class ProfilingAgent {
	public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
	  // NOTE: we are adding transformer that won't be applied to classes that are already loaded
	  // This should be ok because premain should be executed before main is executed so Scala library
	  // and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
	  // not depend on Scala library. In case our assumptions are wrong we can always insert call to
	  // inst.retransformClasses.
	  inst.addTransformer(new ASMTransformer(), false);
	}
}

Set `canRetransform` flag to `false` in instrumentation.


public class Ex {

	public void frotz(Object o, int y) {
		if (y == 6) {
			synchronized (o) {
				y += o.hashCode();
				if ((y & 1) == 0)
					throw new RuntimeException();
			}
		}
	}

}

public class Ex {

	public void frotz(Object o, int y) {
		if (y == 6) {
			synchronized (o) {
				y += o.hashCode();
				if ((y & 1) == 0)
					throw new RuntimeException();
			}
		}
	}

	public void alwaysThrow() {
		throw new RuntimeException();
	}

}

Add a method that always throws an unhandled exception.


package ol.geom;

import ol.BaseTestCase;
import ol.Coordinate;
import ol.OLFactory;

/**
 * A test case for {@link Circle}.
 *
 * @author Tino Desjardins
 */
public class CircleTest extends BaseTestCase {

    public void test() {

        double radius = 5;

        Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
        assertNotNull(circle);
        assertTrue(circle instanceof Geometry);

        Coordinate coordinate = circle.getCenter();
        assertNotNull(coordinate);
        assert(10 == coordinate.getX());
        assert(10 == coordinate.getY());

        assert(radius == circle.getRadius());

    }

}

package ol.geom;

import ol.Coordinate;
import ol.GwtOL3BaseTestCase;
import ol.OLFactory;

/**
 * A test case for {@link Circle}.
 *
 * @author Tino Desjardins
 */
public class CircleTest extends GwtOL3BaseTestCase {

    public void testCircle() {

    	injectUrlAndTest(new TestWithInjection() {

			@Override
			public void test() {

				double radius = 5;

		        Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
		        assertNotNull(circle);
		        assertTrue(circle instanceof Geometry);

		        Coordinate coordinate = circle.getCenter();
		        assertNotNull(coordinate);
		        assert(10 == coordinate.getX());
		        assert(10 == coordinate.getY());

		        assert(radius == circle.getRadius());

			}});

    }

}

Add test for circle geometry


import java.awt.Image;
import java.net.URL;

public class MediaCheck {

    public static void media(URL url) {

	    Image image = null;
    }
 }

Create a method which contains URL as argument and create an Image variable


package com.darwinsys.springbootdemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller()
public class NotAServlet {

	@RequestMapping("/notaservlet")
	protected String doWork(@RequestParam(value="name") String name, Model model) {
		model.addAttribute("greets", String.format("
Hello %s!!
", name));
		return "hello";
	}
}

package com.darwinsys.springbootdemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller()
public class NotAServlet {

	@RequestMapping(value="/notaservlet", method=RequestMethod.GET)
	public String doWork(@RequestParam("name") String name, ModelMap model) {
		System.out.println("NotAServlet.doWork()");
		model.addAttribute("greetings", String.format("
Hello %s!!
", name));
		return "hello";
	}
}

Clean up; use ModelMap not Model; only GET method.


package net.teamio.blockunit;

/**
 * Created by oliver on 2017-07-03.
 */
public class TestingHarness {
	public void assertEquals(int a, int b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b);
		}
	}

	public void assertEquals(boolean a, boolean b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b);
		}
	}

	public void assertNull(Object o) {
		if (o != null) {
			throw new TestAssertionException("AssertNull: passed object is not null");
		}
	}

	public void assertNotNull(Object o) {
		if (o == null) {
			throw new TestAssertionException("AssertNotNull: passed object is null");
		}
	}

	public void assertTrue(boolean b) {
		if (!b) {
			throw new TestAssertionException("AssertTrue: passed value is false");
		}
	}

	public void assertFalse(boolean b) {
		if (b) {
			throw new TestAssertionException("AssertFalse: passed value is true");
		}
	}
}

package net.teamio.blockunit;

/**
 * Created by oliver on 2017-07-03.
 */
public class TestingHarness {
	public void assertEquals(int a, int b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b);
		}
	}

	public void assertEquals(boolean a, boolean b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b);
		}
	}

	public void assertNull(Object o) {
		if (o != null) {
			throw new TestAssertionException("AssertNull: passed object is not null");
		}
	}

	public void assertNotNull(Object o) {
		if (o == null) {
			throw new TestAssertionException("AssertNotNull: passed object is null");
		}
	}

	public void assertTrue(boolean b) {
		if (!b) {
			throw new TestAssertionException("AssertTrue: passed value is false");
		}
	}

	public void assertFalse(boolean b) {
		if (b) {
			throw new TestAssertionException("AssertFalse: passed value is true");
		}
	}

	public void fail() {
		throw new TestAssertionException("Test failed");
	}

	public void fail(String message) {
		throw new TestAssertionException("Test failed: %s", message);
	}
}

Add fail option to testing harness


public class Prova {

	public static void main(String[] args) {
		System.out.println(42);
	}

}

public class Prova {

	public static void main(String[] args) {
		System.out.println(42);
		System.out.println("Prova di modifica");
	}

}

Test di verifica di aggiornamento


package org.nusco.swimmers.creature.genetics;

class OrganParser {

	private final int[] genes;
	private int index_in_genes = 0;

	public OrganParser(DNA dna) {
		genes = dna.getGenes();
	}

	public int[] nextPart() {
		int[] result = new int[OrganBuilder.GENES_PER_PART];
		int index_in_result = 0;
		while(index_in_result < result.length) {
			if(index_in_genes >= genes.length)
				return result;
			if(isTerminator(genes[index_in_genes])) {
				index_in_genes++;
				return result;
			}
			result[index_in_result] = genes[index_in_genes];
			index_in_result++;
			index_in_genes++;
		}
		return result;
	}

	private boolean isTerminator(int b) {
		// TODO: is the idea of a terminator ever useful?
		// (for sure, it wasn't working the way I implemented it)
		return false;
	}
}

package org.nusco.swimmers.creature.genetics;

class OrganParser {

	private final int[] genes;
	private int index_in_genes = 0;

	public OrganParser(DNA dna) {
		genes = dna.getGenes();
	}

	public int[] nextPart() {
		int[] result = new int[OrganBuilder.GENES_PER_PART];
		int index_in_result = 0;
		while(index_in_result < result.length) {
			if(index_in_genes >= genes.length)
				return result;
			result[index_in_result] = genes[index_in_genes];
			index_in_result++;
			index_in_genes++;
		}
		return result;
	}
}

Remove the concept of a DNA terminator


package spacefront;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.Set;

public class Shot extends SpaceObject {

    private static final double SIZE = 8;
    private static final Shape SHAPE
        = new Ellipse2D.Double(-SIZE / 2, -SIZE / 2, SIZE, SIZE);

    private static final long serialVersionUID = 1L;

    private static final double SPEED = 8;

    public Shot(double destx, double desty) {
        super(0, 0, 0);
        double a = Math.atan2(desty, destx);
        setSpeed(Math.cos(a) * SPEED, Math.sin(a) * SPEED, 0);
        setShape(SHAPE);
    }

    public Meteoroid step(Set<Meteoroid> targets) {
        super.step();
        for (Meteoroid m : targets) {
            if (m.get().contains(getX(), getY())) {
                return m;
            }
        }
        return null;
    }

    public void paint(Graphics2D g) {
        g.setColor(Color.RED);
        g.fill(get());
    }
}

package spacefront;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.Set;

public class Shot extends SpaceObject {

    private static final long serialVersionUID = 1L;

    /* Appearance */
    private static final double SIZE = 8;
    public static final Color COLOR = Color.RED;
    public static final Shape SHAPE =
        new Ellipse2D.Double(-SIZE / 2, -SIZE / 2, SIZE, SIZE);
    private static final double OSCILLATION_RATE = 32;
    private static final double OSCILLATION_SCALE = 3;

    /* Behavior */
    private static final double SPEED = 8;

    public Shot(double destx, double desty) {
        super(0, 0, 0);
        double a = Math.atan2(desty, destx);
        setSpeed(Math.cos(a) * SPEED, Math.sin(a) * SPEED, 0);
        setShape(SHAPE);
    }

    public Meteoroid step(Set<Meteoroid> targets) {
        super.step();
        for (Meteoroid m : targets) {
            if (m.get().contains(getX(), getY())) {
                return m;
            }
        }
        return null;
    }

    public void paint(Graphics2D g) {
        g.setColor(COLOR);
        Shape self = get();
        long time = System.currentTimeMillis();
        double scale = Math.sin(time / OSCILLATION_RATE) /
            OSCILLATION_SCALE + 1d;
        AffineTransform at = getTransform();
        at.scale(scale, scale);
        g.fill(at.createTransformedShape(getShape()));
    }
}

Make the shots a little more interesting.


package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.gml;

import com.sensia.relaxNG.RNGElement;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;
import com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.element.EditSimpleElementPanel;
import com.sensia.tools.client.swetools.editors.sensorml.utils.Utils;

public class GMLEditNamePanel extends EditSimpleElementPanel{

	public GMLEditNamePanel(RNGElement element) {
		super(element,Utils.findLabel(element.getParent()));
	}

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

package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.gml;

import com.sensia.relaxNG.RNGElement;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;
import com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.element.EditSimpleElementPanel;
import com.sensia.tools.client.swetools.editors.sensorml.utils.Utils;

public class GMLEditNamePanel extends EditSimpleElementPanel{

	public GMLEditNamePanel(RNGElement element) {
		super(element,Utils.findLabel(element));
	}

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

Use findLabel on tag itself instead of parent


package com.saucelabs.common;

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

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class SauceHelperTest {
    private SauceHelper sauceHelper;
    @Before
    public void runBeforeEveryTest()
    {
        sauceHelper = new SauceHelper();
    }
    @Test
    public void shouldReturnPassedForTrueResult()
    {
        assertStringsEqual("sauce:job-result=", true);
    }
    @Test
    public void shouldReturnFailedForFalseResult()
    {
        assertStringsEqual("sauce:job-result=", false);
    }
    @Test
    public void shouldReturnCorrectStringForTestName()
    {
        String testName = "MyTestName";
        assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
    }
    @Test
    public void shouldReturnSauceContextString()
    {
        String comment = "This is a comment";
        assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
    }
    @Test
    public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
    {
        JavaScriptInvokerManager mockCustomJsManager = mock(JavaScriptInvokerManager.class);
        JavaScriptInvokerFactory.setJavaScriptInvoker(mockCustomJsManager);

        sauceHelper.setTestStatus("pass");
        verify(mockCustomJsManager, times(1)).executeScript("sauce:job-result=pass");
    }
    private void assertStringsEqual(String s, boolean b) {
        assertEquals(s + b, sauceHelper.getTestResultString(b));
    }
}

package com.saucelabs.common;

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

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class SauceHelperTest {
    private SauceHelper sauceHelper;
    @Before
    public void runBeforeEveryTest()
    {
        sauceHelper = new SauceHelper();
    }
    @Test
    public void shouldReturnPassedForTrueResult()
    {
        assertStringsEqual("sauce:job-result=", true);
    }
    @Test
    public void shouldReturnFailedForFalseResult()
    {
        assertStringsEqual("sauce:job-result=", false);
    }
    @Test
    public void shouldReturnCorrectStringForTestName()
    {
        String testName = "MyTestName";
        assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
    }
    @Test
    public void shouldReturnSauceContextString()
    {
        String comment = "This is a comment";
        assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
    }
    @Test
    public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
    {
        JavaScriptInvokerManager javascriptExecutor = mock(JavaScriptInvokerManager.class);
        JavaScriptInvokerFactory.setJavaScriptInvoker(javascriptExecutor);

        sauceHelper.setTestStatus("pass");
        verify(javascriptExecutor, times(1)).executeScript("sauce:job-result=pass");
    }
    private void assertStringsEqual(String s, boolean b) {
        assertEquals(s + b, sauceHelper.getTestResultString(b));
    }
}

Rename variable to javascriptExecutor in unit test


package sfBugs;

import edu.umd.cs.findbugs.annotations.DesireNoWarning;

public class Bug3062023 {
	private enum E {
		A, B, C, D
	}

	@DesireNoWarning("DB_DUPLICATE_SWITCH_CLAUSES")
	private void noWarning(E e) {
		switch (e) {
			case A:
				something();
				break;
			case B:
				//Nothing to report
				break;
			case C:
				something();
				break;
			case D:
				something();
				break;
			default:
				something();
				break;
		}
	}

	private void something() {
	}
}

package sfBugs;

import edu.umd.cs.findbugs.annotations.DesireNoWarning;

public class Bug3062023 {
	private enum E {
		A, B, C, D
	}

	@DesireNoWarning("DB_DUPLICATE_SWITCH_CLAUSES")
	private void noWarning(E e) {
		switch (e) {
			case A:
				something(1);
				break;
			case B:
				//Nothing to report
				break;
			case C:
				something(2);
				break;
			case D:
				break;
			default:
				something(10);
				break;
		}
	}

	private void something(int i) {
	}
}

Update test case for 3062023 to reflect actual bug being reported


package com.dglogik.common;

import android.app.Application;
import android.support.multidex.MultiDex;

import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;

@ReportsCrashes(
        formKey = "",
        mode = ReportingInteractionMode.DIALOG,
        mailTo = "k.endfinger@dglogik.com"
)
public class DGApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        MultiDex.install(this);
        // The following line triggers the initialization of ACRA
        ACRA.init(this);
    }
}

package com.dglogik.common;

import android.app.Application;
import android.support.multidex.MultiDex;

import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;

@ReportsCrashes(
        formKey = "",
        mode = ReportingInteractionMode.DIALOG,
        mailTo = "k.endfinger@dglogik.com"
)
public class DGApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // The following line triggers the initialization of ACRA
        ACRA.init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

Fix where multidex is installed.


package io.vertx.codegen;

/**
 * Describes a module.
 *
 * @author Julien Viet
 */
public class ModuleInfo {

  private final String fqn;
  private final String name;

  public ModuleInfo(String fqn, String name) {
    this.fqn = fqn;
    this.name = name;
  }

  /**
   * @return the module fqn, i.e the name of the package annotated with the {@link io.vertx.codegen.annotations.GenModule} annotation
   */
  public String getFqn() {
    return fqn;
  }

  /**
   * @return the module name
   */
  public String getName() {
    return name;
  }
}

package io.vertx.codegen;

/**
 * Describes a module.
 *
 * @author Julien Viet
 */
public class ModuleInfo {

  private final String fqn;
  private final String name;

  public ModuleInfo(String fqn, String name) {
    this.fqn = fqn;
    this.name = name;
  }

  /**
   * @return the module fqn, i.e the name of the package annotated with the {@link io.vertx.codegen.annotations.GenModule} annotation
   */
  public String getFqn() {
    return fqn;
  }

  /**
   * @return the module name
   */
  public String getName() {
    return name;
  }

  /**
   * @param _case the formatting case
   * @return the module name in the specified case
   */
  public String getName(Case _case) {
    return _case.format(Case.CAMEL.parse(name));
  }
}

Allow to format a module name with a case


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

package ch.myniva.gradle.caching.s3;

import org.gradle.api.Action;
import org.gradle.api.credentials.AwsCredentials;
import org.gradle.caching.configuration.AbstractBuildCache;

public class AwsS3BuildCache extends AbstractBuildCache {

  private AwsCredentials credentials;
  private String region;
  private String bucket;

  /**
   * Returns the credentials used to access the AWS S3 bucket.
   */
  public AwsCredentials getCredentials() {
    return credentials;
  }

  /**
   * Configures the credentials used to access the AWS S3 bucket.
   */
  public void credentials(Action<? super AwsCredentials> configuration) {
    configuration.execute(credentials);
  }

  public String getRegion() {
    return region;
  }

  public void setRegion(String region) {
    this.region = region;
  }

  public String getBucket() {
    return bucket;
  }

  public void setBucket(String bucket) {
    this.bucket = bucket;
  }
}

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

package ch.myniva.gradle.caching.s3;

import org.gradle.caching.configuration.AbstractBuildCache;

public class AwsS3BuildCache extends AbstractBuildCache {

  private String region;
  private String bucket;

  public String getRegion() {
    return region;
  }

  public void setRegion(String region) {
    this.region = region;
  }

  public String getBucket() {
    return bucket;
  }

  public void setBucket(String bucket) {
    this.bucket = bucket;
  }
}

Remove AWS credentioals from build cache config