/*
 * Copyright 2009 Jan Ouwens
 *
 * 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 nl.jqno.equalsverifier;

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

public class EqualsVerifierTestBase {
	public void verifyFailure(String message, EqualsVerifier<?> equalsVerifier) {
		try {
			equalsVerifier.verify();
		}
		catch (AssertionError e) {
			// Using startsWith because Assert class sometimes adds extra info to the error message.
			assertTrue("Assertion has incorrect message: expected <" + message + "> but was <" + e.getMessage() + ">",
					e.getMessage().startsWith(message));
			return;
		}
		catch (Throwable e) {
			e.printStackTrace();
			fail("Wrong exception thrown: " + e.getClass());
		}
		fail("Assertion didn't fail");
	}
}

/*
 * Copyright 2009 Jan Ouwens
 *
 * 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 nl.jqno.equalsverifier;

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

public class EqualsVerifierTestBase {
	public void verifyFailure(String message, EqualsVerifier<?> equalsVerifier) {
		try {
			equalsVerifier.verify();
		}
		catch (AssertionError e) {
			// Using startsWith because Assert class sometimes adds extra info to the error message.
			assertTrue("Assertion has incorrect message. Expected:\n  " + message + "\nbut was\n  " + e.getMessage(),
					e.getMessage().startsWith(message));
			return;
		}
		catch (Throwable e) {
			e.printStackTrace();
			fail("Wrong exception thrown: " + e.getClass());
		}
		fail("Assertion didn't fail");
	}
}

Make error message easier to read

Make error message easier to read


package de.kimminich.kata.botwars.effects;

import de.kimminich.kata.botwars.Bot;
import de.kimminich.kata.botwars.messages.Message;

public abstract class AbstractEffect implements Effect {

    private Bot invoker;
    private int duration;

    public AbstractEffect(Bot invoker, Integer duration) {
        this.invoker = invoker;
        this.duration = duration;
    }

    public int getDuration() {
        return duration;
    }

    @Override
    public boolean isExpired() {
        return duration == 0;
    }

    @Override
    public Message apply(Bot target) {
        duration--;
        return applyEffect(invoker, target);
    }

    @Override
    public Message revoke(Bot target) {
        return revokeEffect(invoker, target);
    }

    public abstract Message applyEffect(Bot invoker, Bot target);

    public abstract Message revokeEffect(Bot invoker, Bot target);

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "(" + duration + ")";
    }
}

package de.kimminich.kata.botwars.effects;

import de.kimminich.kata.botwars.Bot;
import de.kimminich.kata.botwars.messages.Message;

public abstract class AbstractEffect implements Effect {

    private Bot invoker;
    private int duration;

    public AbstractEffect(Bot invoker, Integer duration) {
        this.invoker = invoker;
        this.duration = duration;
    }

    @Override
    public boolean isExpired() {
        return duration == 0;
    }

    @Override
    public Message apply(Bot target) {
        duration--;
        return applyEffect(invoker, target);
    }

    @Override
    public Message revoke(Bot target) {
        return revokeEffect(invoker, target);
    }

    public abstract Message applyEffect(Bot invoker, Bot target);

    public abstract Message revokeEffect(Bot invoker, Bot target);

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "(" + duration + ")";
    }
}

Remove unused getter for duration

Remove unused getter for duration


package org.jvirtanen.nassau;

import java.io.IOException;

public class ProtocolException extends IOException {

    public ProtocolException(String message) {
        super(message);
    }

    public ProtocolException(String message, Throwable cause) {
        super(message, cause);
    }

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

}

package org.jvirtanen.nassau;

import java.io.IOException;

/**
 * Indicates a protocol error.
 */
public class ProtocolException extends IOException {

    /**
     * Construct an instance with the specified detail message.
     *
     * @param message the detail message
     */
    public ProtocolException(String message) {
        super(message);
    }

    /**
     * Construct an instance with the specified detail message and cause.
     *
     * @param message the detail message
     * @param cause the cause
     */
    public ProtocolException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Construct an instance with the specified cause.
     *
     * @param cause the cause
     */
    public ProtocolException(Throwable cause) {
        super(cause);
    }

}

Add documentation for protocol exception


package com.gmail.jakekinsella.background;

import com.gmail.jakekinsella.communicator.Communicator;
import com.gmail.jakekinsella.map.Map;
import com.gmail.jakekinsella.robot.RobotControl;

/**
 * Created by jakekinsella on 12/20/16.
 */
public class VisionCollector implements Runnable {

    private Map map;
    private Communicator communicator;
    private RobotControl robotControl;

    public VisionCollector(Map map, Communicator communicator, RobotControl robotControl) {
        this.map = map;
        this.communicator = communicator;
        this.robotControl = robotControl;
    }

