package com.alexstyl.specialdates.events;

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

import com.alexstyl.specialdates.R;

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

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

    private static final Map<Integer, EventType> map;

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

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

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

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

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

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

package com.alexstyl.specialdates.events;

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

import com.alexstyl.specialdates.R;

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

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

    private static final Map<Integer, EventType> map;

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

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

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

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

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

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

Move fields to top and give explicit name to id


package jkind;

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

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

package jkind;

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

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

Change order of solvers to reflect preference


package hello;

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

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

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

	@Autowired
	private MockMvc mvc;

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

}

package hello;

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

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

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

	@Autowired
	private MockMvc mvc;

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

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

}

Test view content in greetings test.

Test view content in greetings test.


package org.wikimedia.wikipedia.data;

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

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

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

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

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

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

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

package org.wikimedia.wikipedia.data;

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

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

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

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

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

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

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

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

Implement deleteAll as a variant of delete

Will need to add tests for this entire thing later.

Change-Id: Ib40fe1d4f126923ed1788417f144d0d45fd24e61


package com.grunka.random.fortuna;

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

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

import static org.junit.Assert.assertEquals;

public class PrefetchingSupplierTest {
    private ExecutorService executorService;

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

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

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

package com.grunka.random.fortuna;

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

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

import static org.junit.Assert.assertEquals;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


package io.github.uetoyo.patterns.specification;

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

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

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

	private final ArrayList<Specification<T>> specifications;

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

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

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

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

}

package io.github.uetoyo.patterns.specification;

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

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

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

	private final ArrayList<Specification<T>> specifications;

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

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

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

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

}

Use explicit scoping instead of the default package private level


package de.retest.recheck.ui.descriptors;

import java.awt.Rectangle;

public class AttributeUtil {

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

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

package de.retest.recheck.ui.descriptors;

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

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

public class AttributeUtil {

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

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

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

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

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

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

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

		if ( identifyingAttributesDifference != null ) {

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

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

}

Add methods for actual outline

Add methods for actual outline


package org.ingrahamrobotics.robottables;

public class TimeConstants {

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

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

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

package org.ingrahamrobotics.robottables;

public class TimeConstants {

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

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

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

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


package software.committed.rejux.utils;

import java.util.List;

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

public final class MiddlewareUtils {

  private MiddlewareUtils() {
    // Singleton
  }

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

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

    return dispatcher;
  }

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

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

    return dispatcher;
  }

}

package software.committed.rejux.utils;

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

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

public final class MiddlewareUtils {

  private MiddlewareUtils() {
    // Singleton
  }

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

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

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

    return dispatcher;
  }

}

Reimplement middleware utils as common code


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

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

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

public class MarvelPassThroughACL {
    private static ACL acl;

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

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

}

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

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

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

public class MarvelPassthroughACL {
    private static ACL acl;

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

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

}

Fix typo preventing build to proceed

Fix typo preventing build to proceed


package org.spoofax.jsglr2.inputstack;

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

public class LayoutSensitiveInputStack extends InputStack {

    private static final int TAB_SIZE = 8;

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

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

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

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

        previousPosition = currentPosition();

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

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

}

package org.spoofax.jsglr2.inputstack;

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

public class LayoutSensitiveInputStack extends InputStack {

    private static final int TAB_SIZE = 8;

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

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

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

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

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

        previousPosition = currentPosition();

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

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

}

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


package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiErrorType;

import java.util.UUID;

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

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

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

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

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

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

package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiErrorType;

import java.util.UUID;

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

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

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

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

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

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

Fix decision unsupported operation on execute


package info.u_team.u_team_core.util.registry;

import java.util.function.Consumer;

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

public class BusRegistry {

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

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

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

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Consumer;

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

public class BusRegistry {

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

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

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

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

}

Add util method for the bus enum

Add util method for the bus enum


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

public class VersionInfo {

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

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

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

}

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

public class VersionInfo {

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

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

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

}

Set version to 0.5.0 final.

Set version to 0.5.0 final.


/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2017 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
@Version("3.10.0")
package com.adobe.acs.commons.mcp.util;

import aQute.bnd.annotation.Version;

/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2017 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
@Version("3.11.0")
package com.adobe.acs.commons.mcp.util;

import aQute.bnd.annotation.Version;

Increment MCP Util package version

Increment MCP Util package version


import java.util.concurrent.locks.*;

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

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

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

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

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

import java.util.concurrent.locks.*;

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

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

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

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

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

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

Call wait() on a Condition.

Call wait() on a Condition.

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@3997 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package de.tse.simplerestfacade;

import java.io.IOException;

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

import de.tse.simplerestfacade.marshalling.Unmarshaller;

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

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

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

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

