package org.mozilla.mozstumbler;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

final class NetworkUtils {
    private static final String LOGTAG = NetworkUtils.class.getName();

    private NetworkUtils() {
    }

    @SuppressWarnings("deprecation")
    static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            Log.e(LOGTAG, "ConnectivityManager is null!");
            return false;
        }

        if (!cm.getBackgroundDataSetting()) {
            Log.w(LOGTAG, "Background data is restricted!");
            return false;
        }

        NetworkInfo network = cm.getActiveNetworkInfo();
        if (network == null) {
            Log.w(LOGTAG, "No active network!");
            return false;
        }

        if (!network.isAvailable()) {
            Log.w(LOGTAG, "Active network is not available!");
            return false;
        }

        if (!network.isConnected()) {
            Log.w(LOGTAG, "Active network is not connected!");
            return false;
        }

        if (network.isRoaming()) {
            Log.w(LOGTAG, "Active network is roaming!");
            return false;
        }

        return true; // Network is OK!
    }

    static String getUserAgentString(Context context) {
        String appName = context.getString(R.string.app_name);
        String appVersion = PackageUtils.getAppVersion(context);

        // "MozStumbler/X.Y.Z"
        return appName + '/' + appVersion;
    }
}

package org.mozilla.mozstumbler;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

final class NetworkUtils {
    private static final String LOGTAG = NetworkUtils.class.getName();

    private NetworkUtils() {
    }

    @SuppressWarnings("deprecation")
    static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            Log.e(LOGTAG, "ConnectivityManager is null!");
            return false;
        }

        if (!cm.getBackgroundDataSetting()) {
            Log.w(LOGTAG, "Background data is restricted!");
            return false;
        }

        NetworkInfo network = cm.getActiveNetworkInfo();
        if (network == null) {
            Log.w(LOGTAG, "No active network!");
            return false;
        }

        if (!network.isAvailable()) {
            Log.w(LOGTAG, "Active network is not available!");
            return false;
        }

        if (!network.isConnected()) {
            Log.w(LOGTAG, "Active network is not connected!");
            return false;
        }

        return true; // Network is OK!
    }

    static String getUserAgentString(Context context) {
        String appName = context.getString(R.string.app_name);
        String appVersion = PackageUtils.getAppVersion(context);

        // "MozStumbler/X.Y.Z"
        return appName + '/' + appVersion;
    }
}

Remove check for network roaming


package edu.umd.cs.findbugs.detect;

import org.apache.bcel.classfile.CodeException;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;

public class DontCatchNullPointerException
        extends PreorderVisitor implements Detector {

    private final BugReporter reporter;
    ClassContext classContext;

    public DontCatchNullPointerException(BugReporter reporter) {
        this.reporter = reporter;
    }

    private static final String NullPtrExceptionID =
            "java.lang.NullPointerException";

    @Override
    public void visit(CodeException exc) {
        int type = exc.getCatchType();

        if (type == 0)
            return;

        String name = getConstantPool()
                .constantToString(getConstantPool()
                        .getConstant(type));

        if (name.equals(NullPtrExceptionID)) {
            BugInstance bug = new BugInstance(this,
                    "DCN_NULLPOINTER_EXCEPTION",
                    NORMAL_PRIORITY);
            bug.addClassAndMethod(this);
            bug.addSourceLine(this.classContext, this, exc.getHandlerPC());

            reporter.reportBug(bug);
        }
    }

    @Override
    public void visitClassContext(ClassContext classContext) {
        this.classContext = classContext;
        this.classContext.getJavaClass().accept(this);
    }

    @Override
    public void report() {
    }
}

package edu.umd.cs.findbugs.detect;

import org.apache.bcel.classfile.CodeException;

import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;

public class DontCatchNullPointerException
        extends BytecodeScanningDetector {

    private final BugReporter reporter;

    public DontCatchNullPointerException(BugReporter reporter) {
        this.reporter = reporter;
    }

    @DottedClassName
    private static final String NULLPOINTER_EXCEPTION_FQCN =
            "java.lang.NullPointerException";

    @Override
    public void visit(CodeException exc) {
        int type = exc.getCatchType();

        if (type == 0)
            return;

        String name = getConstantPool()
                .constantToString(getConstantPool()
                        .getConstant(type));

        if (name.equals(NULLPOINTER_EXCEPTION_FQCN)) {
            BugInstance bug = new BugInstance(this,
                    "DCN_NULLPOINTER_EXCEPTION",
                    NORMAL_PRIORITY);
            bug.addClassAndMethod(this);
            bug.addSourceLine(getClassContext(), this, exc.getHandlerPC());

            reporter.reportBug(bug);
        }
    }
}

Use BytecodeScanningDetector as base class


package forager.client;

import java.io.IOException;

public class StatusMonitor implements Runnable {

    int maxActive = 4;

    boolean online;

    private Forager forager;

    public StatusMonitor(Forager forager) {
        this.forager = forager;
    }

    public void run() {
        online = true;

        while (online) {
            int active = forager.getActiveCount();
            if (active < maxActive) {
                int numTasks = maxActive - active;
                try {
                    forager.submitTaskRequest(numTasks);
                } catch (IOException e) {
                    System.out.println("Failed to submit task request!");
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) { }
        }
    }
}

package forager.client;

import java.io.IOException;

public class StatusMonitor implements Runnable {

    int maxActive = 4;

    boolean online;

    private Forager forager;

    public StatusMonitor(Forager forager) {
        this.forager = forager;
    }

    public void run() {
        online = true;

        while (online) {
            int active = forager.getActiveCount();
            if (active < maxActive) {
                int numTasks = maxActive - active;
                try {
                    forager.submitTaskRequest(numTasks);
                } catch (IOException e) {
                    System.out.println("Failed to submit task request!");
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) { }
        }
    }
}

Increase iteration time a bit


package pw.scho.battleship.persistence.configuration;

import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;

import java.net.UnknownHostException;
import java.util.Arrays;

public class MongoConfiguration {

    public static void stop() {
        Singleton.INSTANCE.mongoSessionManager.close();
    }

    public static MongoSession createSession() {
        return Singleton.INSTANCE.mongoSessionManager.createSession();
    }

    private enum Singleton {

        INSTANCE;

        private final MongoSessionManager mongoSessionManager;

        private Singleton() {
            ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
            Settings settings = null;
            try {
                settings = Settings.defaultInstance()
                        .withDefaultUpdateStrategy(UpdateStrategies.DIFF)
                        .withDbName("battleship")
                        .withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));

            } catch (UnknownHostException e) {
            }
            mongoSessionManager = MongoSessionManager.create(builder, settings);
        }
    }
}

package pw.scho.battleship.persistence.configuration;

import com.mongodb.DB;
import com.mongodb.MongoURI;
import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MongoConfiguration {

    public static void stop() {
        Singleton.INSTANCE.mongoSessionManager.close();
    }

    public static MongoSession createSession() {
        return Singleton.INSTANCE.mongoSessionManager.createSession();
    }

    private enum Singleton {

        INSTANCE;

        private final MongoSessionManager mongoSessionManager;

        private Singleton() {
            ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
            Settings settings = null;
            try {
                settings = Settings.defaultInstance()
                        .withDefaultUpdateStrategy(UpdateStrategies.DIFF)
                        .withDbName("battleship");
                String mongoHqUrl = System.getenv("MONGOHQ_URL");

                if(mongoHqUrl!= null){
                    MongoURI mongoURI = new MongoURI(mongoHqUrl);
                    List<ServerAddress> serverAdresses = new ArrayList<>();
                    for(String host : mongoURI.getHosts()){
                        serverAdresses.add(new ServerAddress(host, 27017));
                    }
                    settings = settings.withAddresses(serverAdresses)
                            .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString());
                } else {
                    settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));
                }
            } catch (UnknownHostException e) {
            }
            mongoSessionManager = MongoSessionManager.create(builder, settings);
        }
    }
}

Add mongo hq authentication for heroku


package io.github.droidkaigi.confsched2017.viewmodel;

import android.databinding.BaseObservable;
import android.support.annotation.NonNull;

import io.github.droidkaigi.confsched2017.model.Contributor;

public class ContributorViewModel extends BaseObservable implements ViewModel {

    private Callback callback;

    private Contributor contributor;

    private String name;

    private String avatarUrl;

    private String htmlUrl;

    private int contributions;

