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


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".


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


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


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);
}

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


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


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


/*
 * 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


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


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.


package org.hamcrest.text;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
import static org.hamcrest.text.IsEmptyString.emptyString;

import org.hamcrest.AbstractMatcherTest;
import org.hamcrest.Matcher;

public class IsEmptyStringTest extends AbstractMatcherTest {

  @Override
  protected Matcher<?> createMatcher() {
    return emptyOrNullString();
  }

  public void testEmptyOrNullIsNull() {
    assertThat(null, emptyOrNullString());
  }

  public void testEmptyIsNotNull() {
    assertThat(null, not(emptyString()));
  }

  public void testMatchesEmptyString() {
    assertMatches("empty string", emptyString(), "");
    assertMatches("empty string", emptyOrNullString(), "");
  }

  public void testDoesNotMatchNonEmptyString() {
    assertDoesNotMatch("non empty string", emptyString(), "a");
  }

  public void testHasAReadableDescription() {
    assertDescription("an empty string", emptyString());
    assertDescription("(null or an empty string)", emptyOrNullString());
  }
}

package org.hamcrest.text;

import static org.hamcrest.AbstractMatcherTest.assertDescription;
import static org.hamcrest.AbstractMatcherTest.assertDoesNotMatch;
import static org.hamcrest.AbstractMatcherTest.assertMatches;
import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription;
import static org.hamcrest.AbstractMatcherTest.assertNullSafe;
import static org.hamcrest.AbstractMatcherTest.assertUnknownTypeSafe;
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
import static org.hamcrest.text.IsEmptyString.emptyString;

import org.hamcrest.Matcher;
import org.junit.Test;

public final class IsEmptyStringTest {

    @Test public void
    copesWithNullsAndUnknownTypes() {
        Matcher<String> matcher = emptyOrNullString();

        assertNullSafe(matcher);
        assertUnknownTypeSafe(matcher);
    }

    @Test public void
    matchesNullAppropriately() {
        assertMatches("didn't match", emptyOrNullString(), null);
        assertDoesNotMatch("matched unexpectedly", emptyString(), null);
    }

    @Test public void
    matchesEmptyString() {
        assertMatches("didn't match", emptyOrNullString(), "");
        assertMatches("didn't match", emptyString(), "");
    }

    @Test public void
    doesNotmatchFilledString() {
        assertDoesNotMatch("matched unexpectedly", emptyOrNullString(), "a");
        assertDoesNotMatch("matched unexpectedly", emptyString(), "a");
    }

    @Test public void
    describesItself() {
        assertDescription("an empty string", emptyString());
        assertDescription("(null or an empty string)", emptyOrNullString());
    }

    @Test public void
    describesAMismatch() {
        assertMismatchDescription("was \"a\"", emptyString(), "a");
        assertMismatchDescription("was \"a\"", emptyOrNullString(), "a");
    }
}

Convert test to JUnit4 (and add mismatch description tests) in preparation for enhancement.


package io.dropwizard.logging;

import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;

import java.util.regex.Pattern;

import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;

/**
 * A {@link RootCauseFirstThrowableProxyConverter} that prefixes stack traces with {@code !}.
 */
public class PrefixedRootCauseFirstThrowableProxyConverter
        extends RootCauseFirstThrowableProxyConverter {

    private static final String CAUSING = PREFIX + "Causing:";
    private static final Pattern CAUSING_PATTERN = Pattern.compile(
            "^" + Pattern.quote(PrefixedThrowableProxyConverter.PREFIX) + "Wrapped by:",
            Pattern.MULTILINE);

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        final String prefixed = PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX);
        return CAUSING_PATTERN.matcher(prefixed).replaceAll(CAUSING);
    }
}

package io.dropwizard.logging;

import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;

import java.util.regex.Pattern;

import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;

/**
 * A {@link RootCauseFirstThrowableProxyConverter} that prefixes stack traces with {@code !}.
 */
public class PrefixedRootCauseFirstThrowableProxyConverter
        extends RootCauseFirstThrowableProxyConverter {

    private static final String CAUSING = PREFIX + "Causing:";
    private static final Pattern CAUSING_PATTERN = Pattern.compile("^" + Pattern.quote(PREFIX) + "Wrapped by:", Pattern.MULTILINE);

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        final String prefixed = PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX);
        return CAUSING_PATTERN.matcher(prefixed).replaceAll(CAUSING);
    }
}

Remove a needless static reference


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

package com.linecorp.bot.model.manageaudience;

import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;

public enum AudienceGroupJobFailedType {
    /**
     * Internal server error.
     */
    INTERNAL_ERROR,
    @JsonEnumDefaultValue
    UNKNOWN
}

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

package com.linecorp.bot.model.manageaudience;

import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;

public enum AudienceGroupJobFailedType {
    /**
     * Internal server error.
     */
    INTERNAL_ERROR,
    /**
     * Audience is insufficient.
     */
    AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT,
    @JsonEnumDefaultValue
    UNKNOWN
}