    @Override
    public void run() {
        while (true) {
            this.map.inputVisionData(this.communicator.getVisionUpdate(), robotControl);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

package com.gmail.jakekinsella.background;

import com.gmail.jakekinsella.communicator.Communicator;
import com.gmail.jakekinsella.map.Map;
import com.gmail.jakekinsella.robot.RobotControl;

/**
 * Created by jakekinsella on 12/20/16.
 */
public class VisionCollector implements Runnable {

    private Map map;
    private Communicator communicator;
    private RobotControl robotControl;

    public VisionCollector(Map map, Communicator communicator, RobotControl robotControl) {
        this.map = map;
        this.communicator = communicator;
        this.robotControl = robotControl;
    }

    @Override
    public void run() {
        while (true) {
            this.map.inputVisionData(this.communicator.getVisionUpdate(), robotControl);

            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Speed up vision collector loop

Speed up vision collector loop


package org.junit.experimental.runners;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.junit.runners.Suite;
import org.junit.runners.model.RunnerBuilder;

/**
 * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class
 * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes
 * to group them for convenience or to share constants. Abstract inner classes are ignored.
 *

 * So, for example:
 *

 * @RunWith(Enclosed.class)
 * public class ListTests {
 *     ...useful shared stuff...
 *     public static class OneKindOfListTest {...}
 *     public static class AnotherKind {...}
 *     abstract public static class Ignored {...}
 * }
 *

 *
 * @see org.junit.tests.manipulation.SortableTest
 */
public class Enclosed extends Suite {
    /**
     * Only called reflectively. Do not use programmatically.
     */
    public Enclosed(Class<?> klass, RunnerBuilder builder) throws Throwable {
        super(builder, klass, filterAbstractClasses(klass.getClasses()));
    }

    private static Class<?>[] filterAbstractClasses(final Class<?>[] classes) {
        final List<Class<?>> filteredList= new ArrayList<Class<?>>(classes.length);

        for (final Class<?> clazz : classes) {
            if (!Modifier.isAbstract(clazz.getModifiers())) {
                filteredList.add(clazz);
            }
        }

        return filteredList.toArray(new Class<?>[filteredList.size()]);
    }
}

package org.junit.experimental.runners;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.junit.runners.Suite;
import org.junit.runners.model.RunnerBuilder;

/**
 * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class
 * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes
 * to group them for convenience or to share constants. Abstract inner classes are ignored.
 *

 * So, for example:
 *

 * @RunWith(Enclosed.class)
 * public class ListTests {
 *     ...useful shared stuff...
 *     public static class OneKindOfListTest {...}
 *     public static class AnotherKind {...}
 *     abstract public static class Ignored {...}
 * }
 *

 */
public class Enclosed extends Suite {
    /**
     * Only called reflectively. Do not use programmatically.
     */
    public Enclosed(Class<?> klass, RunnerBuilder builder) throws Throwable {
        super(builder, klass, filterAbstractClasses(klass.getClasses()));
    }

    private static Class<?>[] filterAbstractClasses(final Class<?>[] classes) {
        final List<Class<?>> filteredList= new ArrayList<Class<?>>(classes.length);

        for (final Class<?> clazz : classes) {
            if (!Modifier.isAbstract(clazz.getModifiers())) {
                filteredList.add(clazz);
            }
        }

        return filteredList.toArray(new Class<?>[filteredList.size()]);
    }
}

Remove JavaDoc reference to test class.

Remove JavaDoc reference to test class.

The test class is no available by JavaDoc.


package de.bmoth.parser.ast.nodes.ltl;

public class BuechiAutomaton {

    public String new_name() {
        return "place holder";
    }

    public BuechiAutomatonNode[] expand(BuechiAutomatonNode node, BuechiAutomatonNode[] nodes_set) {
        return null;
    }

    public BuechiAutomatonNode[] create_graph(LTLFormula formula) {
        String[] initIncoming = {"init"};
        BuechiAutomatonNode[] nodes_set={};
        return expand(new BuechiAutomatonNode(new_name(), initIncoming, new LTLFormula[]{formula},
            new LTLFormula[]{}, new LTLFormula[]{}), nodes_set);
    }
}

package de.bmoth.parser.ast.nodes.ltl;

public class BuechiAutomaton {

    public String new_name() {
        return "place holder";
    }

    public BuechiAutomatonNode nodeIsInNodeSet(BuechiAutomatonNode node, BuechiAutomatonNode[] nodesSet) {
        BuechiAutomatonNode foundNode = null;
        for (BuechiAutomatonNode nodeInSet: nodesSet) {
            if ((nodeInSet.processed == node.processed) && (nodeInSet.next == node.next)) {
                foundNode = nodeInSet;
                break;
            }
        }
        return foundNode;
    }

    public BuechiAutomatonNode[] expand(BuechiAutomatonNode node, BuechiAutomatonNode[] nodesSet) {
        if (node.nonprocessed.length == 0) {
            if (nodeIsInNodeSet(node, nodesSet) != null) {
                return nodesSet;
            }
        }
        return nodesSet;
    }

    public BuechiAutomatonNode[] create_graph(LTLFormula formula) {
        String[] initIncoming = {"init"};
        BuechiAutomatonNode[] nodes_set={};
        return expand(new BuechiAutomatonNode(new_name(), initIncoming, new LTLFormula[]{formula},
            new LTLFormula[]{}, new LTLFormula[]{}), nodes_set);
    }
}

Check if processed node is already in the nodesSet


package test.java;

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

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

import com.xrtb.geo.GeoTag;
import com.xrtb.geo.Solution;

/**
 * Make sure GPS to zip code conversion works as expected.
 * @author Ben M. Faul
 *
 */
public class TestGeoTag  {

	@BeforeClass
	public static void setup() {
		try {
			Config.setup();
			System.out.println("******************  TestGeoTag");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@AfterClass
	public static void stop() {
		Config.teardown();
	}

	@Test
	public void testHaversignCalc()  {
		try {
		GeoTag z = new GeoTag();
		z.initTags("data/zip_codes_states.csv",
					"data/unique_geo_zipcodes.txt");
		Solution p = null;
		long time = System.currentTimeMillis();
		p = z.getSolution(42.378,-71.227);
		assertTrue(p.code==2238);
		assertTrue(p.state.equals("MA"));
		assertTrue(p.county.equals("Middlesex"));
		} catch (Exception error) {
			error.printStackTrace();
			fail(error.toString());
		}
	}
}

package test.java;

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

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

import com.xrtb.geo.GeoTag;
import com.xrtb.geo.Solution;

/**
 * Make sure GPS to zip code conversion works as expected.
 * @author Ben M. Faul
 *
 */
public class TestGeoTag  {

	@BeforeClass
	public static void setup() {
		try {
			Config.setup();
			System.out.println("******************  TestGeoTag");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@AfterClass
	public static void stop() {
		Config.teardown();
	}

	@Test
	public void testHaversignCalc()  {
		try {
		GeoTag z = new GeoTag();
		z.initTags("data/zip_codes_states.csv",
					"data/unique_geo_zipcodes.txt");
		Solution p = null;
		long time = System.currentTimeMillis();
		p = z.getSolution(42.378,-71.227);
		assertTrue(p.code==2138);
		assertTrue(p.state.equals("MA"));
		assertTrue(p.county.equals("Middlesex"));
		assertTrue(p.city.equals("Cambridge"));
		} catch (Exception error) {
			error.printStackTrace();
			fail(error.toString());
		}
	}
}

Add the city for testing.

Add the city for testing.


package org.gestern.gringotts.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import static org.gestern.gringotts.Language.LANG;

/**
 * Player commands.
 */
public class MoneyExecutor extends GringottsAbstractExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LANG.playerOnly);
            return false;
        }
        Player player = (Player) sender;

        if (args.length == 0) {
            // same as balance
            sendBalanceMessage(eco.player(player.getUniqueId()));
            return true;
        }

        String command = args[0];

        double value = 0;
        if (args.length == 2) {
            try {
                value = Double.parseDouble(args[1]);
            } catch (NumberFormatException ignored) {
                return false;
            }

            if ("withdraw".equals(command)) {
                withdraw(player, value);

                return true;
            } else if ("deposit".equals(command)) {
                deposit(player, value);

                return true;
            }
        } else if ( args.length == 3 && "pay".equals(command)) {
            // money pay <amount> <player>
            return pay(player, value, args);
        }
        return false;
    }
}

package org.gestern.gringotts.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import static org.gestern.gringotts.Language.LANG;

/**
 * Player commands.
 */
public class MoneyExecutor extends GringottsAbstractExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LANG.playerOnly);
            return false;
        }
        Player player = (Player) sender;

        if (args.length == 0) {
            // same as balance
            sendBalanceMessage(eco.player(player.getUniqueId()));
            return true;
        }

        String command = args[0];

        double value = 0;
        if (args.length == 2) {
            try {
                value = Double.parseDouble(args[1]);
            } catch (NumberFormatException ignored) {
                return false;
            }

            if ("withdraw".equals(command)) {
                withdraw(player, value);

                return true;
            } else if ("deposit".equals(command)) {
                deposit(player, value);

                return true;
            }
        } else if ( args.length == 3 && "pay".equals(command)) {
            try {
                value = Double.parseDouble(args[1]);
            } catch (NumberFormatException ignored) {
                return false;
            }

            // money pay <amount> <player>
            return pay(player, value, args);
        }
        return false;
    }
}

Fix pay command always sending 0.

Fix pay command always sending 0.

Closes #197
Closes #193


package study.hard.javalib.nativelib;

import org.junit.Test;

public class LanguageTest {

	@Test
	public void testStaticVariable() {
		ClassThatHasStaticVariable a1 = new ClassThatHasStaticVariable();
		ClassThatHasStaticVariable a2 = new ClassThatHasStaticVariable();
	}

}

class ClassThatHasStaticVariable {
	static int count = 0;

	ClassThatHasStaticVariable() {
		count++;
		System.out.print(count);
	}
}

package study.hard.javalib.nativelib;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import study.hard.javalib.commons.entity.BasisObject;

public class LanguageTest {

	private static Logger logger = LoggerFactory.getLogger(LanguageTest.class);

	@Test
	public void testStaticVariable() {
		ClassThatHasStaticVariable a1 = new ClassThatHasStaticVariable();
		logger.debug("a1: " + a1);
		ClassThatHasStaticVariable a2 = new ClassThatHasStaticVariable();
		logger.debug("a2: " + a2);
	}

	private static class ClassThatHasStaticVariable extends BasisObject {
		private static final long serialVersionUID = -8833377195166280242L;

		static int count = 0;

		ClassThatHasStaticVariable() {
			count++;
			logger.debug("count: " + count);
		}
	}
}

Update to use the Logger instead of the System.out.println().


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.entitytype.UEntityType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.entity.BetterEnderPearlEntity;
import net.minecraft.entity.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class TestEntityTypes {

	public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, TestMod.MODID);

	public static final RegistryObject<EntityType<BetterEnderPearlEntity>> BETTER_ENDERPEARL = ENTITY_TYPES.register("better_enderpearl", () -> UEntityType.UBuilder.<BetterEnderPearlEntity> create("better_enderpearl", BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true).build());

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

package info.u_team.u_team_test.init;

import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.entity.BetterEnderPearlEntity;
import net.minecraft.entity.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class TestEntityTypes {

	public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, TestMod.MODID);

	public static final RegistryObject<EntityType<BetterEnderPearlEntity>> BETTER_ENDERPEARL = ENTITY_TYPES.register("better_enderpearl", () -> EntityType.Builder.<BetterEnderPearlEntity> create(BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true).disableSerialization().build(null));

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

Use the normal builder now (maybe we make a custom deferred register for that for easier use)


package io.github.rlee287.jrainbuck.uppering;

public interface UVCreator {

	public byte[] getUV();

}

package io.github.rlee287.jrainbuck.uppering;

public interface UVCreator {

	public byte[] getUV();

	public char getUVType();

}

Add method to return UV type to interface


package jpower.event.test;

import jpower.core.utils.ThreadUtils;
import jpower.event.ClientEventBus;
import jpower.event.EventHandler;
import jpower.event.ServerEventBus;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertTrue;

public class NetworkBusTest
{

   private boolean worked;

   private ServerEventBus server;

   @Before
   public void prepare() throws IOException
   {
      server = new ServerEventBus("127.0.0.1", 46839);
   }

   @Test
   public void testServerClientInteraction() throws IOException
   {
      server.start();
      server.register(this);
      ClientEventBus client = new ClientEventBus("127.0.0.1", 46839);
      client.connect();
      client.post(new TestEvent());
      ThreadUtils.sleep(1000);
      assertTrue(worked);
      worked = false;
      server.unregister(this);
      client.register(this);
      server.post(new TestEvent());
      ThreadUtils.sleep(1000);
      assertTrue(worked);
   }

   @EventHandler
   public void handleEvent(TestEvent event)
   {
      worked = event.getPayload().equals("Success");
   }
}

package jpower.event.test;

import jpower.core.utils.ThreadUtils;
import jpower.event.ClientEventBus;
import jpower.event.EventHandler;
import jpower.event.ServerEventBus;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertTrue;

public class NetworkBusTest
{

   private boolean worked;

   private ServerEventBus server;

   @Before
   public void prepare() throws IOException
   {
      server = new ServerEventBus("127.0.0.1", 46839);
   }

   @Test
   public void testServerClientInteraction() throws IOException
   {
      server.start();
      server.register(this);
      ClientEventBus client = new ClientEventBus("127.0.0.1", 46839);
      client.connect();
      client.post(new TestEvent());
      ThreadUtils.sleep(1000);
      assertTrue(worked);
      worked = false;
      server.unregister(this);
      client.register(this);
      server.post(new TestEvent());
      ThreadUtils.sleep(2000);
      assertTrue(worked);
   }

   @EventHandler
   public void handleEvent(TestEvent event)
   {
      worked = event.getPayload().equals("Success");
   }
}

Fix Network Bus Tests (Hopefully)

Event: Fix Network Bus Tests (Hopefully)


package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarEquality {

	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
	}

}

package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarEquality {

	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
		assertFalse(new Dollar(5).equals(new Dollar(6)));
	}

}