    public ContributorViewModel(@NonNull Contributor contributor) {
        this.contributor = contributor;
        this.avatarUrl = contributor.avatarUrl;
        this.name = contributor.name;
        this.htmlUrl = contributor.htmlUrl;
        this.contributions = contributor.contributions;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void destroy() {
        this.callback = null;
    }

    public interface Callback {

        void onClickContributor();
    }

    public int getContributions() {
        return contributions;
    }

    public Contributor getContributor() {
        return contributor;
    }

    public String getName() {
        return name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }
}

package io.github.droidkaigi.confsched2017.viewmodel;

import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import android.view.View;

import io.github.droidkaigi.confsched2017.model.Contributor;

public class ContributorViewModel extends BaseObservable implements ViewModel {

    private Callback callback;

    private Contributor contributor;

    private String name;

    private String avatarUrl;

    private String htmlUrl;

    private int contributions;

    public ContributorViewModel(@NonNull Contributor contributor) {
        this.contributor = contributor;
        this.avatarUrl = contributor.avatarUrl;
        this.name = contributor.name;
        this.htmlUrl = contributor.htmlUrl;
        this.contributions = contributor.contributions;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void destroy() {
        this.callback = null;
    }

    public interface Callback {

        void onClickContributor(String htmlUrl);
    }

    public void onClickContributor(@SuppressWarnings("UnusedParameters") View view) {
        if (callback != null) {
            callback.onClickContributor(htmlUrl);
        }
    }

    public int getContributions() {
        return contributions;
    }

    public Contributor getContributor() {
        return contributor;
    }

    public String getName() {
        return name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }
}

Fix the problem with handling onClick event


package org.wikipedia.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller;

public final class GeoUtil {

    public static void sendGeoIntent(@NonNull Activity activity,
                                     @NonNull Location location,
                                     @Nullable String placeName) {
        String geoStr = "geo:";
        geoStr += Double.toString(location.getLatitude()) + ","
                + Double.toString(location.getLongitude());
        if (!TextUtils.isEmpty(placeName)) {
            geoStr += "?q=" + Uri.encode(placeName);
        }
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr)));
        } catch (ActivityNotFoundException e) {
            FeedbackUtil.showMessage(activity, R.string.error_no_maps_app);
        }
    }

    @Nullable public static String getGeoIPCountry() {
        try {
            return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country();
        } catch (IllegalArgumentException e) {
            // For our purposes, don't care about malformations in the GeoIP cookie for now.
            return null;
        }
    }

    private GeoUtil() {
    }
}

package org.wikipedia.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller;

public final class GeoUtil {

    public static void sendGeoIntent(@NonNull Activity activity,
                                     @NonNull Location location,
                                     @Nullable String placeName) {
        // Using geo:latitude,longitude doesn't give a point on the map,
        // hence using query
        String geoStr = "geo:0,0?q=" + location.getLatitude()
                + "," + location.getLongitude();
        if (!TextUtils.isEmpty(placeName)) {
            geoStr += "(" + Uri.encode(placeName) + ")";
        }
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr)));
        } catch (ActivityNotFoundException e) {
            FeedbackUtil.showMessage(activity, R.string.error_no_maps_app);
        }
    }

    @Nullable public static String getGeoIPCountry() {
        try {
            return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country();
        } catch (IllegalArgumentException e) {
            // For our purposes, don't care about malformations in the GeoIP cookie for now.
            return null;
        }
    }

    private GeoUtil() {
    }
}

Make Google Maps use the coordinates supplied by Wikipedia app


package com.bugielmarek.timetable.tests.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestUtils {

	 public static String createStringWithLength(int length){
		 	StringBuilder sb = new StringBuilder();
		 	for(int i=0; i<length; i++){
		 		sb.append("a");
		 	}
		 	return sb.toString();
	 }

	/* public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
	        ObjectMapper mapper = new ObjectMapper();
	        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	        return mapper.writeValueAsBytes(object);
	    }*/

	 public static String asJsonString(Object object) throws JsonProcessingException{
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		 return mapper.writeValueAsString(object);
	 }
}

package com.bugielmarek.timetable.tests.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestUtils {

	 public static String createStringWithLength(int length){
		 	StringBuilder sb = new StringBuilder();
		 	for(int i=0; i<length; i++){
		 		sb.append("a");
		 	}
		 	return sb.toString();
	 }

	 public static String asJsonString(Object object) throws JsonProcessingException{
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		 return mapper.writeValueAsString(object);
	 }
}

Delete byte[] method, was superfluous


package io.lithiumsheep.weatherlib;

import io.lithiumsheep.weatherlib.api.HttpClient;
import io.lithiumsheep.weatherlib.models.CurrentWeather;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

public class WeatherLib {

    public static Observable<CurrentWeather> getObservableCurrentWeather(String cityOrZip) {
        return HttpClient.getObservableService().getCurrentWeather(cityOrZip)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static Call<CurrentWeather> getCurrentWeather(String cityOrZip) {
        return HttpClient.getService().getCurrentWeather(cityOrZip);
    }

    public static Call<Void> getWeatherZip(String zip) {
        return HttpClient.getService().getWeatherByZip(zip);
    }
}

package io.lithiumsheep.weatherlib;

import io.lithiumsheep.weatherlib.api.HttpClient;
import io.lithiumsheep.weatherlib.models.CurrentWeather;
import retrofit2.Call;

public class WeatherLib {

    public static Call<CurrentWeather> getCurrentWeather(String cityOrZip) {
        return HttpClient.getService().getCurrentWeather(cityOrZip);
    }

    public static Call<Void> getWeatherZip(String zip) {
        return HttpClient.getService().getWeatherByZip(zip);
    }
}

Remove observable service from facade


package org.springframework.social.salesforce.connect;

import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;

import java.util.Map;

/**
 * Salesforce OAuth2Template implementation.
 * <p/>
 * The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
 *
 * @author Umut Utkan
 */
public class SalesforceOAuth2Template extends OAuth2Template {

    private String instanceUrl = null;

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
    }

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
    }

    @Override
    protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
        this.instanceUrl = (String) response.get("instance_url");

        return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
    }

    public String getInstanceUrl() {
        return instanceUrl;
    }

}

package org.springframework.social.salesforce.connect;

import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;

import java.util.Map;

/**
 * Salesforce OAuth2Template implementation.
 * <p/>
 * The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
 *
 * @author Umut Utkan
 */
public class SalesforceOAuth2Template extends OAuth2Template {

    private String instanceUrl = null;

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        this(clientId, clientSecret, authorizeUrl, null, accessTokenUrl);
    }

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
        this.instanceUrl = (String) response.get("instance_url");

        return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
    }

    public String getInstanceUrl() {
        return instanceUrl;
    }

}

Set OAuth2Template to use parameter-based client authentication (see SOCIAL-320) since Salesforce does not yet support the spec-recommended HTTP Basic client authentication.


package com.hewgill.android.nzsldict;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            Intent startIntent = new Intent(context, FavouritesActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(startIntent);
        }
    }
}

package com.hewgill.android.nzsldict;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            Intent startIntent = new Intent(context, FavouritesActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(startIntent);
            return;
        }

        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            Toast.makeText(context, "Download completed?", Toast.LENGTH_SHORT).show();

        }
    }
}

Add stub to indicate that the download has completed; this needs to be raised to the favourites activity


package com.github.jsonldjava.core;

import com.github.jsonldjava.utils.JsonUtils;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.*;

public class JsonLdFramingTest {

    @Test
    public void testFrame0001() throws IOException, JsonLdError {
        try {
            Object frame = JsonUtils.fromInputStream(
                    getClass().getResourceAsStream("/custom/frame-0001-frame.jsonld"));
            Object in = JsonUtils.fromInputStream(
                    getClass().getResourceAsStream("/custom/frame-0001-in.jsonld"));

            JsonLdProcessor.frame(in, frame, new JsonLdOptions());
        } catch (Throwable t) {
            t.printStackTrace();

            fail();
        }
    }

}

package com.github.jsonldjava.core;

import com.github.jsonldjava.utils.JsonUtils;
import java.io.IOException;
import java.util.Map;

import org.junit.Test;
import static org.junit.Assert.*;

public class JsonLdFramingTest {

    @Test
    public void testFrame0001() throws IOException, JsonLdError {
        Object frame = JsonUtils.fromInputStream(
                getClass().getResourceAsStream("/custom/frame-0001-frame.jsonld"));
        Object in = JsonUtils.fromInputStream(
                getClass().getResourceAsStream("/custom/frame-0001-in.jsonld"));

        Map<String, Object> frame2 = JsonLdProcessor.frame(in, frame, new JsonLdOptions());

        assertEquals(2, frame2.size());
    }

}

Add positive test for completion in the framing test


package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    return (nc.contains(namespaceURI, localName)
	    && (value == null
		|| valuePattern.residual(b, value).isNullable()));
  }
  boolean isAttribute() {
    return true;
  }
}

