package com.skelril.aurora.prayer.PrayerFX;

import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * Author: Turtle9598
 */
public class InventoryFX extends AbstractPrayer {

    int type, amount;

    public InventoryFX() {
        super();
        this.type = BlockID.DIRT;
        this.amount = 1;
    }

    public InventoryFX(int type, int amount) {
        super();
        this.type = type;
        this.amount = amount;
    }

    @Override
    public PrayerType getType() {

        return PrayerType.INVENTORY;
    }

    @Override
    public void add(Player player) {

        ItemStack held = player.getItemInHand().clone();
        ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
        if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
            Item item = player.getWorld().dropItem(player.getLocation(), held);
            item.setPickupDelay(20 * 5);
        }
        player.setItemInHand(stack);
    }

    @Override
    public void clean(Player player) {

        // Nothing to do here
    }
}

package com.skelril.aurora.prayer.PrayerFX;

import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * Author: Turtle9598
 */
public class InventoryFX extends AbstractPrayer {

    private int type, amount;

    public InventoryFX() {
        super();
        this.type = BlockID.DIRT;
        this.amount = 1;
    }

    public InventoryFX(int type, int amount) {
        super();
        this.type = type;
        this.amount = amount;
    }

    @Override
    public PrayerType getType() {

        return PrayerType.INVENTORY;
    }

    @Override
    public void add(Player player) {

        ItemStack held = player.getItemInHand().clone();
        ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
        if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
            Item item = player.getWorld().dropItem(player.getLocation(), held);
            item.setPickupDelay(20 * 5);
        }
        player.setItemInHand(stack);
    }

    @Override
    public void clean(Player player) {

        // Nothing to do here
    }
}

Fix bad habit caused by c++ programming


package com.chbi.rest;

import com.chbi.ApplicationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary.
 */
@Service
public class UrlRewriter {

    public static final String API_JSON_URL_ENDING = "api/json";

    @Autowired
    private ApplicationConfiguration configuration;

    String prepareUrl(String baseUrl) {

        String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(),
                configuration.getUrlReplacement());
        preparedUrl += API_JSON_URL_ENDING;

        return preparedUrl;
    }

    String getPreparedBaseUrl() {
        return prepareUrl(configuration.getBaseUrl());
    }
}

package com.chbi.rest;

import com.chbi.ApplicationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary.
 */
@Service
public class UrlRewriter {

    private static final String API_JSON_URL_ENDING = "api/json";
    private static final String HTML_WHITESPACE = "%20";
    private static final String WHITESPACE = " ";

    @Autowired
    private ApplicationConfiguration configuration;

    String prepareUrl(String baseUrl) {

        String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(),
                configuration.getUrlReplacement());
        preparedUrl = StringUtils.replace(preparedUrl, HTML_WHITESPACE, WHITESPACE);
        preparedUrl += API_JSON_URL_ENDING;

        return preparedUrl;
    }

    String getPreparedBaseUrl() {
        return prepareUrl(configuration.getBaseUrl());
    }
}

Fix urls with %20 instead of whitespaces


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.soundevent.USoundEvent;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestSounds {

	public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use");

	@SubscribeEvent
	public static void register(Register<SoundEvent> event) {
		BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, SoundEvent.class).forEach(event.getRegistry()::register);
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.soundevent.USoundEvent;
import info.u_team.u_team_test.TestMod;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestSounds {

	public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, TestMod.MODID);

	public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use");

	public static void register(IEventBus bus) {
		SOUND_EVENTS.register(bus);
	}

}

Add deferred register to test sounds


package kamkor.covariance;

import org.junit.Test;

public class CovariantArrayExample {

	// Scala solves this by making its Arrays invariant (nonvariant)
	@Test(expected = ArrayStoreException.class)
	public void covariantArraysLeadToRuntimeExceptions() {
		String[] c1 = { "abc" };
		Object[] c2 = c1;
		// OOPS! Line below throws a runtime exception: ArrayStoreException
		// Reason is, that c2 is actually an instance of String array, and
		// we try to update it with an Integer.
		c2[0] = 1;
	}

}

package kamkor.covariance;

import org.junit.Test;

public class CovariantArrayExample {

	// Scala solves this by making its Arrays invariant (nonvariant)
	@Test(expected = ArrayStoreException.class)
	public void covariantArraysLeadToRuntimeExceptions() {
		String[] strings = { "abc" };
		Object[] objects = strings;
		// OOPS! Line below throws a runtime exception: ArrayStoreException
		// Reason is, that objects is actually an instance of String array, and
		// we try to update it with an Integer.
		objects[0] = 1;
	}

}

Refactor Java covariant array example


import java.util.stream.IntStream;

/**
 * @author David Clutter
 */
public class Problem0001 {

    public static void main(final String[] args) {
        System.out.println(
                IntStream.range(1, 1000)
                        .filter(n -> n % 3 == 0 || n % 5 == 0)
                        .sum()
        );
    }
}

import java.util.stream.IntStream;

/**
 * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
 * multiples is 23.
 *
 * Find the sum of all the multiples of 3 or 5 below 1000.
 *
 * @author David Clutter
 */
public class Problem0001 {

    public static void main(final String[] args) {
        System.out.println(
                IntStream.range(1, 1000)
                        .filter(n -> n % 3 == 0 || n % 5 == 0)
                        .sum()
        );
    }
}

Add problem text to javadoc


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.util.time;

import org.testng.annotations.Test;
import org.threeten.bp.LocalDate;

import com.opengamma.util.test.AbstractFudgeBuilderTestCase;

/**
 * Test Fudge encoding.
 */
@Test(groups = "unit")
public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase {

  public void test_inclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_exclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

}

/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.util.time;

import org.testng.annotations.Test;
import org.threeten.bp.LocalDate;

import com.opengamma.util.test.AbstractFudgeBuilderTestCase;

/**
 * Test Fudge encoding.
 */
@Test(groups = "unit")
public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase {

  public void test_inclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_exclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_all() {
    assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL);
  }

}

Add test for fudge serialization of LocalDate.ALL


package se.vidstige.jadb;

import java.io.IOException;
import java.util.Map;

/**
 * Launches the ADB server
 */
public class AdbServerLauncher {
    private final String executable;
    private Subprocess subprocess;

    public AdbServerLauncher(Subprocess subprocess, Map<String, String> environment) {
        this.subprocess = subprocess;
        this.executable = findAdbExecutable(environment);
    }

    private static String findAdbExecutable(Map<String, String> environment) {
        String android_home = environment.get("ANDROID_HOME");
        if (android_home == null || android_home.equals("")) {
            return "adb";
        }
        return android_home + "/platform-tools/adb";
    }

    public void launch() throws IOException, InterruptedException {
        Process p = subprocess.execute(new String[]{executable, "start-server"});
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) throw new IOException("adb exited with exit code: " + exitValue);
    }
}

package se.vidstige.jadb;

import java.io.IOException;
import java.util.Map;

/**
 * Launches the ADB server
 */
public class AdbServerLauncher {
    private final String executable;
    private Subprocess subprocess;

    /**
     * Creates a new launcher loading ADB from the environment.
     *
     * @param subprocess the sub-process.
     * @param environment the environment to use to locate the ADB executable.
     */
    public AdbServerLauncher(Subprocess subprocess, Map<String, String> environment) {
        this(subprocess, findAdbExecutable(environment));
    }

    /**
     * Creates a new launcher with the specified ADB.
     *
     * @param subprocess the sub-process.
     * @param executable the location of the ADB executable.
     */
    public AdbServerLauncher(Subprocess subprocess, String executable) {
        this.subprocess = subprocess;
        this.executable = executable;
    }

    private static String findAdbExecutable(Map<String, String> environment) {
        String android_home = environment.get("ANDROID_HOME");
        if (android_home == null || android_home.equals("")) {
            return "adb";
        }
        return android_home + "/platform-tools/adb";
    }