        validateStatusCode(response);

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

        return unmarshaller.unmarshall(content, returnType);
    }

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

package de.tse.simplerestfacade;

import java.io.IOException;

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

import de.tse.simplerestfacade.marshalling.Unmarshaller;

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

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

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

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

        validateStatusCode(response);

        Object result = null;

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

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

        return result;
    }

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

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

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


package org.gbif.registry;

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

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

package org.gbif.registry;

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

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

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

Add condition on EmailSender bean creation


package com.navigation.reactnative;

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

import androidx.coordinatorlayout.widget.CoordinatorLayout;

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

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

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

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

package com.navigation.reactnative;

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

import androidx.coordinatorlayout.widget.CoordinatorLayout;

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

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

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

Set behavior prop before added to window

Otherwise there's a noticeable flicker before bottom sheet appears


package info.schleichardt.training.java8.lecture2;

public class P2_FunctionalInterfacesFirstClassMembers {

    //show also Automatic-Resource-Management
}

package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

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

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

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

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

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

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

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

Add description how closures can be first class members.


package com.github.ayltai.newspaper.data;

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

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

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

    private static boolean isInitialized;

    private final Context context;

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

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

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

            DataModule.isInitialized = true;
        }

        return Realm.getDefaultInstance();
    }
}

package com.github.ayltai.newspaper.data;

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

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

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

    private static boolean isInitialized;

    private final Context context;

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

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

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

            DataModule.isInitialized = true;
        }

        return Realm.getDefaultInstance();
    }
}

Fix app crash due to Realm database migration


package org.jimmutable.platform_test;

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

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

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

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

package org.jimmutable.platform_test;

import static org.junit.Assert.*;

import org.junit.Test;

public class AppTest extends App
{

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

}

Update to platform_test test class

Update to platform_test test class


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

package net.kazyx.wirespider.sampleapp;

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

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

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

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

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

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

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

package net.kazyx.wirespider.sampleapp;

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

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

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

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

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

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

Set debug level DEBUG in sample application


package info.u_team.u_team_core.container;

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

public class FluidSlot {

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

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

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

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

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

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public boolean isEnabled() {
		return true;
	}
}

package info.u_team.u_team_core.container;

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

public class FluidSlot {

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

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

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

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

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

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

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public boolean isEnabled() {
		return true;
	}
}

Add getSlotCapacity method in fluid slot


package com.pqbyte.coherence;

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

  public static boolean isDebug() {
    return DEBUG;
  }

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

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

package com.pqbyte.coherence;

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

  public static boolean isDebug() {
    return DEBUG;
  }

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

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

Set debug field to false as default

Set debug field to false as default


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

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

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%=packageName%>.service.mapper;

import java.util.List;

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

public interface EntityMapper <D, E> {

    E toEntity(D dto);

    D toDto(E entity);

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

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

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

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

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%=packageName%>.service.mapper;

import java.util.List;

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

public interface EntityMapper <DTO, ENTITY> {

    ENTITY toEntity(DTO dto);

    DTO toDto(ENTITY entity);

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

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

Revert "Rename generic names to single letter"

This reverts commit d7d5eff52385fbe224d36666223948ada966db35.


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

import org.xwiki.stability.Unstable;

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

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

import org.xwiki.stability.Unstable;

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

Make easier to disable deprecated log

XCOMMONS-1824: Make easier to disable deprecated log


package com.nullprogram.maze;

import java.awt.Dimension;

import javax.swing.JApplet;

public class MazeApplet extends JApplet {

    private static final long serialVersionUID = 7742407602430714892L;

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

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

package com.nullprogram.maze;

import java.awt.Dimension;

import javax.swing.JApplet;

public class MazeApplet extends JApplet {

    private static final long serialVersionUID = 7742407602430714892L;

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

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

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

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

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

Use start/stop in the applet.

Use start/stop in the applet.


package problems;

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

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

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

package problems;

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

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

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

Add Container with Most Water

Add Container with Most Water


package de.blogspot.wrongtracks.example;

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

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

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

package de.blogspot.wrongtracks.example;

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

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

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

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

Add method for starting the process after deploying it


package com.ezardlabs.lostsector.objects;

import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;

public abstract class ShieldedEntity extends Entity {
	protected final int maxShield;
	protected int shield;
	private long shieldRegenTime;
	private long nextShieldRegen;

	public ShieldedEntity(int maxHealth, int maxShield, long shieldRegenTime) {
		super(maxHealth);
		this.maxShield = maxShield;
		shield = maxShield;
		this.shieldRegenTime = shieldRegenTime;
	}

	public int getShield() {
		return shield;
	}

	public void addShield(int shield) {
		this.shield += shield;
		if (this.shield > maxShield) {
			this.shield = maxShield;
		}
	}