Add Audience group job failed type: AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT


package com.osdu.model.dto;

import com.google.cloud.firestore.annotation.ServerTimestamp;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SrnToRecordDto {

  String recordId;
  String srn;
  @ServerTimestamp
  Date created;

}

package com.osdu.model.dto;

import com.google.cloud.firestore.annotation.ServerTimestamp;
import java.util.Date;
import lombok.Data;

@Data
public class SrnToRecordDto {

  String recordId;
  String srn;
  @ServerTimestamp
  Date created;

}

Fix RuntimeException for Firestore entity.


package com.danielflower.apprunner.runners;

import com.danielflower.apprunner.Config;
import org.apache.commons.exec.CommandLine;
import org.apache.maven.shared.invoker.InvocationRequest;

import javax.annotation.Nullable;
import java.util.Map;

public interface HomeProvider extends CommandLineProvider {
    HomeProvider default_java_home = new HomeProvider() {
        public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; }

        public CommandLine commandLine(@Nullable Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); }
    };

    InvocationRequest mungeMavenInvocationRequest(InvocationRequest request);
}

package com.danielflower.apprunner.runners;

import com.danielflower.apprunner.Config;
import org.apache.commons.exec.CommandLine;
import org.apache.maven.shared.invoker.InvocationRequest;

import javax.annotation.Nullable;
import java.util.Map;

public interface HomeProvider extends CommandLineProvider {
    HomeProvider default_java_home = new HomeProvider() {
        public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; }

        public CommandLine commandLine(Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); }
    };

    InvocationRequest mungeMavenInvocationRequest(InvocationRequest request);
}

Remove Nullable annotation to avoid build warning


package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
	BREEDING,
	BUILD_IRONGOLEM,
	BUILD_SNOWMAN,
	BUILD_WITHER,
	/**
	 * Deprecated as of 1.14, no longer used.
	 */
	CHUNK_GEN,
	/**
	 * Spawned by plugins
	 */
	CUSTOM,
	/**
	 * Missing spawn reason
	 */
	DEFAULT,
	/**
	 * The kind of egg you throw
	 */
	EGG,
	JOCKEY,
	LIGHTNING,
	NATURAL,
	REINFORCEMENTS,
	SHOULDER_ENTITY,
	SLIME_SPLIT,
	SPAWNER,
	SPAWNER_EGG,
	VILLAGE_DEFENSE,
	VILLAGE_INVASION,
	NETHER_PORTAL,
	DISPENSE_EGG,
	INFECTION,
	CURED,
	OCELOT_BABY,
	SILVERFISH_BLOCK,
	MOUNT,
	TRAP,
	ENDER_PEARL,
	DROWNED,
}

package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
	BREEDING,
	BUILD_IRONGOLEM,
	BUILD_SNOWMAN,
	BUILD_WITHER,
	/**
	 * Deprecated as of 1.14, no longer used.
	 */
	CHUNK_GEN,
	/**
	 * Spawned by plugins
	 */
	CUSTOM,
	/**
	 * Missing spawn reason
	 */
	DEFAULT,
	/**
	 * The kind of egg you throw
	 */
	EGG,
	JOCKEY,
	LIGHTNING,
	NATURAL,
	REINFORCEMENTS,
	SHOULDER_ENTITY,
	SLIME_SPLIT,
	SPAWNER,
	SPAWNER_EGG,
	VILLAGE_DEFENSE,
	VILLAGE_INVASION,
	NETHER_PORTAL,
	DISPENSE_EGG,
	INFECTION,
	CURED,
	OCELOT_BABY,
	SILVERFISH_BLOCK,
	MOUNT,
	TRAP,
	ENDER_PEARL,
	DROWNED,
	SHEARED
}

Add missing SHEARED spawn reason


package by.triumgroup.recourse.document.model.provider.impl;

import by.triumgroup.recourse.document.model.provider.ContentProvider;
import by.triumgroup.recourse.entity.dto.Student;
import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark;

import java.util.*;
import java.util.stream.Collectors;

public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> {
    @Override
    public String createTitle(Student mainEntity) {
        return mainEntity.getName() + " " + mainEntity.getSurname();
    }

    @Override
    public String createFilename(Student user) {
        return String.format("%s_%s_profile", user.getName(), user.getSurname());
    }

    @Override
    public Map<String, String> createSubtitles(Student mainEntity) {
        return new HashMap<String, String>(){{
            put("Total average mark", mainEntity.getTotalAverageMark().toString());
        }};
    }

    @Override
    public List<String> getHeaders() {
        return Arrays.asList("Title", "Average mark");
    }

    @Override
    public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) {
        return "Courses";
    }

    @Override
    public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) {
        return courses.stream()
                .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString()))
                .collect(Collectors.toList());
    }
}

package by.triumgroup.recourse.document.model.provider.impl;