    public void launch() throws IOException, InterruptedException {
        Process p = subprocess.execute(new String[]{executable, "start-server"});
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) throw new IOException("adb exited with exit code: " + exitValue);
    }
}

Allow the location of the ADB binary to be specified.


package hex.schemas;

import hex.tree.drf.DRF;
import hex.tree.drf.DRFModel.DRFParameters;
import water.api.API;
import water.api.SupervisedModelParametersSchema;
import hex.schemas.SharedTreeV2;                        // Yes, this is needed.  Compiler bug.
import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed.  Compiler bug.

public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> {

  public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> {
    static public String[] own_fields = new String[] {
        "mtries",
        "sample_rate",
        "do_grpsplit",
        "build_tree_one_node"
    };

    // Input fields
    @API(help = "Columns to randomly select at each level, or -1 for sqrt(#cols)")
    public int mtries;

    @API(help = "Sample rate, from 0. to 1.0")
    public float sample_rate;

    @API(help = "Check non-contiguous group splits for categorical predictors")
    public boolean do_grpsplit;

    @API(help="Run on one node only; no network overhead but fewer cpus used.  Suitable for small datasets.")
    public boolean build_tree_one_node;
  }
}

package hex.schemas;

import hex.tree.drf.DRF;
import hex.tree.drf.DRFModel.DRFParameters;
import water.api.API;
import water.api.SupervisedModelParametersSchema;
import hex.schemas.SharedTreeV2;                        // Yes, this is needed.  Compiler bug.
import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed.  Compiler bug.

public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> {

  public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> {
    static public String[] own_fields = new String[] {
        "mtries",
        "sample_rate",
        "build_tree_one_node"
    };

    // Input fields
    @API(help = "Number of columns to randomly select at each level, or -1 for sqrt(#cols)")
    public int mtries;

    @API(help = "Sample rate, from 0. to 1.0")
    public float sample_rate;

    @API(help="Run on one node only; no network overhead but fewer cpus used.  Suitable for small datasets.")
    public boolean build_tree_one_node;
  }
}

Fix DRFParametersV2, remove unused do_grpsplit argument.


package mil.nga.giat.geowave.core.store.query.aggregate;

import mil.nga.giat.geowave.core.index.Persistable;

public class CountAggregation<T> implements
		Aggregation<Persistable, CountResult, T>
{
	private CountResult countResult = new CountResult();

	public CountAggregation() {}

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

	@Override
	public void aggregate(
			final T entry ) {
		if (!countResult.isSet()) {
			countResult.count = 0;
		}
		countResult.count += 1;
	}

	@Override
	public Persistable getParameters() {
		return null;
	}

	@Override
	public CountResult getResult() {
		if (!countResult.isSet()) {
			return null;
		}
		return countResult;
	}

	@Override
	public void setParameters(
			final Persistable parameters ) {}

	@Override
	public void clearResult() {
		countResult.count = 0;
	}
}

package mil.nga.giat.geowave.core.store.query.aggregate;

import mil.nga.giat.geowave.core.index.Persistable;

public class CountAggregation<T> implements
		Aggregation<Persistable, CountResult, T>
{
	private long count = Long.MIN_VALUE;

	public CountAggregation() {}

	public boolean isSet() {
		return count != Long.MIN_VALUE;
	}

	@Override
	public String toString() {
		final StringBuffer buffer = new StringBuffer();
		buffer.append(
				"count[count=").append(
				count);
		buffer.append("]");
		return buffer.toString();
	}

	@Override
	public void aggregate(
			final T entry ) {
		if (!isSet()) {
			count = 0;
		}

		count += 1;
	}

	@Override
	public Persistable getParameters() {
		return null;
	}

	@Override
	public CountResult getResult() {
		if (!isSet()) {
			return null;
		}

		return new CountResult(count);
	}

	@Override
	public void setParameters(
			final Persistable parameters ) {}

	@Override
	public void clearResult() {
		count = 0;
	}
}

Return new CountResult on getResult, and use long instead of CountResult object internally


/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

package io.crate.plugin;

import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;

public class SQLModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(DDLStatementDispatcher.class).asEagerSingleton();
        bind(FulltextAnalyzerResolver.class).asEagerSingleton();
        bind(PostgresNetty.class).asEagerSingleton();
    }
}

/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

package io.crate.plugin;

import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.action.sql.SQLOperations;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;

public class SQLModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(DDLStatementDispatcher.class).asEagerSingleton();
        bind(FulltextAnalyzerResolver.class).asEagerSingleton();
        bind(PostgresNetty.class).asEagerSingleton();
        bind(SQLOperations.class).asEagerSingleton();
    }
}

Change SQLOperations to be an eager singleton


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttpserver;

import java.io.IOException;
import com.faveset.log.OutputStreamLog;

public class HttpServer {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.out.println("<port>");
            return;
        }

        int port = new Integer(args[0]);

        OutputStreamLog log = new OutputStreamLog(System.out);

        com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer();
        server.setLog(log);

        server.listenAndServe("127.0.0.1", port);

        log.close();
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttpserver;

import java.io.IOException;
import sun.misc.Signal;
import sun.misc.SignalHandler;

import com.faveset.log.OutputStreamLog;

public class HttpServer {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.out.println("<port>");
            return;
        }

        int port = new Integer(args[0]);

        OutputStreamLog log = new OutputStreamLog(System.out);

        final com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer();
        server.setLog(log);

        // Set up the signal handler.
        Signal.handle(new Signal("INT"), new SignalHandler() {
            @Override
            public void handle(Signal sig) {
                server.stop();
            }
        });
        server.listenAndServe("::", port);

        log.close();
    }
}

Test server maps to all interfaces. Add signal handler for cleaning up on SIGINT.


package com.balancedpayments;

import com.balancedpayments.core.Resource;
import com.balancedpayments.core.ResourceCollection;
import com.balancedpayments.core.ResourceField;
import com.balancedpayments.core.ResourceQuery;
import com.balancedpayments.errors.HTTPError;

import java.util.Map;

public class Callback extends Resource {

    public static final String resource_href = "/callbacks";

    @ResourceField(mutable=true)
    public String url;

    @ResourceField(mutable=true, required=false)
    public String method;

    @ResourceField(mutable=true, required=false)
    public String revision;

    public static class Collection extends ResourceCollection<Callback> {
        public Collection(String href) {
            super(Callback.class, href);
        }
    };

    public Callback() {
        super();
    }

    public Callback(String href) throws HTTPError {
        super(href);
    }

    public Callback(Map<String, Object> payload) throws HTTPError {
        super(payload);
    }

    public static ResourceQuery<Callback> query() {
        return new ResourceQuery<Callback>(Callback.class, resource_href);
    }

    @Override
    public void save() throws HTTPError {
        if (id == null && href == null) {
            href = resource_href;
        }
        super.save();
    }
}

package com.balancedpayments;

import com.balancedpayments.core.Resource;
import com.balancedpayments.core.ResourceCollection;
import com.balancedpayments.core.ResourceField;
import com.balancedpayments.core.ResourceQuery;
import com.balancedpayments.errors.HTTPError;

import java.util.Map;

public class Callback extends Resource {

    public static final String resource_href = "/callbacks";

    @ResourceField(mutable=true)
    public String url;

    @ResourceField(mutable=true, required=false)
    public String method;

    @ResourceField(required=false)
    public String revision;

    public static class Collection extends ResourceCollection<Callback> {
        public Collection(String href) {
            super(Callback.class, href);
        }
    };

    public Callback() {
        super();
    }

    public Callback(String href) throws HTTPError {
        super(href);
    }

    public Callback(Map<String, Object> payload) throws HTTPError {
        super(payload);
    }