Add another condition in test case where it fails due to fake implementation in equals method


package com.devfd.RNGeocoder;

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

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;

public class RNGeocoderPackage implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(
        new RNGeocoderModule(reactContext)
    );
  }

  @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }

}

package com.devfd.RNGeocoder;

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

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;

public class RNGeocoderPackage implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(
        new RNGeocoderModule(reactContext)
    );
  }

    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }

}

Remove @override on createJSModules for latest RN version


package editor.menubar;

import xml.Element;
import xml.ElementXMLSerializer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * The ExportActionListener is used to deal with the user action of exporting
 * an element tree to XML
 */
public class ExportActionListener implements ActionListener {
    private Element root;

    public ExportActionListener(Element root) {
        this.root = root;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        ElementXMLSerializer exs = new ElementXMLSerializer();
        String fileName = "tree.xml";
        System.out.printf("[DEBUG] writing file: %s\n", fileName);
        exs.serializeToFile(root, fileName);
    }
}

package editor.menubar;

import xml.Element;
import xml.ElementXMLSerializer;

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

/**
 * The ExportActionListener is used to deal with the user action of exporting
 * an element tree to XML
 */
public class ExportActionListener implements ActionListener {
    private Element root;

    public ExportActionListener(Element root) {
        this.root = root;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        ElementXMLSerializer exs = new ElementXMLSerializer();
        JFrame exportFileChooserFrame = new JFrame();
        JFileChooser fc = new JFileChooser();
        fc.showSaveDialog(exportFileChooserFrame);
        String fileName = fc.getSelectedFile().getAbsolutePath();
        System.out.printf("[DEBUG] writing file: \"%s\"\n", fileName);
        exs.serializeToFile(root, fileName);
    }
}

Add save dialog for export

Add save dialog for export


package com.marverenic.music.view;

import android.content.Context;
import android.support.v7.widget.LinearSmoothScroller;
import android.util.DisplayMetrics;

public class SnappingScroller extends LinearSmoothScroller {

    private static final int MIN_SCROLL_TIME_MS = 75;
    private static final float MILLISECONDS_PER_INCH = 50f;

    public static final int SNAP_TO_START = LinearSmoothScroller.SNAP_TO_START;
    public static final int SNAP_TO_END = LinearSmoothScroller.SNAP_TO_END;

    private int mSnapPreference;

    public SnappingScroller(Context context, int snap) {
        super(context);
        mSnapPreference = snap;
    }

    @Override
    protected int getHorizontalSnapPreference() {
        return mSnapPreference;
    }

    @Override
    protected int getVerticalSnapPreference() {
        return mSnapPreference;
    }

    @Override
    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
        return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
    }

    @Override
    protected int calculateTimeForScrolling(int dx) {
        return Math.max(MIN_SCROLL_TIME_MS, super.calculateTimeForScrolling(dx));
    }
}

package com.marverenic.music.view;

import android.content.Context;
import android.support.v7.widget.LinearSmoothScroller;
import android.util.DisplayMetrics;
import android.view.View;

public class SnappingScroller extends LinearSmoothScroller {

    private static final float MILLISECONDS_PER_INCH = 100f;

    public static final int SNAP_TO_START = LinearSmoothScroller.SNAP_TO_START;
    public static final int SNAP_TO_END = LinearSmoothScroller.SNAP_TO_END;

    private Context mContext;
    private int mSnapPreference;
    private float mMillisecondsPerPixel;

    public SnappingScroller(Context context, int snap) {
        super(context);
        mContext = context;
        mSnapPreference = snap;
    }

    @Override
    protected int getHorizontalSnapPreference() {
        return mSnapPreference;
    }

    @Override
    protected int getVerticalSnapPreference() {
        return mSnapPreference;
    }

    @Override
    protected void onStart() {
        super.onStart();

        View firstView = getLayoutManager().getChildAt(0);
        int firstViewPosition = getChildPosition(firstView);
        int intermediateViewCount = Math.abs(firstViewPosition - getTargetPosition());

        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        mMillisecondsPerPixel = getSpeedPerPixel(displayMetrics, intermediateViewCount);
    }

    private float getSpeedPerPixel(DisplayMetrics displayMetrics, int intermediateViewCount) {
        int dpi = displayMetrics.densityDpi;
        return MILLISECONDS_PER_INCH / (float) Math.sqrt(intermediateViewCount) / dpi;
    }

    @Override
    protected int calculateTimeForScrolling(int dx) {
        return (int) Math.ceil(Math.abs(dx) * mMillisecondsPerPixel);
    }
}

Reduce scroll time when seeking over many views


package pl.niekoniecznie.p2e;

import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;

public class FileDownloader implements Consumer<PolarEntry> {

    private final Path backupDirectory;
    private final PolarFileSystem filesystem;