package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    if (!nc.contains(namespaceURI, localName))
      return false;
    if (value == null)
      return true;
    if (value.isEmpty() && valuePattern.isNullable())
      return true;
    return valuePattern.residual(b, value).isNullable();
  }
  boolean isAttribute() {
    return true;
  }
}

Allow an empty attribute value to match <empty/>.


package ethereumjava.solidity;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import ethereumjava.exception.EthereumJavaException;
import ethereumjava.module.Eth;

/**
 * Created by gunicolas on 30/08/16.
 */
public class Contract<T extends ContractType> {

    Class<T> abi;
    String address;
    Eth eth;

    public Contract(Eth eth){
        this.eth = eth;
    }

    public Contract<T> withAbi(Class<T> abi){
        this.abi = abi;
        return this;
    }

    public T at(String address){
        this.address = address;
        return (T) Proxy.newProxyInstance(abi.getClassLoader(),new Class[]{abi},new InvocationHandler());
    }

    class InvocationHandler implements java.lang.reflect.InvocationHandler{

        @Override
        public SolidityElement invoke(Object proxy, Method method, Object[] args) throws Throwable {

            if( method.getReturnType().isAssignableFrom(SolidityFunction.class) ){
                return new SolidityFunction(address,method,eth,args);
            } else if( method.getReturnType().isAssignableFrom(SolidityEvent.class) ){
                return new SolidityEvent(address,method,eth);
            }
            throw new EthereumJavaException("Contract element return type is invalid");
        }
    }

}

package ethereumjava.solidity;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import ethereumjava.exception.EthereumJavaException;
import ethereumjava.module.Eth;

/**
 * Created by gunicolas on 30/08/16.
 */
public class Contract {

    String address;
    Eth eth;

    public final class ContractInstance<T extends ContractType> {
        Class<T> clazz;

        public ContractInstance(Class<T> aClazz) {
            clazz = aClazz;
        }

        public T at(String address){
            Contract.this.address = address;
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class[]{clazz},new InvocationHandler());
        }

    }

    public Contract(Eth eth){
        this.eth = eth;
    }

    public <T extends ContractType> ContractInstance<T> withAbi(Class<T> clazz){
        return new ContractInstance(clazz);
    }

    class InvocationHandler implements java.lang.reflect.InvocationHandler{

        @Override
        public SolidityElement invoke(Object proxy, Method method, Object[] args) throws Throwable {

            if( method.getReturnType().isAssignableFrom(SolidityFunction.class) ){
                return new SolidityFunction(address,method,eth,args);
            } else if( method.getReturnType().isAssignableFrom(SolidityEvent.class) ){
                return new SolidityEvent(address,method,eth);
            }
            throw new EthereumJavaException("Contract element return type is invalid");
        }
    }

}

Allow to not cast ethereum Java contract


package org.rundeck.client.util;

import com.simplifyops.toolbelt.ANSIColorOutput;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by greg on 7/19/16.
 */
public class Colorz {
    /**
     * Return a map with key/values replaced with colorized versions, if specified
     *
     * @param data data
     * @param key  key color, or null
     *
     * @return colorized keys/values
     */
    public static Map<?, ?> colorizeMapRecurse(
            Map<?, ?> data,
            ANSIColorOutput.Color key
    )
    {
        LinkedHashMap<Object, Object> result = new LinkedHashMap<>();
        data.keySet().forEach(k -> {
            final Object value = data.get(k);
            result.put(
                    key != null ? ANSIColorOutput.colorize(key, k.toString()) : k,
                    value instanceof Map ? colorizeMapRecurse((Map) value, key) : value
            );
        });
        return result;
    }
}

package org.rundeck.client.util;

import com.simplifyops.toolbelt.ANSIColorOutput;

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

/**
 * Created by greg on 7/19/16.
 */
public class Colorz {
    /**
     * Return a map with key/values replaced with colorized versions, if specified
     *
     * @param data data
     * @param colors  key color, or null
     *
     * @return colorized keys/values
     */
    public static Map<?, ?> colorizeMapRecurse(
            Map<?, ?> data,
            ANSIColorOutput.Color... colors
    )
    {
        LinkedHashMap<Object, Object> result = new LinkedHashMap<>();
        data.keySet().forEach(k -> {
            final Object value = data.get(k);
            ANSIColorOutput.Color keyColor = colors != null && colors.length > 0 ? colors[0] : null;
            ANSIColorOutput.Color[] subcolors = null;
            if (colors != null && colors.length > 1) {
                subcolors = new ANSIColorOutput.Color[colors.length - 1];
                System.arraycopy(colors, 1, subcolors, 0, subcolors.length);
            }
            result.put(
                    keyColor != null
                    ? ANSIColorOutput.colorize(
                            keyColor,
                            k.toString()
                    )
                    : k,

                    value instanceof Map && subcolors != null
                    ? colorizeMapRecurse(
                            (Map) value,
                            subcolors
                    )

                    : value
            );
        });
        return result;
    }
}

Update to support more than one color


/**
 * Abstract Syntax Tree.
 *
 * <pre>
 * Group ::= Abbreviation* Definition*
 *
 * Definition ::= Test | FourPhaseTest | Table
 *
 * Test ::= Assertion*
 *
 * Assertion ::= Proposition* Fixture
 *
 * Proposition ::= QuotedExpr Predicate
 *
 * Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
 *
 * IsPredicate ::= Matcher
 * IsNotPredicate ::= Matcher
 * ThrowsPredicate ::= Matcher
 *
 * Matcher ::= EqualToMatcher
 *           | InstanceOfMatcher
 *           | InstanceSuchThatMatcher
 *           | NullValueMatcher
 *
 * EqualToMatcher ::= QuotedExpr
 * InstanceOfMatcher ::= ClassType
 * InstanceSuchThatMatcher ::= ClassType Proposition+
 *
 * Expr ::= QuotedExpr | StubExpr
 *
 * StubExpr ::= ClassType StubBehavior*
 *
 * StubBehavior ::= MethodPattern Expr
 *
 * MethodPattern ::= Type*
 *
 * Type ::= NonArrayType
 * NonArrayType ::= PrimitiveType | ClassType
 * PrimitiveType ::= Kind
 *
 * Fixture ::= | TableRef | Bindings
 *
 * TableRef ::= Ident+ TableType
 *
 * TableType :: INLINE | CSV | TSV | EXCEL
 *
 * Bindings ::= Binding*
 * Binding ::= Ident Expr
 *
 * FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
 *
 * Phase ::= LetBindings? Execution?
 * VerifyPhase ::= Assertion+
 *
 * Execution ::= QuotedExpr*
 *
 * Table ::= Ident* Row*
 *
 * Row ::= Expr*
 * </pre>
 *
 */
package yokohama.unit.ast;

/**
 * Abstract Syntax Tree.
 *
 * <pre>
 * Group ::= Abbreviation* Definition*
 *
 * Definition ::= Test | FourPhaseTest | Table
 *
 * Test ::= Assertion*
 *
 * Assertion ::= Proposition* Fixture
 *
 * Proposition ::= QuotedExpr Predicate
 *
 * Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
 *
 * IsPredicate ::= Matcher
 * IsNotPredicate ::= Matcher
 * ThrowsPredicate ::= Matcher
 *
 * Matcher ::= EqualToMatcher
 *           | InstanceOfMatcher
 *           | InstanceSuchThatMatcher
 *           | NullValueMatcher
 *
 * EqualToMatcher ::= QuotedExpr
 * InstanceOfMatcher ::= ClassType
 * InstanceSuchThatMatcher ::= ClassType Proposition+
 *
 * Expr ::= QuotedExpr | StubExpr
 *
 * StubExpr ::= ClassType StubBehavior*
 *
 * StubBehavior ::= MethodPattern Expr
 *
 * MethodPattern ::= Type*
 *
 * Type ::= NonArrayType
 * NonArrayType ::= PrimitiveType | ClassType
 * PrimitiveType ::= Kind
 *
 * Fixture ::= | TableRef | Bindings
 *
 * TableRef ::= Ident+ TableType
 *
 * TableType :: INLINE | CSV | TSV | EXCEL
 *
 * Bindings ::= Binding*
 * Binding ::= Ident Expr
 *
 * FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
 *
 * Phase ::= LetBindings? Execution?
 * VerifyPhase ::= Assertion+
 *
 * LetBindings ::= LetBinding+
 * LetBinding ::= Expr
 *
 * Execution ::= QuotedExpr*
 *
 * Table ::= Ident* Row*
 *
 * Row ::= Expr*
 * </pre>
 *
 */
package yokohama.unit.ast;

Add description of LetBindings and LetBinding, which were missing from document


package com.boundary.camel.component.http;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Ignore;
import org.junit.Test;