    public static ResourceQuery<Callback> query() {
        return new ResourceQuery<Callback>(Callback.class, resource_href);
    }

    @Override
    public void save() throws HTTPError {
        if (id == null && href == null) {
            href = resource_href;
        }
        super.save();
    }
}

Remove mutability of callback revision


package com.github.sparkcaller.preprocessing;

import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;

import java.io.File;

public class BamIndexer implements Function<File, File> {
    // Create an index (.bai) file for the given BAM file.
    public File call(File bamFile) throws Exception {
        final SamReader bamReader = SamReaderFactory.makeDefault()
                                              .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
                                              .open(bamFile);
        BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));

        return bamFile;
    }
}

package com.github.sparkcaller.preprocessing;

import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;

import java.io.File;

public class BamIndexer implements Function<File, File> {
    // Create an index (.bai) file for the given BAM file.
    public static void indexBam(File bamFile) throws Exception {
        final SamReader bamReader = SamReaderFactory.makeDefault()
                                              .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
                                              .open(bamFile);
        BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
    }

    @Override
    public File call(File inputBAM) throws Exception {
        BamIndexer.indexBam(inputBAM);
        return inputBAM;
    }
}

Make it easier to run the SAM indexer on a single file.


package at.ac.tuwien.inso.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

import at.ac.tuwien.inso.entity.Lecturer;

public interface LecturerRepository extends CrudRepository<Lecturer, Long> {

    @Query("select l from Lecturer l where ACCOUNT_ID = ?1")
    Lecturer findLecturerByAccountId(Long id);

    public List<Lecturer> findAll();

    public Lecturer findById(Long id);
}

package at.ac.tuwien.inso.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

import at.ac.tuwien.inso.entity.Lecturer;

public interface LecturerRepository extends CrudRepository<Lecturer, Long> {

    @Query("select l from Lecturer l where ACCOUNT_ID = ?1")
    Lecturer findLecturerByAccountId(Long id);

    public List<Lecturer> findAllByIdentificationNumberLikeIgnoreCaseOrNameLikeIgnoreCase(
            String identificationNumber,
            String name
    );

    public Lecturer findById(Long id);
}

Replace findAll with complicated search operation


package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void apply(IResourceProperties properties);

	public abstract ResourceType type();
}

package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void apply(IResourceProperties properties);

	public abstract ResourceType type();

	public abstract IResourceProperties getProperties();
}

Add method to get properties from resource.


package i5.las2peer.persistency;

/**
 * The old XmlAble interface enforced an setStateFromXmlMethod.
 *
 * Due to several problems I decided to remove this method and leave the deserialization
 * in the hand of the programmer.
 *
 * If standard methods are to be used, the programmer of an XmlAble class should used one of
 * the following methods
 *
 *

 *
Use a factory called createFromXml ( String xml )

 * 		This is the preferred idea. An interface may not enforce static methods however...

 *
Use a Constructor with a single String parameter

 *
Use a base constructor in combination with setStateFromXml ( String )

 *  	This corresponds to the old XmlAble.

 *

 *
 * @author Holger Janßen
 *
 */
public interface XmlAble
{

	/**
	 * Returns a XML representation of this object.
	 *
	 * This method will be used by an object manager to get a persistency representation
	 * of this object.
	 *
	 *
	 * @return   a String
	 *
	 */
	public String toXmlString ();

}

package i5.las2peer.persistency;

/**
 * The old XmlAble interface enforced an setStateFromXmlMethod.
 *
 * Due to several problems I decided to remove this method and leave the deserialization
 * in the hand of the programmer.
 *
 * If standard methods are to be used, the programmer of an XmlAble class should used one of
 * the following methods
 *
 *

 *
Use a factory called createFromXml ( String xml )

 * 		This is the preferred idea. An interface may not enforce static methods however...

 *
Use a Constructor with a single String parameter

 *
Use a base constructor in combination with setStateFromXml ( String )

 *  	This corresponds to the old XmlAble.

 *

 *
 * @author Holger Janßen
 *
 */
public interface XmlAble
{

	/**
	 * Returns a XML representation of this object.
	 *
	 *
	 * @return   a String
	 *
	 */
	public String toXmlString ();

}

Comment was just not true anymore


package edu.stuy.starlorn.entities;

import edu.stuy.starlorn.upgrades.GunUpgrade;

import java.util.LinkedList;

public class Ship extends Entity {
    protected LinkedList<GunUpgrade> _gunupgrades;
    protected int _baseDamage, _baseShotSpeed, _health;
    protected double _baseAim;

    public Ship() {
        super();
        _gunupgrades = new LinkedList<GunUpgrade>();
        _baseDamage = 1;
        _baseShotSpeed = 1;
        _health = 10;
        _baseAim = Math.PI/2; //Aim up by default
    }

    public void addUpgrade(GunUpgrade upgrade) {
        _gunupgrades.add(upgrade);
    }

    /*
     * Create the shots based on the available GunUpgrades
     */
    public void shoot() {
        GunUpgrade topShot = _gunupgrades.get(0);
        int damage = _baseDamage;
        int shotSpeed = _baseShotSpeed;
        for (GunUpgrade up : _gunupgrades) {
            if (up.getNumShots() > topShot.getNumShots())
                topShot = up;
            damage = up.getDamage(damage);
            shotSpeed = up.getShotSpeed(shotSpeed);
        }
        // Create new shots, based on dem vars
        int numShots = topShot.getNumShots();
        for (int i = 0; i < numShots; i++) {
            Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
            b.setWorld(this.getWorld());
        }
    }
}

package edu.stuy.starlorn.entities;

import edu.stuy.starlorn.upgrades.GunUpgrade;

import java.util.LinkedList;

public class Ship extends Entity {
    protected LinkedList<GunUpgrade> _gunupgrades;
    protected int _baseDamage, _baseShotSpeed, _health;
    protected double _baseAim;

    public Ship() {
        super();
        _gunupgrades = new LinkedList<GunUpgrade>();
        _baseDamage = 1;
        _baseShotSpeed = 1;
        _health = 10;
        _baseAim = 0; //Aim up by default
    }

    public void addUpgrade(GunUpgrade upgrade) {
        _gunupgrades.add(upgrade);
    }

    /*
     * Create the shots based on the available GunUpgrades
     */
    public void shoot() {
        GunUpgrade topShot = _gunupgrades.get(0);
        int damage = _baseDamage;
        int shotSpeed = _baseShotSpeed;
        for (GunUpgrade up : _gunupgrades) {
            if (up.getNumShots() > topShot.getNumShots())
                topShot = up;
            damage = up.getDamage(damage);
            shotSpeed = up.getShotSpeed(shotSpeed);
        }
        // Create new shots, based on dem vars
        int numShots = topShot.getNumShots();
        for (int i = 0; i < numShots; i++) {
            Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
            b.setWorld(this.getWorld());
        }
    }
}

Change baseAim to 0, since we're using the Y axis


package ljfa.tntutils.gui;

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

import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;

public class TntuConfigGui extends GuiConfig {
    public TntuConfigGui(GuiScreen parent) {
        super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
    }

    /** Compiles a list of config elements */
    private static List<IConfigElement> getConfigElements() {
        List<IConfigElement> list = new ArrayList<IConfigElement>();

        //Add categories to config GUI
        list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(Config.CATEGORY_GENERAL)));
        return list;
    }
}

package ljfa.tntutils.gui;

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

import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;

public class TntuConfigGui extends GuiConfig {
    public TntuConfigGui(GuiScreen parent) {
        super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
    }

    /** Compiles a list of config elements
     * Borrowed from EnderIO's implementation
     */
    private static List<IConfigElement> getConfigElements() {
        List<IConfigElement> list = new ArrayList<IConfigElement>();

        for(String name: Config.conf.getCategoryNames())
            list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name)));

        return list;
    }
}