import by.triumgroup.recourse.document.model.provider.ContentProvider;
import by.triumgroup.recourse.entity.dto.Student;
import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark;

import java.util.*;
import java.util.stream.Collectors;

public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> {
    @Override
    public String createTitle(Student mainEntity) {
        return mainEntity.getFullName();
    }

    @Override
    public String createFilename(Student user) {
        return String.format("%s_profile", user.getFullName());
    }

    @Override
    public Map<String, String> createSubtitles(Student mainEntity) {
        return new HashMap<String, String>(){{
            put("Total average mark", mainEntity.getTotalAverageMark().toString());
        }};
    }

    @Override
    public List<String> getHeaders() {
        return Arrays.asList("Title", "Average mark");
    }

    @Override
    public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) {
        return "Courses";
    }

    @Override
    public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) {
        return courses.stream()
                .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString()))
                .collect(Collectors.toList());
    }
}

Replace name, surname concatenation with getFullName


package org.liveontologies.protege.justification.proof.service;

import java.util.Set;

import org.liveontologies.puli.InferenceJustifier;
import org.liveontologies.puli.Proof;
import org.semanticweb.owlapi.model.OWLAxiom;

public interface JustificationCompleteProof<C> extends Proof<C>, InferenceJustifier<C, Set<? extends OWLAxiom>> {

	C getGoal();
}

package org.liveontologies.protege.justification.proof.service;

/*-
 * #%L
 * Protege Proof Justification
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2016 - 2017 Live Ontologies Project
 * %%
 * 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%
 */

import java.util.Set;

import org.liveontologies.puli.InferenceJustifier;
import org.liveontologies.puli.Proof;
import org.semanticweb.owlapi.model.OWLAxiom;

public interface JustificationCompleteProof<C> extends Proof<C>, InferenceJustifier<C, Set<? extends OWLAxiom>> {

	C getGoal();
}

Update file header with license information


package org.torquebox.stomp.component;

import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;

public class DirectStompletComponent implements Stomplet {

    public DirectStompletComponent(XAStompletComponent component) {
        this.component = component;
    }

    @Override
    public void initialize(StompletConfig config) throws StompException {
        this.component._callRubyMethod( "configure", config );
    }

    @Override
    public void destroy() throws StompException {
        this.component._callRubyMethod( "destroy" );
    }

    @Override
    public void onMessage(StompMessage message) throws StompException {
        this.component._callRubyMethod( "on_message", message );
    }

    @Override
    public void onSubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethod( "on_subscribe", subscriber );
    }

    @Override
    public void onUnsubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethod( "on_unsubscribe", subscriber );
    }

    private XAStompletComponent component;

}

package org.torquebox.stomp.component;

import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;

public class DirectStompletComponent implements Stomplet {

    public DirectStompletComponent(XAStompletComponent component) {
        this.component = component;
    }

    @Override
    public void initialize(StompletConfig config) throws StompException {
        this.component._callRubyMethodIfDefined( "configure", config );
    }

    @Override
    public void destroy() throws StompException {
        this.component._callRubyMethodIfDefined( "destroy" );
    }

    @Override
    public void onMessage(StompMessage message) throws StompException {
        this.component._callRubyMethodIfDefined( "on_message", message );
    }

    @Override
    public void onSubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethodIfDefined( "on_subscribe", subscriber );
    }

    @Override
    public void onUnsubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethodIfDefined( "on_unsubscribe", subscriber );
    }

    private XAStompletComponent component;

}

Call the methods only if they exist.


/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

@ValueAnnotation("Branch One")
package given.reflect.root.branch1.foo;

import given.reflect.annotation.ValueAnnotation;

/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * This package is annotated.
 * One of its {@linkplain given.reflect.root.branch1.foo.sub1 sub-packages} is also annotated
 * with the same type, but a different value.
 */
@ValueAnnotation("Branch One")
package given.reflect.root.branch1.foo;

import given.reflect.annotation.ValueAnnotation;

Improve documentation of the test env.


package utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import models.Project;
import models.User;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CacheStore
 */
public class CacheStore {
    public static Map<String, User> sessionMap = new ConcurrentHashMap<>();
    public static Map<String, Project> projectMap = new HashMap<>();
    public static final int MAXIMUM_CACHED_MARKDOWN_ENTRY = 10000;

    /**
     * Introduced to using LRU Cache. It depends on google Guava.
     * <p>
     * Size expectation: 500 char-per-item * 3 byte * 10000 rendered-entry % 70 gzipped = ~10Mb
     */
    public static LoadingCache<Integer, byte[]> renderedMarkdown = CacheBuilder.newBuilder()
            .maximumSize(MAXIMUM_CACHED_MARKDOWN_ENTRY)
            .build(
                    new CacheLoader<Integer, byte[]>() {
                        public Map<Integer, byte[]> renderedMarkdownMap = new ConcurrentHashMap<>();

                        public byte[] load(@Nonnull Integer key) {
                            return renderedMarkdownMap.get(key);
                        }
                    });
}

package utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import models.Project;
import models.User;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CacheStore
 */
public class CacheStore {
    public static Map<String, User> sessionMap = new ConcurrentHashMap<>();
    public static Map<String, Project> projectMap = new HashMap<>();
    public static final int MAXIMUM_CACHED_MARKDOWN_ENTRY = 10000;

    /**
     * Introduced to using LRU Cache. It depends on google Guava.
     * <p>
     * Size expectation: 500 char-per-item * 3 byte * 10000 rendered-entry % 70 gzipped = ~10Mb
     */
    public static LoadingCache<Integer, byte[]> renderedMarkdown = CacheBuilder.newBuilder()
            .maximumSize(MAXIMUM_CACHED_MARKDOWN_ENTRY)
            .build(
                    new CacheLoader<Integer, byte[]>() {
                        public byte[] load(@Nonnull Integer key) {
                            return null;
                        }
                    });
}

Remove redundant codes from cache loader


package com.groupon.seleniumgridextras.tasks;

import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.sun.net.httpserver.HttpServer;

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

import java.net.InetSocketAddress;

import static org.junit.Assert.assertEquals;

public class StopGridTest {

  private StopGrid task;
  private HttpServer server;
  private final int port = 9999;

  @Before
  public void setUp() throws Exception {
    task = new StopGrid();
    server = HttpServer.create(new InetSocketAddress(port), 0);
    server.setExecutor(null);
    server.start();
  }

  @After
  public void tearDown() throws Exception {
    server.stop(0);
  }

  @Test
  public void testGetWindowsCommand() throws Exception {
    assertEquals(
        "",task.getWindowsCommand("5555"));
  }

  @Test
  public void testGetLinuxCommand() throws Exception {
    String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid();
    assertEquals(expected, task.getLinuxCommand(port));

    final String portToNeverBeFound = "4444444444444444444444444444444";
    assertEquals("", task.getLinuxCommand(portToNeverBeFound));
  }

}

package com.groupon.seleniumgridextras.tasks;

import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.sun.net.httpserver.HttpServer;

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

import java.net.InetSocketAddress;

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

public class StopGridTest {

  private StopGrid task;
  private HttpServer server;
  private final int port = 9999;

  @Before
  public void setUp() throws Exception {
    task = new StopGrid();
    server = HttpServer.create(new InetSocketAddress(port), 0);
    server.setExecutor(null);
    server.start();
  }

  @After
  public void tearDown() throws Exception {
    server.stop(0);
  }

  @Test
  public void testGetWindowsCommand() throws Exception {
    assertTrue(task.getWindowsCommand("5555").contains("taskkill -F -IM "));
  }

  @Test
  public void testGetLinuxCommand() throws Exception {
    String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid();
    assertEquals(expected, task.getLinuxCommand(port));

    final String portToNeverBeFound = "4444444444444444444444444444444";
    assertEquals("", task.getLinuxCommand(portToNeverBeFound));
  }

}

Improve the stop grid command test


/*
 * Copyright (c) 2014 aleon GmbH.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Markus Rathgeb - initial API and implementation and/or initial documentation
 */
package eu.aleon.aleoncean.packet.radio.userdata;

import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;

/**
 *
 * @author Markus Rathgeb <maggu2810@gmail.com>
 */
public class UserData4BS extends UserData {

    public static final int DATA_LENGTH = 4;

    public UserData4BS() {
        super(DATA_LENGTH);
    }

    public UserData4BS(final byte[] data) {
        super(data);
        assert data.length == DATA_LENGTH;
    }

    public boolean isTeachIn() {
        return isTeachIn(getUserData());
    }

    public static boolean isTeachIn(final byte[] userData) {
        return getDataBit(userData, 0, 3) == 0;
    }

    @Override
    public RadioPacket4BS generateRadioPacket() {
        final RadioPacket4BS packet = new RadioPacket4BS();
        packet.setUserDataRaw(getUserData());
        return packet;
    }

}

/*
 * Copyright (c) 2014 aleon GmbH.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Markus Rathgeb - initial API and implementation and/or initial documentation
 */
package eu.aleon.aleoncean.packet.radio.userdata;

import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;

/**
 *
 * @author Markus Rathgeb <maggu2810@gmail.com>
 */
public class UserData4BS extends UserData {

    public static final int DATA_LENGTH = 4;

    private static final int TEACH_IN_DB = 0;
    private static final int TEACH_IN_BIT = 3;

    public static boolean isTeachIn(final byte[] userData) {
        return getDataBit(userData, TEACH_IN_DB, TEACH_IN_BIT) == 0;
    }

    public UserData4BS() {
        super(DATA_LENGTH);
    }

    public UserData4BS(final byte[] data) {
        super(data);
        assert data.length == DATA_LENGTH;
    }

