package me.eddiep.lifxbulb.rave.system;

import com.github.besherman.lifx.LFXHSBKColor;
import com.github.besherman.lifx.LFXLight;

import java.awt.*;

public class LightHolder {
    private LFXLight light;
    private Color originalColor;
    private int r, g, b;
    private int kelvin;

    public LightHolder(LFXLight light) {
        this.light = light;

        LFXHSBKColor color = light.getColor();
        this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness());

        this.r = originalColor.getRed();
        this.g = originalColor.getGreen();
        this.b = originalColor.getBlue();
        this.kelvin = color.getKelvin();
    }

    public void raveWithValue(float num) {
        int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255);

        Color color = new Color(newR, newG, newB);
        light.setColor(new LFXHSBKColor(color, kelvin));
    }
}

package me.eddiep.lifxbulb.rave.system;

import com.github.besherman.lifx.LFXHSBKColor;
import com.github.besherman.lifx.LFXLight;

import java.awt.*;

public class LightHolder {
    private LFXLight light;
    private Color originalColor;
    private int r, g, b;
    private int kelvin;

    public LightHolder(LFXLight light) {
        this.light = light;

        LFXHSBKColor color = light.getColor();
        this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness());

        this.r = originalColor.getRed();
        this.g = originalColor.getGreen();
        this.b = originalColor.getBlue();
        this.kelvin = color.getKelvin();
    }

    public void raveWithValue(float num) {
        int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255);

        Color color = new Color(newR, newG, newB);
        light.setColor(new LFXHSBKColor(color, kelvin), 1);
    }
}

Set fade duration to 1

Set fade duration to 1


package com.ebudgie;

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

import com.facebook.react.ReactApplication;
import io.underscope.react.fbak.RNAccountKitPackage;
import com.cboy.rn.splashscreen.SplashScreenReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNAccountKitPackage(),
            new SplashScreenReactPackage(),
            new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

package com.ebudgie;

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

import com.facebook.react.ReactApplication;
import io.underscope.react.fbak.RNAccountKitPackage;
import com.cboy.rn.splashscreen.SplashScreenReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.modules.storage.ReactDatabaseSupplier;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      long size = 100L * 1024L * 1024L; // 100 MB
      ReactDatabaseSupplier.getInstance(getApplicationContext()).setMaximumSize(size);

      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNAccountKitPackage(),
            new SplashScreenReactPackage(),
            new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

Increase the AsyncStorage capacity fromm 5mb to 100mb


package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }
}

package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;
    @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }

    @NonNull
    public List<ImageSrcSet> getSrcSets() {
        return srcSets != null ? srcSets : Collections.emptyList();
    }

    public class ImageSrcSet implements Serializable {
        @Nullable private String src;
        @Nullable private String scale;

        @Nullable
        public String getSrc() {
            return src;
        }

        @Nullable
        public String getScale() {
            return scale;
        }
    }
}

Add src set data class for media-list endpoint


package org.clafer.ir;

import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrAddTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
        return equal(add(is), sum);
    }

    @Solution
    public Constraint setup(IntVar[] is, IntVar sum) {
        return ICF.sum(is, sum);
    }
}

package org.clafer.ir;

import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrAddTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
        return equal(add(is), sum);
    }

    @Solution
    public Constraint setup(IntVar[] is, IntVar sum) {
        return is.length > 0 ? ICF.sum(is, sum) : ICF.arithm(sum, "=", 0);
    }
}

Fix test for empty summation.

Fix test for empty summation.


//
// $Id$

package playn.java;

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

import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;

/**
 * Tests various JavaImage behavior.
 */
public class JavaImageTest extends AbstractPlayNTest {

  @Test
  public void testMissingImage() {
    final StringBuilder buf = new StringBuilder();
    PlayN.log().setCollector(new Log.Collector() {
      public void logged(Log.Level level, String msg, Throwable cause) {
        buf.append(msg).append("\n");
      }
    });

    Image missing;
    try {
      missing = PlayN.assets().getImage("missing.png");
    } finally {
      PlayN.log().setCollector(null);
    }

    assertNotNull(missing);

    // ensure that width/height do not NPE
    missing.width();
    missing.height();

    // TODO: depending on the error text is somewhat fragile, but I want to be sure that a
    // reasonably appropriate error was logged
    String errlog = buf.toString();
    assertTrue(errlog.startsWith("Could not load image"));
    assertTrue(errlog.contains("missing.png"));

  }
}

//
// $Id$

package playn.java;

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

import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;

/**
 * Tests various JavaImage behavior.
 */
public class JavaImageTest extends AbstractPlayNTest {

  @Test
  public void testMissingImage() {
    final StringBuilder buf = new StringBuilder();
    PlayN.log().setCollector(new Log.Collector() {
      public void logged(Log.Level level, String msg, Throwable cause) {
        buf.append(msg).append("\n");
      }
    });

    Image missing;
    try {
      missing = PlayN.assets().getImageSync("missing.png");
    } finally {
      PlayN.log().setCollector(null);
    }

    assertNotNull(missing);

    // ensure that width/height do not NPE
    missing.width();
    missing.height();

    // TODO: depending on the error text is somewhat fragile, but I want to be sure that a
    // reasonably appropriate error was logged
    String errlog = buf.toString();
    assertTrue(errlog + " must contain 'Could not load image'",
               errlog.startsWith("Could not load image"));
    assertTrue(errlog + " must contain 'missing.png'",
               errlog.contains("missing.png"));
  }
}

Load the missing image synchronously, improve assert error messages.

We need to load sync so that the error is logged while our log collector is in
place. Yay testing.