Make Config GUIs easier to work with


package org.jboss.loom.utils.el;

import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ELUtils {
    private static final Logger log = LoggerFactory.getLogger( ELUtils.class );

    public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) {

        Class curClass = obj.getClass();
        while( curClass != null  &&  ! Object.class.equals( curClass ) ){
            for( Field fld : curClass.getDeclaredFields() ){
                //if( ! fld.getType().equals( String.class ))
                if( ! String.class.isAssignableFrom(  fld.getType() ) )
                    continue;
                final EL ann = fld.getAnnotation( EL.class );
                if( null == ann )
                    continue;
                if( stage != null  &&  ann.stage() != stage )
                    continue;

                try {
                    fld.setAccessible( true );
                    String orig = (String) fld.get( obj );
                    String res = eval.evaluateEL( orig );
                    fld.set( obj, res );
                } catch( IllegalArgumentException | IllegalAccessException ex ) {
                    throw new IllegalStateException("Failed resolving EL in " + obj + ": " + ex.getMessage(), ex);
                }
            }
            curClass = curClass.getSuperclass();
        }
    }

}// class

package org.jboss.loom.utils.el;

import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ELUtils {
    private static final Logger log = LoggerFactory.getLogger( ELUtils.class );

    public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) {

        Class curClass = obj.getClass();
        while( curClass != null  &&  ! Object.class.equals( curClass ) ){
            for( Field fld : curClass.getDeclaredFields() ){
                //if( ! fld.getType().equals( String.class ))
                if( ! String.class.isAssignableFrom(  fld.getType() ) )
                    continue;
                final EL ann = fld.getAnnotation( EL.class );
                if( null == ann )
                    continue;
                if( stage != null  &&  ann.stage() != stage )
                    continue;

                try {
                    fld.setAccessible( true );
                    String orig = (String) fld.get( obj );
                    if( orig == null || orig.trim().isEmpty() )
                        continue;
                    String res = eval.evaluateEL( orig );
                    fld.set( obj, res );
                } catch( IllegalArgumentException | IllegalAccessException ex ) {
                    throw new IllegalStateException("Failed resolving EL in " + obj + "." + fld.getName() + ": " + ex.getMessage(), ex);
                }
            }
            curClass = curClass.getSuperclass();
        }
    }

}// class

Fix NPE if property with @EL is null.