	@Override
	public final void update() {
		if (shield < maxShield && System.currentTimeMillis() > nextShieldRegen) {
			shield++;
			nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
		}
	}

	@Override
	public void applyDamage(float damage, DamageType damageType, Vector2 attackOrigin) {
		if (damage == 0) return;
		if (shield > 0) {
			shield--;
			super.applyDamage(0, damageType, attackOrigin);
		} else {
			super.applyDamage(damage, damageType, attackOrigin);
		}
		nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
	}
}

package com.ezardlabs.lostsector.objects;

import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;

public abstract class ShieldedEntity extends Entity {
	protected final int maxShield;
	protected int shield;
	private long shieldRegenTime;
	private long nextShieldRegen;

	public ShieldedEntity(int maxHealth, int maxShield, long shieldRegenTime) {
		super(maxHealth);
		this.maxShield = maxShield;
		shield = maxShield;
		this.shieldRegenTime = shieldRegenTime;
	}

	public int getShield() {
		return shield;
	}

	public void addShield(int shield) {
		this.shield += shield;
		if (this.shield > maxShield) {
			this.shield = maxShield;
		}
	}

	@Override
	public void update() {
		if (shield < maxShield && System.currentTimeMillis() > nextShieldRegen) {
			shield++;
			nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
		}
	}

	@Override
	public void applyDamage(float damage, DamageType damageType, Vector2 attackOrigin) {
		if (damage == 0) return;
		if (shield > 0) {
			shield--;
			super.applyDamage(0, damageType, attackOrigin);
		} else {
			super.applyDamage(damage, damageType, attackOrigin);
		}
		nextShieldRegen = System.currentTimeMillis() + shieldRegenTime;
	}
}

Allow update to be overridden

Allow update to be overridden


package org.meteogroup.griblibrary.grib2.model;

import org.meteogroup.griblibrary.grib2.model.gdstemplates.GDSTemplate;
import org.meteogroup.griblibrary.util.LatLon;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@EqualsAndHashCode
public class Grib2GDS {

	private int length;

    private int numberOfVerticalsCoordinateParams;
    private int locationOfVerticalCoordinateParams;
    private int locationListPer;
    private int representationType;
    private int numberOfPoints;

    private double north;
    private double south;
    private double lat1;
    private double lat2;

    private double Dj;

    private LatLon[] latLons;

    private int ni;
    private int[] nis;
    private int nj;

    // GRIB2 variables

    private int gridDefinitionTemplateNumber;

    private GDSTemplate gdsTemplate;
}

package org.meteogroup.griblibrary.grib2.model;

import org.meteogroup.griblibrary.grib2.model.gdstemplates.GDSTemplate;
import org.meteogroup.griblibrary.util.LatLon;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@EqualsAndHashCode
public class Grib2GDS {

	private int length;

    private int numberOfVerticalsCoordinateParams;
    private int locationOfVerticalCoordinateParams;
    private int locationListPer;
    private int representationType;
    private int numberOfPoints;

    private double north;
    private double south;
    private double lat1;
    private double lat2;

    private double Dj;

//    private LatLon[] latLons;

    private int ni;
    private int[] nis;
    private int nj;

    // GRIB2 variables

    private int gridDefinitionTemplateNumber;

    private GDSTemplate gdsTemplate;
}

Comment out unused field "latLons".

Comment out unused field "latLons".


package com.grayben.riskExtractor.headingMarker;

import com.grayben.riskExtractor.headingMarker.elector.ElectedTextList;

import java.util.List;

public class MarkedText {

	ElectedTextList text;

    public MarkedText(ElectedTextList text) {
        this.text = text;
    }

    public List<String> subSelections() {
        return null;
    }

}

package com.grayben.riskExtractor.headingMarker;

import com.grayben.riskExtractor.headingMarker.elector.ElectedTextList;

import java.util.List;

public class MarkedText {

	ElectedTextList text;

    public MarkedText(ElectedTextList text) {
        super();
        if(text == null){
            throw new IllegalArgumentException("The argument passed was null");
        }
        this.text = text;
    }

    public List<String> subSelections() {
        return null;
    }

}

Make test pass by throwing IllegalArgumentException


package com.paritytrading.parity.ticker;

import com.paritytrading.parity.book.MarketListener;

abstract class MarketDataListener implements MarketListener {

    static final double PRICE_FACTOR = 100.0;

    private long second;

    private long timestamp;

    public void timestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public long timestampMillis() {
        return timestamp / 1_000_000;
    }

}

package com.paritytrading.parity.ticker;

import com.paritytrading.parity.book.MarketListener;

abstract class MarketDataListener implements MarketListener {