package de.cketti.matelight;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MateLight {
    private static final String HOST = "matelight.cbrp3.c-base.org";
    private static final int PORT = 1337;
    private static final String SUCCESS = "KTHXBYE!";
    private static final int TIMEOUT = 60 * 1000;

    private Socket mSocket;

    public void sendMessage(String message) throws IOException {
        mSocket = new Socket();
        mSocket.connect(new InetSocketAddress(HOST, PORT));
        try {
            OutputStream out = mSocket.getOutputStream();
            try {
                mSocket.setSoTimeout(TIMEOUT);

                out.write(message.getBytes());
                out.write('\n');
                out.flush();

                InputStream in = mSocket.getInputStream();
                try {
                    BufferedReader buf = new BufferedReader(new InputStreamReader(in));
                    String response = buf.readLine();

                    if (!SUCCESS.equals(response)) {
                        throw new RuntimeException("No success message from server");
                    }
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        } finally {
            mSocket.close();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

package de.cketti.matelight;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MateLight {
    private static final String HOST = "ml.jaseg.net";
    private static final int PORT = 1337;
    private static final String SUCCESS = "KTHXBYE!";
    private static final int TIMEOUT = 60 * 1000;

    private Socket mSocket;

    public void sendMessage(String message) throws IOException {
        mSocket = new Socket();
        mSocket.connect(new InetSocketAddress(HOST, PORT));
        try {
            OutputStream out = mSocket.getOutputStream();
            try {
                mSocket.setSoTimeout(TIMEOUT);

                out.write(message.getBytes());
                out.write('\n');
                out.flush();

                InputStream in = mSocket.getInputStream();
                try {
                    BufferedReader buf = new BufferedReader(new InputStreamReader(in));
                    String response = buf.readLine();

                    if (!SUCCESS.equals(response)) {
                        throw new RuntimeException("No success message from server");
                    }
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        } finally {
            mSocket.close();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

Change host name to ml.jaseg.net

Change host name to ml.jaseg.net


package fp.grados.tipos;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AlumnoImpl2 extends AlumnoImpl implements Alumno {

	public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){
		super(DNI, nombre, apellidos, fecha, email);
	}

	public AlumnoImpl2(String s) {
		super(s);
	}

	@Override
	public Integer getCurso() {
		Integer res = 0;
		Stream<Asignatura> stream = this.getAsignaturas().stream();
		Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso));
		if(opt.isPresent()) {
			res = opt.get().getCurso();
		}

		return res;
	}

	public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() {
		return this.getExpediente().getNotas().stream().collect(Collectors.toMap(Nota::getAsignatura, Nota::getCalificacion, (p1, p2) -> p1, TreeMap::new));
	}
}

package fp.grados.tipos;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AlumnoImpl2 extends AlumnoImpl implements Alumno {

	public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){
		super(DNI, nombre, apellidos, fecha, email);
	}

	public AlumnoImpl2(String s) {
		super(s);
	}

	@Override
	public Integer getCurso() {
		Integer res = 0;
		Stream<Asignatura> stream = this.getAsignaturas().stream();
		Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso));
		if(opt.isPresent()) {
			res = opt.get().getCurso();
		}

		return res;
	}

	public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() {
		Map<Asignatura, Calificacion> res = getExpediente().getNotas().stream().collect(Collectors.toMap(n -> n.getAsignatura(), n -> n.getCalificacion(), (p1, p2)->calificacionMayor(p1, p2)));
		return new TreeMap<Asignatura, Calificacion>(res);
	}

	private Calificacion calificacionMayor(Calificacion c1, Calificacion c2) {
		if (c1.compareTo(c2) >= 0) {
			return c1;
		} else {
			return c2;
		}
	}

}

Fix ALL failures in Java

Fix ALL failures in Java


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/location")
public class LocationServlet extends HttpServlet {
    private Double latitude = 0.0;
    private Double longitude = 0.0;
    private final String BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
    private final String API_KEY = ""; // Insert actual API key to test.

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {

    }

}

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/location")
public class LocationServlet extends HttpServlet {
    private double latitude = 0.0;
    private double longitude = 0.0;
    private final String BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
    private final String API_KEY = ""; // Insert actual API key to test.

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
      String queryParam = String.format("latlng=%1$f,%2$f", latitude, longitude);
      String apiKeyParam = String.format("&key=%s", API_KEY);
      String fullPath = BASE_URL + queryParam + apiKeyParam;
      try {
        URL url = new URL(queryPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
          String json = getJson(url);
          System.out.println(json); // test
        } else {
          System.out.println("Error: connection response code is: " + responseCode);
        }
      } catch(Exception e) {
        e.printStackTrace();
     }
    }

    public void getJson() {
      // TODO: implement this method.
    }

}

Implement doGet for location servlet (not yet tested.


package com.coreoz.plume.file.services.cache;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import javax.inject.Singleton;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Singleton
public class FileCacheServiceGuava implements FileCacheService {

	@Override
	public LoadingCache<Long, CachedFile> newCache(Function<Long, CachedFile> loadingData) {
		return CacheBuilder
			.newBuilder()
			.expireAfterWrite(1, TimeUnit.HOURS)
			.maximumSize(100)
			.build(CacheLoader.from(loadingData::apply));
	}

}

package com.coreoz.plume.file.services.cache;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import javax.inject.Singleton;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Singleton
public class FileCacheServiceGuava implements FileCacheService {

	@Override
	public LoadingCache<Long, CachedFile> newCache(Function<Long, CachedFile> loadingData) {
		return CacheBuilder
			.newBuilder()
			.expireAfterAccess(1, TimeUnit.DAYS)
			.maximumSize(100)
			.build(CacheLoader.from(loadingData::apply));
	}

}

Remove only unused files from cache

Remove only unused files from cache


/*
 * Author:  Filip Dvořák <filip.dvorak@runbox.com>
 *
 * Copyright (c) 2013 Filip Dvořák <filip.dvorak@runbox.com>, all rights reserved
 *
 * Publishing, providing further or using this program is prohibited
 * without previous written permission of the author. Publishing or providing
 * further the contents of this file is prohibited without previous written
 * permission of the author.
 */
package fape.scripting;

import fape.core.planning.Planner;
import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author FD
 */
public class Exp1 extends ExperimentRunner {

    public static void main(String[] args) throws InterruptedException {
        run("C:/ROOT/PROJECTS/fape/FAPE/problems/generated");
    }

}

/*
 * Author:  Filip Dvořák <filip.dvorak@runbox.com>
 *
 * Copyright (c) 2013 Filip Dvořák <filip.dvorak@runbox.com>, all rights reserved
 *
 * Publishing, providing further or using this program is prohibited
 * without previous written permission of the author. Publishing or providing
 * further the contents of this file is prohibited without previous written
 * permission of the author.
 */
package fape.scripting;

import fape.core.planning.Planner;
import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author FD
 */
public class Exp1 extends ExperimentRunner {

    public static void main(String[] args) throws InterruptedException {
        run("problems/generated");
    }

}

Make the problems/generated directory usage relative


package org.slc.sli.util;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import org.slc.sli.security.SLIPrincipal;

/**
 * Class, which allows user to access security context
 * @author svankina
 *
 */
public class SecurityUtil {

    public static UserDetails getPrincipal() {
        return  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static String getToken() {
        UserDetails user = getPrincipal();
        if (user instanceof SLIPrincipal) {
            return ((SLIPrincipal) user).getId();
        }

        return null;
    }

}

package org.slc.sli.util;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import org.slc.sli.security.SLIPrincipal;

/**
 * Class, which allows user to access security context
 * @author svankina
 *
 */
public class SecurityUtil {

    public static UserDetails getPrincipal() {
        return  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static String getToken() {
        UserDetails user = getPrincipal();
        if (user instanceof SLIPrincipal) {
            return ((SLIPrincipal) user).getId();
        } else {
            // gets here in mock server mode
            return user.getUsername();
        }
    }

}

Make security util to work for mock dashboard server mode.


package com.fasterxml.sort.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.BlockingQueue;

import com.fasterxml.sort.DataReader;

/**
 * Base implementation for {@link DataReader} that uses a
 * {@link BlockingQueue} for getting input.
 * The only missing part is implementation for
 * {@link #estimateSizeInBytes(Object)}, since there is no way
 * to provide a meaningful estimate without knowing object type.
 */
public abstract class BlockingQueueReader<E>
    extends DataReader<E>
{
    protected final BlockingQueue<E> _queue;

    public BlockingQueueReader(BlockingQueue<E> q) {
        _queue = q;
    }

    @Override
    public void close() throws IOException {
        // no-op
    }

    @Override
    public abstract int estimateSizeInBytes(E item);

    @Override
    public E readNext() throws IOException {
        try {
            return _queue.take();
        } catch (InterruptedException e) {
            InterruptedIOException ie = new InterruptedIOException();
            ie.initCause(e);
            throw ie;
        }
    }

}

package com.fasterxml.sort.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.BlockingQueue;

import com.fasterxml.sort.DataReader;

/**
 * Base implementation for {@link DataReader} that uses a
 * {@link BlockingQueue} for getting input.
 * The only missing part is implementation for
 * {@link #estimateSizeInBytes(Object)}, since there is no way
 * to provide a meaningful estimate without knowing object type.
 */
public abstract class BlockingQueueReader<E>
    extends DataReader<E>
{
    protected final BlockingQueue<E> _queue;

    protected final E _endMarker;

    protected boolean _closed;

    @Deprecated
    public BlockingQueueReader(BlockingQueue<E> q) {
        this(q, null);
    }

    /**
     * @param q Queue to read entries from
     * @param endMarker Value that is used to signal end-of-input; when this value
     *   is gotten from queue, reader assumes that no more input is coming and
     *   will return null from {@link #readNext}.
     */
    public BlockingQueueReader(BlockingQueue<E> q, E endMarker) {
        _queue = q;
        _endMarker = endMarker;
    }

    @Override
    public void close() throws IOException {
        _closed = true;
    }

    @Override
    public abstract int estimateSizeInBytes(E item);

    @Override
    public E readNext() throws IOException {
        if (_closed) {
            return null;
        }
        try {
            E value = _queue.take();
            if (value == _endMarker) {
                _closed = true;
                return null;
            }
            return value;
        } catch (InterruptedException e) {
            InterruptedIOException ie = new InterruptedIOException();
            ie.initCause(e);
            throw ie;
        }
    }
}

Add support for end-marker token

Add support for end-marker token


package net.darkmist.alib.generics;

public class GenericFudge
{
	@SuppressWarnings("unchecked")
	static public <T> Class<? extends T> getClass(T obj)
	{
		return (Class<? extends T>)obj.getClass();
	}
}

package net.darkmist.alib.generics;

import java.util.Map;

/**
 * Static methods to get around issues with generics...
 */
@SuppressWarnings("unchecked")
public class GenericFudge
{
	/** Only static methods. */
	private GenericFudge()
	{
	}

	/**
	 * Fudge the return from getClass to include the generic.
	 */
	static public <T> Class<? extends T> getClass(T obj)
	{
		return (Class<? extends T>)obj.getClass();
	}

	/**
	 * Fudge a ungenericified map to be one.
	 */
	static public <K,V> Map<K,V> map(Map map)
	{
		return map;
	}
}

Add method to allow ungenericed map to genericed map fudge


package fi.evident.apina.model.settings;

import fi.evident.apina.utils.PatternSet;

import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Collections.unmodifiableCollection;

/**
 * Various settings guiding the translation.
 */
public final class TranslationSettings {

    public final PatternSet blackBoxClasses = new PatternSet();
    private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
    private final Set<String> importedTypes = new TreeSet<>();

    public boolean isBlackBoxClass(String name) {
        return blackBoxClasses.test(name);
    }

    public void addImport(String typeName, String moduleName) {
        if (!importedTypes.add(typeName))
            throw new IllegalArgumentException("type " + typeName + " is already imported");

        importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
    }

    public Collection<ImportDefinition> getImports() {
        return unmodifiableCollection(importsByModule.values());
    }

    public boolean isImported(String typeName) {
        return importedTypes.contains(typeName);
    }
}

package fi.evident.apina.model.settings;

import fi.evident.apina.utils.PatternSet;

import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Collections.unmodifiableCollection;

/**
 * Various settings guiding the translation.
 */
public final class TranslationSettings {

    public final PatternSet blackBoxClasses = new PatternSet();
    private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
    private final Set<String> importedTypes = new TreeSet<>();

    public boolean isBlackBoxClass(String name) {
        return blackBoxClasses.test(name);
    }

    public void addImport(String moduleName, Collection<String> types) {
        ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);

        for (String type : types) {
            if (!importedTypes.add(type))
                throw new IllegalArgumentException("type " + type + " is already imported");

            importDefinition.addType(type);
        }
    }

    public Collection<ImportDefinition> getImports() {
        return unmodifiableCollection(importsByModule.values());
    }

    public boolean isImported(String typeName) {
        return importedTypes.contains(typeName);
    }
}

Allow multiple types to be imported with single call

Since both the command line client and the Gradle task support
specifying multiple imports from a module with a shorthand syntax, it
makes things simpler for callers to allow passing multiple types in a
single addImport-call.


package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.GenericsPlugin;
import com.jcwhatever.bukkit.musical.commands.CommandHandler;
import com.jcwhatever.bukkit.musical.regions.RegionManager;
import org.bukkit.ChatColor;

public class MusicalRegions extends GenericsPlugin {

	private static MusicalRegions _instance;

	private RegionManager _regionManager;

	public static MusicalRegions getInstance() {
		return _instance;
	}

	public MusicalRegions() {
		super();
	}

	@Override
	protected void init() {
		_instance = this;
	}

    @Override
	public String getChatPrefix() {
		return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET;
	}

	@Override
	public String getConsolePrefix() {
		return "[Music] ";
	}

	public RegionManager getRegionManager() {
		return _regionManager;
	}

    @Override
    protected void onEnablePlugin() {
        registerCommands(new CommandHandler());
        registerEventListeners(new EventListener());

        _regionManager = new RegionManager(this.getSettings().getNode("regions"));
    }

    @Override
    protected void onDisablePlugin() {

    }

}

package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.GenericsPlugin;
import com.jcwhatever.bukkit.musical.commands.CommandHandler;
import com.jcwhatever.bukkit.musical.regions.RegionManager;
import org.bukkit.ChatColor;

public class MusicalRegions extends GenericsPlugin {

	private static MusicalRegions _instance;

	private RegionManager _regionManager;

	public static MusicalRegions getInstance() {
		return _instance;
	}

	public MusicalRegions() {
		super();
	}

	@Override
	protected void init() {
		_instance = this;
	}

    @Override
	public String getChatPrefix() {
		return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET;
	}

	@Override
	public String getConsolePrefix() {
		return "[Music] ";
	}

	public RegionManager getRegionManager() {
		return _regionManager;
	}

    @Override
    protected void onEnablePlugin() {
        registerCommands(new CommandHandler());
        registerEventListeners(new EventListener());

        _regionManager = new RegionManager(this.getDataNode().getNode("regions"));
    }

    @Override
    protected void onDisablePlugin() {

    }

}

Add comments to GenericsPlugin, refactor GenericsPlugin.getSettings to getDataNode


package uk.ac.ebi.quickgo.ontology.traversal.read;

/**
 * Enumeration representing the columns of the relationship source files.
 *
 * CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE
 *
 * Created 18/05/16
 * @author Edd
 */
public enum Columns {
    COLUMN_CHILD(0, "child"),
    COLUMN_PARENT(1, "parent"),
    COLUMN_RELATIONSHIP(2,"relationship");

    private int position;
    private String columnName;

    Columns(int position, String columnName) {
        this.position = position;
        this.columnName = columnName;
    }

    public int getPosition() {
        return position;
    }

    public String getName() {
        return columnName;
    }

    public static int numColumns() {
        return Columns.values().length;
    }
}

package uk.ac.ebi.quickgo.ontology.traversal.read;

/**
 * Enumeration representing the columns of the relationship source files.
 *
 * Columns: CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE
 *
 * Created 18/05/16
 * @author Edd
 */
public enum Columns {
    COLUMN_CHILD(0, "child"),
    COLUMN_PARENT(1, "parent"),
    COLUMN_RELATIONSHIP(2,"relationship");

    private int position;
    private String columnName;

    Columns(int position, String columnName) {
        this.position = position;
        this.columnName = columnName;
    }

    public int getPosition() {
        return position;
    }

    public String getName() {
        return columnName;
    }

    public static int numColumns() {
        return Columns.values().length;
    }
}

Clarify comments for columns of the ontology relations datafiles


package com.google.maps.android.data.kml;

import com.google.maps.android.data.Geometry;

import java.util.ArrayList;

/**
 * Created by thorin on 22/02/2017.
 */

public class KmlMultiTrack extends KmlMultiGeometry {
    /**
     * Creates a new MultiGeometry object
     *
     * @param tracks array of KmlTrack objects contained in the MultiGeometry
     */
    public KmlMultiTrack(ArrayList<KmlTrack> tracks) {
        super(createGeometries(tracks));
    }

    private static ArrayList<Geometry> createGeometries(ArrayList<KmlTrack> tracks) {
        ArrayList <Geometry> geometries = new ArrayList<>();

        for (KmlTrack track : tracks) {
            geometries.add(track);
        }

        return geometries;
    }
}

package com.google.maps.android.data.kml;

import com.google.maps.android.data.Geometry;

import java.util.ArrayList;

/**
 * Created by thorin on 22/02/2017.
 */

public class KmlMultiTrack extends KmlMultiGeometry {
    /**
     * Creates a new MultiGeometry object
     *
     * @param tracks array of KmlTrack objects contained in the MultiGeometry
     */
    public KmlMultiTrack(ArrayList<KmlTrack> tracks) {
        super(createGeometries(tracks));
    }

    private static ArrayList<Geometry> createGeometries(ArrayList<KmlTrack> tracks) {
        ArrayList <Geometry> geometries = new ArrayList<>();

        if (tracks == null) {
            throw new IllegalArgumentException("Tracks cannot be null");
        }

        for (KmlTrack track : tracks) {
            geometries.add(track);
        }

        return geometries;
    }
}

Throw IllegalArgumentException if constructor is called with a null argument


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

BREAK BUILD

/**
 * Interface implemented by components that can be named, such as via configuration, and wish to have that name
 * set once it has been configured.
 *
 * @author Les Hazlewood
 * @since 0.9
 */
public interface Nameable {

    /**
     * Sets the (preferably application unique) name for this component.
     * @param name the preferably application unique name for this component.
     */
    void setName(String name);
}

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

/**
 * Interface implemented by components that can be named, such as via configuration, and wish to have that name
 * set once it has been configured.
 *
 * @author Les Hazlewood
 * @since 0.9
 */
public interface Nameable {

    /**
     * Sets the (preferably application unique) name for this component.
     * @param name the preferably application unique name for this component.
     */
    void setName(String name);
}

Fix the build to test Hudson

Fix the build to test Hudson

git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736937 13f79535-47bb-0310-9956-ffa450edef68


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends TaskManagerGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.hoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.hoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Task manager has been cleared!");
    }
}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends TaskManagerGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.hoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.hoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Task Manager has been cleared!");
    }
}

Change clear command success message

Change clear command success message


package com.ushahidi.android.domain.repository;

import com.ushahidi.android.domain.entity.FormAttribute;
import com.ushahidi.android.domain.entity.From;

import java.util.List;

import rx.Observable;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface FormAttributeRepository {

    /**
     * Get a list of {@link FormAttribute} from either the database or online.
     *
     * @param deploymentId An ID of {@link com.ushahidi.android.domain.entity.Deployment}
     * @param from         Where to get the formattribute from. Either from local storage or online
     * @return The retrieved form attribute.
     */
    Observable<List<FormAttribute>> getForms(Long deploymentId, From from);

    /**
     * Add/Update a {@link FormAttribute}.
     *
     * @param form The FormAttribute to be saved.
     * @return The row affected
     */
    Observable<Long> putForm(FormAttribute form);
}

Add repo for form attribute

Add repo for form attribute


/**
 * Copyright (C) 2010-2011 LShift Ltd.
 *
 * 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 net.lshift.diffa.participant.changes;

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

public class ChangeEventTest {

  @Test
  public void shouldRejectMissingMandatoryFields() {
    ChangeEvent bogusEvent = new ChangeEvent();
    assertFalse(bogusEvent.containsMandatoryFields());
  }

  @Test
  public void shouldAcceptMinimumFields() {
    ChangeEvent validEvent = new ChangeEvent();
    validEvent.setId("id");
    validEvent.setVersion("vsn");
    assertTrue(validEvent.containsMandatoryFields());
  }
}

/**
 * Copyright (C) 2010-2011 LShift Ltd.
 *
 * 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 net.lshift.diffa.participant.changes;

import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

@RunWith(Theories.class)
public class ChangeEventTest {

  @DataPoint public static ChangeEvent completelyEmptyEvent = new ChangeEvent();
  @DataPoint public static ChangeEvent nullIdWithValidVersion = new ChangeEvent(null,"vsn", null, null, null);
  @DataPoint public static ChangeEvent emptyIdWithValidVersion = new ChangeEvent("" ,"vsn", null, null, null);
  @DataPoint public static ChangeEvent validIdWithEmptyVersion = new ChangeEvent("id" , "", null, null, null);
  @DataPoint public static ChangeEvent validIdWithNullVersion = new ChangeEvent("id" , null, null, null, null);

  @Theory
  public void shouldRejectMissingMandatoryFields(ChangeEvent bogusEvent) {
    assertFalse(bogusEvent.containsMandatoryFields());
  }

  @Test
  public void shouldAcceptMinimumFields() {
    ChangeEvent validEvent = new ChangeEvent();
    validEvent.setId("id");
    validEvent.setVersion("vsn");
    assertTrue(validEvent.containsMandatoryFields());
  }
}

Add some more data points to ChangeEvent check


package prims;

import prims.Prims;

/*
	This class tests class Prims (Minimum Spanning Tree Algorithm)
*/

class TestPrims{

	// Tests MST and prints MST edges

	public static void testMST1(){

		int N = 9;		// No. of Vertices
		int M = 14;		// No. of Edges

		int[][] edges = {	{1,2,4}, 	// Edges
							{1,8,8},
							{2,8,11},
							{2,3,8},
							{3,4,7},
							{3,9,2},
							{3,6,4},
							{4,6,14},
							{4,5,9},
							{5,6,10},
							{6,7,2},
							{7,8,1},
							{7,9,6},
							{8,9,7}
						  };

		Prims prims = new Prims(N, M, edges);
		prims.findMST();
		System.out.println("MST Edges are: ");
		prims.printMSTEdges();
	}

	public static void main(String args[]){

		// Call testMST1
		testMST1();
	}
}

Add test class for prims MST

Add test class for prims MST


package hudson.plugins.git.browser;

import hudson.plugins.git.GitChangeSet;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class GitilesTest {

    private final String repoUrl = "https://gwt.googlesource.com/gwt/";

    private final boolean useAuthorName;
    private final GitChangeSetSample sample;

    public GitilesTest(String useAuthorName) {
        this.useAuthorName = Boolean.valueOf(useAuthorName);
        sample = new GitChangeSetSample(this.useAuthorName);
    }

    @Parameterized.Parameters(name = "{0}")
    public static Collection permuteAuthorName() {
        List<Object[]> values = new ArrayList<Object[]>();
        String[] allowed = {"true", "false"};
        for (String authorName : allowed) {
            Object[] combination = {authorName};
            values.add(combination);
        }
        return values;
    }

    @Test
    public void testGetChangeSetLink() throws Exception {
        URL result = (new Gitiles(repoUrl)).getChangeSetLink(sample.changeSet);
        assertEquals(new URL(repoUrl + "+/" + sample.id + "%5E%21"), result);
    }

    @Test
    public void testGetDiffLink() throws Exception {
        Gitiles gitiles = new Gitiles(repoUrl);
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL diffLink = gitiles.getDiffLink(path);
            URL expectedDiffLink = new URL(repoUrl + "+/" + sample.id + "%5E%21");
            String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName();
            assertEquals(msg, expectedDiffLink, diffLink);
        }
    }

    @Test
    public void testGetFileLink() throws Exception {
        Gitiles stash = new Gitiles(repoUrl);
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL fileLink = stash.getFileLink(path);
            URL expectedFileLink = new URL(repoUrl + "+blame/" + sample.id + "/" + path.getPath());
            String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName();
            assertEquals(msg, expectedFileLink, fileLink);
        }
    }
}