    public boolean isTeachIn() {
        return isTeachIn(getUserData());
    }

    public void setTeachIn(final boolean teachIn) {
        setDataBit(TEACH_IN_DB, TEACH_IN_BIT, teachIn ? 0 : 1);
    }

    @Override
    public RadioPacket4BS generateRadioPacket() {
        final RadioPacket4BS packet = new RadioPacket4BS();
        packet.setUserDataRaw(getUserData());
        return packet;
    }

}

Add function to modify teach-in bit


/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertFalse("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

Revert "fail test again to check email notification"


package com.ecchilon.sadpanda.api;

import java.util.List;

import com.ecchilon.sadpanda.overview.GalleryEntry;
import com.google.inject.Inject;
import lombok.Getter;
import rx.Observable;

public class GalleryScroller {

	private final GalleryClient galleryClient;

	@Getter
	private boolean isLoading = false;
	@Getter
	private boolean hasMoreItems = true;

	@Inject
	GalleryScroller(GalleryClient galleryClient) {
		this.galleryClient = galleryClient;
	}

	public Observable<List<GalleryEntry>> loadPage(String base, int page) {
		isLoading = true;
		return galleryClient.getGalleryIndex(base, page).doOnNext(galleryEntries -> {
			isLoading = false;
			if (galleryEntries.size() < DataLoader.GALLERIES_PER_PAGE) {
				hasMoreItems = false;
			}
		});
	}
}

package com.ecchilon.sadpanda.api;

import java.util.List;

import com.ecchilon.sadpanda.overview.GalleryEntry;
import com.google.inject.Inject;
import lombok.Getter;
import rx.Observable;

public class GalleryScroller {

	private final GalleryClient galleryClient;

	@Getter
	private boolean isLoading = false;
	@Getter
	private boolean hasMoreItems = true;

	@Inject
	GalleryScroller(GalleryClient galleryClient) {
		this.galleryClient = galleryClient;
	}

	public Observable<List<GalleryEntry>> loadPage(String base, int page) {
		isLoading = true;
		return galleryClient.getGalleryIndex(base, page).doOnNext(galleryEntries -> {
			isLoading = false;
			if (galleryEntries.isEmpty()) {
				hasMoreItems = false;
			}
		});
	}
}

Fix early stop of gallery


package network.thunder.core.communication;

import network.thunder.core.communication.objects.subobjects.AuthenticationObject;

public class Node {
	private byte[] pubkey;
	private boolean isAuth;
	private boolean sentAuth;
	private boolean authFinished;
	private boolean isReady;
	private boolean hasOpenChannel;

	public boolean processAuthentication (AuthenticationObject authentication) {
		//TODO: Check authentication based on the supplied pubkey

		return true;
	}

	public AuthenticationObject getAuthenticationObject () {
		//TODO: Produce a proper authentication object..

		return new AuthenticationObject();
	}

	public boolean hasSentAuth () {
		return sentAuth;
	}

	public boolean isAuth () {
		return isAuth;
	}

	public boolean allowsAuth () {
		return !isAuth;
	}

	public void finishAuth () {
		authFinished = true;
	}

	public boolean isAuthFinished () {
		return authFinished;
	}
}

package network.thunder.core.communication;

import network.thunder.core.communication.objects.subobjects.AuthenticationObject;

public class Node {
	private byte[] pubkey;
	private boolean isAuth;
	private boolean sentAuth;
	private boolean authFinished;
	private boolean isReady;
	private boolean hasOpenChannel;

	public boolean processAuthentication (AuthenticationObject authentication) {
		//TODO: Check authentication based on the supplied pubkey

		isAuth = true;
		if (sentAuth) {
			authFinished = true;
		}
		return true;
	}

	public AuthenticationObject getAuthenticationObject () {
		//TODO: Produce a proper authentication object..

		sentAuth = true;
		return new AuthenticationObject();
	}

	public boolean hasSentAuth () {
		return sentAuth;
	}

	public boolean isAuth () {
		return isAuth;
	}

	public boolean allowsAuth () {
		return !isAuth;
	}

	public void finishAuth () {
		authFinished = true;
	}

	public boolean isAuthFinished () {
		return authFinished;
	}
}

Fix node to set sentAuth whenever the object was generated


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import com.mojang.datafixers.DataFixUtils;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
	}

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

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(null));
	}

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

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