    static final double PRICE_FACTOR = 100.0;

    private long timestamp;

    public void timestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public long timestampMillis() {
        return timestamp / 1_000_000;
    }

}

Clean up code in stock ticker

Clean up code in stock ticker


package de.japkit.examples.freebuilder;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

import javax.lang.model.element.Modifier;

import de.japkit.metaannotations.Clazz;
import de.japkit.metaannotations.TemplateCall;
import de.japkit.metaannotations.Trigger;

@Trigger(template=FreeBuilderTemplate.class)
@Target(ElementType.TYPE)
public @interface FreeBuilder {
	boolean shadow() default false;
}

package de.japkit.examples.freebuilder;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

import de.japkit.metaannotations.Trigger;

@Trigger(template = FreeBuilderTemplate.class)
@Target(ElementType.TYPE)
public @interface FreeBuilder {
	boolean shadow() default false;
}

Support for Clazz annotation at template class instead of trigger annotation


package jp.tomorrowkey.appengine.regularexpression.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class IndexController extends Controller {

    @Override
    protected Navigation run() throws Exception {
        return forward("index.jsp");
    }

}

package jp.tomorrowkey.appengine.regularexpression.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class IndexController extends Controller {

    @Override
    protected Navigation run() throws Exception {
        requestScope("multiline", true);
        return forward("index.jsp");
    }

}

Change default value of multiline

Change default value of multiline


package colector.co.com.collector.listeners;

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

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

public interface OnAddPhotoListener {

    void onAddPhotoClicked(PhotoItemViewContainer container);
}

package colector.co.com.collector.listeners;

import android.widget.LinearLayout;

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

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

public interface OnAddPhotoListener {

    void onAddPhotoClicked(PhotoItemViewContainer container);

    void onPhotoClicked(LinearLayout container, PhotoItemView view);
}

:star: Add method to notify when a photo has been clicked


/**
 * Created by Alex on 8/28/2015.
 */
public class SummonerCollector extends AbstractCollector {

    public SummonerCollector(String apiKey) {
        super(apiKey);
    }

    public void collectChallengerLadder() {
        //TODO
    }
}

import constant.Region;
import database.models.Summoner;
import dto.League.League;
import dto.League.LeagueEntry;
import main.java.riotapi.RiotApiException;

/**
 * Created by Alex on 8/28/2015.
 */
public class SummonerCollector extends AbstractCollector {

    public SummonerCollector(String apiKey) {
        super(apiKey);
    }

    public void collectChallengerLadder() throws RiotApiException {
        League league = this.api.getChallengerLeagues();
        for (Region r : Region.values())
            for (LeagueEntry entry : league.getEntries()) {
                    new Summoner().insertObject(new Summoner(
                            Integer.parseInt(entry.getPlayerOrTeamId()),
                            api.getRegion(),
                            entry.getPlayerOrTeamName(),
                            entry.getLeaguePoints(),
                            entry.getDivision()));
                }
    }

    /**
     * Method to update info for summoners, filtering out ones that already exist
     * TODO
     */
    public void updateChallengeLadderInfo() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

Add method for collecting Summoner information from Challenger ladder


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

package co.cask.cdap.api.service;

import co.cask.cdap.internal.service.DefaultServiceSpecification;

/**
 * An abstract implementation of {@link Service}. Users may extend this to write their own
 * custom service.
 */
public abstract class AbstractService implements Service {
  protected ServiceConfigurer configurer;

  @Override
  public final ServiceSpecification configure(ServiceConfigurer serviceConfigurer) {
    this.configurer = serviceConfigurer;
    configure();

    return new DefaultServiceSpecification(getClass().getSimpleName(), configurer.getName(),
                                           configurer.getDescription(), configurer.getProperties(),
                                           configurer.getWorkers(), configurer.getHandlers());
  }

  /**
   * Implement this method and use a {@link ServiceConfigurer} to add a request handler
   * and workers.
   */
  protected abstract void configure();

}

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

package co.cask.cdap.api.service;

import co.cask.cdap.internal.service.DefaultServiceSpecification;

/**
 * An abstract implementation of {@link Service}. Users may extend this to write a {@link Service}.
 *
 * The default no-op constructor must be implemented.
 */
public abstract class AbstractService implements Service {
  protected ServiceConfigurer configurer;

  @Override
  public final ServiceSpecification configure(ServiceConfigurer serviceConfigurer) {
    this.configurer = serviceConfigurer;
    configure();

    return new DefaultServiceSpecification(getClass().getSimpleName(), configurer.getName(),
                                           configurer.getDescription(), configurer.getProperties(),
                                           configurer.getWorkers(), configurer.getHandlers());
  }