Add test for Gitiles repo browser

Add test for Gitiles repo browser


package org.apache.ddlutils.platform;

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

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

import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.model.Database;

/**
 * Test the SqlBuilder (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: $
 */
public class SqlBuilderTest extends TestPlatformBase {

    String xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
                 "<database name='ddlutils'>\n"+
                 "
\n"+
                 "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
                 "    <column name='name' type='VARCHAR' size='15'/>\n"+
                 "
\n"+
                 "</database>";

    public void setUp()
    {
    }

    /**
     * Test the updateSql method
     */
    public void testUpdateSql()
    {
        SqlBuilder sqlBuilder = new SqlBuilderImpl(new PlatformInfo());
        Database database = parseDatabaseFromString(xml);
        Map map = new HashMap();
        map.put("name", "ddlutils");
        map.put("id", new Integer(0));
        String sql = sqlBuilder.getUpdateSql(database.getTable(0), map, false);
        assertEquals("UPDATE \"TestTable\" SET \"name\" = 'ddlutils' WHERE \"id\" = '0'", sql);
    }

    protected String getDatabaseName() {
        return null;
    }

    public class SqlBuilderImpl extends SqlBuilder {

        public SqlBuilderImpl(PlatformInfo info) {
            super(info);
        }
    }
}

Add test for updateSql. Far from complete, but a start..