    public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
        this.backupDirectory = backupDirectory;
        this.filesystem = filesystem;
    }

    @Override
    public void accept(PolarEntry entry) {
        if (entry.isDirectory()) {
            return;
        }

        InputStream source = filesystem.get(entry);
        Path destination = Paths.get(backupDirectory.toString(), entry.getPath());

        try {
            Files.copy(source, destination);
            Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

package pl.niekoniecznie.p2e;

import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;

public class FileDownloader implements Consumer<PolarEntry> {

    private final Path backupDirectory;
    private final PolarFileSystem filesystem;

    public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
        this.backupDirectory = backupDirectory;
        this.filesystem = filesystem;
    }

    @Override
    public void accept(PolarEntry entry) {
        if (entry.isDirectory()) {
            return;
        }

        InputStream source = filesystem.get(entry);
        Path destination = Paths.get(backupDirectory.toString(), entry.getPath());

        try {
            Files.deleteIfExists(destination);
            Files.copy(source, destination);
            Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Delete existing files before downloading them again


package com.royalrangers.model.achievement;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.royalrangers.model.BaseModel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;

@Getter
@Setter
@Entity
public class Task extends BaseModel {

    private String name;

    private String description;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "test_id", nullable = true)
    private Test test;

}

package com.royalrangers.model.achievement;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import com.royalrangers.model.BaseModel;
import com.royalrangers.model.Views;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;

@Getter
@Setter
@Entity
public class Task extends BaseModel {

    @JsonView(Views.Achievement.class)
    private String name;

    @JsonView(Views.Achievement.class)
    private String description;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "test_id", nullable = true)
    private Test test;

}

Add JsonView to name and description

Add JsonView to name and description


/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/licenses/publicdomain
 */

/*
 * Modified in Apache Harmony to comply with Java 5 signature
 * specification.
 */

package java.util.concurrent;

import java.util.*;

/**
 * A mix-in style interface for marking objects that should be
 * acted upon after a given delay.
 *
 * <p>An implementation of this interface must define a
 * <tt>compareTo</tt> method that provides an ordering consistent with
 * its <tt>getDelay</tt> method.
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface Delayed extends Comparable<Delayed> {

    /**
     * Returns the remaining delay associated with this object, in the
     * given time unit.
     *
     * @param unit the time unit
     * @return the remaining delay; zero or negative values indicate
     * that the delay has already elapsed
     */
    long getDelay(TimeUnit unit);
}

/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/licenses/publicdomain
 */

package java.util.concurrent;

import java.util.*;

/**
 * A mix-in style interface for marking objects that should be
 * acted upon after a given delay.
 *
 * <p>An implementation of this interface must define a
 * <tt>compareTo</tt> method that provides an ordering consistent with
 * its <tt>getDelay</tt> method.
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface Delayed extends Comparable<Delayed> {

    /**
     * Returns the remaining delay associated with this object, in the
     * given time unit.
     *
     * @param unit the time unit
     * @return the remaining delay; zero or negative values indicate
     * that the delay has already elapsed
     */
    long getDelay(TimeUnit unit);
}

Remove misleading comment - the only diff from latest Doug Lea version.

svn path=/harmony/; revision=800268


package com.github.aureliano.achmed.os;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public class LinuxTest {

	@Test
	public void testGetPsCommand() {
		final String cmd = "ps -ef";
		assertEquals(cmd, this.createDefaultOs().getPsCommand());
	}

	private Linux createDefaultOs() {
		return new Linux() {

			public OperatingSystemFamily getOperatingSystemFamily() {
				return null;
			}

			public IPackageManager getDefaultPackageManager() {
				return null;
			}
		};
	}
}

package com.github.aureliano.achmed.os;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.types.OS;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public class LinuxTest {

	private Linux linux;

	public LinuxTest() {
		this.linux = this.createDefaultOs();
	}

	@Test
	public void testGetOperatingSystem() {
		assertEquals(OS.LINUX, this.linux.getOperatingSystem());
	}

	@Test
	public void testGetPsCommand() {
		final String cmd = "ps -ef";
		assertEquals(cmd, this.linux.getPsCommand());
	}

	private Linux createDefaultOs() {
		return new Linux() {

			public OperatingSystemFamily getOperatingSystemFamily() {
				return null;
			}

			public IPackageManager getDefaultPackageManager() {
				return null;
			}
		};
	}
}

Add unit test to get operating system method.


package io.undertow.servlet.test.streams;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Stuart Douglas
 */
public class ContentLengthCloseFlushServlet extends HttpServlet {

    private boolean completed = false;

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        if (completed) {
            resp.getWriter().write("OK");
        } else {
            resp.setContentLength(1);
            ServletOutputStream stream = resp.getOutputStream();
            stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
            stream.flush();
            stream.close();
            completed = true;
        }
    }
}

package io.undertow.servlet.test.streams;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Stuart Douglas
 */
public class ContentLengthCloseFlushServlet extends HttpServlet {

    private boolean completed = false;

    @Override
    protected synchronized void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        if (completed) {
            resp.getWriter().write("OK");
        } else {
            resp.setContentLength(1);
            ServletOutputStream stream = resp.getOutputStream();
            stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
            stream.flush();
            stream.close();
            completed = true;
        }
    }
}

Fix race condition in test

Fix race condition in test


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

package org.terasology.world.sun;

/**
 * An interface for celestial systems (with only one sun)
 */
//@FunctionalInterface
public interface CelestialSystem {

    /**
     * @return angle of the sun in radians
     */
    float getSunPosAngle();

    /**
     * Toggles the halting of sun's position and angle
     *
     * @param timeInDays
     */
    void toggleSunHalting(float timeInDays);

    /**
     * @return Whether the sun is currently halted or not
     */
    boolean isSunHalted();
}

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

package org.terasology.world.sun;

/**
 * An interface for celestial systems (with only one sun)
 */
public interface CelestialSystem {

    /**
     * @return angle of the sun in radians
     */
    float getSunPosAngle();

    /**
     * Toggles the halting of sun's position and angle
     *
     * @param timeInDays
     */
    void toggleSunHalting(float timeInDays);

    /**
     * @return Whether the sun is currently halted or not
     */
    boolean isSunHalted();
}

Remove comment containing `@FunctionalInterface` as per review comments.


package moe.tristan.easyfxml.util;

import java.util.function.Consumer;
import java.util.function.Supplier;

import javafx.beans.property.Property;

public final class Properties {

    private Properties() {
    }

    public static <T, P extends Property<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) {
        final P property = propertyFactory.get();
        whenPropertyIsSet(property, callback);
        return property;
    }

    public static <T, P extends Property<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) {
        property.addListener((o, prev, cur) -> doWhenSet.accept(cur));
        if (property.getValue() != null) {
            doWhenSet.accept(property.getValue());
        }
    }

}

package moe.tristan.easyfxml.util;

import java.util.function.Consumer;
import java.util.function.Supplier;

import javafx.beans.property.Property;

public final class Properties {

    private Properties() {
    }

    public static <T, P extends Property<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) {
        final P property = propertyFactory.get();
        whenPropertyIsSet(property, callback);
        return property;
    }

    public static <T, P extends Property<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) {
        whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue()));
    }

    public static <T, P extends Property<T>> void whenPropertyIsSet(P property, Runnable doWhenSet) {
        property.addListener((o, prev, cur) -> doWhenSet.run());
        if (property.getValue() != null) {
            doWhenSet.run();
        }
    }

}

Add basic convenience async property runnable execution


// Copyright 2019 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.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;");
    response.getWriter().println("
Hello world!
");
  }
}

Test push from my own branch

Test push from my own branch


//
// $Id: SimpleServer.java,v 1.1 2002/02/05 22:12:42 mdb Exp $

package com.threerings.micasa.simulator.server;

import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.server.CrowdServer;

/**
 * A simple simulator server implementation that extends the crowd server
 * and provides no special functionality.
 */
public class SimpleServer extends CrowdServer
    implements SimulatorServer
{
    /**
     * Called by the simulator manager to map a username to a particular
     * body object. This should only be called from the dobjmgr thread.
     *
     * <p> This is copied from {@link CrowdServer#mapBody} as that
     * implementation is protected and cannot be referenced by classes in
     * the simulator package, but we know what we're doing and so we
     * knowingly expose this functionality to other classes in our
     * package.
     */
    public void fakeBodyMapping (String username, BodyObject bodobj)
    {
        _bodymap.put(username, bodobj);
    }
}

//
// $Id: SimpleServer.java,v 1.2 2002/02/05 22:57:10 mdb Exp $

package com.threerings.micasa.simulator.server;

import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.server.CrowdServer;

/**
 * A simple simulator server implementation that extends the crowd server
 * and provides no special functionality.
 */