import com.boundary.camel.component.common.ServiceStatus;
import com.boundary.camel.component.port.PortResult;

public class HttpComponentTest extends CamelTestSupport {

    @Test
    public void testHttp() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.await(5, TimeUnit.SECONDS);

        mock.assertIsSatisfied();
        List <Exchange> receivedExchanges = mock.getReceivedExchanges();
        for(Exchange e: receivedExchanges) {
        	HttpInfo status = e.getIn().getBody(HttpInfo.class);

        	assertTrue("check http status",status.getStatus() == ServiceStatus.SUCCESS);
        }
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                from("http://foo?host=localhost&delay=5")
                  .to("mock:result");
            }
        };
    }
}

package com.boundary.camel.component.url;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Ignore;
import org.junit.Test;

import com.boundary.camel.component.common.ServiceStatus;

public class UrlComponentTest extends CamelTestSupport {

    @Test
    public void testHttp() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.await(5, TimeUnit.SECONDS);

        mock.assertIsSatisfied();
        List <Exchange> receivedExchanges = mock.getReceivedExchanges();
        for(Exchange e: receivedExchanges) {
        	UrlResult result = e.getIn().getBody(UrlResult.class);

        	assertTrue("check http status",result.getStatus() == ServiceStatus.SUCCESS);
        }
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                from("http://foo?host=localhost&delay=5")
                  .to("mock:result");
            }
        };
    }
}

Change to support name change


package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Tony Wardell
 * Date: 05/10/2016
 * Time: 16:41
 * Created with IntelliJ IDEA.
 */
public class CoTermsAggregatorMocker {

    /**
     * Mocks the {@code CoTermsAggregator#getGeneProductCounts} to product a count of gene products annotated by a
     * single GO Term.
     * @param count
     * @param termsLists
     * @return
     */
    static Map<String, AtomicLong> makeGpCountForTerm(int count, List<String>... termsLists ){
        Map<String, AtomicLong> termGpCount = new HashMap<>();

        for (int i = 0; i < termsLists.length; i++) {
            List<String> terms = termsLists[i];

            for (int j = 0; j < terms.size(); j++) {
                String s =  terms.get(j);
                termGpCount.put(s, new AtomicLong(count));
            }
        }

        return termGpCount;
    }
}

package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Tony Wardell
 * Date: 05/10/2016
 * Time: 16:41
 * Created with IntelliJ IDEA.
 */
public class CoTermsAggregatorMocker {

    /**
     * Mocks the {@code CoTermsAggregator#getGeneProductCounts} to product a count of gene products annotated by a
     * single GO Term.
     * @param count the number that the count for Gene Product will be set to.
     * @param termsLists a list of GO Term identifiers used to seed a map of term::count used in testing
     * @return a map of term::count used in testing
     */
    @SafeVarargs
    static Map<String, AtomicLong> makeGpCountForTerm(int count, List<String>... termsLists ){
        Map<String, AtomicLong> termGpCount = new HashMap<>();

        for (List<String> terms : termsLists) {
            for (String s : terms) {
                termGpCount.put(s, new AtomicLong(count));
            }
        }

        return termGpCount;
    }
}

Add some javadoc. Add @SafeVarags annotation. Change for loops to for each.


package ${package};

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

/**
 * Application object for your web application.
 * If you want to run this application without deploying, run the Start class.
 *
 * @see ${package}.Start#main(String[])
 */
public class WicketApplication extends WebApplication
{
	/**
	 * @see org.apache.wicket.Application#getHomePage()
	 */
	@Override
	public Class<? extends WebPage> getHomePage()
	{
		return HomePage.class;
	}

	/**
	 * @see org.apache.wicket.Application#init()
	 */
	@Override
	public void init()
	{
		super.init();

		// add your configuration here
	}
}

package ${package};

import org.apache.wicket.csp.CSPDirective;
import org.apache.wicket.csp.CSPDirectiveSrcValue;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

/**
 * Application object for your web application.
 * If you want to run this application without deploying, run the Start class.
 *
 * @see ${package}.Start#main(String[])
 */
public class WicketApplication extends WebApplication
{
	/**
	 * @see org.apache.wicket.Application#getHomePage()
	 */
	@Override
	public Class<? extends WebPage> getHomePage()
	{
		return HomePage.class;
	}

	/**
	 * @see org.apache.wicket.Application#init()
	 */
	@Override
	public void init()
	{
		super.init();

		// needed for the styling used by the quickstart
		getCspSettings().blocking()
			.add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF)
			.add(CSPDirective.STYLE_SRC, "https://fonts.googleapis.com/css")
			.add(CSPDirective.FONT_SRC, "https://fonts.gstatic.com");

		// add your configuration here
	}
}

Fix CSP for styling in quickstart


package org.openforis.collect.earth.planet;

import java.util.Comparator;;

public class FeatureSorter implements Comparator<Feature>{

	@Override
	public int compare(Feature o1, Feature o2) {
		if( o1.getProperties().getCloudPercent() !=null && o2.getProperties().getCloudPercent() != null  )
			if( o1.getProperties().getCloudPercent() == o2.getProperties().getCloudPercent()) {
					return o2.getProperties().getVisibleConfidencePercent() - o1.getProperties().getVisibleConfidencePercent();
				}else {
					return o1.getProperties().getCloudPercent() - o2.getProperties().getCloudPercent();
				}
		else if( o1.getProperties().getCloudPercent() != null ) {
			return -1;
		}else if( o2.getProperties().getCloudPercent() != null) {
			return 1;
		}else {
			return (int) ( (o1.getProperties().getCloudCover() - o2.getProperties().getCloudCover() ) * 100 );
		}
	}

}

package org.openforis.collect.earth.planet;

import java.util.Comparator;;

public class FeatureSorter implements Comparator<Feature>{

	@Override
	public int compare(Feature o1, Feature o2) {
		if( o1.getProperties().getCloudPercent() !=null && o2.getProperties().getCloudPercent() != null  ) {
			if( o1.getProperties().getCloudPercent() == o2.getProperties().getCloudPercent()) {
					if( o2.getProperties().getVisibleConfidencePercent() !=null &&  o1.getProperties().getVisibleConfidencePercent() != null ) {
						return o2.getProperties().getVisibleConfidencePercent() - o1.getProperties().getVisibleConfidencePercent();
					}else if( o2.getProperties().getVisibleConfidencePercent() !=null ) {
						return 1;
					}else{
						return -1;
					}
				}else {
					return o1.getProperties().getCloudPercent() - o2.getProperties().getCloudPercent();
				}
		}else if( o1.getProperties().getCloudPercent() != null ) {
			return -1;
		}else if( o2.getProperties().getCloudPercent() != null) {
			return 1;
		}else {
			if( o1.getProperties().getCloudCover()!=null && o2.getProperties().getCloudCover()!=null ) {
				return (int) ( (o1.getProperties().getCloudCover() - o2.getProperties().getCloudCover() ) * 100 );
			}else
				return 1; // No way to know so return the latest
		}
	}

}

Fix null exception when images have no visible percent properties


package de.hilling.cdi.sampleapp.ejb;

import de.hilling.junit.cdi.annotations.GlobalTestImplementation;

@GlobalTestImplementation
public class JEETestConfiguration implements de.hilling.junit.cdi.jee.JEETestConfiguration {
    @Override
    public String getTestPersistenceUnitName() {
        return "cdi-test-unit-eclipselink";
    }
}

package de.hilling.cdi.sampleapp.ejb;

import de.hilling.junit.cdi.annotations.GlobalTestImplementation;
import de.hilling.junit.cdi.scope.TestSuiteScoped;

@GlobalTestImplementation
@TestSuiteScoped
public class JEETestConfiguration implements de.hilling.junit.cdi.jee.JEETestConfiguration {
    @Override
    public String getTestPersistenceUnitName() {
        return "cdi-test-unit-eclipselink";
    }
}

Fix Scope (error during release)


#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.ejb;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggerProducer {

    @Produces
    public Logger getLogger(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(
                              injectionPoint.getBean().getBeanClass());
    }

}

#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.ejb;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggerProducer {

    @Produces
    public Logger getLogger(InjectionPoint injectionPoint) {
        Class<?> clazz;
        if (injectionPoint.getBean() != null) {
            clazz = injectionPoint.getBean().getBeanClass();
        } else {
            clazz = injectionPoint.getMember().getDeclaringClass();
        }
        return LoggerFactory.getLogger(clazz);
    }
}

Fix Logger injection in GlassFish 4


package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.NullableComputable;
import com.intellij.psi.JavaPsiFacade;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    return ApplicationManager.getApplication().runReadAction(new NullableComputable<PositionManager>() {
      @Override
      public PositionManager compute() {
        if (JavaPsiFacade.getInstance(process.getProject()).findPackage("com.springsource.loaded") != null) {
          return new SpringLoadedPositionManager(process);
        }
        return null;
      }
    });
  }
}