git-svn-id: b9063b25153de5216c397e252c209c32bc9c47ff@331927 13f79535-47bb-0310-9956-ffa450edef68


package com.connectsdk.device;

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

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.connectsdk.service.DeviceService;
import com.connectsdk.service.capability.Launcher;
import com.connectsdk.service.capability.MediaPlayer;

public class ConnectableDeviceTest {

	private ConnectableDevice device;

	@Before
	public void setUp() {
		device = new ConnectableDevice();
	}

	@Test
	public void testHasCapabilityWithEmptyServices() {
		Assert.assertFalse(device.hasCapability(MediaPlayer.Display_Video));
	}

	@Test
	public void testHasCapabilityWithServices() {
		DeviceService service = Mockito.mock(DeviceService.class);
		Mockito.when(service.hasCapability(MediaPlayer.Display_Video)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);
		Assert.assertTrue(device.hasCapability(MediaPlayer.Display_Video));
	}

	@Test
	public void testHasAnyCapabilities() {
		DeviceService service = Mockito.mock(DeviceService.class);
		String[] capabilities = {Launcher.Browser, Launcher.YouTube};
		Mockito.when(service.hasAnyCapability(capabilities)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);
		Assert.assertTrue(device.hasAnyCapability(capabilities));
	}

	@Test
	public void testHasAnyCapabilitiesWithoutServices() {
		DeviceService service = Mockito.mock(DeviceService.class);
		String[] capabilities = {Launcher.Browser, Launcher.YouTube};
		Mockito.when(service.hasAnyCapability(capabilities)).thenReturn(Boolean.FALSE);
		device.services.put("service", service);
		Assert.assertFalse(device.hasAnyCapability(capabilities));
	}

	@Test
	public void testHasCapabilities() {
		DeviceService service = Mockito.mock(DeviceService.class);
		Mockito.when(service.hasCapability(Launcher.Browser)).thenReturn(Boolean.TRUE);
		Mockito.when(service.hasCapability(Launcher.YouTube)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);

		List<String> capabilities = new ArrayList<String>();
		capabilities.add(Launcher.Browser);
		capabilities.add(Launcher.YouTube);

		Assert.assertTrue(device.hasCapabilities(capabilities));
	}

}

Add test for hasCapability* methods of ConnectableDevice


package org.fxmisc.richtext.model;

import org.fxmisc.richtext.InlineCssTextArea;
import org.junit.Test;

public class AreaTest {