package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class TDPExceptionController {

    private static HttpEntity<String> buildHttpEntity(TDPException e) {
        StringWriter writer = new StringWriter();
        e.writeTo(writer);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new HttpEntity<>(writer.toString(), headers);
    }

    @ExceptionHandler(InternalException.class)
    public HttpEntity<String> handleInternalError(HttpServletResponse response, InternalException e) {
        HttpEntity<String> entity = buildHttpEntity(e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return entity;
    }

    @ExceptionHandler(UserException.class)
    public HttpEntity<String> handleUserError(HttpServletResponse response, UserException e) {
        HttpEntity<String> entity = buildHttpEntity(e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return entity;
    }

}

package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class TDPExceptionController {

    public static final Logger LOGGER = LoggerFactory.getLogger(TDPExceptionController.class);

    @ExceptionHandler(InternalException.class)
    public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

    @ExceptionHandler(UserException.class)
    public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

}

Use @ResponseBody to write exception message.


package fault.metrics;

import fault.Status;

/**
 * Created by timbrooks on 11/20/14.
 */
public interface ActionMetrics {
    int getFailuresForTimePeriod(int milliseconds);

    void reportActionResult(Status status);

    int getSuccessesForTimePeriod(int milliseconds);

    int getErrorsForTimePeriod(int milliseconds);

    int getTimeoutsForTimePeriod(int milliseconds);
}

package fault.metrics;

import fault.Status;

/**
 * Created by timbrooks on 11/20/14.
 */
public interface ActionMetrics {
    public void reportActionResult(Status status);

    public int getFailuresForTimePeriod(int milliseconds);

    public int getSuccessesForTimePeriod(int milliseconds);

    public int getErrorsForTimePeriod(int milliseconds);

    public int getTimeoutsForTimePeriod(int milliseconds);
}

Modify interface to have public methods


package net.wequick.example.small.app.main;

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

/**
 * Created by Administrator on 2016/2/17.
 */
public class AppContext extends Application {

    public AppContext(){
        Log.d("main application","AppContext()");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println(this.getSharedPreferences("small.app-versions", 0).getAll());
        Log.d("main application","onCreate()");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

package net.wequick.example.small.app.main;

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

/**
 * Created by Administrator on 2016/2/17.
 */
public class AppContext extends Application {

    private static final String TAG = "Main Plugin";

    public AppContext() {
        Log.d(TAG, "AppContext()");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");

        // Test shared data
        Log.d(TAG, this.getSharedPreferences("small.app-versions", 0).getAll().toString());

        // Test resources
        String s = this.getString(R.string.action_settings);
        Log.d(TAG, s);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

Add sample for using resources in plugin application


package com.michaldabski.utils;

import java.io.File;

import android.graphics.Bitmap;
import android.util.LruCache;

public class FilePreviewCache extends LruCache<File, Bitmap>
{
	public static final int DEFAULT_CACHE_SZE = 4*1024*1024;
	/**
	 * create new cache
	 * @param maxSize max size in bytes
	 */
	public FilePreviewCache(int maxSize) {
		super(maxSize);
		// TODO Auto-generated constructor stub
	}

	public FilePreviewCache()
	{
		this(DEFAULT_CACHE_SZE);
	}

	@Override
	protected int sizeOf(File key, Bitmap value)
	{
		return value.getByteCount();
	}

}

package com.michaldabski.utils;

import java.io.File;

import android.graphics.Bitmap;
import android.util.LruCache;

public class FilePreviewCache extends LruCache<File, Bitmap>
{
	public static final int DEFAULT_CACHE_SZE = 24*1024*1024;
	/**
	 * create new cache
	 * @param maxSize max size in bytes
	 */
	public FilePreviewCache(int maxSize) {
		super(maxSize);
		// TODO Auto-generated constructor stub
	}

	public FilePreviewCache()
	{
		this(DEFAULT_CACHE_SZE);
	}

	@Override
	protected int sizeOf(File key, Bitmap value)
	{
		return value.getByteCount();
	}

}

Increment allowed cache size to 24mb


package org.twig.loader;

import org.twig.exception.LoaderException;

import java.util.HashMap;

/**
 * Used for unit tests only
 */
public class HashMapLoader implements Loader {
    HashMap<String, String> hashMap;

    /**
     * Default constructor
     */
    public HashMapLoader() {
        hashMap = new HashMap<>();
    }

    /**
     * Construct the loader with an existing hash map
     * @param hashMap The hashMap with templates
     */
    public HashMapLoader(HashMap<String, String> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public String getSource(String name) throws LoaderException {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        }

        throw LoaderException.notDefined(name);
    }

    @Override
    public String getCacheKey(String name) throws LoaderException {
        if (!this.hashMap.containsKey(name)) {
            throw LoaderException.notDefined(name);
        }

        return this.hashMap.get(name);
    }

    /**
     * Get the hash map
     * @return The hashMap with templates
     */
    public HashMap<String, String> getHashMap() {
        return hashMap;
    }

    /**
     * Set the hashmap
     * @param hashMap The hashMap with templates
     */
    public void setHashMap(HashMap<String, String> hashMap) {
        this.hashMap = hashMap;
    }
}

package org.twig.loader;

import org.twig.exception.LoaderException;

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

/**
 * Used for unit tests only
 */
public class HashMapLoader implements Loader {
    Map<String, String> hashMap;

    /**
     * Default constructor
     */
    public HashMapLoader() {
        hashMap = new HashMap<>();
    }

    /**
     * Construct the loader with an existing hash map
     * @param hashMap The hashMap with templates
     */
    public HashMapLoader(Map<String, String> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public String getSource(String name) throws LoaderException {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        }

        throw LoaderException.notDefined(name);
    }

    @Override
    public String getCacheKey(String name) throws LoaderException {
        if (!this.hashMap.containsKey(name)) {
            throw LoaderException.notDefined(name);
        }

        return this.hashMap.get(name);
    }

    /**
     * Get the hash map
     * @return The hashMap with templates
     */
    public Map<String, String> getHashMap() {
        return hashMap;
    }

    /**
     * Set the hashmap
     * @param hashMap The hashMap with templates
     */
    public void setHashMap(Map<String, String> hashMap) {
        this.hashMap = hashMap;
    }
}

Make hashmaploader use Map instead of hashmap


package seedu.ezdo.model.todo;

import seedu.ezdo.commons.exceptions.IllegalValueException;

/**
 * Represents the due date of a todo.
 */
public class DueDate {

    public static final String MESSAGE_DUEDATE_CONSTRAINTS =
            "Due dates should be in the format DD/MM/YYYY, and it should not be blank";

    public static final String DUEDATE_VALIDATION_REGEX = ".+";

    public final String value;

    /**
     * Validates given due date.
     *
     * @throws IllegalValueException if given due date string is invalid.
     */
    public DueDate(String dueDate) throws IllegalValueException {
        assert dueDate != null;
        if (!isValidDueDate(dueDate)) {
            throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS);
        }
        this.value = dueDate;
    }

    /**
     * Returns true if a given string is a valid due date.
     */
    public static boolean isValidDueDate(String test) {
        return test.matches(DUEDATE_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DueDate // instanceof handles nulls
                && this.value.equals(((DueDate) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

}

package seedu.ezdo.model.todo;

import seedu.ezdo.commons.exceptions.IllegalValueException;

/**
 * Represents the due date of a todo.
 */
public class DueDate {

    public static final String MESSAGE_DUEDATE_CONSTRAINTS =
            "Due dates should be in the format DD/MM/YYYY, and it should not be blank";

    public static final String DUEDATE_VALIDATION_REGEX = "([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";

    public final String value;

    /**
     * Validates given due date.
     *
     * @throws IllegalValueException if given due date string is invalid.
     */
    public DueDate(String dueDate) throws IllegalValueException {
        assert dueDate != null;
        if (!isValidDueDate(dueDate)) {
            throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS);
        }
        this.value = dueDate;
    }

    /**
     * Returns true if a given string is a valid due date.
     */
    public static boolean isValidDueDate(String test) {
        return test.matches(DUEDATE_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DueDate // instanceof handles nulls
                && this.value.equals(((DueDate) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

}

Update regex to fit DD/MM/YYYY format


package org.apache.maven.continuum.web.action;

import org.codehaus.plexus.xwork.action.PlexusActionSupport;
import org.apache.maven.continuum.Continuum;
import org.apache.maven.continuum.initialization.ContinuumInitializationException;
import com.opensymphony.xwork.Preparable;
/*
 * Copyright 2005 The Codehaus.
 *
 * 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.
 */

/**
 * ContinuumActionSupport:
 *
 * @author: Jesse McConnell <jesse@codehaus.org>
 * @version: $ID:$
 */
public class ContinuumActionSupport
    extends PlexusActionSupport
    implements Preparable
{

    /**
     * @plexus.requirement
     */
    protected Continuum continuum;

    public void prepare()
        throws Exception
    {
        getLogger().info("checking the continuum configuration");

        if ( !continuum.getConfiguration().isInitialized() )
        {
            throw new ContinuumInitializationException( "continuum not initialized" );
        }

    }

    public Continuum getContinuum()
    {
        return continuum;
    }

    public void setContinuum( Continuum continuum )
    {
        this.continuum = continuum;
    }
}

package org.apache.maven.continuum.web.action;

/*
 * Copyright 2005-2006 The Apache Software Foundation.
 *
 * 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.
 *
 */

import org.apache.maven.continuum.Continuum;
import org.codehaus.plexus.xwork.action.PlexusActionSupport;

import com.opensymphony.xwork.Preparable;

/**
 * ContinuumActionSupport
 *
 * @author Jesse McConnell <jesse@codehaus.org>
 * @version $Id$
 */
public abstract class ContinuumActionSupport
    extends PlexusActionSupport
    implements Preparable
{

    /**
     * @plexus.requirement
     */
    protected Continuum continuum;

    public void prepare()
        throws Exception
    {
    }

    public Continuum getContinuum()
    {
        return continuum;
    }

    public void setContinuum( Continuum continuum )
    {
        this.continuum = continuum;
    }
}

Remove continuum initialization from action, need another way to do it


package com.glasstunes;

import android.database.Cursor;
import android.net.Uri;

import com.glasstunes.cards.ActionCard;
import com.glasstunes.screenslide.CardFragment;

public class DetailActivity extends BaseContentCardActivity {

	@Override
	protected Uri getContentUri() {
		return Uri.withAppendedPath(getIntent().getData(), "/sections");
	}

	@Override
	protected CardFragment getCardFromCursor(Cursor cursor) {
		return ActionCard.newInstance(
				cursor.getString(cursor.getColumnIndex("display_name")),
				cursor.getString(cursor.getColumnIndex("intent_uri")));
	}

}

package com.glasstunes;

import android.database.Cursor;
import android.net.Uri;

import com.glasstunes.cards.ActionCard;
import com.glasstunes.screenslide.CardFragment;

public class DetailActivity extends BaseContentCardActivity {

	@Override
	protected Uri getContentUri() {
		return Uri.withAppendedPath(getIntent().getData(), "/actions");
	}

	@Override
	protected CardFragment getCardFromCursor(Cursor cursor) {
		return ActionCard.newInstance(
				cursor.getString(cursor.getColumnIndex("display_name")),
				cursor.getString(cursor.getColumnIndex("intent_uri")));
	}

}

Fix wrong path in detail activity


package com.amee.service.item;

import com.amee.domain.IDataCategoryReference;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.data.DataItem;
import com.amee.domain.item.data.DataItemNumberValue;
import com.amee.domain.item.data.DataItemTextValue;

import java.util.Date;
import java.util.List;
import java.util.Set;

public interface DataItemServiceDAO extends ItemServiceDAO {

    public long getDataItemCount(IDataCategoryReference dataCategory);

    public List<DataItem> getDataItems(IDataCategoryReference dataCategory);

    public List<DataItem> getDataItems(Set<Long> dataItemIds);

    public DataItem getItemByUid(String uid);

    public Set<BaseItemValue> getDataItemValues(DataItem dataItem);

    public List<DataItemNumberValue> getDataItemNumberValues(DataItem dataItem);

    public List<DataItemTextValue> getDataItemTextValues(DataItem dataItem);

    public void persist(DataItem dataItem);

    public DataItem getDataItemByPath(IDataCategoryReference parent, String path);

    public Date getDataItemsModified(DataCategory dataCategory);

    public boolean isDataItemUniqueByPath(DataItem dataItem);
}

package com.amee.service.item;

import com.amee.domain.IDataCategoryReference;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.data.DataItem;
import com.amee.domain.item.data.DataItemNumberValue;
import com.amee.domain.item.data.DataItemTextValue;

import java.util.Date;
import java.util.List;
import java.util.Set;

public interface DataItemServiceDAO extends ItemServiceDAO {

    long getDataItemCount(IDataCategoryReference dataCategory);

    List<DataItem> getDataItems(IDataCategoryReference dataCategory);

    List<DataItem> getDataItems(Set<Long> dataItemIds);

    @Override
    DataItem getItemByUid(String uid);

    Set<BaseItemValue> getDataItemValues(DataItem dataItem);

    List<DataItemNumberValue> getDataItemNumberValues(DataItem dataItem);

    List<DataItemTextValue> getDataItemTextValues(DataItem dataItem);

    void persist(DataItem dataItem);

    DataItem getDataItemByPath(IDataCategoryReference parent, String path);

    Date getDataItemsModified(DataCategory dataCategory);

    boolean isDataItemUniqueByPath(DataItem dataItem);
}

Remove redundant access modifiers in interface.


package org.orekit.data;

/**
 * Holds a mutable static field since {@link DataContext} cannot.
 *
 * @author Evan Ward
 * @since 10.1
 */
class DefaultDataContextHolder {

    /** The default Orekit data context. */
    static LazyLoadedDataContext INSTANCE = new LazyLoadedDataContext();

    /** Private Constructor. */
    private DefaultDataContextHolder() {
    }

}

package org.orekit.data;

/**
 * Holds a mutable static field since {@link DataContext} cannot.
 *
 * @author Evan Ward
 * @since 10.1
 */
class DefaultDataContextHolder {

    /** The default Orekit data context. */
    static volatile LazyLoadedDataContext INSTANCE = new LazyLoadedDataContext();

    /** Private Constructor. */
    private DefaultDataContextHolder() {
    }

}

Make default data context volatile


package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore skull profiles
            || name.equalsIgnoreCase("profile")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore repair costs
            || name.equalsIgnoreCase("repairCost")
            // Ignore skull profiles
            || name.equalsIgnoreCase("profile")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

Exclude noisy "repairCost" meta field


/**
 * Created by Nathan_Zeplowitz on 4/14/15.
 */
interface Monster {
    public abstract void takeDamage(int amount);
    public abstract String name();
    public abstract int currentHitpoints();
}

/**
 * Created by Nathan_Zeplowitz on 4/14/15.
 */
interface Monster {
    void takeDamage(int amount);
    String name();
    int currentHitpoints();
}

Refactor Out Unnecessary Public Abstract Keywords


package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;
import org.togglz.servlet.TogglzFilter;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public FilterRegistrationBean togglzFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new TogglzFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

Revert "Make Togglz compatible to not embedded Tomcat"


package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    @Inject
    private ITicSource ticSource_;
    private long startTic_;

    public GameTimer() {
        startTic_ = ticSource_.tic();
    }

    @Override
    public long timeLeft() {
        return ticSource_.tic() -startTic_;
    }

    @Override
    public void pauseTimer() {

    }

    @Override
    public void startTimer() {
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    private ITicSource ticSource_;
    private long startTic_;

    @Inject
    public GameTimer(ITicSource ticSource) {
        ticSource_ = ticSource;
    }

    @Override
    public long timeLeft() {
        return ticSource_.tic() -startTic_;
    }

    @Override
    public void pauseTimer() {

    }

    @Override
    public void startTimer() {
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

Use constructor injection instead of member injection


package org.osgi.test.cases.repository.junit;

import org.osgi.framework.Bundle;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;

public class RepositoryTest extends DefaultTestBundleControl {
    public void testFoo() {
        for (Bundle b : getContext().getBundles()) {
            System.out.println("**** " + b.getSymbolicName());
        }
    }

    public void testBar() {
    }
}

package org.osgi.test.cases.repository.junit;

import java.util.Arrays;

import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.test.support.OSGiTestCase;

public class RepositoryTest extends OSGiTestCase {
    public void testFooXX() throws Exception {
        for (Bundle b : getContext().getBundles()) {
            System.err.println("@@@@ " + b.getSymbolicName());
        }

        for (ServiceReference<?> sr : getContext().getAllServiceReferences(null, null)) {
            System.err.println("**** " + Arrays.toString((String []) sr.getProperty(Constants.OBJECTCLASS)));
        }
    }

    public void testBar() {
    }
}

Test to output some basic info - bundles deploy ok.


package beaform.utilities;

public class SystemTime {

	private static final TimeSource defaultSrc = new TimeSource(){
		@Override
		public long getSystemTime() {
			return System.currentTimeMillis();
		}

	};

	private static TimeSource source;

	public static void reset() {
		source = null;
	}

	public static long getAsLong() {
		return getCurrentTimeSource().getSystemTime();
	}

	private static TimeSource getCurrentTimeSource() {
		return (source == null) ? defaultSrc : source;
	}

	public static void setTimeSource(TimeSource timeSource) {
		source = timeSource;
	}
}

package beaform.utilities;

public class SystemTime {

	private static final TimeSource defaultSrc = new TimeSource(){
		@Override
		public long getSystemTime() {
			return System.currentTimeMillis();
		}

	};

	private static volatile TimeSource source;

	public static void reset() {
		source = null;
	}

	public static long getAsLong() {
		return getCurrentTimeSource().getSystemTime();
	}

	private static TimeSource getCurrentTimeSource() {
		return (source == null) ? defaultSrc : source;
	}

	public static void setTimeSource(TimeSource timeSource) {
		source = timeSource;
	}
}

Make the non-default time source volatile to avoid some threading issues


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

import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 *
 * @author Jingjing
 */
public class TestEnvironment {

    private static String modelPath = null;

    public static void initializePath() {
        ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL url = cs.getLocation();
        File f = new File(url.getFile());
        File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
        String ap = targetFile.getAbsolutePath() + "\\Models\\Arm26\\arm26.osim";
        modelPath = ap;

    }

    public static String getModelPath() {
        if (modelPath == null) {
            initializePath();
        }
        return modelPath;
    }
}

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

import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 *
 * @author Jingjing
 */
public class TestEnvironment {

    private static String modelPath = null;

    public static void initializePath() {
        ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL url = cs.getLocation();
        File f = new File(url.getFile());
        File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
        String ap = targetFile.getAbsolutePath() + "\\opensim-models\\Models\\Arm26\\arm26.osim";
        modelPath = ap;

    }

    public static String getModelPath() {
        if (modelPath == null) {
            initializePath();
        }
        return modelPath;
    }
}

Use new path name to Models for test case


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.tool;

import android.support.annotation.Nullable;
import timber.log.Timber;

public final class OffloaderHelper {

  private OffloaderHelper() {
    throw new RuntimeException("No instances");
  }

  public static void cancel(@Nullable ExecutedOffloader offloader) {
    if (offloader == null) {
      Timber.w("Offloader is NULL");
      return;
    }

    if (!offloader.isCancelled()) {
      offloader.cancel();
    }
  }
}

/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.tool;

import android.support.annotation.Nullable;
import timber.log.Timber;

public final class OffloaderHelper {

  private OffloaderHelper() {
    throw new RuntimeException("No instances");
  }

  public static void cancel(@Nullable ExecutedOffloader offloader) {
    if (offloader == null) {
      Timber.w("Offloader is NULL");
      return;
    }

    if (!offloader.isCancelled()) {
      offloader.cancel();
    }
  }

  public static void cancel(@Nullable ExecutedOffloader... offloaders) {
    if (offloaders == null) {
      Timber.w("Offloaders are NULL");
      return;
    }

    for (final ExecutedOffloader offloader : offloaders) {
      cancel(offloader);
    }
  }
}

Add offloader helper method for multiple


/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import com.skelril.nitro.Clause;

import java.util.Collection;

public interface ModifierService {
    void setExpiry(String modifier, long time);
    long expiryOf(String modifier);
    default long statusOf(String modifier) {
        return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifier) {
        return statusOf(modifier) != 0;
    }

    Collection<Clause<String, Long>> getActiveModifiers();
}

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import java.util.Map;

public interface ModifierService {
    void setExpiry(String modifier, long time);
    long expiryOf(String modifier);
    default long statusOf(String modifier) {
        return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifier) {
        return statusOf(modifier) != 0;
    }

    Map<String, Long> getActiveModifiers();
}

Use a map for the collection of active modifiers


package heroku.template.service;

import heroku.template.model.Person;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PersonServiceImpl implements PersonService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public void addPerson(Person person) {
    	em.persist(person);
    }

    @Transactional
    public List<Person> listPeople() {
    	CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
        Root<Person> p = c.from(Person.class);
        return em.createQuery(c).getResultList();
    }

    @Transactional
    public void removePerson(Integer id) {
		Person person = (Person) em.find(Person.class, id);
		if (null != person) {
			em.remove(person);
		}
    }

}

package heroku.template.service;

import heroku.template.model.Person;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public void addPerson(Person person) {
    	em.persist(person);
    }

    @Transactional
    public List<Person> listPeople() {
    	CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
        c.from(Person.class);
        return em.createQuery(c).getResultList();
    }

    @Transactional
    public void removePerson(Integer id) {
		Person person = em.find(Person.class, id);
		if (null != person) {
			em.remove(person);
		}
    }

}

Remove unnecessary assignment and cast


package j8spec;

import static j8spec.J8Spec.var;
import static java.util.Objects.isNull;

class VarInitializer<T> implements UnsafeBlock {

    private final Var<T> variable;
    private final UnsafeFunction<T> function;
    private T value;

    VarInitializer(Var<T> variable, UnsafeFunction<T> function) {
        this.variable = variable;
        this.function = function;
    }

    @Override
    public void tryToExecute() throws Throwable {
        if (isNull(value)) {
            value = function.tryToGet();
        }
        var(variable, value);
    }
}

package j8spec;

import static j8spec.J8Spec.*;

class VarInitializer<T> implements UnsafeBlock {

    private final Var<T> variable;
    private final UnsafeFunction<T> function;
    private T value;

    VarInitializer(Var<T> variable, UnsafeFunction<T> function) {
        this.variable = variable;
        this.function = function;
    }

    @Override
    public void tryToExecute() throws Throwable {
        if (value == null) {
            value = function.tryToGet();
        }
        var(variable, value);
    }
}

Replace isNull with literal null


/*
 * Copyright 2008 ZXing 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 com.google.zxing.client.result;

import com.google.zxing.Result;

/**
 * Parses a "tel:" URI result, which specifies a phone number.
 *
 * @author Sean Owen
 */
final class TelResultParser extends ResultParser {

  private TelResultParser() {
  }

  public static TelParsedResult parse(Result result) {
    String rawText = result.getText();
    if (rawText == null || (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:"))) {
      return null;
    }
    String telURI = rawText;
    // Drop tel, query portion
    int queryStart = rawText.indexOf('?', 4);
    if (queryStart < 0) {
      rawText = rawText.substring(4);
    } else {
      rawText = rawText.substring(4, queryStart);
    }
    return new TelParsedResult(rawText, telURI, null);
  }

}

/*
 * Copyright 2008 ZXing 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 com.google.zxing.client.result;

import com.google.zxing.Result;

/**
 * Parses a "tel:" URI result, which specifies a phone number.
 *
 * @author Sean Owen
 */
final class TelResultParser extends ResultParser {

  private TelResultParser() {
  }

  public static TelParsedResult parse(Result result) {
    String rawText = result.getText();
    if (rawText == null || (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:"))) {
      return null;
    }
    // Normalize "TEL:" to "tel:"
    String telURI = rawText.startsWith("TEL:") ? "tel:" + rawText.substring(4) : rawText;
    // Drop tel, query portion
    int queryStart = rawText.indexOf('?', 4);
    String number = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart);
    return new TelParsedResult(number, telURI, null);
  }

}

Normalize TEL: to tel: to make sure it works with Android


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

import org.apache.wicket.markup.html.border.MarkupComponentBorder;

/**
 * Simple example to show how a border works. Adding this border to e.g. a label that displays 'x'
 * results in '[ x ]' being displayed.
 *
 * @author jcompagner
 */
public class BeforeAndAfterBorder extends MarkupComponentBorder
{
}

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

import org.apache.wicket.markup.html.border.BorderBehavior;

/**
 * Simple example to show how a border works. Adding this border to e.g. a label that displays 'x'
 * results in '[ x ]' being displayed.
 *
 * @author jcompagner
 */
public class BeforeAndAfterBorder extends BorderBehavior
{
}

Use BorderBehavior instead of the deprecated MarkupComponentBorder


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.react.fabric.mounting.mountitems;

import androidx.annotation.NonNull;
import com.facebook.react.fabric.mounting.MountingManager;

public class InsertMountItem implements MountItem {

  private int mReactTag;
  private int mParentReactTag;
  private int mIndex;

  public InsertMountItem(int reactTag, int parentReactTag, int index) {
    mReactTag = reactTag;
    mParentReactTag = parentReactTag;
    mIndex = index;
  }

  @Override
  public void execute(@NonNull MountingManager mountingManager) {
    mountingManager.addViewAt(mParentReactTag, mReactTag, mIndex);
  }

  public int getParentReactTag() {
    return mParentReactTag;
  }

  public int getIndex() {
    return mIndex;
  }

  @Override
  public String toString() {
    return "InsertMountItem ["
        + mReactTag
        + "] - parentTag: "
        + mParentReactTag
        + " - index: "
        + mIndex;
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.react.fabric.mounting.mountitems;

import androidx.annotation.NonNull;
import com.facebook.react.fabric.mounting.MountingManager;

public class InsertMountItem implements MountItem {

  private int mReactTag;
  private int mParentReactTag;
  private int mIndex;

  public InsertMountItem(int reactTag, int parentReactTag, int index) {
    mReactTag = reactTag;
    mParentReactTag = parentReactTag;
    mIndex = index;
  }

  @Override
  public void execute(@NonNull MountingManager mountingManager) {
    mountingManager.addViewAt(mParentReactTag, mReactTag, mIndex);
  }

  public int getParentReactTag() {
    return mParentReactTag;
  }

  public int getIndex() {
    return mIndex;
  }

  @Override
  public String toString() {
    return "InsertMountItem ["
        + mReactTag
        + "] - parentTag: ["
        + mParentReactTag
        + "] - index: "
        + mIndex;
  }
}

Add square brackets around tags in logs in FabricUIManager


package us.myles.ViaVersion.protocols.protocol1_12to1_11_1;

import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_12Types;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;

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

public class MetadataRewriter {
    public static void handleMetadata(int entityId, Entity1_12Types.EntityType type, List<Metadata> metadatas, UserConnection connection) {
        for (Metadata metadata : new ArrayList<>(metadatas)) {
            try {
                if (metadata.getValue() instanceof Item) {
                    // Apply rewrite
                    BedRewriter.toClientItem((Item) metadata.getValue());
                }
            } catch (Exception e) {
                metadatas.remove(metadata);
                if (!Via.getConfig().isSuppressMetadataErrors() || Via.getManager().isDebug()) {
                    Via.getPlatform().getLogger().warning("An error occurred with entity metadata handler");
                    Via.getPlatform().getLogger().warning("Metadata: " + metadata);
                    e.printStackTrace();
                }
            }
        }

    }
}

package us.myles.ViaVersion.protocols.protocol1_12to1_11_1;

import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_12Types;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;

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

public class MetadataRewriter {
    public static void handleMetadata(int entityId, Entity1_12Types.EntityType type, List<Metadata> metadatas, UserConnection connection) {
        for (Metadata metadata : new ArrayList<>(metadatas)) {
            try {
                if (metadata.getValue() instanceof Item) {
                    // Apply rewrite
                    BedRewriter.toClientItem((Item) metadata.getValue());
                }
                // Evocation Illager aggressive property became 13
                if (type.is(Entity1_12Types.EntityType.EVOCATION_ILLAGER)) {
                    if (metadata.getId() == 12) {
                        metadata.setId(13);
                    }
                }
            } catch (Exception e) {
                metadatas.remove(metadata);
                if (!Via.getConfig().isSuppressMetadataErrors() || Via.getManager().isDebug()) {
                    Via.getPlatform().getLogger().warning("An error occurred with entity metadata handler");
                    Via.getPlatform().getLogger().warning("Metadata: " + metadata);
                    e.printStackTrace();
                }
            }
        }

    }
}

Fix Evocation Illager animation on 1.12


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String id();
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String id();
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String description();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add new tab JSON field


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

package org.opendaylight.controller.netconf.api;

import org.w3c.dom.Document;

import com.google.common.base.Optional;

/**
 * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for
 * implementing ProtocolMessage interface.
 */
public final class NetconfMessage {

    private static final long serialVersionUID = 462175939836367285L;

    private final Document doc;

    private String additionalHeader;

    public NetconfMessage(final Document doc) {
        this(doc, null);
    }

    public NetconfMessage(Document doc, String additionalHeader) {
        this.doc = doc;
        this.additionalHeader = additionalHeader;
    }

    public Document getDocument() {
        return this.doc;
    }

    public Optional<String> getAdditionalHeader() {
        return additionalHeader== null ? Optional.<String>absent() : Optional.of(additionalHeader);
    }
}

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

package org.opendaylight.controller.netconf.api;

import org.w3c.dom.Document;

import com.google.common.base.Optional;

/**
 * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for
 * implementing ProtocolMessage interface.
 */
public final class NetconfMessage {
    private final String additionalHeader;
    private final Document doc;

    public NetconfMessage(final Document doc) {
        this(doc, null);
    }

    public NetconfMessage(Document doc, String additionalHeader) {
        this.doc = doc;
        this.additionalHeader = additionalHeader;
    }

    public Document getDocument() {
        return this.doc;
    }

    public Optional<String> getAdditionalHeader() {
        return additionalHeader== null ? Optional.<String>absent() : Optional.of(additionalHeader);
    }
}

Fix a warning and make field final


package fr.tvbarthel.apps.simpleweatherforcast.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class SharedPreferenceUtils {
	private static String KEY_LAST_UPDATE = "SharedPreferenceUtils.Key.LastUpdate";
	private static String KEY_LAST_KNOWN_JSON_WEATHER = "SharedPreferenceUtils.Key.LastKnownJsonWeather";

	private static SharedPreferences getDefaultSharedPreferences(final Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context);
	}

	public static String getLastKnownWeather(final Context context) {
		return getDefaultSharedPreferences(context).getString(KEY_LAST_KNOWN_JSON_WEATHER, null);
	}

	public static long getLastUpdate(final Context context) {
		return getDefaultSharedPreferences(context).getLong(KEY_LAST_UPDATE, 0);
	}

	public static void storeWeather(final Context context, final String jsonWeather) {
		final Editor editor = getDefaultSharedPreferences(context).edit();
		editor.putString(KEY_LAST_KNOWN_JSON_WEATHER, jsonWeather);
		editor.putLong(KEY_LAST_UPDATE, System.currentTimeMillis());
		editor.apply();
	}

}

package fr.tvbarthel.apps.simpleweatherforcast.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

import fr.tvbarthel.apps.simpleweatherforcast.R;

public class SharedPreferenceUtils {
	private static String KEY_LAST_UPDATE = "SharedPreferenceUtils.Key.LastUpdate";
	private static String KEY_LAST_KNOWN_JSON_WEATHER = "SharedPreferenceUtils.Key.LastKnownJsonWeather";
	private static String KEY_TEMPERATURE_UNIT_SYMBOL = "SharedPreferenceUtils.Key.TemperatureUnitSymbol";

	private static SharedPreferences getDefaultSharedPreferences(final Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context);
	}

	public static String getLastKnownWeather(final Context context) {
		return getDefaultSharedPreferences(context).getString(KEY_LAST_KNOWN_JSON_WEATHER, null);
	}

	public static long getLastUpdate(final Context context) {
		return getDefaultSharedPreferences(context).getLong(KEY_LAST_UPDATE, 0);
	}

	public static void storeWeather(final Context context, final String jsonWeather) {
		final Editor editor = getDefaultSharedPreferences(context).edit();
		editor.putString(KEY_LAST_KNOWN_JSON_WEATHER, jsonWeather);
		editor.putLong(KEY_LAST_UPDATE, System.currentTimeMillis());
		editor.apply();
	}

	public static void storeTemperatureUnitSymbol(final Context context, final String unitSymbol) {
		final Editor editor = getDefaultSharedPreferences(context).edit();
		editor.putString(KEY_TEMPERATURE_UNIT_SYMBOL, unitSymbol);
		editor.apply();
	}

	public static String getTemperatureUnitSymbol(final Context context) {
		return getDefaultSharedPreferences(context).getString(KEY_TEMPERATURE_UNIT_SYMBOL,
				context.getString(R.string.temperature_unit_celsius_symbol));
	}

}

Implement method to store and get the temperature unit


/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.gui.main;

import java.awt.*;
import java.awt.event.*;

import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;

/**
 * The dial pad button in the contact list.
 *
 * @author Yana Stamcheva
 */
public class DialPadButton
    extends SIPCommTextButton
{
    /**
     * The dial pad dialog that this button opens.
     */
    GeneralDialPadDialog dialPad;

    /**
     * Creates an instance of <tt>DialPadButton</tt>.
     */
    public DialPadButton()
    {
        super("");

        loadSkin();

        addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (dialPad == null)
                    dialPad = new GeneralDialPadDialog();

                dialPad.clear();
                dialPad.setVisible(true);
            }
        });
    }

    /**
     * Loads images and sets history view.
     */
    public void loadSkin()
    {
        Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);

        setBgImage(image);

        this.setPreferredSize(new Dimension(image.getWidth(this),
                                            image.getHeight(this)));
    }
}

/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.gui.main;

import java.awt.*;
import java.awt.event.*;

import javax.swing.BorderFactory;

import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;

/**
 * The dial pad button in the contact list.
 *
 * @author Yana Stamcheva
 */
public class DialPadButton
    extends SIPCommTextButton
{
    /**
     * The dial pad dialog that this button opens.
     */
    GeneralDialPadDialog dialPad;

    /**
     * Creates an instance of <tt>DialPadButton</tt>.
     */
    public DialPadButton()
    {
        super("");

        loadSkin();
        setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

        addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (dialPad == null)
                    dialPad = new GeneralDialPadDialog();

                dialPad.clear();
                dialPad.setVisible(true);
            }
        });
    }

    /**
     * Loads images and sets history view.
     */
    public void loadSkin()
    {
        Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);

        setBgImage(image);

        this.setPreferredSize(new Dimension(image.getWidth(this),
                                            image.getHeight(this)));
    }
}

Remove border from dialpad-button to hide the button style on ubuntu


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

package com.google.android.gnd;

import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
import dagger.hilt.android.testing.HiltTestApplication;

public class CustomTestRunner extends AndroidJUnitRunner {

  @Override
  public Application newApplication(ClassLoader cl, String className,
    Context context)
    throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    return super.newApplication(cl, HiltTestApplication.class.getName(), context);
  }
}

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

package com.google.android.gnd;

import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
import dagger.hilt.android.testing.HiltTestApplication;
import timber.log.Timber;
import timber.log.Timber.DebugTree;

public class CustomTestRunner extends AndroidJUnitRunner {

  @Override
  public Application newApplication(ClassLoader cl, String className,
    Context context)
    throws ClassNotFoundException, IllegalAccessException, InstantiationException {

    Timber.plant(new DebugTree());
    return super.newApplication(cl, HiltTestApplication.class.getName(), context);
  }
}

Allow Timber output from tests