package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.JavaPsiFacade;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
    try {
      if (JavaPsiFacade.getInstance(process.getProject()).findPackage("com.springsource.loaded") != null) {
        return new SpringLoadedPositionManager(process);
      }
      return null;
    }
    finally {
      accessToken.finish();
    }
  }
}

Use ApplicationManager.getApplication().acquireReadActionLock() instead of ApplicationManager.getApplication().runReadAction()


package io.quarkus.it.rabbitmq;

import javax.enterprise.context.ApplicationScoped;

import org.eclipse.microprofile.reactive.messaging.Outgoing;

import io.smallrye.mutiny.Multi;

@ApplicationScoped
public class PeopleProducer {
    @Outgoing("people-out")
    public Multi<Person> generatePeople() {
        return Multi.createFrom().items(
                new Person("bob"),
                new Person("alice"),
                new Person("tom"),
                new Person("jerry"),
                new Person("anna"),
                new Person("ken"));
    }
}

package io.quarkus.it.rabbitmq;

import java.time.Duration;

import javax.enterprise.context.ApplicationScoped;

import org.eclipse.microprofile.reactive.messaging.Outgoing;

import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;

@ApplicationScoped
public class PeopleProducer {
    @Outgoing("people-out")
    public Multi<Person> generatePeople() {
        return Uni.createFrom().nullItem()
                .onItem().delayIt().by(Duration.ofSeconds(3))
                .onItem().transformToMulti(n -> Multi.createFrom()
                        .items(new Person("bob"),
                                new Person("alice"),
                                new Person("tom"),
                                new Person("jerry"),
                                new Person("anna"),
                                new Person("ken")));
    }
}

Add delay to ensure queue is created and bound.


package seedu.ezdo.model;

import java.util.EmptyStackException;
//@@author A0139248X
/*
 * Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
 * If stack goes past max capacity, the oldest item to be pushed is replaced.
 */
public class FixedStack<T> {
    private int index;
    private T[] array;

    public FixedStack(int capacity) {
        array = (T[]) new Object[capacity];
        index = -1;
    }

    public void push(T item) {
        index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around
        array[index] = item;
    }

    public T pop() throws EmptyStackException {
        if (index == -1 || array[index] == null) {
            throw new EmptyStackException();
        }
        T item = array[index];
        array[index] = null;
        if (index == 0) {
            index = array.length - 1;
        } else {
            index = index - 1;
        }
        return item;
    }

    public boolean isEmpty() {
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                return false;
            }
        }
        return true;
    }

    public void clear() {
        for (int i = 0; i < array.length; i++) {
            array[i] = null;
        }
        index = -1;
    }
}

//@@author A0139248X
package seedu.ezdo.model;

import java.util.EmptyStackException;

/**
 * Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
 * If stack goes past max capacity, the oldest item that was pushed is replaced.
 */
public class FixedStack<T> {

    private static final int STARTING_INDEX = -1;

    private int index;
    private T[] array;

    public FixedStack(int capacity) {
        array = (T[]) new Object[capacity];
        index = STARTING_INDEX;
    }

    public void push(T item) {
        index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around
        array[index] = item;
    }

    public T pop() throws EmptyStackException {
        if (index == STARTING_INDEX || array[index] == null) {
            throw new EmptyStackException();
        }
        T item = array[index];
        array[index] = null;
        if (index == 0) { // top of stack is 0, need to wrap around
            index = array.length - 1;
        } else {
            index = index - 1;
        }
        return item;
    }

    public boolean isEmpty() {
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                return false;
            }
        }
        return true;
    }

    public void clear() {
        for (int i = 0; i < array.length; i++) {
            array[i] = null;
        }
        index = STARTING_INDEX;
    }
}

Add header comments Remove magic numbers


/*
 * This file is part of LibrePlan
 *
 * Copyright (C) 2011 WirelessGalicia, S.L.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.libreplan.business.externalcompanies.entities;

import static org.libreplan.business.i18n.I18nHelper._;

/**
 * Enum for specified the type of {@link CustomerCommunication}
 *
 * @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
 */
public enum CommunicationType {

    NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance"));

    private String description;

    private CommunicationType(String description) {
        this.description = description;
    }

    public String toString() {
        return this.description;
    }

    public static CommunicationType getDefault() {
        return NEW_PROJECT;
    }
}

/*
 * This file is part of LibrePlan
 *
 * Copyright (C) 2011 WirelessGalicia, S.L.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.libreplan.business.externalcompanies.entities;

import static org.libreplan.business.i18n.I18nHelper._;

/**
 * Enum for specified the type of {@link CustomerCommunication}
 *
 * @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
 */
public enum CommunicationType {

    NEW_PROJECT(_("New project")), REPORT_PROGRESS(_("Report advance")), UPDATE_DELIVERING_DATE(
            _("Update Delivering Date"));

    private String description;

    private CommunicationType(String description) {
        this.description = description;
    }

    public String toString() {
        return this.description;
    }

    public static CommunicationType getDefault() {
        return NEW_PROJECT;
    }
}

Create new subcontractor communication type: UPDATE_DELIVERING_DATE


package com.github.rtyley.android.screenshot.paparazzo.processors;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;

public class AnimatedGifCreator implements ScreenshotProcessor {

    private final AnimatedGifEncoder gifEncoder;
    private final File file;

    public AnimatedGifCreator(File file) {
        this.file = file;
        gifEncoder = new AnimatedGifEncoder();
        gifEncoder.setDelay(500);
    }

    @Override
    public void process(BufferedImage image, Map<String, String> requestData) {
        if (!gifEncoder.isStarted()) {
            gifEncoder.start(file.getAbsolutePath());
        }
        gifEncoder.addFrame(image);
    }

    @Override
    public void finish() {
        gifEncoder.finish();
    }

}

package com.github.rtyley.android.screenshot.paparazzo.processors;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;

public class AnimatedGifCreator implements ScreenshotProcessor {

    private final AnimatedGifEncoder gifEncoder;
    private final File file;

    public AnimatedGifCreator(File file) {
        this.file = file;
        gifEncoder = new AnimatedGifEncoder();
        gifEncoder.setDelay(500);
        gifEncoder.setRepeat(0);
    }

    @Override
    public void process(BufferedImage image, Map<String, String> requestData) {
        if (!gifEncoder.isStarted()) {
            gifEncoder.start(file.getAbsolutePath());
        }
        gifEncoder.addFrame(image);
    }

    @Override
    public void finish() {
        gifEncoder.finish();
    }

}

Set Animated GIFs to repeat


package uk.ac.ebi.quickgo.annotation.validation.service;

import com.google.common.base.Preconditions;
import java.util.Objects;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Validate the with/from values used to filter annotations.
 *
 * @author Tony Wardell
 * Date: 21/11/2016
 * Time: 16:37
 * Created with IntelliJ IDEA.
 */
public class WithFromValuesValidation implements ConstraintValidator<WithFromValidator, String[]> {

    private final ValidationEntityChecker validator;

    @Autowired
    public WithFromValuesValidation(ValidationEntityChecker validator) {
        Preconditions.checkArgument(Objects.nonNull(validator), "The ValidationEntityChecker instance cannot be null");
        this.validator = validator;
    }

    @Override public void initialize(WithFromValidator constraintAnnotation) {}

    /**
     * If the entire list of values passed to this method can be successfully validated, or not validated at all then
     * isValid will return true.
     * @param values list of potential database cross reference identifiers. Can be null.
     * @param context of the isValid call.
     * @return validation result as boolean.
     */
    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null || Stream.of(values).allMatch(validator::isValid);
    }
}

package uk.ac.ebi.quickgo.annotation.validation.service;

import com.google.common.base.Preconditions;
import java.util.Objects;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Validate the with/from values used to filter annotations.
 *
 * @author Tony Wardell
 * Date: 21/11/2016
 * Time: 16:37
 * Created with IntelliJ IDEA.
 */
public class WithFromValuesValidation implements ConstraintValidator<WithFromValidator, String[]> {

    private final ValidationEntityChecker validator;

    @Autowired
    public WithFromValuesValidation(ValidationEntityChecker validator) {
        Preconditions.checkArgument(Objects.nonNull(validator), "The ValidationEntityChecker instance cannot be null" +
                ".");
        this.validator = validator;
    }

    @Override public void initialize(WithFromValidator constraintAnnotation) {}

    /**
     * If the entire list of values passed to this method can be successfully validated, or not validated at all then
     * isValid will return true.
     * @param values list of potential database cross reference identifiers. Can be null.
     * @param context of the isValid call.
     * @return validation result as boolean.
     */
    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null || Stream.of(values).allMatch(validator::isValid);
    }
}