    private InlineCssTextArea area = new InlineCssTextArea();

    @Test
    public void deletingTextThatWasJustInsertedShouldNotMergeTheTwoChanges() {
        area.replaceText(0, 0, "text");
        area.replaceText(0, area.getLength(), "");
        area.undo();
    }
}

Add test to insure mergeWith does not throw Exception


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.threads;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

import junit.framework.TestCase;

/**
 * @author David M. Lloyd
 */
public class DeferredInterruptTestCase extends TestCase {

    public void testDeferral() throws Exception {
        final AtomicBoolean delivered0 = new AtomicBoolean();
        final AtomicBoolean deferred = new AtomicBoolean();
        final AtomicBoolean delivered = new AtomicBoolean();
        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        final JBossThread thread = new JBossThread(new Runnable() {
            public void run() {
                latch1.countDown();
                LockSupport.parkNanos(3000000000L);
                delivered0.set(Thread.interrupted());
                JBossThread.executeWithInterruptDeferred(new Runnable() {
                    public void run() {
                        latch2.countDown();
                        LockSupport.parkNanos(500000000L);
                        deferred.set(! Thread.interrupted());
                    }
                });
                delivered.set(Thread.interrupted());
            }
        });
        thread.start();
        latch1.await();
        thread.interrupt();
        latch2.await();
        thread.interrupt();
        thread.join();
        assertTrue(delivered0.get());
        assertTrue(deferred.get());
        assertTrue(delivered.get());
    }
}

Test case for interrupt deferral

Test case for interrupt deferral


// default package

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;

import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

class UtilTests {

  @Nested
  class Args {

    @Test
    void empty() {
      var args = new Bach.Util.Args();
      assertLinesMatch(List.of(), args.list());
      assertEquals("Args{}", args.toString());
      assertArrayEquals(new String[0], args.toStrings());
    }

    @Test
    void touch() {
      var args =
          new Bach.Util.Args()
              .add(1)
              .add("key", "value")
              .add(true, "first")
              .add(true, "second", "more")
              .add(false, "suppressed")
              .forEach(List.of('a', 'b', 'c'), Bach.Util.Args::add);
      assertLinesMatch(
          List.of("1", "key", "value", "first", "second", "more", "a", "b", "c"), args.list());
    }
  }
}

Add unit test for common utilities

Add unit test for common utilities


package org.sagebionetworks.bridge.redis;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisOpsTest {

    private Jedis jedis;
    private JedisOps ops;

    @Before
    public void before() {
        jedis = mock(Jedis.class);
        JedisPool pool = mock(JedisPool.class);
        when(pool.getResource()).thenReturn(jedis);
        ops = new JedisOps(pool);
    }

    @Test
    public void testZadd() {
        ops.zadd("key", 1.1, "member");
        verify(jedis, times(1)).zadd("key", 1.1, "member");
    }

    @Test
    public void testZscore() {
        ops.zscore("key", "member");
        verify(jedis, times(1)).zscore("key", "member");
    }

    @Test
    public void testZrank() {
        ops.zrank("key", "member");
        verify(jedis, times(1)).zrank("key", "member");
    }

    @Test
    public void testZrangeByScore() {
        ops.zrangeByScore("key", 1.1, 1.2);
        verify(jedis, times(1)).zrangeByScore("key", 1.1, 1.2);
    }
}

Add tests to the sorted set commands

Add tests to the sorted set commands


import java.io.*;
import java.util.*;

public class <+FILEBASE+> {
	public static void main(String[] args) throws Exception {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			br.lines()
				.map(line -> Arrays.stream(line.split(" "))
						.mapToInt(Integer::parseInt)
						.toArray())
				.forEach(intArray -> {
					<+CURSOR+>
				});
		}
	}
}

Fix a programming contest template for Java8


/* **********************************************************************
    Copyright 2006 Rensselaer Polytechnic Institute. All worldwide rights reserved.

    Redistribution and use of this distribution in source and binary forms,
    with or without modification, are permitted provided that:
       The above copyright notice and this permission notice appear in all
        copies and supporting documentation;

        The name, identifiers, and trademarks of Rensselaer Polytechnic
        Institute are not used in advertising or publicity without the
        express prior written permission of Rensselaer Polytechnic Institute;

    DISCLAIMER: The software is distributed" AS IS" without any express or
    implied warranty, including but not limited to, any implied warranties
    of merchantability or fitness for a particular purpose or any warrant)'
    of non-infringement of any current or pending patent rights. The authors
    of the software make no representations about the suitability of this
    software for any particular purpose. The entire risk as to the quality
    and performance of the software is with the user. Should the software
    prove defective, the user assumes the cost of all necessary servicing,
    repair or correction. In particular, neither Rensselaer Polytechnic
    Institute, nor the authors of the software are liable for any indirect,
    special, consequential, or incidental damages related to the software,
    to the maximum extent the law permits.
*/

package edu.rpi.sss.util;

import org.apache.log4j.Logger;

import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

/** Implement a pool of objects whose values appear frequently enough that pooling
 * will result in a substantial reduction in space and or cpu.
 *
 * <p>Objects pooled must be either immutable or sharable because they will be
 * shared.
 *
 * @author Mike Douglass
 *
 * @param <T>
 */
public class ObjectPool<T> implements Serializable {
  private WeakHashMap<T, SoftReference<T>> pool =
    new WeakHashMap<T, SoftReference<T>>();

  private static long refs;
  private static long hits;

  private transient Logger log;
  private boolean debug = false;

  /**
   * @param val
   * @return value in pool
   */
  public T get(T val) {
    if (debug &&
        ((refs % 500) == 0)) {
      getLogger().debug("pool refs " + refs + ": hits " + hits);
    }
    refs++;
    SoftReference<T> poolVal = pool.get(val);

    if (poolVal != null) {
      T tval = poolVal.get();
      if (tval != null) {
        hits++;
        return tval;
      }
    }

    synchronized (pool) {
      pool.put(val, new SoftReference<T>(val));
      return val;
    }
  }

  private Logger getLogger() {
    if (log == null) {
      log = Logger.getLogger(this.getClass());
    }

    return log;
  }
}

Add an object pool to cache immutable or shared objects.


package leetcode.find_minimum_in_rotated_sorted_array;

public class Solution {
    public int findMin(int[] num) {
    	int size = num.length;
    	if(num[0] <= num[size - 1]){ // Not rotated
    		return num[0];
    	}
    	int L = -1, U = size;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(num[mid] > num[size - 1]){
    			L = mid;
    		}else{
    			U = mid;
    		}
    	}
    	return num[U];
    }
}

Add java solution for 153. Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/


package com.iluwatar.composite;

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

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

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

/**
 * Date: 12/11/15 - 8:12 PM
 *
 * @author Jeroen Meulemeester
 */
public class MessengerTest {

  /**
   * The buffer used to capture every write to {@link System#out}
   */
  private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();

  /**
   * Keep the original std-out so it can be restored after the test
   */
  private final PrintStream realStdOut = System.out;

  /**
   * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
   */
  @Before
  public void setUp() {
    this.stdOutBuffer = new ByteArrayOutputStream();
    System.setOut(new PrintStream(stdOutBuffer));
  }

  /**
   * Removed the mocked std-out {@link PrintStream} again from the {@link System} class
   */
  @After
  public void tearDown() {
    System.setOut(realStdOut);
  }

  /**
   * Test the message from the orcs
   */
  @Test
  public void testMessageFromOrcs() {
    final Messenger messenger = new Messenger();
    testMessage(
        messenger.messageFromOrcs(),
        "Where there is a whip there is a way."
    );
  }

  /**
   * Test the message from the elves
   */
  @Test
  public void testMessageFromElves() {
    final Messenger messenger = new Messenger();
    testMessage(
        messenger.messageFromElves(),
        "Much wind pours from your mouth."
    );
  }

  /**
   * Test if the given composed message matches the expected message
   *
   * @param composedMessage The composed message, received from the messenger
   * @param message         The expected message
   */
  private void testMessage(final LetterComposite composedMessage, final String message) {
    // Test is the composed message has the correct number of words
    final String[] words = message.split(" ");
    assertNotNull(composedMessage);
    assertEquals(words.length, composedMessage.count());

    // Print the message to the mocked stdOut ...
    composedMessage.print();

    // ... and verify if the message matches with the expected one
    assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim());
  }

}

Add proper unit tests for composite pattern


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

public final class ValidationConfigBuilder implements ValidationConfig
{
    private boolean validateExceptionHandler = true;
    private boolean validateProxyInterfaces = false;