public class SimpleServer extends CrowdServer
    implements SimulatorServer
{
    // documentation inherited
    public void init ()
        throws Exception
    {
        super.init();

        // create the simulator manager
        SimulatorManager simmgr = new SimulatorManager();
        simmgr.init(config, invmgr, plreg, clmgr, omgr, this);
    }

    // documentation inherited
    public void fakeBodyMapping (String username, BodyObject bodobj)
    {
        _bodymap.put(username, bodobj);
    }
}

Set up our SimulatorManager on init().

Set up our SimulatorManager on init().

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@940 542714f4-19e9-0310-aa3c-eee0fc999fb1


/*
 * Copyright (c) TESOBE Ltd. 2016. All rights reserved.
 *
 * Use of this source code is governed by a GNU AFFERO license
 * that can be found in the LICENSE file.
 *
 */
package com.tesobe.obp.kafka;

import java.util.Map;

/**
 * @since 2016.9
 */
@SuppressWarnings("WeakerAccess") public class SimpleNorth
  extends SimpleTransport
{
  public SimpleNorth(String producerTopic, String consumerTopic)
  {
    super(consumerTopic, producerTopic);
  }

  public SimpleNorth(String consumerTopic, String producerTopic,
    Map<String, Object> consumerProps, Map<String, Object> producerProps)
  {
    super(consumerTopic, producerTopic, consumerProps, producerProps);
  }
}

/*
 * Copyright (c) TESOBE Ltd. 2016. All rights reserved.
 *
 * Use of this source code is governed by a GNU AFFERO license
 * that can be found in the LICENSE file.
 *
 */
package com.tesobe.obp.kafka;

import java.util.Map;

/**
 * @since 2016.9
 */
@SuppressWarnings("WeakerAccess") public class SimpleNorth
  extends SimpleTransport
{
  public SimpleNorth(String consumerTopic, String producerTopic)
  {
    super(consumerTopic, producerTopic);
  }

  public SimpleNorth(String consumerTopic, String producerTopic,
    Map<String, Object> consumerProps, Map<String, Object> producerProps)
  {
    super(consumerTopic, producerTopic, consumerProps, producerProps);
  }
}

Remove kafka topic confusion: consumer topic always comes first


package com.github.davidcanboni.jenkins.values;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by david on 15/07/2015.
 */
public enum GitRepo {

    babbage("https://github.com/ONSdigital/babbage.git", true),
    florence("https://github.com/ONSdigital/florence.git", true),
    zebedee("https://github.com/Carboni/zebedee.git"),
    zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
    brian("https://github.com/thomasridd/project-brian.git"),
    thetrain("https://github.com/Carboni/The-Train.git");

    public URL url;
    public boolean nodeJs;
    public boolean submodule;

    GitRepo(String url, boolean... parameters) {
        try {
            this.url = new URL(url);
            if (parameters.length > 0) this.nodeJs = parameters[0];
            if (parameters.length > 1) this.submodule = parameters[1];
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error in url: " + url, e);
        }
    }

    @Override
    public String toString() {
        // Transform zebedeeReader into zebedee-reader:
        return name().replace("R", "-r");
    }
}

package com.github.davidcanboni.jenkins.values;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by david on 15/07/2015.
 */
public enum GitRepo {

    babbage("https://github.com/ONSdigital/babbage.git", true),
    florence("https://github.com/ONSdigital/florence.git", true),
    zebedee("https://github.com/Carboni/zebedee.git"),
    zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
    brian("https://github.com/ONSdigital/project-brian.git"),
    thetrain("https://github.com/Carboni/The-Train.git");

    public URL url;
    public boolean nodeJs;
    public boolean submodule;

    GitRepo(String url, boolean... parameters) {
        try {
            this.url = new URL(url);
            if (parameters.length > 0) this.nodeJs = parameters[0];
            if (parameters.length > 1) this.submodule = parameters[1];
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error in url: " + url, e);
        }
    }

    @Override
    public String toString() {
        // Transform zebedeeReader into zebedee-reader:
        return name().replace("R", "-r");
    }
}

Update project brian to use new ONSDigital repo location.


// Copyright (c) Cognitect, Inc.
// All rights reserved.

package com.cognitect.transit;

public class TestRoundtrip {

    public static void main(String [] args) throws Exception {

        // TODO: use argument to set up json or msgpack
        Reader reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
        Writer writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());

        try {
            while(true) {
                Object o = reader.read();
                writer.write(o);
            }
        }
        catch(Exception e) {
            // exit
        }
    }
}

// Copyright (c) Cognitect, Inc.
// All rights reserved.

package com.cognitect.transit;

public class TestRoundtrip {

    public static void main(String [] args) throws Exception {

        String encoding = args[0];

        Reader reader;
        Writer writer;

        if(encoding.equals("msgpack")) {
            reader = Reader.getMsgpackInstance(System.in, Reader.defaultDecoders());
            writer = Writer.getMsgpackInstance(System.out, Writer.defaultHandlers());
        }
        else {
            reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
            writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());
        }

        try {
            while(true) {
                Object o = reader.read();
                writer.write(o);
            }
        }
        catch(Exception e) {
            // exit
        }
    }
}

Use args to create the desired instance of transit


package protocolsupport.protocol.legacyremapper.chunk;

import protocolsupport.utils.netty.Compressor;

public class EmptyChunk {

	private static final byte[] fake18ChunkDataSky = new byte[8192 + 2048 + 256];
	private static final byte[] fake18ChunkDataNoSky = new byte[8192 + 2048 + 2048 + 256];
	public static byte[] get18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fake18ChunkDataSky : fake18ChunkDataNoSky;
	}

	private static final byte[] fakePre18ChunkDataSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 256]);
	private static final byte[] fakePre18ChunkDataNoSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 2048 + 256]);
	public static byte[] getPre18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fakePre18ChunkDataSky : fakePre18ChunkDataNoSky;
	}

}

package protocolsupport.protocol.legacyremapper.chunk;

import protocolsupport.utils.netty.Compressor;

public class EmptyChunk {

	private static final byte[] fake18ChunkDataSky = new byte[8192 + 2048 + 2048 + 256];
	private static final byte[] fake18ChunkDataNoSky = new byte[8192 + 2048 + 256];
	public static byte[] get18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fake18ChunkDataSky : fake18ChunkDataNoSky;
	}

	private static final byte[] fakePre18ChunkDataSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 2048 + 256]);
	private static final byte[] fakePre18ChunkDataNoSky	= Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 256]);
	public static byte[] getPre18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fakePre18ChunkDataSky : fakePre18ChunkDataNoSky;
	}

}

Fix empty chunk precached byte arrays

Fix empty chunk precached byte arrays


package org.datavaultplatform.common.metadata;

public class Project {

    private String id;
    private String name;

    public Project() {}

    public String getID() {
        return id;
    }