  /**
   * Implement this method and use a {@link ServiceConfigurer} to add a request handler
   * and workers.
   */
  protected abstract void configure();

}

Add note about default constructor

Add note about default constructor


package uk.sacko.m2m.sitra.trace.engine;

import java.util.List;

import uk.sacko.m2m.sitra.engine.ContextAware;
import uk.sacko.m2m.sitra.engine.Transformer;
import uk.sacko.m2m.sitra.trace.Invocation;

public interface TraceableTransformer extends Transformer, ContextAware {
	public List<Invocation<?, ?>> getTransformationTrace();
}

package uk.sacko.m2m.sitra.trace.engine;

import java.util.List;

import uk.sacko.m2m.sitra.engine.ContextAware;
import uk.sacko.m2m.sitra.engine.Transformer;
import uk.sacko.m2m.sitra.trace.Invocation;

public interface TraceableTransformer extends Transformer, ContextAware {
	public List<? extends Invocation<?, ?>> getTransformationTrace();
}

Allow any Invocation type for all engines.


package beaform.events;

import java.text.SimpleDateFormat;
import java.util.Date;

import beaform.utilities.SystemTime;

public class FormulaCreatedEvent implements Event {
	private static final String EVENT_TYPE = "FormulaCreated";
	private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SS";
	private final String name;
	private final long timestamp;

	public FormulaCreatedEvent(String name) {
		this.name = name;
		this.timestamp = SystemTime.getAsLong();
	}

	@Override
	public String toEventString() {
		final SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
		final String formattedTimeStamp = dateFormat.format(new Date(this.timestamp));
		return "[" + formattedTimeStamp + "] " + EVENT_TYPE + " " + this.name;
	}

}

package beaform.events;

import java.text.SimpleDateFormat;
import java.util.Date;

import beaform.utilities.SystemTime;

public class FormulaCreatedEvent implements Event {
	private static final String EVENT_TYPE = "FormulaCreated";
	private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
	private final String name;
	private final long timestamp;

	public FormulaCreatedEvent(String name) {
		this.name = name;
		this.timestamp = SystemTime.getAsLong();
	}

	@Override
	public String toEventString() {
		final SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
		final String formattedTimeStamp = dateFormat.format(new Date(this.timestamp));
		return "[" + formattedTimeStamp + "] " + EVENT_TYPE + " " + this.name;
	}

}

Fix date format for events

Fix date format for events


package com.biekerwebdesign.openexoplanetcatalogue;

import android.app.Fragment;

/**
 * Created by Bieker on 12/6/13.
 */
public class StarFragment extends Fragment {
}

package com.biekerwebdesign.openexoplanetcatalogue;

import android.app.Fragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.biekerwebdesign.beans.*;
import com.biekerwebdesign.beans.System;
import com.biekerwebdesign.xml.XMLPullParserStar;
import com.biekerwebdesign.xml.XMLPullParserSystem;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bieker on 12/6/13.
 */
public class StarFragment extends ListFragment {

    private ListView listView;
    private XMLPullParserStar parser;
    private List<Star> stars;
    private ArrayAdapter<Star> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.star_list_fragment, container, false);
        Log.i("Fragment", "OnCreateView(): View Created");
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        listView = (ListView) getView().findViewById(android.R.id.list); //Should be the list in star_list_fragment
        stars = new ArrayList<Star>();

        List<Star> stars = null;
        try {
            XMLPullParserStar parser = new XMLPullParserStar();
            stars = parser.parse(getActivity().getAssets().open("11 Com.xml"));
            Log.i("Parser:", "Assets Opened");
            ArrayAdapter<Star> adapter =
                    new ArrayAdapter<Star>(this.getActivity(), R.layout.list_item, stars);
            listView.setAdapter(adapter);
            Log.i("Adapter:", "ArrayAdapter Set");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException x) {
            x.printStackTrace();
        }
    }

    public void onListItemClicked(ListView l, View v, int position, long id) {
        //TODO Call to create Planet Fragment when Item clicked
        super.onListItemClick(l, v, position, id);
    }
}

Change to ListFragment and start work on AsyncTask for XML parsing


package io.quarkus.arc.runtime;

import java.lang.annotation.Annotation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Singleton;

import org.jboss.logging.Logger;

import io.quarkus.arc.log.LoggerName;

@Singleton
public class LoggerProducer {

    private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();

    @Dependent
    @Produces
    Logger getSimpleLogger(InjectionPoint injectionPoint) {
        return loggers.computeIfAbsent(injectionPoint.getMember().getDeclaringClass().getName(), Logger::getLogger);
    }