    @Override
    public boolean validateProxyInterfaces()
    {
        return validateProxyInterfaces;
    }

    public void validateProxyInterfaces(boolean validateProxyInterfaces)
    {
        this.validateProxyInterfaces = validateProxyInterfaces;
    }

    @Override
    public boolean validateExceptionHandler()
    {
        return validateExceptionHandler;
    }

    public void validateExceptionHandler(boolean validateExceptionHandler)
    {
        this.validateExceptionHandler = validateExceptionHandler;
    }
}

Revert "delete unused class". Only unused within the project itself.

This reverts commit f1830a3726e7393eb89b02cd0092c7d2f6f2991a.


package org.scijava.notebook.converter;

public class HTMLTableBuilder {

    /** Returns the style tag used to style HTML tables */
    public static String getTableStyle(final boolean displayRowLabel) {
        String style = "";

        return style;
    }

    public static String startTable() {
        return "

";
    }

    public static String appendRowLabelHeading() {
        return " 	";
    }

    public static String appendHeadings(final String data,
        final boolean end)
    {
        final String html = "" + data + "	";
        if (end) return html + "

";
        return html;
    }

    public static String appendData(final String data,
        final boolean start, final boolean end)
    {
        String html = "";
        if (start) html += "
";
        html += "" + data + "	";
        if (end) html += "
";
        return html;
    }

    public static String appendRowLabelData(final String data) {
        String html = "
";

        if (data == null) html += " ";
        else html += data;

        html += "	";
        return html;
    }

    public static String endTable() {
        return "

";
    }
}

Add utiltiy class for making HTML tables


import java.util.Scanner;

/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class VerticalLine {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number");
        int n = in.nextInt();
        for (int i = 0; i < n; i++)
            System.out.println("*");
    }

}

Add Third Exercise Veritcal Line

Add Third Exercise Veritcal Line


package jsr305;

import javax.annotation.meta.When;

public class TestFooNoControlFlow {

	public @Foo(when=When.NEVER) Object notFoo;
	public @Foo(when=When.ALWAYS) Object foo;

	public @Foo(when=When.NEVER) Object returnsNotFoo() { return null; };
	public @Foo(when=When.ALWAYS) Object returnsFoo() { return null; };

	public void requiresNotFoo( @Foo(when=When.NEVER)  Object x) {  };
	public void requiresFoo( @Foo(when=When.ALWAYS)  Object x) {  };

	public void test12() {
		foo = notFoo;
	}
	public void test32() {
		foo = returnsNotFoo();
	}

	public void test21() {
		notFoo = foo;
	}
	public void test41() {
		notFoo = returnsFoo();
	}

	public void test16() {
		requiresFoo(notFoo);
	}
	public void test36() {
		requiresFoo(returnsNotFoo());
	}
	public void test25() {
		requiresNotFoo(foo);
	}
	public void test45() {
		requiresNotFoo(returnsFoo());
	}

	public void ok22() {
		foo = foo;
	}
	public void ok42() {
		foo = returnsFoo();
	}

	public void ok11() {
		notFoo = notFoo;
	}
	public void ok31() {
		notFoo = returnsNotFoo();
	}

	public void ok26() {
		requiresFoo(foo);
	}
	public void ok46() {
		requiresFoo(returnsFoo());
	}
	public void ok15() {
		requiresNotFoo(notFoo);
	}
	public void ok35() {
		requiresNotFoo(returnsNotFoo());
	}

}

Add test case for custom type qualifiers

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


import com.fizzed.rocker.RockerModel;
import com.fizzed.rocker.runtime.StringBuilderOutput;

public class Main {

    public static void main(String[] args) {
        RockerModel model = Hello.template("Switzerland");
        StringBuilderOutput output = model.render(StringBuilderOutput.FACTORY);
        System.out.println(output.getBuffer().toString());
    }

}

Add source files that consumes generated sources files


package net.wisedog.android.whooing.advsms.test;

import java.util.ArrayList;

import net.wisedog.android.whooing.advsms.CardInfo;
import junit.framework.TestCase;

public class CardInfoTest extends TestCase {

	public void testConvertIntArrayToString(){
		ArrayList<Integer> array = new ArrayList<Integer>();
		array.add(1);
		array.add(100);
		assertEquals("1,100", CardInfo.convertIntArrayToString(array));

		array.add(50);
		array.add(25);
		assertEquals("1,100,50,25", CardInfo.convertIntArrayToString(array));
	}

	public void testConvertStringToIntArray(){
		ArrayList<Integer> array = CardInfo.convertStringToIntArray("1,50,70");
		assertEquals(1, array.get(0).intValue());
		assertEquals(50, array.get(1).intValue());
		assertEquals(70, array.get(2).intValue());
	}
}

Add Test case for CardInfo class

Add Test case for CardInfo class


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

/**
 * Given an String containing a number expressed using cientific notation, can you write a method to
 * return the value of that number?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class CientificNotation {
}

Add statement to problem 30

Add statement to problem 30


package com.sonian.elasticsearch;

import org.testng.annotations.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * @author dakrone
 */
public class DiskShardsAllocatorTests {

    @Test
    public void testEnoughDiskForShard() {
        assertThat(2 + 2, equalTo(4));
    }
}

Add blank test for disk equilibrium allocator


/**
 * You and your friends are going trick-or-treating. Like everyone else, you want to
 * get as much candy as possible. Like a true engineer, you want to optimize the route so that you
 * don't have to walk too much.
 *
 * However, your mom said you can only hit one house per row so that you don't get kidnapped or worse, lost.
 * To save yourself from walking too much, you are limited to choosing the house directly below it or the house
 * at the exact diagonal to it.
 *
 * So if your neighborhood looked something like this:
 * [
 *   [ a, b, c, d ],
 *   [ e, f, g, h ],
 *   [ i, j, k, l ],
 * ]
 * From house a, the next possible houses are either e or f.
 * From house b, the next possibles houses are e, f or g.
 * From house c, the next possibles houses are f, g or h.
 * From house d, the next possibles houses are g or h.
 * From house g, the next possibles houses are i, k or l.
 *
 * Once you have reached the last row of houses, then you're done and head home.
 *
 * Given a matrix of houses and how much candy you can get at each house, find the maximum amount of candy you can
 * get while following the rules above.
 *
 * Example:
 * Input: [
 *   [ 3, 2, 4, 1 ],
 *   [ 5, 1, 6, 3 ],
 *   [ 1, 8, 2, 4 ],
 *   [ 2, 3, 1, 6 ]
 * ]
 *
 * The maximum amount of candy you can get is 21 from the route 4 -> 6 -> 8 -> 3.
 */
public int optimalRoute(int[][] houses) {}

Add trick or treat problem

Add trick or treat problem


/*
    An example of a menu system in a while loop
*/

import java.util.Scanner;

public class WhileMenu
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        char choice = 'Z';

        while(choice != 'X')
        {
            System.out.println("Welcome to the Menu System.");
            System.out.println("Enter \'A\' option A ");
            System.out.println("Enter \'B\' option B ");
            System.out.println("Enter \'X\' to Exit ");
            System.out.println("Please enter your choice: ");
            choice = input.next().charAt(0);
            choice = Character.toUpperCase(choice);

            switch(choice)
            {
                case 'A': System.out.println("Your choice was \'A\'");
                    break;
                case 'B': System.out.println("Your choice was \'B\'");
                    break;
                case 'X':
                    break;
                default: System.out.println("You entered an invalid choice.");
                    System.out.println("Please enter your choice: ");
                    choice = input.next().charAt(0);
                    choice = Character.toUpperCase(choice);
                    break;
            }
        }
        System.out.println("Goodbye.");

    }
}

Add an example of a menu system in a while loop


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

import io.netty.buffer.ByteBufAllocator;
import io.netty.util.internal.ObjectUtil;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSessionContext;
import java.util.List;

/**
 * Adapter class which allows to wrap another {@link SslContext} and init {@link SSLEngine} instances.
 */
public abstract class DelegatingSslContext extends SslContext {

    private final SslContext ctx;

    protected DelegatingSslContext(SslContext ctx) {
        this.ctx = ObjectUtil.checkNotNull(ctx, "ctx");
    }

    @Override
    public final boolean isClient() {
        return ctx.isClient();
    }

    @Override
    public final List<String> cipherSuites() {
        return ctx.cipherSuites();
    }

    @Override
    public final long sessionCacheSize() {
        return ctx.sessionCacheSize();
    }

    @Override
    public final long sessionTimeout() {
        return ctx.sessionTimeout();
    }