Add fullstop to error message.


/*
 * Copyright 2013-2015 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.cloud.netflix.sidecar;

import java.net.URI;

import lombok.Data;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author Spencer Gibb
 */
@Data
@ConfigurationProperties("sidecar")
public class SidecarProperties {

	private URI healthUri;

	private URI homePageUri;

	private int port;

}

/*
 * Copyright 2013-2015 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.cloud.netflix.sidecar;

import java.net.URI;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import lombok.Data;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author Spencer Gibb
 */
@Data
@ConfigurationProperties("sidecar")
public class SidecarProperties {

	private URI healthUri;

	private URI homePageUri;

	@Max(65535)
	@Min(1)
	private int port;

}

Put min/max constraints on sidecar.port


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

package org.gradle.process.internal.worker.child;

import org.gradle.initialization.GradleUserHomeDirProvider;

import java.io.File;

public class DefaultWorkerDirectoryProvider implements WorkerDirectoryProvider {
    private final File gradleUserHomeDir;

    public DefaultWorkerDirectoryProvider(GradleUserHomeDirProvider gradleUserHomeDirProvider) {
        this.gradleUserHomeDir = gradleUserHomeDirProvider.getGradleUserHomeDirectory();
    }

    @Override
    public File getIdleWorkingDirectory() {
        File defaultWorkerDirectory = new File(gradleUserHomeDir, "workers");
        if (!defaultWorkerDirectory.exists() && !defaultWorkerDirectory.mkdirs()) {
            throw new IllegalStateException("Unable to create default worker directory at " + defaultWorkerDirectory.getAbsolutePath());
        }
        return defaultWorkerDirectory;
    }
}

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

package org.gradle.process.internal.worker.child;

import org.gradle.initialization.GradleUserHomeDirProvider;
import org.gradle.util.GFileUtils;

import java.io.File;

public class DefaultWorkerDirectoryProvider implements WorkerDirectoryProvider {
    private final File gradleUserHomeDir;

    public DefaultWorkerDirectoryProvider(GradleUserHomeDirProvider gradleUserHomeDirProvider) {
        this.gradleUserHomeDir = gradleUserHomeDirProvider.getGradleUserHomeDirectory();
    }

    @Override
    public File getIdleWorkingDirectory() {
        File defaultWorkerDirectory = new File(gradleUserHomeDir, "workers");
        if (!defaultWorkerDirectory.exists()) {
            GFileUtils.mkdirs(defaultWorkerDirectory);
        }
        return defaultWorkerDirectory;
    }
}

Change WorkerDirectoryProvider to use GFileUtils.mkdirs()


package main;

import search.SqRoomExploration;
import lejos.nxt.SensorPort;
import lejos.nxt.addon.tetrix.TetrixMotorController;
import lejos.nxt.addon.tetrix.TetrixRegulatedMotor;
import lejos.nxt.addon.tetrix.TetrixControllerFactory;
import lejos.robotics.navigation.DifferentialPilot;

/** This is the  class StartUp
 *  Created by OneNationUnderCanadia
 *  To start the robot
 *
 *  Created on Feb 16, 2015 at 8:48:15 AM
 */

public class StartUp {

	private static TetrixControllerFactory cf;
	private static TetrixMotorController mc;

	public static void main(String[] args) {

		// TODO headlights

		cf = new TetrixControllerFactory(SensorPort.S1);
		mc = cf.newMotorController();

		TetrixRegulatedMotor motor1 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_1);
		TetrixRegulatedMotor motor2 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_2);
		DifferentialPilot pilot = new DifferentialPilot((double) 10, (double) 10, motor1, motor2);

		SqRoomExploration mapper = new SqRoomExploration(pilot, 60, 60);

	}

}

package main;

import search.SqRoomExploration;
import lejos.nxt.SensorPort;
import lejos.nxt.addon.tetrix.TetrixMotorController;
import lejos.nxt.addon.tetrix.TetrixRegulatedMotor;
import lejos.nxt.addon.tetrix.TetrixControllerFactory;
import lejos.robotics.navigation.DifferentialPilot;

/** This is the  class StartUp
 *  Created by OneNationUnderCanadia
 *  To start the robot
 *
 *  Created on Feb 16, 2015 at 8:48:15 AM
 */

public class StartUp {

	private static TetrixControllerFactory cf;
	private static TetrixMotorController mc;

	public static void main(String[] args) {

		// TODO headlights

		cf = new TetrixControllerFactory(SensorPort.S1);
		mc = cf.newMotorController();

		TetrixRegulatedMotor motor1 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_1);
		TetrixRegulatedMotor motor2 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_2);
		DifferentialPilot pilot = new DifferentialPilot(7.5, 31.9, motor1, motor2);

		SqRoomExploration mapper = new SqRoomExploration(pilot, 60, 60);

	}

}

Put in numbers that are at least kinda right


/*
 * Copyright 2010 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.test.fixtures.file;

import org.junit.runners.model.FrameworkMethod;

import java.io.File;

/**
 * A JUnit rule which provides a unique temporary folder for the test.
 */
public class TestNameTestDirectoryProvider extends AbstractTestDirectoryProvider {
    static {
        // NOTE: the space in the directory name is intentional
        root = new TestFile(new File("build/tmp/test files"));
    }

    public static TestNameTestDirectoryProvider newInstance() {
        return new TestNameTestDirectoryProvider();
    }

    public static TestNameTestDirectoryProvider newInstance(FrameworkMethod method, Object target) {
        TestNameTestDirectoryProvider testDirectoryProvider = new TestNameTestDirectoryProvider();
        testDirectoryProvider.init(method.getName(), target.getClass().getSimpleName());
        return testDirectoryProvider;
    }
}

/*
 * Copyright 2010 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.test.fixtures.file;

import org.junit.runners.model.FrameworkMethod;

import java.io.File;

/**
 * A JUnit rule which provides a unique temporary folder for the test.
 */
public class TestNameTestDirectoryProvider extends AbstractTestDirectoryProvider {
    static {
        // NOTE: the space in the directory name is intentional
        root = new TestFile(new File("build/tmp/test files"));
    }

    public static TestNameTestDirectoryProvider newInstance() {
        return new TestNameTestDirectoryProvider();
    }

    public static TestNameTestDirectoryProvider newInstance(FrameworkMethod method, Object target) {
        TestNameTestDirectoryProvider testDirectoryProvider = new TestNameTestDirectoryProvider();
        testDirectoryProvider.init(method.getName(), target.getClass().getSimpleName());
        return testDirectoryProvider;
    }

    public TestNameTestDirectoryProvider withSuppressCleanup() {
        suppressCleanup();
        return this;
    }
}

Simplify keeping test temp files


package ca.ubc.cs411.abe;

public class If extends ABE {
    private ABE pred, conseq, altern;

    public If(ABE pred, ABE conseq, ABE altern) {
        if (pred.typeOf() != Type.BOOL) {
            throw new Error("If constructor passed a non-Bool predicate: " + pred);
        } else if (conseq.typeOf() != altern.typeOf()) {
            throw new Error("If constructor passed consequence and alternative expressions with different types: " + conseq + ", " + altern);
        }
        this.pred = pred;
        this.conseq = conseq;
        this.altern = altern;
    }

    @Override
    public Value interp() {
        if (pred.interp().toBool()) {
            return conseq.interp();
        }
        return altern.interp();
    }

    @Override
    public Type typeOf() {
        // Invariant: conseq and altern have the same type
        return conseq.typeOf();
    }

    @Override
    public String toString() {
        return "If(" + pred + "," + conseq + "," + altern + ")";
    }
}

package ca.ubc.cs411.abe;

public class If extends ABE {
    private ABE pred, conseq, altern;

    public If(ABE pred, ABE conseq, ABE altern) {
        this.pred = pred;
        this.conseq = conseq;
        this.altern = altern;
    }

    @Override
    public Value interp() {
        if (pred.interp().toBool()) {
            return conseq.interp();
        }
        return altern.interp();
    }

    @Override
    public Type typeOf() {
        if (pred.typeOf() != Type.BOOL) {
            throw new Error("If constructor passed a non-Bool predicate: " + pred);
        } else if (conseq.typeOf() != altern.typeOf()) {
            throw new Error("If constructor passed consequence and alternative expressions with different types: " + conseq + ", " + altern);
        }
        return conseq.typeOf();
    }

    @Override
    public String toString() {
        return "If(" + pred + "," + conseq + "," + altern + ")";
    }
}

Allow any ABE expressions to be used for predicate/consequence/alternative expressions, only throw type checking errors in typeOf


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