Fix the tile entity type (just push out null. We don't need this here)


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

public class TestFileUtil {
    protected static final String DATA_PATH = "./test/crosslanguagefiles";

    public static void writeToFile(String path, byte[] data) throws IOException {
        try (FileOutputStream stream = new FileOutputStream(path)) {
            stream.write(data);
        }
    }

    /**
     * Write `data` to `path` using UTF-8 as binary encoding format.
     */
    public static void writeToFile(String path, String data) throws IOException {
        writeToFile(path, data.getBytes(Charset.forName("UTF-8")));
    }

    /**
     * Returns the path to use for data files.
     *
     * @param filename The name of the file to include in the path.
     * @return The data file path.
     */
    public static String getPath(String filename) {
        return DATA_PATH + "/" + filename;
    }

    public static byte[] readFile(String path) throws IOException {
        try (FileInputStream stream = new FileInputStream(path)) {
            byte[] data = new byte[stream.available()];
            int read = stream.read(data);
            if (read != data.length) {
                throw new IOException(String.format("Truncated read (expected %d bytes, read %d)", data.length, read));
            }
            return data;
        }
    }

}

// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TestFileUtil {
    protected static final String DATA_PATH = "./test/crosslanguagefiles";

    public static void writeToFile(String path, byte[] data) throws IOException {
        try (FileOutputStream stream = new FileOutputStream(path)) {
            stream.write(data);
        }
    }

    /**
     * Write `data` to `path` using UTF-8 as binary encoding format.
     */
    public static void writeToFile(String path, String data) throws IOException {
        writeToFile(path, data.getBytes(Charset.forName("UTF-8")));
    }

    /**
     * Returns the path to use for data files.
     *
     * @param filename The name of the file to include in the path.
     * @return The data file path.
     */
    public static String getPath(String filename) {
        return DATA_PATH + "/" + filename;
    }

    public static byte[] readFile(String path) throws IOException {
        return Files.readAllBytes(Paths.get(path));
    }
}

Fix loading of file so it loads full file every time.


/*
 * Copyright 2014 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.gradle.testfixtures.internal;

import org.gradle.internal.nativeintegration.services.NativeServices;

import java.io.File;

public class NativeServicesTestFixture {
    static NativeServices nativeServices;
    static boolean initialized;

    public static synchronized void initialize() {
        if (!initialized) {
            File nativeDir = getNativeServicesDir();
            NativeServices.initialize(nativeDir);
            initialized = true;
        }
    }

    public static synchronized NativeServices getInstance() {
        if (nativeServices == null) {
            initialize();
            nativeServices = NativeServices.getInstance();
        }
        return nativeServices;
    }

    public static File getNativeServicesDir() {
        return new File("build/native-libs");
    }
}

/*
 * Copyright 2014 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.gradle.testfixtures.internal;

import org.gradle.internal.nativeintegration.services.NativeServices;

import java.io.File;

public class NativeServicesTestFixture {
    static NativeServices nativeServices;
    static boolean initialized;

    public static synchronized void initialize() {
        if (!initialized) {
            System.setProperty("org.gradle.native", "true");
            File nativeDir = getNativeServicesDir();
            NativeServices.initialize(nativeDir);
            initialized = true;
        }
    }

    public static synchronized NativeServices getInstance() {
        if (nativeServices == null) {
            initialize();
            nativeServices = NativeServices.getInstance();
        }
        return nativeServices;
    }

    public static File getNativeServicesDir() {
        return new File("build/native-libs");
    }
}

Fix tests depending on native services


/*******************************************************************************
 * Copyright (c) 2005, 2006 Subclipse project and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Subclipse project committers - initial API and implementation
 ******************************************************************************/
package org.tigris.subversion.subclipse.core;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;

/**
 * Preference Initializer.
 * Called at startup by Eclipse to initialize any default preferences.
 *
 * @author markphip
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer {

    public PreferenceInitializer() {
        super();
    }

    public void initializeDefaultPreferences() {
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_RECURSIVE_STATUS_UPDATE, true);
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_SHOW_OUT_OF_DATE_FOLDERS, false);
    }

}

/*******************************************************************************
 * Copyright (c) 2005, 2006 Subclipse project and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Subclipse project committers - initial API and implementation
 ******************************************************************************/
package org.tigris.subversion.subclipse.core;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;

/**
 * Preference Initializer.
 * Called at startup by Eclipse to initialize any default preferences.
 *
 * @author markphip
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer {

    public PreferenceInitializer() {
        super();
    }

    public void initializeDefaultPreferences() {
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_RECURSIVE_STATUS_UPDATE, true);
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_SHOW_OUT_OF_DATE_FOLDERS, true);
    }

}

Make Show Out of Date folders preference on by default. Now that the performance problems are fixed, it should be on since it resolves a lot of user problems.


package net.omniscimus.fireworks.commands;

import java.io.UnsupportedEncodingException;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import net.omniscimus.fireworks.ShowHandler;
import net.omniscimus.fireworks.commands.exceptions.WrongArgumentsNumberException;

/**
 * This command stops all currently running fireworks shows.
 *
 * @author Omniscimus
 */
public class StopallCommand extends FireworksCommand {

    private final ShowHandler showHandler;

    public StopallCommand(ShowHandler showHandler) {
	this.showHandler = showHandler;
    }