    @LoggerName("")
    @Dependent
    @Produces
    Logger getLoggerWithCustomName(InjectionPoint injectionPoint) {
        String name = null;
        for (Annotation qualifier : injectionPoint.getQualifiers()) {
            if (qualifier.annotationType().equals(LoggerName.class)) {
                name = ((LoggerName) qualifier).value();
            }
        }
        if (name == null || name.isEmpty()) {
            throw new IllegalStateException("Unable to derive the logger name at " + injectionPoint);
        }
        return loggers.computeIfAbsent(name, Logger::getLogger);
    }

    @PreDestroy
    void destroy() {
        loggers.clear();
    }

}

package io.quarkus.arc.runtime;

import java.lang.annotation.Annotation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Singleton;

import org.jboss.logging.Logger;

import io.quarkus.arc.DefaultBean;
import io.quarkus.arc.log.LoggerName;

@Singleton
public class LoggerProducer {

    private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();

    @Dependent
    @Produces
    @DefaultBean
    Logger getSimpleLogger(InjectionPoint injectionPoint) {
        return loggers.computeIfAbsent(injectionPoint.getMember().getDeclaringClass().getName(), Logger::getLogger);
    }

    @LoggerName("")
    @Dependent
    @Produces
    @DefaultBean
    Logger getLoggerWithCustomName(InjectionPoint injectionPoint) {
        String name = null;
        for (Annotation qualifier : injectionPoint.getQualifiers()) {
            if (qualifier.annotationType().equals(LoggerName.class)) {
                name = ((LoggerName) qualifier).value();
            }
        }
        if (name == null || name.isEmpty()) {
            throw new IllegalStateException("Unable to derive the logger name at " + injectionPoint);
        }
        return loggers.computeIfAbsent(name, Logger::getLogger);
    }

    @PreDestroy
    void destroy() {
        loggers.clear();
    }

}

Set produced Logger as DefaultBean

Set produced Logger as DefaultBean


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

package org.springframework.web.client;

import java.io.IOException;

/**
 * Exception thrown when an I/O error occurs.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
public class ResourceAccessException extends RestClientException {

	private static final long serialVersionUID = -8513182514355844870L;

	/**
	 * Construct a new {@code HttpIOException} with the given message.
	 * @param msg the message
	 */
	public ResourceAccessException(String msg) {
		super(msg);
	}

	/**
	 * Construct a new {@code HttpIOException} with the given message and {@link IOException}.
	 * @param msg the message
	 * @param ex the {@code IOException}
	 */
	public ResourceAccessException(String msg, IOException ex) {
		super(msg, ex);
	}

}

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

package org.springframework.web.client;

import java.io.IOException;

/**
 * Exception thrown when an I/O error occurs.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
public class ResourceAccessException extends RestClientException {

	private static final long serialVersionUID = -8513182514355844870L;

	/**
	 * Construct a new {@code ResourceAccessException} with the given message.
	 * @param msg the message
	 */
	public ResourceAccessException(String msg) {
		super(msg);
	}

	/**
	 * Construct a new {@code ResourceAccessException} with the given message and {@link IOException}.
	 * @param msg the message
	 * @param ex the {@code IOException}
	 */
	public ResourceAccessException(String msg, IOException ex) {
		super(msg, ex);
	}

}

Fix class name in javadoc

Fix class name in javadoc

Closes gh-1530


package com.pengrad.telegrambot.request;

import com.pengrad.telegrambot.response.BaseResponse;

/**
 * Stas Parshin
 * 07 May 2016
 */
public class AnswerCallbackQuery extends BaseRequest<AnswerCallbackQuery, BaseResponse> {

    public AnswerCallbackQuery(String callbackQueryId) {
        super(BaseResponse.class);
        add("callback_query_id", callbackQueryId);
    }

    public AnswerCallbackQuery text(String text) {
        return add("text", text);
    }

    public AnswerCallbackQuery showAlert(boolean showAlert) {
        return add("show_alert", showAlert);
    }

}

package com.pengrad.telegrambot.request;

import com.pengrad.telegrambot.response.BaseResponse;

/**
 * Stas Parshin
 * 07 May 2016
 */
public class AnswerCallbackQuery extends BaseRequest<AnswerCallbackQuery, BaseResponse> {

    public AnswerCallbackQuery(String callbackQueryId) {
        super(BaseResponse.class);
        add("callback_query_id", callbackQueryId);
    }

    public AnswerCallbackQuery text(String text) {
        return add("text", text);
    }

    public AnswerCallbackQuery showAlert(boolean showAlert) {
        return add("show_alert", showAlert);
    }

    public AnswerCallbackQuery url(String url) {
        return add("url", url);
    }
}

Use the new url parameter in answerCallbackQuery to create buttons that open your bot with user-specific parameters


package com.siirush.localwiki.search;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Provider;

import org.apache.lucene.store.Directory;

public class LuceneSearchEngineImpl implements SearchEngine {
	private Directory index;
	private final Provider<LuceneFileCrawler> crawlerProvider;
	private final Provider<LuceneSearcher> searchProvider;