package org.opendaylight.controller.messagebus.app.impl;

import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;

public class TopicDOMNotification implements DOMNotification {

    private static final SchemaPath TOPIC_NOTIFICATION_ID = SchemaPath.create(true, TopicNotification.QNAME);
    private final ContainerNode body;

    public TopicDOMNotification(final ContainerNode body) {
        this.body = body;
    }

    @Override
    public SchemaPath getType() {
        return TOPIC_NOTIFICATION_ID;
    }

    @Override
    public ContainerNode getBody() {
        return body;
    }

    @Override
    public String toString() {
        return "TopicDOMNotification [body=" + body + "]";
    }
}

Fix license header violations in messagebus


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

import org.junit.runner.RunWith;
import org.xwiki.rendering.test.integration.RenderingTestSuite;

/**
 * Run all tests found in {@code *.test} files located in the classpath. These {@code *.test} files must follow
 * the conventions described in {@link org.xwiki.rendering.test.integration.TestDataParser}.
 *
 * @version $Id$
 * @since 4.1M1
 */
@RunWith(RenderingTestSuite.class)
public class IntegrationTests
{
}

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

import org.junit.runner.RunWith;
import org.xwiki.rendering.test.integration.RenderingTestSuite;

/**
 * Run all tests found in {@code *.test} files located in the classpath. These {@code *.test} files must follow the
 * conventions described in {@link org.xwiki.rendering.test.integration.TestDataParser}.
 *
 * @version $Id$
 * @since 4.1M1
 */
@RunWith(RenderingTestSuite.class)
public class IntegrationTests
{
}

Convert Pegdown AST to an XDOM instead of relying on the Pegdown HTML renderer * Misc formatting


package com.victorsima.uber.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by victorsima on 3/22/15.
 */
public class Driver {
    @Expose
    @SerializedName("phone_number")
    private String phoneNumber;
    @Expose
    @SerializedName("rating")
    private int rating;
    @Expose
    @SerializedName("picture_url")
    private String pictureUrl;
    @Expose
    @SerializedName("name")
    private String name;

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public String getPictureUrl() {
        return pictureUrl;
    }

    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }

    public String getName() {
        return name;
    }

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

package com.victorsima.uber.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by victorsima on 3/22/15.
 */
public class Driver {
    @Expose
    @SerializedName("phone_number")
    private String phoneNumber;
    @Expose
    @SerializedName("rating")
    private float rating;
    @Expose
    @SerializedName("picture_url")
    private String pictureUrl;
    @Expose
    @SerializedName("name")
    private String name;

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public float getRating() {
        return rating;
    }

    public void setRating(float rating) {
        this.rating = rating;
    }

    public String getPictureUrl() {
        return pictureUrl;
    }

    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }

    public String getName() {
        return name;
    }

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

Fix NumberFormatException when atempting to convert float to int in driver.rating


package org.ngrinder.infra.init;

import javax.annotation.PostConstruct;

import org.ngrinder.model.Role;
import org.ngrinder.model.User;
import org.ngrinder.user.repository.UserRepository;
import org.ngrinder.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DBInit {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserService userService;

	@PostConstruct
	@Transactional
	public void init() {
		createDefaultUserIfNecessary();
	}

	private void createDefaultUserIfNecessary() {
		// If there is no users.. make admin and user and U, S, A roles.
		if (userRepository.count() == 0) {
			User user = new User();
			user.setUserId("admin");
			user.setPassword("admin");
			user.setRole(Role.ADMIN);
			userService.saveUser(user);

			User user2 = new User();
			user2.setUserId("user");
			user2.setPassword("user");
			user2.setRole(Role.USER);
			userService.saveUser(user2);
		}
	}
}

package org.ngrinder.infra.init;

import javax.annotation.PostConstruct;

import org.ngrinder.model.Role;
import org.ngrinder.model.User;
import org.ngrinder.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DBInit {
	@Autowired
	private UserRepository userRepository;

	@PostConstruct
	@Transactional
	public void init() {
		createDefaultUserIfNecessary();
	}

	private void createDefaultUserIfNecessary() {
		// If there is no users.. make admin and user and U, S, A roles.
		if (userRepository.count() == 0) {
			User user = new User();
			user.setUserId("admin");
			user.setPassword("admin");
			user.setRole(Role.ADMIN);
			userRepository.save(user);

			User user2 = new User();
			user2.setUserId("user");
			user2.setPassword("user");
			user2.setRole(Role.USER);
			userRepository.save(user2);
		}
	}
}

Add default user if there is no user in db. If we use userService to save, The ModelAspect will work to get current user from context and set it as created user. But at this time, there is no user in context because not logging in.


package net.exkazuu;

import java.io.IOException;

public class GitManager {
	private static GitManager gm;
	private Runtime rt;
	private GitManager() {
		rt = Runtime.getRuntime();
	}

	public static GitManager getInstance() {
		if(gm == null) {
			gm = new GitManager();
		}
		return gm;
	}