    @Override
    public void run(CommandSender sender, String[] args)
	    throws WrongArgumentsNumberException, UnsupportedEncodingException {

	if (args.length == 0) {
	    showHandler.stopAllShows();
	    sender.sendMessage(ChatColor.GOLD + "All " + showHandler.getNumberOfRunningShows() + " fireworks shows have stopped.");
	} else {
	    throw new WrongArgumentsNumberException();
	}

    }

}

package net.omniscimus.fireworks.commands;

import java.io.UnsupportedEncodingException;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import net.omniscimus.fireworks.ShowHandler;
import net.omniscimus.fireworks.commands.exceptions.WrongArgumentsNumberException;

/**
 * This command stops all currently running fireworks shows.
 *
 * @author Omniscimus
 */
public class StopallCommand extends FireworksCommand {

    private final ShowHandler showHandler;

    public StopallCommand(ShowHandler showHandler) {
	this.showHandler = showHandler;
    }

    @Override
    public void run(CommandSender sender, String[] args)
	    throws WrongArgumentsNumberException, UnsupportedEncodingException {

	if (args.length == 0) {
            int number = showHandler.getNumberOfRunningShows();
	    showHandler.stopAllShows();
	    sender.sendMessage(ChatColor.GOLD + "All " + number + " fireworks shows have stopped.");
	} else {
	    throw new WrongArgumentsNumberException();
	}

    }

}

Fix wrong number of stopped shows in stopall cmd


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

package com.google.firebase.codelab.friendlychat;

import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    // Add instrumentation test here
}

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

package com.google.firebase.codelab.friendlychat;

import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    // Add instrumentation test here
    @Test
    public void verifySignUpButtonDisplayed() {
        onView(ViewMatchers.withId(R.id.sign_in_button)).check(matches(isDisplayed()));
    }
}

Configure Firebase Test Lab Espresso test for MainActivity


package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.BaseCheckTestCase;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;

import java.io.File;
public class ReturnCountCheckTest extends BaseCheckTestCase
{
    public void testDefault() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        final String[] expected = {
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }
}

package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.BaseCheckTestCase;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;

import java.io.File;
public class ReturnCountCheckTest extends BaseCheckTestCase
{
    public void testDefault() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        final String[] expected = {
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }

    public void testFormat() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        checkConfig.addAttribute("format", "^$");
        final String[] expected = {
            "5:5: Return count is 7 (max allowed is 2).",
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }
}

Test for format property of ReturnCount check


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

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

import java.util.List;

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

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

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

    String thumbnailUrl();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

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

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

import java.util.List;

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

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

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

    String thumbnailUrl();

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

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add 'type' field to tab enumeration JSON protocol


package org.graphwalker.core.machine;

import org.graphwalker.core.condition.VertexCoverage;
import org.graphwalker.core.generator.ShortestAllPaths;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Edge;
import org.graphwalker.core.model.Model;
import org.graphwalker.core.model.Vertex;
import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.core.Is.is;

/**
 * @author Nils Olsson
 */
public class AccessModelTest {

    @Test
    public void read() {
        ExecutionContext context = createContext();
        Assert.assertThat((Double)context.getAttribute("x"), is(1.0));
    }

    @Test
    public void write() {
        ExecutionContext context = createContext();
        context.setAttribute("y", 2);
        Assert.assertThat((Integer)context.getAttribute("y"), is(2));
    }

    private ExecutionContext createContext() {
        Model model = new Model();
        model.addEdge(new Edge()
                .setSourceVertex(new Vertex())
                .setTargetVertex(new Vertex()));
        ExecutionContext context = new TestExecutionContext(model, new ShortestAllPaths(new VertexCoverage(100)));
        context.execute(new Action("x = 1;"));
        return context;
    }
}

package org.graphwalker.core.machine;

import org.graphwalker.core.condition.VertexCoverage;
import org.graphwalker.core.generator.ShortestAllPaths;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Edge;
import org.graphwalker.core.model.Model;
import org.graphwalker.core.model.Vertex;
import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.core.Is.is;

/**
 * @author Nils Olsson
 */
public class AccessModelTest {

    @Test
    public void read() {
        ExecutionContext context = createContext();
        Assert.assertThat(round(context.getAttribute("x")), is(1));
    }

    private int round(Object value) {
        if (value instanceof Double) {
            return (int) Math.round((Double) value);
        } else {
            return (Integer) value;
        }
    }

    @Test
    public void write() {
        ExecutionContext context = createContext();
        context.setAttribute("y", 2);
        Assert.assertThat((Integer)context.getAttribute("y"), is(2));
    }

    private ExecutionContext createContext() {
        Model model = new Model();
        model.addEdge(new Edge()
                .setSourceVertex(new Vertex())
                .setTargetVertex(new Vertex()));
        ExecutionContext context = new TestExecutionContext(model, new ShortestAllPaths(new VertexCoverage(100)));
        context.execute(new Action("x = 1;"));
        return context;
    }
}

Fix test issue with different jdk (javascript engines)


package algorithms;

import java.util.Arrays;