	@Inject
	public LuceneSearchEngineImpl(Provider<LuceneFileCrawler> crawlerProvider, Provider<LuceneSearcher> searchProvider) {
		this.crawlerProvider = crawlerProvider;
		this.searchProvider = searchProvider;
	}

	public void index() {
		index = crawlerProvider.get().crawl();
	}

	public List<String> search(String query) {
		return searchProvider.get().search(index,query);
	}
}

package com.siirush.localwiki.search;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Provider;

import org.apache.lucene.store.Directory;

public class LuceneSearchEngineImpl implements SearchEngine {
	private Directory index;
	private final Provider<LuceneFileCrawler> crawlerProvider;
	private final LuceneSearcher searcher;

	@Inject
	public LuceneSearchEngineImpl(Provider<LuceneFileCrawler> crawlerProvider, LuceneSearcher searcher) {
		this.crawlerProvider = crawlerProvider;
		this.searcher = searcher;
	}

	public void index() {
		index = crawlerProvider.get().crawl();
	}

	public List<String> search(String query) {
		return searcher.search(index,query);
	}
}

Change the scope of the injection for searchers.


package ecse321.fall2014.group3.bomberman.physics.ai;

import com.flowpowered.math.vector.Vector2f;

import ecse321.fall2014.group3.bomberman.physics.entity.mob.Mob;
import ecse321.fall2014.group3.bomberman.world.Map;

/**
 *
 */
public class DumbAI extends AI {
    public DumbAI(Mob target) {
        super(target);
    }

    @Override
    public Vector2f nextPosition(long dt, Map map) {
        if((target.getTileCollisionList()).isEmpty())
            return (target.getPosition() + target.getVelocity()*dt);
        else {
            Random random = new Random();
            switch(random.nextInt(3)) {
            case 0:
                return (target.getPosition() + target.getVelocity()*dt).negate();
                break;
            case 1:
                return (target.getPosition() + target.getVelocity()*dt).getPerpendicular();
                break;
            case 2:
                return (target.getPosition() + target.getVelocity()*dt).getPerpendicular().negate();
                break;
            }
        }
    }
}

package ecse321.fall2014.group3.bomberman.physics.ai;

import com.flowpowered.math.vector.Vector2f;

import ecse321.fall2014.group3.bomberman.physics.entity.mob.Mob;
import ecse321.fall2014.group3.bomberman.world.Map;

/**
 *
 */
public class DumbAI extends AI {
    public DumbAI(Mob target) {
        super(target);
    }

    @Override
    public Vector2f nextPosition(long dt, Map map) {
        // TODO implement me, for now just return the same position
        return target.getPosition();
    }
}

Remove broken AI code: doesn't compile

Remove broken AI code: doesn't compile


package com.mangofactory.swagger.paths;

import javax.servlet.ServletContext;

public class  RelativeSwaggerPathProvider extends SwaggerPathProvider {
    public static final String ROOT = "/";
  private final ServletContext servletContext;

  public RelativeSwaggerPathProvider(ServletContext servletContext) {
    super();
    this.servletContext = servletContext;
  }

  @Override
    protected String applicationPath() {
        return servletContext.getContextPath();
    }

    @Override
    protected String getDocumentationPath() {
        return ROOT;
    }
}

package com.mangofactory.swagger.paths;

import javax.servlet.ServletContext;

import static com.google.common.base.Strings.isNullOrEmpty;

public class  RelativeSwaggerPathProvider extends SwaggerPathProvider {
    public static final String ROOT = "/";
  private final ServletContext servletContext;

  public RelativeSwaggerPathProvider(ServletContext servletContext) {
    super();
    this.servletContext = servletContext;
  }

  @Override
    protected String applicationPath() {
        return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
    }

    @Override
    protected String getDocumentationPath() {
        return ROOT;
    }
}

Fix for when the context path is at the root the 'try this' doesnt work


package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.graphics.Rect;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    private final int margin;

    public MarginItemDecoration(@Px final int margin) {
        this.margin = margin;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.bottom = margin;
        outRect.left = margin;
        outRect.right = margin;

        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = margin;
        }
    }
}

package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.graphics.Rect;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    private final int margin;

    public MarginItemDecoration(@Px final int margin) {
        this.margin = margin;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        final int position = params.getViewLayoutPosition();
        final int marginTop = position == 0 ? margin : 0;
        outRect.set(margin, marginTop, margin, margin);
    }
}

Simplify and optimize getItemOffsets() logic


package com.google.cloud.pubsub.sql.providers;