	public void clone(String address, String name) {
		String command = "git clone " + address;
		try {
			rt.exec(command);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Boolean test() {
		String command = "mvn test";
		try {
			rt.exec(command);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}

	public void stop() {
		try {
			Thread.sleep(300000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

package net.exkazuu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GitManager {
	private static GitManager gm;
	private Runtime rt;
	private GitManager() {
		rt = Runtime.getRuntime();
	}

	public static GitManager getInstance() {
		if(gm == null) {
			gm = new GitManager();
		}
		return gm;
	}

	public void clone(String address, String name) {
		String command = ("git clone " + address + " C:/" + name);
		try {
			rt.exec(command);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Boolean test(String name) {
		String command = "mvn test C:/" + name;
		try {
			Process p =rt.exec(command);
			InputStream is = p.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);

			String res;
			Boolean flag = false;
			while((res = br.readLine()) != null) {
				if(res.contains("SUCCESSFULL")) {
					flag = true;
				}
			}

			if(flag) {
				System.out.println(name);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}

	public void stop() {
		try {
			Thread.sleep(300000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Create new class for using git and maven.


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.hibernate.repositories;

import com.codeup.movies.Movie;
import com.codeup.movies.Movies;
import org.hibernate.Session;
import org.hibernate.query.Query;

import java.util.List;

public class MoviesRepository implements Movies {
    private final Session session;

    public MoviesRepository(Session session) {
        this.session = session;
    }

    public void add(Movie movie) {
        session.beginTransaction();
        session.save(movie);
        session.getTransaction().commit();
    }

    public Movie with(int id) {
        Query query = session.createQuery("FROM Movie WHERE id = ?");
        query.setParameter(0, id);

        return (Movie) query.uniqueResult();
    }

    @Override
    public List<Movie> withTitleSimilarTo(String title) {
        Query query = session.createQuery("FROM Movie WHERE title LIKE ?");
        query.setParameter(0, title);

        @SuppressWarnings("unchecked")
        List movies = query.getResultList();

        return movies;
    }
}

/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.hibernate.repositories;

import com.codeup.movies.Movie;
import com.codeup.movies.Movies;
import org.hibernate.Session;
import org.hibernate.query.Query;

import java.util.List;

public class MoviesRepository implements Movies {
    private final Session session;

    public MoviesRepository(Session session) {
        this.session = session;
    }

    public void add(Movie movie) {
        session.beginTransaction();
        session.save(movie);
        session.getTransaction().commit();
    }

    public Movie with(int id) {
        Query query = session.createQuery("FROM Movie WHERE id = ?");
        query.setParameter(0, id);

        return (Movie) query.uniqueResult();
    }

    @Override
    public List<Movie> withTitleSimilarTo(String title) {
        Query query = session.createQuery("FROM Movie WHERE title LIKE ?");
        query.setParameter(0, "%" + title + "%");

        @SuppressWarnings("unchecked")
        List movies = query.getResultList();

        return movies;
    }
}

Fix error in query parameter.


package net.elprespufferfish.rssreader;

import android.support.v4.view.ViewPager;

/**
 * Handles marking articles as read
 */
public class ArticleReadListener implements ViewPager.OnPageChangeListener {

    private final ArticlePagerAdapter articlePagerAdapter;
    private int lastPosition = 0;

    public ArticleReadListener(ArticlePagerAdapter articlePagerAdapter) {
        this.articlePagerAdapter = articlePagerAdapter;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // unused
    }

    @Override
    public void onPageSelected(int position) {
        ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(lastPosition);
        Article article = articleFragment.getArguments().getParcelable(ArticleFragment.ARTICLE_KEY);
        Feeds.getInstance().markArticleRead(article);

        lastPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // unused
    }

}

package net.elprespufferfish.rssreader;

import android.support.v4.view.ViewPager;

/**
 * Handles marking articles as read
 */
public class ArticleReadListener implements ViewPager.OnPageChangeListener {

    private final ArticlePagerAdapter articlePagerAdapter;

    public ArticleReadListener(ArticlePagerAdapter articlePagerAdapter) {
        this.articlePagerAdapter = articlePagerAdapter;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // unused
    }

    @Override
    public void onPageSelected(int position) {
        ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(position);
        Article article = articleFragment.getArguments().getParcelable(ArticleFragment.ARTICLE_KEY);
        Feeds.getInstance().markArticleRead(article);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // unused
    }

}

Mark article read as it comes into view, rather than when it leaves


/*
 * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;

import io.github.bonigarcia.wdm.PhantomJsDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;

/**
 * Test asserting PhatomJS versions.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
public class PhantomJsVersionTest extends BaseVersionTst {

	@Before
	public void setup() {
		browserManager = PhantomJsDriverManager.getInstance();
		specificVersions = new String[] { "1.9.7", "1.9.8", "2.1.1" };
	}

}

/*
 * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;

import io.github.bonigarcia.wdm.PhantomJsDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;

/**
 * Test asserting PhatomJS versions.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
public class PhantomJsVersionTest extends BaseVersionTst {

	@Before
	public void setup() {
		browserManager = PhantomJsDriverManager.getInstance();
		specificVersions = new String[] { "1.9.7", "1.9.8", "2.1.1", "2.5.0" };
	}

}

Include version 2.5.0 in PhantomJs test for versions


package org.obda.query.domain;

/**
 * This class defines a type of {@link Term} in which it expresses a relation
 * to one or more other variables in terms of which it may be expressed or on
 * which its value depends.
 */
public interface Function extends Term {

}

package org.obda.query.domain;

import java.util.List;

/**
 * This class defines a type of {@link Term} in which it denotes a mapping of
 * one or more elements in a set (called the domain of the function) into a
 * unique element of another set (the range of the function).
 *

 * A function expression is a function symbol followed by its arguments.
 * The arguments are elements from the domain of the function; the number of
 * arguments is equal to the {@code arity} of the function. The arguments are
 * enclosed in parentheses and separated by commas, e.g.,
 *

 *
 * f(X,Y)

 * father(david)

 * price(apple)

 *
 *

 * are all well-formed function expressions.
 */
public interface Function extends Term {

	/**
	 * Get a list of terms (or arguments) that are contained in the function
	 * symbol.
	 *
	 * @return a list of terms.
	 */
	public List<Term> getTerms();

	/**
	 * Get the number of terms (or arguments) in the function symbol.
	 * @return
	 */
	public int getArity();
}

Add new abstract methods: getTerms() and getArity(). Also, there is a bit modification to the class description.


package editor.util;

import java.util.function.Supplier;

/**
 * This class "lazily" supplies a value by not evaluating it until the first time
 * it is requested.  Then that function's result is cached so it doesn't have to
 * be reevaluated again.
 *
 * @param <T> Type of object that is being lazily evaluated
 * @author Alec Roelke
 */
public class Lazy<T> implements Supplier<T>
{

    /**
     * Cached value.
     */
    private T value;

    /**
     * Supplier for the cached value.
     */
    private Supplier<T> supplier;

    /**
     * Create a new Lazy supplier.
     *
     * @param val Function supplying the value to lazily evaluate.
     */
    public Lazy(Supplier<T> val)
    {
        value = null;
        supplier = val;
    }

    /**
     * If the value has not been computed, compute it and then return it.  Otherwise,
     * just return it.
     *
     * @return The value computed by the function
     */
    @Override
    public T get()
    {
        if (value == null)
            value = supplier.get();
        return value;
    }
}

package editor.util;

import java.util.function.Supplier;

/**
 * This class "lazily" supplies a value by not evaluating it until the first time
 * it is requested.  Then that function's result is cached so it doesn't have to
 * be reevaluated again.
 *
 * @param <T> Type of object that is being lazily evaluated
 * @author Alec Roelke
 */
public class Lazy<T> implements Supplier<T>
{

    /**
     * Cached value.
     */
    private T value;

    /**
     * Supplier for the cached value.
     */
    private Supplier<T> supplier;

    /**
     * Create a new Lazy supplier.
     *
     * @param val Function supplying the value to lazily evaluate.
     */
    public Lazy(Supplier<T> val)
    {
        value = null;
        supplier = val;
    }

    /**
     * If the value has not been computed, compute it and then return it.  Otherwise,
     * just return it.
     *
     * @return The value computed by the function
     */
    @Override
    public T get()
    {
        if (value == null)
        {
            value = supplier.get();
            supplier = null;
        }
        return value;
    }
}

Discard supplier after it's used


package controllers.crawlers;

import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;

import java.io.IOException;
import java.security.GeneralSecurityException;

public class Google extends Controller {
    private crawlers.google.Google crawler;

    public Google() throws GeneralSecurityException, IOException {
        crawler = new crawlers.google.Google();
    }

    public Result redirectToGoogle() {
        return redirect(crawler.getAuthorizationUrl());
    }

    @Transactional
    public Result authenticated() throws IOException {
        return ok("Processed " + crawler.processPeople(request().getQueryString("code")) + " people");
    }
}

package controllers.crawlers;

import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;

import java.io.IOException;
import java.security.GeneralSecurityException;

public class Google extends Controller {
    private crawlers.google.Google crawler;

    public Google() throws GeneralSecurityException, IOException {
        crawler = new crawlers.google.Google();
    }

    public Result redirectToGoogle() {
        return redirect(crawler.getAuthorizationUrl());
    }

    @Transactional
    public Result authenticated() throws IOException {
        flash("success", "Processed " + crawler.processPeople(request().getQueryString("code")) + " people");
        return redirect(controllers.people.routes.People.get());
    }
}

Use nicer "Processing succeeded" message


package me.prettyprint.cassandra.connection;

public class NullOpTimer implements HOpTimer {

  @Override
  public Object start() {
    return this;
  }

  @Override
  public void stop(Object token, String tagName, boolean success) {
  }

}

package me.prettyprint.cassandra.connection;

import java.io.Serializable;

public class NullOpTimer implements HOpTimer, Serializable {

  private static final long serialVersionUID = -4762728985083933452L;

  @Override
  public Object start() {
    return this;
  }

  @Override
  public void stop(Object token, String tagName, boolean success) {
  }

}

Make default OpTimer serializable and fix build


package nl.tudelft.dnainator.ui;

import nl.tudelft.dnainator.graph.DNAGraph;
import nl.tudelft.dnainator.graph.DNALayout;

import org.graphstream.graph.Graph;
import org.graphstream.ui.layout.Layout;
import org.graphstream.ui.view.Viewer;

/**
 * The viewer is responsible for managing the interactable views of the the strain graph.
 * Use the addDefaultView() method to obtain a view.
 */
public class DNAViewer extends Viewer {
	/**
	 * Creates a new GraphViewer, with a default graph
	 * and ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
	 */
	public DNAViewer() {
		this(new DNAGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
	}

	/**
	 * Creates a new GraphViewer, with ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
	 * @param graph The graph of strains.
	 */
	public DNAViewer(Graph graph) {
		this(graph, ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
	}

	/**
	 * Creates a new GraphViewer.
	 * @param graph	The graph of strains.
	 * @param model	The ThreadingModel to use.
	 */
	public DNAViewer(Graph graph, ThreadingModel model) {
		super(graph, model);

		Layout layout = new DNALayout(graph);
		this.enableAutoLayout(layout);
		this.setCloseFramePolicy(Viewer.CloseFramePolicy.EXIT);
	}
}

package nl.tudelft.dnainator.ui;

import nl.tudelft.dnainator.graph.DNAGraph;

import org.graphstream.graph.Graph;
import org.graphstream.ui.view.Viewer;

/**
 * The viewer is responsible for managing the interactable views of the the strain graph.
 * Use the addDefaultView() method to obtain a view.
 */
public class DNAViewer extends Viewer {
	/**
	 * Creates a new GraphViewer, with a default graph
	 * and ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
	 */
	public DNAViewer() {
		this(new DNAGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
	}

	/**
	 * Creates a new GraphViewer, with ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
	 * @param graph The graph of strains.
	 */
	public DNAViewer(Graph graph) {
		this(graph, ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
	}

	/**
	 * Creates a new GraphViewer.
	 * @param graph	The graph of strains.
	 * @param model	The ThreadingModel to use.
	 */
	public DNAViewer(Graph graph, ThreadingModel model) {
		super(graph, model);

		this.enableAutoLayout();
		this.setCloseFramePolicy(Viewer.CloseFramePolicy.EXIT);
	}
}

Remove tree layout, use default layout instead.