public class MaxPairwiseProduct {
	static long getMaxPairwiseProduct(Integer[] numbers) {
		if (numbers.length == 1) {
			return 0;
		}
		Arrays.sort(numbers, (x, y) -> x - y);
		int lastIndex = numbers.length - 1;
		long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
		return bigResult;
	}

	public static void main(String[] args) {
		System.out.println(
				"Type number to calculate the maximum pairwise product. "
						+ "The first number is a total count of numbers.");
		FastScanner scanner = new FastScanner(System.in);
		int numberOfNumbers = scanner.popNextInt();
		if (numberOfNumbers > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
		}
		Integer[] numbers = new Integer[numberOfNumbers];
		for (int i = 0; i < numberOfNumbers; i++) {
			numbers[i] = scanner.popNextInt();
		}
		System.out.println(getMaxPairwiseProduct(numbers));
	}
}

package algorithms;

public class MaxPairwiseProduct {
	static long getMaxPairwiseProduct(Integer[] numbers) {
		if (numbers.length == 1) {
			return 0;
		}
		Integer maxIndex1 = null;
		Integer maxIndex2 = null;
		for (int i = 0; i < numbers.length; ++i) {
			if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
				maxIndex2 = maxIndex1;
				maxIndex1 = i;
			} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
				maxIndex2 = i;
			}
		}
		return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
	}

	public static void main(String[] args) {
		System.out.println(
				"Type number to calculate the maximum pairwise product. "
						+ "The first number is a total count of numbers.");
		FastScanner scanner = new FastScanner(System.in);
		int numberOfNumbers = scanner.popNextInt();
		if (numberOfNumbers > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
		}
		Integer[] numbers = new Integer[numberOfNumbers];
		for (int i = 0; i < numberOfNumbers; i++) {
			numbers[i] = scanner.popNextInt();
		}
		System.out.println(getMaxPairwiseProduct(numbers));
	}
}

Improve efficiency to constant O(n)


package com.strohwitwer.awesomevalidation.validator;

import android.app.Activity;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utils.ValidationCallback;

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

public abstract class Validator {

    protected ArrayList<ValidationHolder> mValidationHolderList;

    public Validator() {
        mValidationHolderList = new ArrayList<ValidationHolder>();
    }

    public void set(EditText editText, String regex, String errMsg) {
        Pattern pattern = Pattern.compile(regex);
        ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg);
        mValidationHolderList.add(validationHolder);
    }

    public void set(Activity activity, int viewId, String regex, int errMsgId) {
        EditText editText = (EditText) activity.findViewById(viewId);
        String errMsg = activity.getResources().getString(errMsgId);
        set(editText, regex, errMsg);
    }

    protected boolean checkFields(ValidationCallback callback) {
        boolean result = true;
        for (ValidationHolder validationHolder : mValidationHolderList) {
            Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText());
            if (!matcher.matches()) {
                callback.execute(validationHolder, matcher);
                result = false;
            }
        }
        return result;
    }

    public abstract boolean trigger();

    public abstract void halt();

}

package com.strohwitwer.awesomevalidation.validator;

import android.app.Activity;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utils.ValidationCallback;

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

public abstract class Validator {

    protected ArrayList<ValidationHolder> mValidationHolderList;

    public Validator() {
        mValidationHolderList = new ArrayList<ValidationHolder>();
    }

    public void set(EditText editText, String regex, String errMsg) {
        Pattern pattern = Pattern.compile(regex);
        ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg);
        mValidationHolderList.add(validationHolder);
    }

    public void set(Activity activity, int viewId, String regex, int errMsgId) {
        EditText editText = (EditText) activity.findViewById(viewId);
        String errMsg = activity.getResources().getString(errMsgId);
        set(editText, regex, errMsg);
    }

    protected boolean checkFields(ValidationCallback callback) {
        boolean result = true;
        boolean hasFailed = false;
        for (ValidationHolder validationHolder : mValidationHolderList) {
            Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText());
            if (!matcher.matches()) {
                callback.execute(validationHolder, matcher);
                if (!hasFailed) {
                    EditText editText = validationHolder.getEditText();
                    editText.requestFocus();
                    editText.setSelection(editText.getText().length());
                    hasFailed = true;
                }
                result = false;
            }
        }
        return result;
    }

    public abstract boolean trigger();

    public abstract void halt();

}

Set focus to the first failed validation field.


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

package com.googlesource.gerrit.plugins.javamelody;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.inject.Scopes;

public class HttpModule extends HttpPluginModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), AllRequestFilter.class)
        .to(GerritMonitoringFilter.class)
        .in(Scopes.SINGLETON);
  }
}

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

package com.googlesource.gerrit.plugins.javamelody;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;

public class HttpModule extends ServletModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), AllRequestFilter.class)
        .to(GerritMonitoringFilter.class)
        .in(Scopes.SINGLETON);
  }
}

Extend ServletModule instead of HttpPluginModule