import com.google.auto.service.AutoService;
import com.google.cloud.pubsub.sql.Rows;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;

@AutoService({StandardSourceProvider.class, StandardSinkProvider.class})
public class PubsubLiteProvider implements StandardSourceProvider, StandardSinkProvider {

  @Override
  public StandardSink getSink() {
    return new StandardSqlSink() {
      @Override
      public Schema nativeSchema() {
        return Rows.STANDARD_SCHEMA;
      }

      @Override
      public String query() {
        return "SELECT * FROM PCOLLECTION";
      }
    };
  }

  private static final Schema READ_SCHEMA = Schema.builder()
      .addByteArrayField(Rows.PAYLOAD_FIELD)
      .addByteArrayField(Rows.MESSAGE_KEY_FIELD)
      .addDateTimeField("publish_timestamp")
      .addField(Rows.EVENT_TIMESTAMP_FIELD, FieldType.DATETIME.withNullable(true))
      .addArrayField(Rows.ATTRIBUTES_FIELD, Schema.FieldType.row(Rows.ATTRIBUTES_ENTRY_SCHEMA))
      .build();

  @Override
  public StandardSource getSource() {
    return new StandardSqlSource() {
      @Override
      public String query() {
        return "SELECT payload, message_key, attributes, IFNULL(event_timestamp, publish_timestamp) FROM PCOLLECTION";
      }

      @Override
      public Schema nativeSchema() {
        return READ_SCHEMA;
      }
    }; // Pub/Sub lite uses the standard schema.
  }

  @Override
  public String identifier() {
    return "pubsublite";
  }
}

package com.google.cloud.pubsub.sql.providers;

import com.google.auto.service.AutoService;
import com.google.cloud.pubsub.sql.Rows;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;

@AutoService({StandardSourceProvider.class, StandardSinkProvider.class})
public class PubsubLiteProvider implements StandardSourceProvider, StandardSinkProvider {

  @Override
  public StandardSink getSink() {
    return new StandardSqlSink() {
      @Override
      public Schema nativeSchema() {
        return Rows.STANDARD_SCHEMA;
      }

      @Override
      public String query() {
        return "SELECT * FROM PCOLLECTION";
      }
    };
  }

  private static final Schema READ_SCHEMA = Schema.builder()
      .addByteArrayField(Rows.PAYLOAD_FIELD)
      .addByteArrayField(Rows.MESSAGE_KEY_FIELD)
      .addDateTimeField("publish_timestamp")
      .addField(Rows.EVENT_TIMESTAMP_FIELD, FieldType.DATETIME.withNullable(true))
      .addArrayField(Rows.ATTRIBUTES_FIELD, Schema.FieldType.row(Rows.ATTRIBUTES_ENTRY_SCHEMA))
      .build();

  @Override
  public StandardSource getSource() {
    return new StandardSqlSource() {
      @Override
      public String query() {
        return "SELECT payload, message_key, attributes, IFNULL(event_timestamp, publish_timestamp) FROM PCOLLECTION";
      }

      @Override
      public Schema nativeSchema() {
        return READ_SCHEMA;
      }
    };
  }

  @Override
  public String identifier() {
    return "pubsublite";
  }
}

Fix following testing, add instructions for uploading


package net.bytebuddy.test.utility;

import com.sun.jna.Platform;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;

public class UnixRule implements MethodRule {

    private final boolean enabled;

    public UnixRule() {
        this.enabled = !Platform.isWindows() && !Platform.isWindowsCE();
    }

    public Statement apply(Statement base, FrameworkMethod method, Object target) {
        return enabled || method.getAnnotation(Enforce.class) == null
                ? base
                : new NoOpStatement();
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Enforce {

    }

    private static class NoOpStatement extends Statement {

        public void evaluate() {
            Logger.getLogger("net.bytebuddy").warning("Ignoring Unix sockets on this machine");
        }
    }
}

package net.bytebuddy.test.utility;

import com.sun.jna.Platform;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;

public class UnixRule implements MethodRule {

    private final boolean enabled;

    public UnixRule() {
        this.enabled = !Platform.isWindows() && !Platform.isWindowsCE() && System.getProperty("java.vm.vendor").contains("OpenJ9");
    }

    public Statement apply(Statement base, FrameworkMethod method, Object target) {
        return enabled || method.getAnnotation(Enforce.class) == null
                ? base
                : new NoOpStatement();
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Enforce {

    }

    private static class NoOpStatement extends Statement {

        public void evaluate() {
            Logger.getLogger("net.bytebuddy").warning("Ignoring Unix sockets on this machine");
        }
    }
}

Exclude emulated attachment on OpenJ9.

Exclude emulated attachment on OpenJ9.