    public void setID(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

package org.datavaultplatform.common.metadata;

public class Project {

    private String id;
    private String url;
    private String name;

    public Project() {}

    public String getID() {
        return id;
    }

    public void setID(String id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

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

Add Url field (may not be required - id could be a Uri)


package org.col.parser;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 *
 */
public class BooleanParserTest extends ParserTestBase<Boolean> {

  public BooleanParserTest() {
    super(BooleanParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse(true, "true");
    assertParse(true, "-1-");
    assertParse(true, "yes!");
    assertParse(true, " t    ");
    assertParse(true, "T");
    assertParse(true, "si");
    assertParse(true, "ja");
    assertParse(true, "oui");
    assertParse(true, "wahr");

    assertParse(false,"f");
    assertParse(false,"f");
    assertParse(false,"no");
    assertParse(false,"nein");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("t ru e", "a", "2");
  }

}

package org.col.parser;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 *
 */
public class BooleanParserTest extends ParserTestBase<Boolean> {

  public BooleanParserTest() {
    super(BooleanParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse(true, "true");
    assertParse(true, "yes");
    assertParse(true, " t    ");
    assertParse(true, "T");
    assertParse(true, "si");
    assertParse(true, "ja");
    assertParse(true, "oui");
    assertParse(true, "wahr");

    assertParse(false,"f");
    assertParse(false,"f");
    assertParse(false,"no");
    assertParse(false,"nein");
    assertParse(false, "-1");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("t ru e", "a", "2");
  }

}

Fix boolean parser, expecting -1 to become false


package game.geography.rest;

public class LandEndpointTest {

    // TODO test: add unit test for the LandEndpoint

    // @Mock
    // Map map;
}

package game.geography.rest;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class LandEndpointTest {

    // TODO test: add unit test for the LandEndpoint

    // @Mock
    // Map map;

    @Test
    public void shouldNotFailInMaven() {
        assertTrue(true);
    }
}

Add dummy test so Maven 2 does not fail on empty test.


package com.continuuity.passport;

/**
 *
 */
public class PassportConstants {
  //Config key passport server address
  public final static String CFG_PASSPORT_SERVER_URI = "passport.server.uri";
  //Config for api header
  public final static String CONTINUUITY_API_KEY_HEADER = "X-Continuuity-ApiKey";
  public final static String CONTENT_TYPE_HEADER = "Content-Type";
  public final static String CONTENT_TYPE = "application/json";
}

package com.continuuity.passport;

/**
 *
 */
public class PassportConstants {
  //Config key passport server address
  public final static String CFG_PASSPORT_SERVER_URI = "passport.server.uri";
  public final static String DEFAULT_PASSPORT_SERVER_URI = "http://localhost/";
  //Config for api header
  public final static String CONTINUUITY_API_KEY_HEADER = "X-Continuuity-ApiKey";
  public final static String CONTENT_TYPE_HEADER = "Content-Type";
  public final static String CONTENT_TYPE = "application/json";
}

Add passport defaults for server_uri

Add passport defaults for server_uri


package org.jboss.pnc.causeway.rest;

public class BrewNVR {

    private final String name;
    private final String version;
    private final String release;

    public BrewNVR(String name, String version, String release) {
        this.name = name;
        this.version = version;
        this.release = release;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public String getRelease() {
        return release;
    }

    public String getNVR(){
        return name + "-" + version + "-" + release;
    }
}

package org.jboss.pnc.causeway.rest;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class BrewNVR {

    private final String name;
    private final String version;
    private final String release;

    public BrewNVR(String name, String version, String release) {
        this.name = name;
        this.version = version;
        this.release = release;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public String getRelease() {
        return release;
    }

    @JsonIgnore
    public String getNVR(){
        return name + "-" + version + "-" + release;
    }
}

Add @JsonIgnore to NVR getter

Add @JsonIgnore to NVR getter


package org.jusecase.properties.ui;

import org.jusecase.properties.entities.Key;
import org.jusecase.properties.entities.KeyPopulation;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class KeyListCellRenderer extends DefaultListCellRenderer {
    Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>();

    public KeyListCellRenderer() {
        backgroundColorForPopulation.put(KeyPopulation.Complete, new Color(240, 255, 230));
        backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(255, 251, 230));
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Key key = (Key) value;
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (!isSelected) {
            Color color = backgroundColorForPopulation.get(key.getPopulation());
            if (color != null) {
                label.setBackground(color);
            }
        }

        return label;
    }
}

package org.jusecase.properties.ui;

import org.jusecase.properties.entities.Key;
import org.jusecase.properties.entities.KeyPopulation;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class KeyListCellRenderer extends DefaultListCellRenderer {
    Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>();

    public KeyListCellRenderer() {
        backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(231, 211, 186));
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Key key = (Key) value;
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (!isSelected) {
            Color color = backgroundColorForPopulation.get(key.getPopulation());
            if (color != null) {
                label.setBackground(color);
            }
        }

        return label;
    }
}

Make sparse / complete more distinguishable


package uk.gov.register.resources.v2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.gov.register.views.representations.ExtraMediaType;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.Method;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class EntryResourceTest {
    @Test
    public void findByEntryNumberAvailableInV2() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes,
                hasItems(MediaType.APPLICATION_JSON,
                        ExtraMediaType.TEXT_CSV));
    }
}

package uk.gov.register.resources.v2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.gov.register.views.representations.ExtraMediaType;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.Method;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class EntryResourceTest {
    @Test
    public void findByEntryNumberAvailableInV2() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes,
                hasItems(MediaType.APPLICATION_JSON,
                        ExtraMediaType.TEXT_CSV));
    }

    @Test
    public void v2DropsSupportForContentTypes() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_YAML)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.APPLICATION_SPREADSHEET)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_TSV)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_TTL)));
    }
}

Test that V2 API removes old content types

This is not intended to be a thorough test, it's just something to capture
this difference between v1 and v2 that might not be clear from the code.


package com.mongodb.memphis.config;

import org.bson.BsonDocument;

import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Collection {

	private String name;
	private WriteConcern writeConcern;
	private ReadConcern readConcern;
	private ReadPreference readPreference;

	public final String getName() {
		return name;
	}

	public final WriteConcern getWriteConcern() {
		return writeConcern;
	}

	public final ReadConcern getReadConcern() {
		return readConcern;
	}

	public final ReadPreference getReadPreference() {
		return readPreference;
	}

	public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) {
		MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class);

		if (writeConcern != null) {
			collection.withWriteConcern(writeConcern);
		}
		if (readConcern != null) {
			collection.withReadConcern(readConcern);
		}
		if (readPreference != null) {
			collection.withReadPreference(readPreference);
		}

		return collection;
	}

}

package com.mongodb.memphis.config;

import org.bson.BsonDocument;

import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Collection {

	private String name;
	private WriteConcern writeConcern;
	private ReadConcern readConcern;
	private ReadPreference readPreference;

	public final String getName() {
		return name;
	}

	public final WriteConcern getWriteConcern() {
		return writeConcern;
	}

	public final ReadConcern getReadConcern() {
		return readConcern;
	}

	public final ReadPreference getReadPreference() {
		return readPreference;
	}

	public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) {
		MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class);

		if (writeConcern != null) {
			collection = collection.withWriteConcern(writeConcern);
		}
		if (readConcern != null) {
			collection = collection.withReadConcern(readConcern);
		}
		if (readPreference != null) {
			collection = collection.withReadPreference(readPreference);
		}

		return collection;
	}

}

FIX - write concerns not added to collection


package to.etc.domui.component.ntbl;

import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;

/**
 * Event handler for row-based editors.
 *
 * @author Frits Jalvingh
 * Created on Dec 21, 2009
 */
public interface IRowEditorEvent<T, E extends NodeContainer & IEditor> {
	/**
	 * Called after a row has been edited in an editable table component, when editing is (somehow) marked
	 * as complete. When called the editor's contents has been moved to the model by using the bindings. This method
	 * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
	 *
	 * @param tablecomponent
	 * @param editor
	 * @param instance
	 * @return false to refuse the change.
	 * @throws Exception
	 */
	boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}

package to.etc.domui.component.ntbl;

import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;

/**
 * Event handler for row-based editors.
 *
 * @author Frits Jalvingh
 * Created on Dec 21, 2009
 */
public interface IRowEditorEvent<T, E extends NodeContainer> {
	/**
	 * Called after a row has been edited in an editable table component, when editing is (somehow) marked
	 * as complete. When called the editor's contents has been moved to the model by using the bindings. This method
	 * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
	 *
	 * @param tablecomponent
	 * @param editor
	 * @param instance
	 * @return false to refuse the change.
	 * @throws Exception
	 */
	boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}

Reduce bounds on generic: Java lacks most of the stuff to actually use it.


package io.particle.android.sdk.devicesetup;

import android.content.Context;
import android.content.Intent;

public interface SetupCompleteIntentBuilder {
    Intent buildIntent(Context ctx, SetupResult result);
}

package io.particle.android.sdk.devicesetup;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

public interface SetupCompleteIntentBuilder {
    Intent buildIntent(Context ctx, @Nullable SetupResult result);
}

Add annotation to make it clear the SetupResult parameter may be null.


package com.crowdin.cli.utils.file;

import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.ResourceBundle;

public class FileReader {

    private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";

    private static final String YAML_EXTENSION = ".yaml";

    private static final String YML_EXTENSION = ".yml";