    @Override
    public final ApplicationProtocolNegotiator applicationProtocolNegotiator() {
        return ctx.applicationProtocolNegotiator();
    }

    @Override
    public final SSLEngine newEngine(ByteBufAllocator alloc) {
        SSLEngine engine = ctx.newEngine(alloc);
        initEngine(engine);
        return engine;
    }

    @Override
    public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
        SSLEngine engine = ctx.newEngine(alloc, peerHost, peerPort);
        initEngine(engine);
        return engine;
    }

    @Override
    public final SSLSessionContext sessionContext() {
        return ctx.sessionContext();
    }

    /**
     * Init the {@link SSLEngine}.
     */
    protected abstract void initEngine(SSLEngine engine);
}

Allow to wrap another SslContext implementation and do extra init steps on the SSLEngine.

Motivation:

Sometimes its needed to customize the SSLEngine (like setting protocols etc). For this it would be useful if the user could wrap an SslContext and do init steps on the SSLEngine.

Modifications:

Add new SslContext implementation which can wrap another one and allow to customize the SSLEngine

Result:

More flexible usage of SslContext.


package de.retest.recheck.meta;

import static org.assertj.core.api.Assertions.assertThatCode;

import org.junit.jupiter.api.Test;

class GlobalMetadataProviderTest {

	@Test
	void retrieve_should_not_throw_an_exception() throws Exception {
		final MetadataProvider cut = new GlobalMetadataProvider();

		assertThatCode( cut::retrieve ).doesNotThrowAnyException();
	}
}

Add test to ensure there are no duplicates


package sfBugsNew;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1179 {

    @NoWarning("OBL_UNSATISFIED_OBLIGATION")
    public void bug(Connection connection) throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement("SELECT * FROM Employees");

        } catch (Exception e) {

        } finally {
            if (ps != null)
                ps.close();
        }
    }
}

Add test case; could not reproduce false positive report

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


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

package org.opensaml.xml.signature.impl;

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

import org.apache.log4j.Logger;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureTrustEngine;

/**
 * Evaluate a signature in sequence using a chain of subordinate trust engines.  If the signature may be established as
 * trusted by any of the subordinate engines, the token is considered trusted. Otherwise it is considered
 * untrusted.
 *
 */
public class ChainingSignatureTrustEngine implements SignatureTrustEngine {

    /** Class logger. */
    private static Logger log = Logger.getLogger(ChainingSignatureTrustEngine.class);

    /** The chain of subordinate trust engines.  */
    private List<SignatureTrustEngine> engines;

    /** Constructor. */
    public ChainingSignatureTrustEngine() {
        engines = new ArrayList<SignatureTrustEngine>();
    }

    /**
     * Get the list of configured trust engines which constitute the trust evaluation chain.
     *
     * @return the modifiable list of trust engines in the chain
     */
    public  List<SignatureTrustEngine> getChain() {
        return engines;
    }

    /** {@inheritDoc} */
    public KeyInfoCredentialResolver getKeyInfoResolver() {
        // Chaining signature trust engine does not support an attached KeyInfoResolver
        return null;
    }

    /** {@inheritDoc} */
    public boolean validate(Signature token, CriteriaSet trustBasisCriteria) throws SecurityException {
        for (SignatureTrustEngine engine : engines) {
            if (engine.validate(token, trustBasisCriteria)) {
                if (log.isDebugEnabled()) {
                    log.debug("Signature was trusted by chain member: " + engine.getClass().getName());
                }
                return true;
            }
        }
        return false;
    }

    /** {@inheritDoc} */
    public boolean validate(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria,
            Credential candidateCredential) throws SecurityException {
        for (SignatureTrustEngine engine : engines) {
            if (engine.validate(signature, content, algorithmURI, trustBasisCriteria, candidateCredential)) {
                if (log.isDebugEnabled()) {
                    log.debug("Signature was trusted by chain member: " + engine.getClass().getName());
                }
                return true;
            }
        }
        return false;
    }

}

Add impl of chaining signature trust engine.

git-svn-id: 46308aa6df3a13aea5930e6665b35c8b83c3a711@428 9fbd0cf9-a10c-0410-82c1-be8c084f3200


/*
 * Copyright (C) 2016-2019 Dennis Neufeld
 *
 * 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 space.npstr.wolfia.config;

import io.undertow.connector.ByteBufferPool;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * This just exists to get rid off a nasty Undertow warning
 * <p>
 * io.undertow.websockets.jsr: "UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used"
 */
@Configuration
public class WebsocketConfig {

    @Bean
    public WebServerFactoryCustomizer undertowWebSocketServletWebServerCustomizer() {
        return new UndertowWebSocketServletWebServerCustomizer();
    }

    private static class UndertowWebSocketServletWebServerCustomizer
            implements WebServerFactoryCustomizer<UndertowServletWebServerFactory>, Ordered, DisposableBean {

        // Optimal size for direct buffers is 16kB according to Undertow docs
        // http://undertow.io/undertow-docs/undertow-docs-2.0.0/index.html#the-undertow-buffer-pool
        private final ByteBufferPool buffers = new DefaultByteBufferPool(true, 16 * 1024, 100, 12);

        @Override
        public void customize(UndertowServletWebServerFactory factory) {
            factory.addDeploymentInfoCustomizers(deploymentInfo -> {
                WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
                if (info == null) {
                    info = new WebSocketDeploymentInfo();
                    deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info);
                }

                info.setBuffers(this.buffers);
            });
        }

        @Override
        public int getOrder() {
            return Ordered.LOWEST_PRECEDENCE;
        }

        @Override
        public void destroy() {
            this.buffers.close();
        }
    }
}

Fix undertow warning about missing config


package com.oasisfeng.pattern.update;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;

/**
 * Device experience friendly package update observer, eliminated the legacy broadcast receiver if running on Android 3.1+
 *
 *
First, define two classes extending this abstract class, as following:
 *

   class PackageUpdateObserver extends AbstractPackageUpdateObserver {

       {@literal @}Override protected void onPackageUpdated(final Context context) {
           // Anything to be done after package update
       }
   }

   class PackageUpdateObserverLegacy extends PackageUpdateObserver {
   }

 * Then, declare two broadcast receivers in your AndroidManifest.xml
 *

   <receiver android:name=".PackageUpdateObserverLegacy">
       <intent-filter>
           <action android:name="android.intent.action.PACKAGE_REPLACED" />
           <data android:scheme="package" />
       </intent-filter>
   </receiver>

   <receiver android:name=".PackageUpdateObserver">
       <intent-filter>
           <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
       </intent-filter>
   </receiver>

 * @author Oasis
 */
public abstract class AbstractPackageUpdateObserver extends BroadcastReceiver {

    abstract protected void onPackageUpdated(final Context context);

    @Override public void onReceive(final Context context, final Intent intent) {
        if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
            // Disable legacy receiver on Android 3.1+ for better device experience.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                for (final ResolveInfo receiver : context.getPackageManager().queryBroadcastReceivers(intent, 0)) {
                    Class<?> clazz; try { clazz = Class.forName(receiver.activityInfo.name);
                    } catch (final ClassNotFoundException e) {
                        Log.e(TAG, "Cannot find receiver: " + receiver.activityInfo.name);
                        continue;
                    }
                    if (! AbstractPackageUpdateObserver.class.isAssignableFrom(clazz)) continue;  // Skip other receivers.
                    final ComponentName component = new ComponentName(context, clazz);
                    context.getPackageManager().setComponentEnabledSetting(component,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
                }
                return;     // No need to proceed since Intent.ACTION_MY_PACKAGE_REPLACED will also be triggered.
            }
            // Ignore packages other than myself
            if (! context.getPackageName().equals(intent.getData().getSchemeSpecificPart())) return;
        } else if (! Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) return;

        Log.i(TAG, "Package updated");
        onPackageUpdated(context);
    }

    private static final String TAG = "Installer";
}

Add device experience friendly package update observer pattern.


package de.lmu.ifi.dbs.elki.algorithm.clustering;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.result.clustering.ClusteringResult;
import de.lmu.ifi.dbs.elki.algorithm.result.clustering.Clusters;
import de.lmu.ifi.dbs.elki.data.ClassLabel;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.utilities.Description;

/**
 * Pseudo clustering using labels.
 *
 * This "algorithm" puts elements into the same cluster when they agree in their labels.
 * I.e. it just uses a predefined clustering, and is mostly useful for testing and evaluation
 * (e.g. comparing the result of a real algorithm to a reference result / golden standard).
 *
 * @author Erich Schubert
 *
 * @param <O>
 */