    public Map<String, Object> readCliConfig(File fileCfg) {
        if (fileCfg == null) {
            throw new NullPointerException("FileReader.readCliConfig has null args");
        }
        if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
            System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
        }

        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(fileCfg);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
        }
        Map<String, Object> result = null;
        try {
            result = (Map<String, Object>) yaml.load(inputStream);
        } catch (Exception e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
        }
        return result;
    }
}

package com.crowdin.cli.utils.file;

import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;

public class FileReader {

    private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";

    private static final String YAML_EXTENSION = ".yaml";

    private static final String YML_EXTENSION = ".yml";

    public Map<String, Object> readCliConfig(File fileCfg) {
        if (fileCfg == null) {
            throw new NullPointerException("FileReader.readCliConfig has null args");
        }
        if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
            System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
        }

        Yaml yaml = new Yaml();
        try (InputStream inputStream = new FileInputStream(fileCfg)){
            return (Map<String, Object>) yaml.load(inputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
        } catch (Exception e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
        }
    }
}

Fix old bug - close stream after reading


package vaccination.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

package vaccination.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Add location header to be a safe giver in CORS


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

package com.github.triceo.robozonky.remote;

public enum MainIncomeType {

    EMPLOYMENT, // "zaměstnanec"
    SELF_EMPLOYMENT, // "OSVČ"
    ENTREPRENEUR // "podnikatel"

}

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

package com.github.triceo.robozonky.remote;

public enum MainIncomeType {

    EMPLOYMENT, // "zaměstnanec"
    SELF_EMPLOYMENT, // "OSVČ"
    ENTREPRENEUR, // "podnikatel"
    PENSION // "důchodce"

}

Add "PENSION" main income type

Add "PENSION" main income type

Fixes #30.


package de.christinecoenen.code.zapp.app.settings.ui;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import java.util.Objects;

import de.christinecoenen.code.zapp.R;

class ChannelSelectionHelpDialog extends DialogFragment {

	@NonNull
	@Override
	public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
		return new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
			.setTitle(R.string.activity_channel_selection_title)
			.setMessage(R.string.activity_channel_selection_help_text)
			.setPositiveButton(android.R.string.ok, null)
			.create();
	}

}

package de.christinecoenen.code.zapp.app.settings.ui;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import java.util.Objects;

import de.christinecoenen.code.zapp.R;

public class ChannelSelectionHelpDialog extends DialogFragment {

	@NonNull
	@Override
	public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
		return new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
			.setTitle(R.string.activity_channel_selection_title)
			.setMessage(R.string.activity_channel_selection_help_text)
			.setPositiveButton(android.R.string.ok, null)
			.create();
	}

}

Fix crash when getting help on channel selection


package org.col.parser;

import java.util.List;

import com.google.common.collect.Lists;
import org.junit.Test;

/**
 *
 */
public class LanguageParserTest extends ParserTestBase<String> {

  public LanguageParserTest() {
    super(LanguageParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse("deu", "de");
    assertParse("deu", "deu");
    assertParse("deu", "german");
    assertParse("deu", "deutsch");
    assertParse("deu", "GER");
    assertParse("eng", "en");

    assertUnparsable("unknown");
    assertUnparsable("zz");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("term", "deuter");
  }
}

package org.col.parser;

import java.util.List;

import com.google.common.collect.Lists;
import org.junit.Test;

/**
 *
 */
public class LanguageParserTest extends ParserTestBase<String> {

  public LanguageParserTest() {
    super(LanguageParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse("deu", "de");
    assertParse("deu", "deu");
    assertParse("deu", "german");
    assertParse("deu", "deutsch");
    assertParse("deu", "GER");
    assertParse("eng", "en");

    for (String x : new String[]{"Limburgan", "Limburger", "Limburgish", "Lim", "li"}) {
      assertParse("lim", x);
    }

    assertUnparsable("unknown");
    assertUnparsable("zz");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("term", "deuter");
  }
}

Add more lang parse tests

Add more lang parse tests


package model;

/**
 * Top-level player container.
 */
public class PlayerModel {
  public Level level = null;
  public Move move = null;

  public VariationCtrl variation = null;
  public PlayerState playerState = PlayerState.NONE;

  /**
   * Create a new player model.
   *
   * @constructor
   */
  public PlayerModel() {}
}

package model;

import controller.PlayerVariationCtrl;

/**
 * Top-level player container.
 */
public class PlayerModel {
  public Level level = null;
  public Move move = null;

  public PlayerVariationCtrl variation = null;
  public PlayerState playerState = PlayerState.NONE;

  /**
   * Create a new player model.
   *
   * @constructor
   */
  public PlayerModel() {}
}

Fix variable type in model

Fix variable type in model


package com.suse.salt.netapi.calls.modules;

import com.suse.salt.netapi.calls.LocalCall;

import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * salt.modules.state
 */
public class State {

    private State() { }

    public static LocalCall<Map<String, Object>> apply(List<String> mods) {
        return apply(mods, Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(String... mods) {
        return apply(Arrays.asList(mods), Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(List<String> mods,
            Optional<Map<String, Object>> pillar) {
        Map<String, Object> args = new LinkedHashMap();
        args.put("mods", mods);
        if (pillar.isPresent()) {
            args.put("pillar", pillar.get());
        }
        return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args),
                new TypeToken<Map<String, Object>>() { });
    }

    public static LocalCall<Object> showHighstate() {
        return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(),
                new TypeToken<Object>() { });
    }

}

package com.suse.salt.netapi.calls.modules;

import com.suse.salt.netapi.calls.LocalCall;

import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * salt.modules.state
 */
public class State {

    private State() { }

    public static LocalCall<Map<String, Object>> apply(List<String> mods) {
        return apply(mods, Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(String... mods) {
        return apply(Arrays.asList(mods), Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(List<String> mods,
            Optional<Map<String, Object>> pillar) {
        Map<String, Object> args = new LinkedHashMap<>();
        args.put("mods", mods);
        if (pillar.isPresent()) {
            args.put("pillar", pillar.get());
        }
        return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args),
                new TypeToken<Map<String, Object>>() { });
    }

    public static LocalCall<Object> showHighstate() {
        return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(),
                new TypeToken<Object>() { });
    }

}

Fix warning about type safety

Fix warning about type safety


package de.haw.rnp01.newsticker;

import de.haw.rnp01.newsticker.model.News;
import de.haw.rnp01.newsticker.model.RandomGenerator;
import de.haw.rnp01.newsticker.view.NewsView;

import java.util.ArrayList;

/**
 * Created by daniel on 21.03.2016.
 */
public class Controller {

    private ArrayList<News> news;
    private RandomGenerator randomGenerator;
    private NewsView view;

    public void showView() {

    }
}

package de.haw.rnp01.newsticker;

import de.haw.rnp01.newsticker.model.News;
import de.haw.rnp01.newsticker.model.RandomGenerator;
import de.haw.rnp01.newsticker.view.NewsView;

import java.util.ArrayList;

/**
 * Created by daniel on 21.03.2016.
 */
public class Controller {

    private ArrayList<News> news;
    private RandomGenerator randomGenerator;
    private NewsView view;

    public Controller() {
        this.news = new ArrayList<News>();
        this.randomGenerator = new RandomGenerator();
        this.view = new NewsView();
    }

    public void showView() {
        this.view.setVisible(true);
    }
}

Make view visible on creation

Make view visible on creation


package com.oldterns.vilebot.handlers.admin;

import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.LogDB;
import net.engio.mbassy.listener.Handler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by eunderhi on 18/08/15.
 */
@HandlerContainer
public class GetLog {

    private static final Pattern showLog = Pattern.compile("^!showLog$");
    private static final Pattern deleteLog = Pattern.compile("^!deleteLog$");

    @Handler
    private void getLog(ReceivePrivmsg event) {
        String text = event.getText();
        boolean showLogMatches = showLog.matcher(text).matches();
        boolean deleteLogMatches = deleteLog.matcher(text).matches();

        if (showLogMatches) {
            event.reply(LogDB.getLog());
        }
        else if(deleteLogMatches) {
            LogDB.deleteLog();
        }
    }
}

package com.oldterns.vilebot.handlers.admin;

import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.GroupDB;
import com.oldterns.vilebot.db.LogDB;
import com.oldterns.vilebot.util.Sessions;
import net.engio.mbassy.listener.Handler;

import java.util.regex.Pattern;

/**
 * Created by eunderhi on 18/08/15.
 */
@HandlerContainer
public class GetLog {