public class ByLabelClustering<O extends DatabaseObject> extends AbstractAlgorithm<O> implements Clustering<O> {
  /**
   * Holds the result of the algorithm.
   */
  private ClusteringResult<O> result;

  /**
   * Return clustering result
   */
  public ClusteringResult<O> getResult() {
    return result;
  }

  /**
   * Obtain a description of the algorithm
   */
  public Description getDescription() {
    return new Description("ByLabelClustering", "Clustering by label",
        "Cluster points by a (pre-assigned!) label. For comparing results with a reference clustering.", "");
  }

  /**
   * Run the actual clustering algorithm.
   *
   * @param database The database to process
   */
  @Override
  protected void runInTime(Database<O> database) throws IllegalStateException {
    HashMap<String, Collection<Integer>> labelmap = new HashMap<String, Collection<Integer>>();

    for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
      Integer id = iter.next();
      String label = null;

      // try class label first
      ClassLabel classlabel = database.getAssociation(AssociationID.CLASS, id);
      if (classlabel != null) label = classlabel.toString();

      // fall back to other labels
      if (label == null)
        label = database.getAssociation(AssociationID.LABEL, id);

      if (labelmap.containsKey(label))
        labelmap.get(label).add(id);
      else {
        Collection<Integer> n = new java.util.Vector<Integer>();
        n.add(id);
        labelmap.put(label,n);
      }
    }

    Integer[][] rarray = new Integer[labelmap.size()][];
    int i = 0;
    for (Collection<Integer> ids : labelmap.values()) {
      rarray[i] = (Integer[]) ids.toArray(new Integer[0]);
      i++;
    }
    result = new Clusters<O>(rarray, database);
  }
}

Add a new trivial clustering algorithm using existing labels. Useful for comparing results to a golden standard.


package org.apache.poi;

/**
 * This is an internal class, it should not be considered as a public API:
 * this class will be deleted without any warning.
 */
@Deprecated
public class PptPoiBridge {

	public static void removeRelation(POIXMLDocumentPart parent, POIXMLDocumentPart child) {
		parent.removeRelation(child);
	}

}

Enable to replace an image while keeping its properties and order


//
// ParallelRead.java
//

import java.io.File;
import loci.formats.ImageReader;

/**
 * Reads all files in given directory in parallel,
 * using a separate thread for each.
 *
 *

Source code:

 *
Trac,
 * SVN

 */
public class ParallelRead implements Runnable {
  private String id;

  public ParallelRead(String id) {
    this.id = id;
  }

  public void run() {
    try {
      ImageReader r = new ImageReader();
      r.setId(id);
      System.out.println(Thread.currentThread().getName() +
        ": id=" + id +
        ", sizeX=" + r.getSizeX() +
        ", sizeY=" + r.getSizeY() +
        ", sizeZ=" + r.getSizeZ() +
        ", sizeT=" + r.getSizeT() +
        ", sizeC=" + r.getSizeC());
      r.close();
    }
    catch (Exception exc) {
      exc.printStackTrace();
    }
  }

  public static void main(String[] args) {
    String dir = args[0];
    File[] list = new File(dir).listFiles();
    for (int i=0; i<list.length; i++) {
      ParallelRead pr = new ParallelRead(list[i].getAbsolutePath());
      new Thread(pr).start();
    }
  }
}

Test class for reading from many files in parallel.


package org.bitcoinj.net.discovery;

import org.bitcoinj.evolution.SimplifiedMasternodeList;
import org.bitcoinj.evolution.SimplifiedMasternodeListEntry;

import javax.annotation.Nullable;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * Created by hashengineering on 12/5/18.
 */
public class MasternodePeerDiscovery implements PeerDiscovery {

    ArrayList<InetSocketAddress> masternodeSeeds;
    private int pnseedIndex;

    /**
     * Supports finding peers by IP addresses
     *
     * @param mnList IP addresses for seed addresses.
     */
    public MasternodePeerDiscovery(SimplifiedMasternodeList mnList) {
        masternodeSeeds = new ArrayList<InetSocketAddress>(mnList.size());
        mnList.forEachMN(true, new SimplifiedMasternodeList.ForeachMNCallback() {
            @Override
            public void processMN(SimplifiedMasternodeListEntry mn) {
                masternodeSeeds.add(mn.getService().toSocketAddress());
            }
        });
    }

    /**
     * Acts as an iterator, returning the address of each node in the list sequentially.
     * Once all the list has been iterated, null will be returned for each subsequent query.
     *
     * @return InetSocketAddress - The address/port of the next node.
     * @throws PeerDiscoveryException
     */
    @Nullable
    public InetSocketAddress getPeer() throws PeerDiscoveryException {
        try {
            return nextPeer();
        } catch (UnknownHostException e) {
            throw new PeerDiscoveryException(e);
        }
    }

    @Nullable
    private InetSocketAddress nextPeer() throws UnknownHostException, PeerDiscoveryException {
        if (masternodeSeeds == null || masternodeSeeds.isEmpty())
            throw new PeerDiscoveryException("No masternodes seeds configured; unable to find any peers");

        if (pnseedIndex >= masternodeSeeds.size()) return null;
        return masternodeSeeds.get(pnseedIndex++);
    }

    /**
     * Returns an array containing all the Dash nodes within the list.
     */
    @Override
    public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
        if (services != 0)
            throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services);
        try {
            return allPeers();
        } catch (UnknownHostException e) {
            throw new PeerDiscoveryException(e);
        }
    }

    private InetSocketAddress[] allPeers() throws UnknownHostException {
        return masternodeSeeds.toArray(new InetSocketAddress[0]);
    }

    @Override
    public void shutdown() {
    }
}

Add PeerDiscovery for getting peers from a simplified masternode list

Signed-off-by: HashEngineering <cdfd0e2929fd184ec34228d20f211727fcb487d4@gmail.com>


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

import com.vaadin.server.Page;
import com.vaadin.shared.Position;
import com.vaadin.ui.Notification;

/**
 * Utility class for formatted notifications.
 *
 * @author Ryan Gilera
 */
public class NotificationUtil {
    /**
     * Creates an error notification with a single parameter for caption.
     *
     * @param caption The main message of the notification
     */
    public static void showError(String caption) {
        showError(caption, "");
    }

    /**
     * Creates an error notification with two parameters for caption and
     * description.
     *
     * @param caption The main message of the notification
     * @param description Secondary description message
     */
    public static void showError(String caption, String description) {
        Notification errorNotification;

        caption = "<i class=\"fa fa-exclamation-circle fa-2x\"></i>  "
                    + caption;
        if (description.isEmpty()) {
            errorNotification = new Notification(caption,
                    Notification.Type.ERROR_MESSAGE);
        } else {
            errorNotification = new Notification(caption, description,
                    Notification.Type.ERROR_MESSAGE);
        }

        errorNotification.setHtmlContentAllowed(true);
        errorNotification.setPosition(Position.TOP_CENTER);

        errorNotification.show(Page.getCurrent());
    }
}

Add custom notification utility helper

Add custom notification utility helper


package lintcode.bst;

import fundamentals.tree.TreeNode;

/**
 */
public class MyBst {

    // 85-Insert Node in a Binary Search Tree
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null) return node;
        if (node.val < root.val) {
            root.left = insertNode(root.left, node);
        } else {
            root.right = insertNode(root.right, node);
        }
        return root;
    }

}

Implement my binary search tree

Implement my binary search tree


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

public class RandomArrayGenerator {

	private final int size;

	private final int min;
	private final int max;

	public RandomArrayGenerator(int recordSize, int max) {
		this(recordSize, max, 0);
	}

	public RandomArrayGenerator(int recordSize, int max, int min) {
		this.size = recordSize;
		this.max = max;
		this.min = min;
	}

	public List<Integer> generateRandomNumbers() {
		Random generator = new Random();
		List<Integer> list = new ArrayList<>(size);
		for (int i = 0; i < size; i++) {
			list.add(generator.nextInt(max - min) + min);
		}
		return list;
	}
}

Add an utility to generate random arrays for algorith testing


/*
  Insert Node at the end of a linked list
  head pointer input could be NULL as well for empty list
  Node is defined as
  class Node {
     int data;
     Node next;
  }
*/
    // This is a "method-only" submission.
    // You only need to complete this method.
Node Reverse(Node head) {

  Node prev = null;
  Node curr = head;
  Node next = null;

  while(curr != null) {
    next = curr.next;
    curr.next = prev;
    prev = curr;

    curr = next;
  }

  return prev;
}

Solve reverse a linked list

Solve reverse a linked list

This helped: http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/