    private static final Pattern showLog = Pattern.compile("!admin showLog$");
    private static final Pattern deleteLog = Pattern.compile("!admin deleteLog$");

    @Handler
    private void getLog(ReceivePrivmsg event) {
        String text = event.getText();
        String sender = event.getSender();
        String username = Sessions.getSession(sender);

        boolean showLogMatches = showLog.matcher(text).matches();
        boolean deleteLogMatches = deleteLog.matcher(text).matches();

        if(GroupDB.isAdmin(username)) {
            if (showLogMatches) {
                event.reply(LogDB.getLog());
            } else if (deleteLogMatches) {
                LogDB.deleteLog();
            }
        }
    }
}

Make showLog and deleteLog admin commands


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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER, SERVICE;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

Add a new plugin type

feat(service): Add a new plugin type


package org.soujava.exchange.ecb;

import org.tomitribe.sabot.Config;

import javax.inject.Inject;

class SQLQuery {

    @Inject
    @Config(value = "query-rate")
    private String queryRate;

    @Inject
    @Config(value = "query-historic")
    private String queryHistoric;

    public String getQueryRate() {
        return queryRate;
    }

    public String getQueryHistoric() {
        return queryHistoric;
    }
}

package org.soujava.exchange.ecb;

import org.tomitribe.sabot.Config;

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

@ApplicationScoped
class SQLQuery {

    @Inject
    @Config(value = "query-rate")
    private String queryRate;

    @Inject
    @Config(value = "query-historic")
    private String queryHistoric;

    public String getQueryRate() {
        return queryRate;
    }

    public String getQueryHistoric() {
        return queryHistoric;
    }
}

Define scope to ECBQuery configuration

Define scope to ECBQuery configuration


package com.grayben.riskExtractor.htmlScorer.elementScorers;

/**
 * Element scorer interface. Provide an implementing class to {@link ScoringAndFlatteningVisitor}.
 * <p/>
 * This interface contains a single method that takes an {@link org.jsoup.nodes.Element} and returns a score.
 * @author beng
 *
 */
public interface ElementScorer<T> {

	/**
	 *
	 * @param input the Element to score
	 * @return the score of element
	 */
	public int score(T input);
}

package com.grayben.riskExtractor.htmlScorer.elementScorers;

import org.jsoup.nodes.Element;

/**
 * Element scorer interface. Provide an implementing class to {@link ScoringAndFlatteningVisitor}.
 * <p/>
 * This interface contains a single method that takes an {@link org.jsoup.nodes.Element} and returns a score.
 * @author beng
 *
 */
public interface ElementScorer {

	/**
	 *
	 * @param input the Element to score
	 * @return the score of element
	 */
	public int score(Element input);
}

Remove generic type, use com.jsoup.nodes.Element type


import org.junit.*;
import static org.junit.Assert.*;
import java.io.File;
import se.soy.gpg.GPG;

public class Decrypt extends SearchInHeap {
  @Test public void decrypt() {
    GPG.decrypt(new File(System.getProperty("test.resources") + "/test.asc")).localUser("0xF870C097").output(System.out, "println");
  }

  void theAssert(int found) {
      assertEquals("Secret not found!", 0, found);
  }
}

import org.junit.*;
import static org.junit.Assert.*;
import java.io.File;
import se.soy.gpg.GPG;
import java.io.PrintStream;
import java.io.OutputStream;

public class Decrypt extends SearchInHeap {
  @Test public void decrypt() {
    // FIXME Disable stdout temporarily since Gradles test output makes the
    // secret stored on the heap.
    PrintStream old_out = System.out;
    System.setOut(new PrintStream(new OutputStream() { public void write(int b) {}}));
    GPG.decrypt(new File(System.getProperty("test.resources") + "/test.asc")).localUser("0xF870C097").output(System.out, "println");
    System.setOut(old_out);
  }

  void theAssert(int found) {
      assertEquals("Secret not found!", 0, found);
  }
}

Disable the output stream on decryotion

Disable the output stream on decryotion

Since the output is put in Gradles test output buffer which is stored in
the heap and is found by SearchInHeap.


/*
 * UG Name Util for Syndicate
 */
package SyndicateHadoop.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.apache.hadoop.conf.Configuration;

/**
 *
 * @author iychoi
 */
public class UGNameUtil {

    private static String getIPAddress() throws SocketException {
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while(e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while(ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();

                if(i instanceof Inet4Address) {
                    if(i.isLoopbackAddress())
                        continue;
                    if(i.isMulticastAddress())
                        continue;
                    if(i.isSiteLocalAddress())
                        continue;

                    return i.getHostAddress();
                }
            }
        }

        return null;
    }

    public static String getUGName(String prefix) {
        String address = null;

        try {
            address = getIPAddress();
        } catch (SocketException ex) {}

        if(address == null || address.isEmpty()) {
            return null;
        } else {
            if(prefix == null)
                return address.replaceAll("\\.", "_");
            else
                return prefix + address.replaceAll("\\.", "_");
        }
    }
}

/*
 * UG Name Util for Syndicate
 */
package SyndicateHadoop.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 *
 * @author iychoi
 */
public class UGNameUtil {

    private static String ipAddress = null;
    private static boolean ipAddressChecked = false;

    private static String getIPAddress() {
        if(!ipAddressChecked) {
            try {
                Enumeration e = NetworkInterface.getNetworkInterfaces();
                while (e.hasMoreElements()) {
                    NetworkInterface n = (NetworkInterface) e.nextElement();
                    Enumeration ee = n.getInetAddresses();
                    while (ee.hasMoreElements()) {
                        InetAddress i = (InetAddress) ee.nextElement();

                        if (i instanceof Inet4Address) {
                            if (i.isLoopbackAddress()) {
                                continue;
                            }
                            if (i.isMulticastAddress()) {
                                continue;
                            }
                            if (i.isSiteLocalAddress()) {
                                continue;
                            }

                            // get first ipaddress
                            ipAddress = i.getHostAddress();
                            ipAddressChecked = true;
                            return ipAddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                ipAddress = null;
                ipAddressChecked = true;
                return null;
            }
        }

        return ipAddress;
    }

    public static String getUGName(String prefix) {
        String address = null;
        address = getIPAddress();

        if(address == null || address.isEmpty()) {
            return null;
        } else {
            if(prefix == null)
                return address.replaceAll("\\.", "_");
            else
                return prefix + address.replaceAll("\\.", "_");
        }
    }
}

Store local IP address for next call

Store local IP address for next call


package uk.co.czcz.speedreader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) == null)
        {
            // Initial run of this activity, so lets display a fragment
            getSupportFragmentManager().beginTransaction().add(new SpeedReadingFragment(), SpeedReadingFragment.TAG).commit();
        }
    }
}

package uk.co.czcz.speedreader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) == null)
        {
            displayInitialSpeedReadingFragment();
        }
    }

    private void displayInitialSpeedReadingFragment() {
        getSupportFragmentManager().beginTransaction().add(new SpeedReadingFragment(), SpeedReadingFragment.TAG).commit();
    }
}

Refactor to make it obvious what's going on.


package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;

public final class SwitchCompatUtils {
  private SwitchCompatUtils() {}

  /**
   * Set toggle state without any animations.
   */
  public static void setCheckedWithoutAnimation(final @NonNull SwitchCompat switchCompat, final boolean checked) {
    switchCompat.setChecked(checked);
    switchCompat.clearAnimation();
  }
}

package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;
import android.view.View;

public final class SwitchCompatUtils {
  private SwitchCompatUtils() {}

  /**
   * Set toggle state without any animations.
   */
  public static void setCheckedWithoutAnimation(final @NonNull SwitchCompat switchCompat, final boolean checked) {
    switchCompat.setVisibility(View.INVISIBLE);
    switchCompat.setChecked(checked);
    switchCompat.setVisibility(View.VISIBLE);
  }
}

Return to previous method of toggling animation state

Inspecting `setChecked`, this is the only reasonable way to do this.
`clearAnimation` leaves the UI in a bad state.