package com.alexrnl.request.shows;

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

import com.alexrnl.request.Request;
import com.alexrnl.request.Verb;

/**
 * Archive a show in the logged member account.

 * @author Alex
 */
public class ShowUnarchive extends Request {

	/** Address of the method */
	private static final String	ADDRESS			= "/shows/archive";
	/** Name of the id parameter */
	private static final String	PARAMETER_ID	= "id";

	/** The id of the show to archive */
	private final Integer		id;

	/**
	 * Constructor #1.

	 * @param id
	 *        the id of the show to archive.
	 */
	public ShowUnarchive (final Integer id) {
		super(Verb.DELETE, ADDRESS);
		this.id = id;
	}

	/**
	 * Return the attribute id.
	 * @return the attribute id.
	 */
	public Integer getId () {
		return id;
	}

	@Override
	public Map<String, String> getParameters () {
		final Map<String, String> parameters = new HashMap<>();
		parameters.put(PARAMETER_ID, getId().toString());
		return parameters;
	}

}

Add request for unarchiving show

Add request for unarchiving show


package com.example.web;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    // Convert a predefined exception to an HTTP Status code
    @ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Id must be an integer.") // Default: 400
    @ExceptionHandler(NumberFormatException.class)
    public void idParseError() {
        // Nothing to do
    }
}

Fix id parse error (String can not be parsed to Long)


package org.corpus_tools.annis.gui.admin;

import static com.github.mvysny.kaributesting.v8.LocatorJ._click;
import static com.github.mvysny.kaributesting.v8.LocatorJ._get;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.github.mvysny.kaributesting.v8.MockVaadin;
import com.vaadin.spring.internal.UIScopeImpl;
import com.vaadin.ui.Button;
import com.vaadin.ui.TabSheet;
import java.io.IOException;
import net.jcip.annotations.NotThreadSafe;
import org.corpus_tools.annis.gui.AnnisUI;
import org.corpus_tools.annis.gui.SingletonBeanStoreRetrievalStrategy;
import org.corpus_tools.annis.gui.admin.reflinks.MigrationPanel;
import org.corpus_tools.annis.gui.admin.reflinks.ReferenceLinkEditor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringBootTest
@ActiveProfiles({"desktop", "test", "headless"})
@WebAppConfiguration
@NotThreadSafe
class AdminViewTest {

  @Autowired
  private BeanFactory beanFactory;

  private AnnisUI ui;

  @BeforeEach
  void setup() throws IOException {
    UIScopeImpl.setBeanStoreRetrievalStrategy(new SingletonBeanStoreRetrievalStrategy());
    this.ui = beanFactory.getBean(AnnisUI.class);

    MockVaadin.setup(() -> ui);

    _click(_get(Button.class, spec -> spec.withCaption("Administration")));

  }

  @AfterEach
  public void tearDown() throws IOException {
    MockVaadin.tearDown();
  }

  @Test
  void testFragmentChanges() throws Exception {
    // Select all of the available tabs and check that the fragment is updated
    TabSheet tab = _get(TabSheet.class);

    tab.setSelectedTab(_get(ImportPanel.class));
    assertEquals("!admin/import", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(CorpusAdminPanel.class));
    assertEquals("!admin/corpora", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(ReferenceLinkEditor.class));
    assertEquals("!admin/reference-link-editor", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(MigrationPanel.class));
    assertEquals("!admin/reference-link-migration", ui.getPage().getUriFragment());
  }

}

Add a test that the admin view fragment changes


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.processing;

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

/**
 * This is an annotation for marking an IOperation as having a threadsafe execute method
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Atomic {

}

Add atomic thread safe marker annotation


package com.bignerdranch.android.photogallery;

import android.os.HandlerThread;
import android.util.Log;

public class ThumbnailDownloader<T> extends HandlerThread {

    private static final String TAG = "ThumbnailDownloader";

    public ThumbnailDownloader() {
        super(TAG);
    }

    public void queueThumbnail(T target, String url) {
        Log.i(TAG, "Gor a URL: " + url);
    }
}

Create class that will manage image download in background


import junit.framework.*;

public class AssignInExpr extends TestCase {

    public void testExpr() {
        int a = 1, b = 2, c = 3;

        a = b += c;
        Assert.assertEquals(b, 5);
        Assert.assertEquals(a, 5);

        a = b += c += a;
        Assert.assertEquals(c, 8);
        Assert.assertEquals(b, 13);
        Assert.assertEquals(a, 13);

        a = (b = 1) * (c = 10);
        Assert.assertEquals(a, 10);
        Assert.assertEquals(b, 1);
        Assert.assertEquals(a, 10);

    }

    public void testIf() {
        int a = 4, b = 6, c = 10;

        if ((a +=b) == c) {
            c = 20;
        }
        Assert.assertEquals(a, 10);
        Assert.assertEquals(b, 6);
        Assert.assertEquals(c, 20);
    }

    public void testWhile() {
        int i = 0;

        while (++i < 10) {
            Assert.assertTrue(i < 10);
        }
        Assert.assertEquals(i, 10);

    }

    public void testDo() {
        int i = 0;
        do {
            Assert.assertTrue(i < 10);
        } while (++i < 10);
        Assert.assertEquals(i, 10);
    }

    public void testPostIncDec() {
        int i = 0, j = 0, k = 0;
        i = j++;
        Assert.assertEquals(i, 0);
        Assert.assertEquals(j, 1);

        if (++i == j++) {
            k = 3;
        }
        Assert.assertEquals(i, 1);
        Assert.assertEquals(j, 2);
        Assert.assertEquals(k, 3);
    }

    public void testAndOr() {
        int i = 0, j = 0;

        if (i++ == 1 && j++ == 1) {
            Assert.fail("and test fail");
        } else {
            Assert.assertEquals(i, 1);
            Assert.assertEquals(j, 0);
        }

        if (--i != 0 || j-- == 0) {
            Assert.assertEquals(i, 0);
            Assert.assertEquals(j, -1);
        } else {
            Assert.fail("or test fail");
        }

    }

}

Add assign in expression testcase

Add assign in expression testcase


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

package com.google.sps.servlets;

import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Delivers a list of strings representing today's trending searches worldwide
@WebServlet("/trending")
public class TrendingServlet extends HttpServlet {

    private List<String> trendingSearches = new ArrayList<>();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        getTrendingSearches();
        Gson gson = new Gson();
        response.setContentType("text/html;");
        response.getWriter().println(gson.toJson(trendingSearches));
    }

    public void getTrendingSearches() {
        //fetch trending searches from db - hard coded data for now
        trendingSearches.add("Giraffes");
        trendingSearches.add("Chicken nuggets");
    }
}

Add servlet to deliver today's trending searches


package net.restlesscoder.sandbox.imagej;

import java.io.IOException;

import net.imagej.Dataset;
import net.imagej.ImageJ;
import net.imagej.ImgPlus;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.converter.Converters;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;

public class ConvertersClamp {

	public static void main(final String... args) throws IOException {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		// Load an image of a colorful bird.
		final String path = "/Users/curtis/data/toucan.png";
		final Dataset toucan = ij.scifio().datasetIO().open(path);
		final ImgPlus<UnsignedByteType> img = toucan.typedImg(new UnsignedByteType());

		// Make bird less colorful.
		RandomAccessibleInterval<UnsignedByteType> clamped = clamp(img, 50, 100, new UnsignedByteType());
		ij.ui().show("Clamped", clamped);
	}

	public static <T extends RealType<T>> RandomAccessibleInterval<T> clamp(
		final RandomAccessibleInterval<T> image, final double min, final double max, final T type)
	{
		return Converters.convert(image, (in, out) -> {
			double value = in.getRealDouble();
			if (value < min) value = min;
			else if (value > max) value = max;
			out.setReal(value);
		}, type);
	}
}

Add example that clamps image values to (min, max)


package org.robockets.stronghold.robot.highgoalshooter;

import edu.wpi.first.wpilibj.command.Command;
import org.robockets.stronghold.robot.Robot;

/**
 * Roll the jeff rollers to fire a cannonball.
 */
public class FireShooter extends Command {

    public FireShooter() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	setTimeout(0.7);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.shooter.spinJeffRollers(1);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return isTimedOut();
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.shooter.spinJeffRollers(0);
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}

Add shoot command for high goal shooter.


@Configuration
public class ServerConfig {

	public class FaviconConfiguration extends WebMvcConfigurerAdapter{

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry){
			registry.setOrder(Integer.MIN_VALUE);
			registry.addResourceHandler("/favicon.ico").addResourceLocations("/");

			registry.addResourceHandler("/static/**")
			        .addResourceLocations("/")
			        .resourceChain(false)
			        .addResolver(new GzipResourceResolver())
			        .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
		}
	}
}

Enable gzip in springboot project

Enable gzip in springboot project


/**
 *
 */
package com.trendrr.strest.tests;

import junit.framework.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

import com.trendrr.strest.examples.HelloWorld;
import com.trendrr.strest.server.routing.MatchedRoute;
import com.trendrr.strest.server.routing.RouteMatcher;
import com.trendrr.strest.server.routing.UriMapping;

/**
 * @author Dustin Norlander
 * @created Jun 28, 2011
 *
 */
public class RouteMatchingTests {

	protected Log log = LogFactory.getLog(RouteMatchingTests.class);

	@Test
	public void testRoutes() {

		RouteMatcher tree = new RouteMatcher();

		tree.addMapping(new UriMapping("/", HelloWorld.class));
		tree.addMapping(new UriMapping("/test", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/*filenames", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/:name/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/idmatch/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/idmatch/namematch", HelloWorld.class));

		/*
		 * Notes on matching:
		 *
		 * matched route allways strips leading /
		 *
		 * Will always return the MOST specific match, ie exact matches take precidence over wildcards
		 *
		 */

		Assert.assertTrue(match(tree, "hello", null));
		Assert.assertTrue(match(tree, "/", ""));

		Assert.assertTrue(match(tree, "/test/1/2/3/4", "test/*filenames"));
		Assert.assertTrue(match(tree, "/test/1", "test/:id"));
		Assert.assertTrue(match(tree, "/test/name/1", "test/:name/:id"));

		Assert.assertTrue(match(tree, "/test/idmatch/1", "test/idmatch/:id"));
		Assert.assertTrue(match(tree, "/test/idmatch/namematch", "test/idmatch/namematch"));

//		System.out.println(tree.find("/dustin/blah"));
//		System.out.println(tree.find("/dustin/blah/asdf"));
//		System.out.println(tree.find("/"));

	}

	protected boolean match(RouteMatcher tree, String route, String expected) {
		MatchedRoute rt = tree.find(route);
		if (rt == null && expected == null)
			return true;
		if (rt == null) {
			log.warn("Route matched was null: " + route);
			return false;
		}
		if (rt.getMapping().getRoute().equals(expected)) {
			return true;
		}

		log.warn("Route didn't match: " + route + " GOT: " + rt.getMapping().getRoute() + " EXPECTED: " + expected);

		return false;
	}
}

Add tests for route matching

Add tests for route matching


package com.kurento.kmf.media;

import com.kurento.kmf.media.events.ErrorEvent;
import com.kurento.kmf.media.events.MediaEventListener;
import com.kurento.tool.rom.RemoteClass;

@RemoteClass
public interface MediaObject {

	MediaPipeline getMediaPipeline();

	void getMediaPipeline(Continuation<MediaPipeline> cont);

	MediaObject getParent();

	void getParent(Continuation<MediaObject> cont);

	ListenerRegistration addErrorListener(
			MediaEventListener<ErrorEvent> listener);

	void addErrorListener(MediaEventListener<ErrorEvent> listener,
			Continuation<ListenerRegistration> cont);

	void release();

	void release(Continuation<Void> continuation);
}

package com.kurento.kmf.media;

import com.kurento.kmf.media.events.ErrorEvent;
import com.kurento.kmf.media.events.MediaEventListener;
import com.kurento.tool.rom.RemoteClass;

@RemoteClass
public interface MediaObject {

	MediaPipeline getMediaPipeline();

	void getMediaPipeline(Continuation<MediaPipeline> cont);

	MediaObject getParent();

	void getParent(Continuation<MediaObject> cont);

	ListenerRegistration addErrorListener(
			MediaEventListener<ErrorEvent> listener);

	void addErrorListener(MediaEventListener<ErrorEvent> listener,
			Continuation<ListenerRegistration> cont);

	/**
	 *
	 * Explicitly release a media object form memory. All of its children will
	 * also be released.
	 *
	 **/
	void release();

	/**
	 *
	 * Explicitly release a media object form memory. All of its children will
	 * also be released. Asynchronous call.
	 *
	 * @param continuation
	 *            {@link #onSuccess(void)} will be called when the actions
	 *            complete. {@link #onError} will be called if there is an
	 *            exception.
	 *
	 **/
	void release(Continuation<Void> continuation);

}

Add generated documentation for release methods

Change-Id: Id29eacefc9ba8e0a38840b8c99fede7cb3055c02


package moe.tristan.easyfxml.util;

import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;

import java.util.function.Consumer;

public final class Buttons {

    private Buttons() {
    }

    public static void setOnClick(final Button button, final Runnable action) {
        button.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> Platform.runLater(action));
    }

    public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) {
        setOnClick(button, () -> action.accept(node));
    }

}

Add convenience methods for Button on-click event reaction


package probos;

import static org.junit.Assert.*;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;

import org.junit.Test;

public class TestPosix {
	//static final

	@Test public void testGroup()
	{
		POSIX posix = POSIXFactory.getPOSIX();
		System.err.println(posix.isNative());
		String egroup = posix.getgrgid(posix.getegid()).getName();
		assertNotNull(egroup);
	}
}

Check posix calls work on this platform

Check posix calls work on this platform


/*
 * AsTest.java
 *
 * Created on 10. September 2001, 09:44
 */

package freetds;
import java.sql.*;
import java.math.BigDecimal;
import com.internetcds.util.Logger;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.AssertionFailedError;
import java.io.*;
import java.lang.reflect.*;

/**
 *
 * @author  builder
 * @version
 */
public class AsTest extends DatabaseTestCase {

  public AsTest(String name) {
    super(name);
  }

  public static void main(String args[]) {
    try {
      Logger.setActive(true);
    }
    catch (java.io.IOException ex) {
      throw new RuntimeException("Unexpected Exception " + ex + " occured in main");
    }
    if (args.length > 0) {
      junit.framework.TestSuite s = new TestSuite();
      for (int i = 0; i < args.length; i++) {
        s.addTest(new AsTest(args[i]));
      }
      junit.textui.TestRunner.run(s);
    }
    else
      junit.textui.TestRunner.run(AsTest.class);
  }

  public void testProc1() throws Exception
  {

    boolean passed = false;
    Statement stmt = con.createStatement();
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec')) drop procedure spTestExec");
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec2')) drop procedure spTestExec2");

    stmt.executeUpdate(" create procedure spTestExec2 as " +
                    "select 'Did it work?' as Result");
    stmt.executeUpdate("create procedure spTestExec as " +
		"create table #tmp ( Result varchar(50) ) " +
		"insert #tmp execute spTestExec2 " +
		"select * from #tmp");
    CallableStatement cstmt = con.prepareCall("exec spTestExec");
    ResultSet rs = cstmt.executeQuery();
    while (rs.next()) {
      passed = true;
    }
    assertTrue(passed);
    // stmt.executeQuery("execute spTestExec");

  }

}

Test PMoores Problem with Procedure sptestexec

git-svn-id: 1fece92013051e73d27f0f6eaec2bf855927aa58@23 97a8069c-bbaa-4fa2-9e49-561d8e0b19ef


/**
 *
 */
package com.trendrr.oss;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.trendrr.oss.concurrent.ReinitObject;

/**
 *
 * A threadsafe file cache.
 *
 *
 * @author Dustin Norlander
 * @created Apr 7, 2011
 *
 */
public class FileCache {

	protected Log log = LogFactory.getLog(FileCache.class);

	private static ConcurrentHashMap<String, ReinitObject<byte[]>> cache = new ConcurrentHashMap<String, ReinitObject<byte[]>> ();

	/**
	 * loads a file from the cache.  All exceptions are logged as warnings, and null is returned.
	 * @param filename filename to load
	 * @param timeoutPeriod number of milliseconds between reload of the file.
	 * @return
	 */
	public byte[] getFileBytes(String filename, long timeoutPeriod) {
		final String f = filename;

		//fancy timeout cache.
		cache.putIfAbsent(filename, new ReinitObject<byte[]>(timeoutPeriod) {
			@Override
			public byte[] init() {
				try {
					System.out.println("LOADING FROM FILE SYSTEM!");
					return FileHelper.loadBytes(f);
				} catch (Exception e) {
					log.warn("Caught", e);
				}
				return null;
			}
		});
		return cache.get(filename).get();
	}
}

Add a simple, fast, threadsafe file cache


/**
 *
 */
/**
 * @author roart
 *
 */
module iclij.evolutionchromosome {
    exports roart.iclij.evolution.marketfilter.chromosome.impl;
    exports roart.iclij.evolution.chromosome.impl;
    exports roart.iclij.evolution.chromosome.winner;
    requires iclij.common.config;
    requires iclij.common.componentdata;
    requires iclij.evolutionmarketfilter;
    requires iclij.evolutioniclijconfigmap;
    requires evolution.gene;
    requires evolution.model;
    requires common.util;
    requires io.jenetics.base;
    requires com.fasterxml.jackson.core;
    requires com.fasterxml.jackson.databind;
    requires slf4j.api;
    requires common.constants;
    requires iclij.common.model;
    requires common.config;
    requires org.apache.commons.lang3;
    requires jackson.annotations;
}

Move to subproject, Jackson annotations and remove classes, evolution refactor (I111).


package leetcode;

/**
 * https://leetcode.com/problems/edit-distance/
 */
public class Problem72 {
    public int minDistance(String word1, String word2) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem72 prob = new Problem72();
        System.out.println(prob.minDistance("geek", "gesek")); // 1
        System.out.println(prob.minDistance("cat", "cut")); // 1
        System.out.println(prob.minDistance("sunday", "saturday")); // 3
    }
}

Create a skeleton for problem 72

Create a skeleton for problem 72


package starpunk;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main
{
  public static void main( final String[] args )
  {
    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = 1280;
    configuration.height = 900;
    configuration.useCPUSynch = false;
    configuration.vSyncEnabled = false;
    configuration.title = "Star Punk";
    new LwjglApplication( new ApplicationListener() {
      @Override
      public void create()
      {
      }

      @Override
      public void resize( final int width, final int height )
      {
      }

      @Override
      public void render()
      {
      }

      @Override
      public void pause()
      {
      }

      @Override
      public void resume()
      {
      }

      @Override
      public void dispose()
      {
      }
    }, configuration );
  }
}

Add minimal do nothig application

Add minimal do nothig application


package com.lightbulbz.net;

import java.io.IOException;
import java.net.*;

/**
 * Created by kevin on 6/3/15.
 */
public class WOLPacketSender {
    private static final byte FF = (byte) 0xff;
    private static final byte[] PAYLOAD_START = {FF, FF, FF, FF, FF, FF};
    private static final int WOL_PACKET_SIZE = 6 + 16 * 6;
    private DatagramPacket packet;
    private final DatagramSocket sock;

    public WOLPacketSender(InetAddress targetAddr, MacAddress targetMac) throws SocketException {
        sock = new DatagramSocket();
        byte[] packetBytes = new byte[WOL_PACKET_SIZE];
        byte[] macBytes = targetMac.getAddressBytes();
        System.arraycopy(PAYLOAD_START, 0, packetBytes, 0, PAYLOAD_START.length);
        for (int i = PAYLOAD_START.length; i < WOL_PACKET_SIZE; i += macBytes.length) {
            System.arraycopy(macBytes, 0, packetBytes, i, macBytes.length);
        }
        packet = new DatagramPacket(packetBytes, packetBytes.length, new InetSocketAddress(targetAddr, 9));
    }

    public void sendPacket() throws IOException {
        sock.send(packet);
    }
}

Move code to send WOL packet into library


package com.zulip.android.networking;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * TODO: add description
 */

public class UploadProgressResponse extends ResponseBody {
    private final ResponseBody responseBody;
    private final ProgressListener progressListener;
    private BufferedSource bufferedSource;
    private int mNotificationId;

    public UploadProgressResponse(ResponseBody responseBody, ProgressListener progressListener,
                                  int notificationId) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
        this.mNotificationId = notificationId;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1, mNotificationId);
                return bytesRead;
            }
        };
    }

    public interface ProgressListener {
        void update(long bytesRead, long contentLength, boolean done, int notificationId);
    }
}

Add custom upload progress RequestBody.

Add custom upload progress RequestBody.


package checkpoint.andela.members;

import org.junit.Test;
import checkpoint.andela.main.Book;

import static org.junit.Assert.*;

/**
 * Created by Semiu on 26/11/2015.
 */
public class StudentTest {
  Student student1 = new Student();
  Book book4 = new Book();

  @Test
  public void testBorrowBook() throws Exception {
    book4.setNumberOfCopies(10);
    student1.borrowBook(book4);
    assertEquals(book4.getNumberOfCopies(), 9);
  }

  @Test
  public void testReturnBook() throws Exception {
    book4.setNumberOfCopies(9);
    student1.returnBook(book4);
    assertEquals(book4.getNumberOfCopies(), 10);
  }
}

Update Test for Student class

Update Test for Student class


/*
 * Copyright 2015 Attribyte, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 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.attribyte.metrics.cloudwatch;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import org.attribyte.metrics.RegistryTranslation;
import org.junit.Test;

import java.io.FileInputStream;
import java.util.Properties;

public class CloudwatchReporterTest {

   @Test
   public void reportToCloudwatch() throws Exception  {

      Properties secrets = new Properties();
      String userHome = System.getProperty("user.home");
      try(FileInputStream fis = new FileInputStream(userHome+"/cwsecrets")) {
         secrets.load(fis);
      }

      Properties props = new Properties(secrets);
      props.put(CloudwatchReporter.METRIC_NAMESPACE_PROPERTY, "test01");
      props.put(RegistryTranslation.TRANSLATE_PREFIX + "internal-counter-02", "counter-02");

      MetricRegistry registry = new MetricRegistry();
      Counter counter01 = registry.counter("internal-counter-01");
      counter01.inc(14L);
      Counter counter02 = registry.counter("internal-counter-02");
      counter02.inc(15L);
      Counter counter03 = registry.counter("internal-counter-03");
      counter03.inc(16L);

      CloudwatchReporter reporter = new CloudwatchReporter();
      reporter.init("cloudwatch", props, registry, null); //No filter...
      reporter.start();
      Thread.sleep(61000L);
      reporter.stop();
   }
}

Add cloudwatch reporter test. Requires manual verification...but have verified that the mechanics do work.


@API(apiVersion = "1.0.0", owner = "Boilerplate", provides = "Boilerplate|FantasyKingdomAPI")
package boilerplate.kingdomapi;

import cpw.mods.fml.common.API;

Add the base class for the FantasyKingdoms API.

Note to Tobs: I store APIs for all mods in boilerplate at the moment - which is a slightly odd design decision, but go with it :P


package ca.nrc.cadc.vos;

import javax.sql.DataSource;

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

public abstract class VOSpaceFileMetadataSourceTest extends PersistenceTest
{
    private VOSpaceFileMetadataSource vospaceFileMetadataSource;
    private DataNode testNode;

    @Before
    public void before() throws Exception
    {
        super.commonBefore();
        vospaceFileMetadataSource = new VOSpaceFileMetadataSource();
        vospaceFileMetadataSource.setNodePersistence(nodeDAO);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getFromParent(getRootContainerName(), null);
        testNode = new DataNode(getVOSURIPrefix() + getRootContainerName() + "/" + getNodeName("testNode"));
        nodeDAO.putInContainer(testNode, rootContainer);
    }

    public abstract DataSource getDataSource();

    public abstract NodeDAO getNodeDAO(DataSource dataSource);

    public abstract String getVOSURIPrefix();

    public abstract String getRootContainerName();

    public abstract String getNodeOwner();

    @Test
    public void testMetadata() throws Exception
    {

    }

}

Put common persistence test code in abstract class PersistenceTest

git-svn-id: 311fcc5b8b03427d323cee07bbb9e5a14d8d22e9@624 728ff76a-78ac-11de-a72b-d90af8dea425


package leetcode._4sum;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
    	int length = num.length;
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	Arrays.sort(num);
    	for(int i = 0; i < length; i++){
    		if(i > 0 && num[i] == num[i - 1]) continue;
    		for(int j = i + 1; j < length; j++){
    			if(j > i + 1 && num[j] == num[j - 1]) continue;
    			int head = j + 1, tail = length - 1;
        		while(head < tail){
        			while(head > j + 1 && head < tail && num[head] == num[head - 1]) head++;
        			while(tail < length - 1 && head < tail && num[tail] == num[tail + 1]) tail--;
        			int sum = num[i] + num[j] + num[head] + num[tail];
        			if(head < tail){
        				if(sum < target){
        					head++;
        				}else if(sum > target){
        					tail--;
        				}else{
        					ans.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{num[i], num[j], num[head], num[tail]})));
        					head++;
        					tail--;
        				}
        			}
        		}
    		}
    	}
    	return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> row : new Solution().fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0)){
    		for(int x : row){
    			System.err.print(x + " ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 18. 4Sum

Add java solution for 18. 4Sum

18. 4Sum: https://leetcode.com/problems/4sum/


package net.darkmorford.btweagles.eventhandler;

import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.item.Item;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod.EventBusSubscriber
public class EventHandlerMappings
{
	@SubscribeEvent
	public static void missingItemMapping(RegistryEvent.MissingMappings<Item> event)
	{
		BetterThanWeagles.logger.warn("Caught missing item mappings! Attempting to repair them...");

		for (RegistryEvent.MissingMappings.Mapping<Item> mapping : event.getMappings())
		{
			BetterThanWeagles.logger.info("Item mapping for " + mapping.key + " is missing, taking default action.");
		}
	}
}

Add an event handler to deal with missing item mappings.


package openmods.calc;

import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import openmods.Log;

public class SingleExprEvaluator<E, M> {

	public interface EnvironmentConfigurator<E> {
		public void accept(Environment<E> env);
	}

	private final Calculator<E, M> calculator;

	private boolean useFallback;

	private M exprType;

	private String expr;

	private IExecutable<E> compiledExpr;

	public SingleExprEvaluator(Calculator<E, M> calculator) {
		this.calculator = calculator;
	}

	public static <E, M> SingleExprEvaluator<E, M> create(Calculator<E, M> calculator) {
		return new SingleExprEvaluator<E, M>(calculator);
	}

	public void setExpr(M exprType, String expr) {
		this.exprType = exprType;
		this.expr = expr;
		this.compiledExpr = null;
		this.useFallback = false;
	}

	public E evaluate(EnvironmentConfigurator<E> conf, Supplier<E> fallbackValue) {
		if (useFallback || Strings.isNullOrEmpty(expr) || exprType == null) return fallbackValue.get();

		if (compiledExpr == null) {
			try {
				compiledExpr = calculator.compilers.compile(exprType, expr);
			} catch (Exception ex) {
				useFallback = true;
				Log.warn(ex, "Failed to compile formula %s", expr);
				return fallbackValue.get();
			}
		}

		conf.accept(calculator.environment);

		try {
			return calculator.environment.executeAndPop(compiledExpr);
		} catch (Exception ex) {
			useFallback = true;
			Log.warn(ex, "Failed to execute formula %s", expr);
			return fallbackValue.get();
		}
	}

}

Add helper for single-formula calculators


package flyway.myplaces;

import fi.nls.oskari.domain.map.OskariLayer;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.json.JSONException;
import org.json.JSONObject;
import org.oskari.usercontent.LayerHelper;

/**
 * The label for field "link" on my places layers for english, finnish and swedish
 */
public class V1_0_14__change_link_label extends BaseJavaMigration {

    private static final String NAME = "oskari:my_places";

    public void migrate(Context ignored) throws Exception {
        OskariLayer layer = LayerHelper.getLayerWithName(NAME);
        JSONObject attrs = layer.getAttributes();
        modifyAttributes(attrs);
        layer.setAttributes(attrs);
        LayerHelper.update(layer);
    }

    /**
     * Set up for overriding to make future migration easier
     * @param attrs
     * @throws JSONException
     */
    void modifyAttributes(JSONObject attrs) throws JSONException {
        String field = "link";
        // this repeats digging the locale from attributes multiple times
        // but allows developers to easily adjust other fields and languages as well in the future
        changeLabel(attrs, "en", field, "More information");
        changeLabel(attrs, "fi", field, "Lisätiedot");
        changeLabel(attrs, "sv", field, "Mera information");
    }

    /**
     * Note! This can throw null pointer if the database was modified outside the
     * Flyway migrations and these blocks were removed.
     *
     * But it's better to catch that with failing migration than
     * let the migration die silently
     *
     * @param attrs
     * @return
     * @throws JSONException
     */
    void changeLabel(JSONObject attrs, String lang, String field, String label) throws JSONException {
        JSONObject data = attrs.optJSONObject("data");
        JSONObject locale = data.optJSONObject("locale");
        JSONObject en = locale.optJSONObject(lang);
        en.put(field, label);
    }
}

Change label for myplaces link

Change label for myplaces link


public class Solution {

    public int removeElement(int[] nums, int val) {

        int lenCount = 0;

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] != val) {
                nums[lenCount] = nums[i];
                lenCount++;
            }

        }

        return lenCount;

    }

}

Create : 27 Remove Element

Create : 27 Remove Element


package com.github.aureliano.achmed.resources.types;

import static org.junit.Assert.assertEquals;

import static com.github.aureliano.achmed.resources.types.PackageProvider.*;
import static com.github.aureliano.achmed.resources.types.OperatingSystemFamily.*;

import org.junit.Test;

public class PackageProviderTest {

	@Test
	public void testOperatingSystemFamily() {
		assertEquals(DEBIAN, APT.getOperatingSystemFamily());
		assertEquals(RPM, YUM.getOperatingSystemFamily());
		assertEquals(APP, GEM.getOperatingSystemFamily());
	}

	@Test
	public void testPackageManagement() {
		assertEquals("apt-get", APT.getPackageManagement());
		assertEquals("yum", YUM.getPackageManagement());
		assertEquals("gem", GEM.getPackageManagement());
	}
}

Create unit test to package provider type.


import io.specto.hoverfly.junit.HoverflyRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;

import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON;

public class URLHoverflyRuleTest {

    @Rule
    public HoverflyRule hoverflyRule = HoverflyRule.buildFromUrl("http://raw.githubusercontent.com/SpectoLabs/hoverfly-junit/d0d41dfdcb250c6bb02ada63d304b4afddf5f2e4/src/test/resources/test-service.json").build();

    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        restTemplate = new RestTemplate();
    }

    @Test
    public void shouldBeAbleToMakeABookingUsingHoverfly() throws URISyntaxException {
        // Given
        final RequestEntity<String> bookFlightRequest = RequestEntity.post(new URI("http://www.my-test.com/api/bookings"))
                .contentType(APPLICATION_JSON)
                .body("{\"flightId\": \"1\"}");

        // When
        final ResponseEntity<String> bookFlightResponse = restTemplate.exchange(bookFlightRequest, String.class);

        // Then
        assertThat(bookFlightResponse.getStatusCode()).isEqualTo(CREATED);
        assertThat(bookFlightResponse.getHeaders().getLocation()).isEqualTo(new URI("http://localhost/api/bookings/1"));
    }

    @Test
    public void shouldBeAbleToGetABookingUsingHoverfly() {
        // When
        final ResponseEntity<String> getBookingResponse = restTemplate.getForEntity("http://www.my-test.com/api/bookings/1", String.class);

        // Then
        assertThat(getBookingResponse.getStatusCode()).isEqualTo(OK);
        assertThatJson(getBookingResponse.getBody()).isEqualTo("{" +
                "\"bookingId\":\"1\"," +
                "\"origin\":\"London\"," +
                "\"destination\":\"Singapore\"," +
                "\"time\":\"2011-09-01T12:30\"," +
                "\"_links\":{\"self\":{\"href\":\"http://localhost/api/bookings/1\"}}" +
                "}");
    }

}

Test for rule where a URL is configured as the source json

Former-commit-id: cda9e44042c47044dd06c31804e9ad8be95399fe


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

package org.gradle.api.internal.file;

import org.gradle.api.file.FileTree;

public interface FileTreeInternal extends FileTree, FileCollectionInternal {
}

Add missing file from previous commit.

Add missing file from previous commit.

+review REVIEW-5481


/*
   Copyright (C) 2011-2014 AC Inc. (Andy Cheung)

   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.net.*;
import java.io.*;

public class ReserveMC{
  public static void main(String[] a){
    System.out.println("Craftbukkit Port Preserve Util");
    System.out.println("(C) 2011-2014 AC Inc.");
    System.out.println();
    new Thread(new PortReserveThread(25565)).start();
    new Thread(new PortReserveThread(1139)).start();
  }
}

class PortReserveThread implements Runnable{
  int port; // This thread's port.

  // The TCP Settings Part.
  Socket s; //The Socket, not for use.
  ServerSocket ss; // The ServerSocket.

  public void out(String t){
    System.out.println(t);
  }

  public PortReserveThread(int which){
    out("Creating instance of PRT...");
    port = which; // Set port.
    try {
      ss = new ServerSocket(port);  //Get New SS (ServerSocket[TCP]) instance.
      out("Created instance of TCP Socket. This will reserve port " + port);
    } catch (IOException e) {  //Catch the exception.
      System.out.println("Error,Will exit.");
      System.exit(1);
    }
  }

  public void run(){ // Thread method body.
    while(true){ // Unlimited Accept.
      try{
        out("Accepting TCP on " + port);
        s = ss.accept(); // Reserve TCP.
        s.close();
      }
      catch(SocketTimeoutException ste){
        try {
          s.close();
	} catch (IOException e) {
          System.out.println("Error,Will exit.");
          System.exit(1);
	}
      }
      catch(IOException ioe){
	try {
	  s.close();
	} catch (IOException e) {
	  System.out.println("Error,Will exit.");
	  System.exit(1);
	}
      }
      finally{
	try {
	  s.close();
	} catch (IOException e) {
	  System.out.println("Error,Will exit.");
	  System.exit(1);
	}
        s = null;
      }
    }
  }

  public void stopSelf(){  //Stop Procress.
    Thread.currentThread().interrupt();
  }
  public int getPort(){
    return port;
  }
}

Add a very simple killer.

Add a very simple killer.


package forklift.decorators;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Specify how many processor threads should be launched by forklift for the annotated processor.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface MultiThreaded {
    /**
     * The maximum number of threads to run.
     */
    int value();
}

Add a multithreaded annotation that will allow forklift to spin up a specified number of threads to run a processor.


package leetcode.min_stack;

class MinStack {
	private static final int SIZE = 100000;
	private int[] mList = new int[SIZE];
	private int[] mMinList = new int[SIZE];
	private int mSize = 0;

	public void push(int x) {
		mList[mSize] = x;
		int minVal = x;
		if(mSize > 0){
			minVal = Math.min(mMinList[mSize - 1], x);
		}
		mMinList[mSize] = minVal;
		mSize++;
    }

    public void pop() {
    	mSize--;
    }

    public int top() {
        return mList[mSize - 1];
    }

    public int getMin() {
        return mMinList[mSize - 1];
    }
}

Add java solution for 155. Min Stack

Add java solution for 155. Min Stack

155. Min Stack: https://leetcode.com/problems/min-stack/


package problems;

public class FindMinInRotatedSortedArray {
    public int findMin(int[] num) {
        if (num == null || num.length == 0)
            return 0;

        return findMinHelper(num, 0, num.length - 1);
    }

    int findMinHelper(int[] A, int l, int r) {
        if (r - l <= 1)
            return Math.min(A[l], A[r]);

        int mid = (l + r) / 2;
        if (A[mid] >= A[l] && A[mid] > A[r])
            return findMinHelper(A, mid, r);
        if (A[mid] == A[l] && A[mid] == A[r])
            return Math.min(findMinHelper(A, mid, r), findMinHelper(A, l, mid - 1));
        return findMinHelper(A, l, mid);
    }

    public static void main(String[] args) {
        FindMinInRotatedSortedArray fm = new FindMinInRotatedSortedArray();
        int[] num = { 4, 5, 6, 7, 0, 1, 2, 2 };
        System.out.println(fm.findMin(num));
    }
}

Add Find Minimum in Rotated Sortes Array


package us.crast.mondochest.util;

public class GenericUtil {
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object x) {
        return (T) x;
    }
}

Add in Generic Typecast support

Add in Generic Typecast support


package com.opcoach.e4.modelmerger.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TestMergeDuration extends TestMerge {

	@Test
	public void testMergeDuration() {

		long start = System.currentTimeMillis();
		merger.mergeModels(master, model);
		long end = System.currentTimeMillis();

		System.out.println("Merge duration is : " + (end-start) + " ms");
		assertTrue("Merge must be done in less than 10 ms ", ((end-start) <= 10));
	}

}

Add a test to watch merge duration during dev.


package readinstruction;

import java.util.UUID;

/**
 * Created by Karol on 2017-04-20.
 */
public class ReadInstructionImpl extends ReadInstruction {
    public ReadInstructionImpl(UUID instructionId, int readAddres, int arrivalTime, boolean hasDeadline) {
        super(instructionId, readAddres, arrivalTime, hasDeadline);
    }
}

Implement concrete implementation of ReadInstruction


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Subsample;
import net.imglib2.RandomAccessible;
import net.imglib2.view.SubsampleView;
import net.imglib2.view.Views;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.Subsample.class, name = ViewOps.Subsample.NAME)
public class DefaultSubsample<T> extends
		AbstractView<RandomAccessible<T>, SubsampleView<T>> implements
		Subsample<RandomAccessible<T>, SubsampleView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private long step;

	@Override
	public SubsampleView<T> compute(RandomAccessible<T> input) {
		return Views.subsample(input, step);
	}

}

Add default implementation of Subsample interface.


package scratchlib.objects;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.junit.Test;

import scratchlib.objects.fixed.data.ScratchObjectString;
import scratchlib.objects.inline.ScratchObjectBoolean;
import scratchlib.project.ScratchProject;
import scratchlib.project.ScratchVersion;
import scratchlib.reader.ScratchInputStream;

public class ScratchObjectsTest
{
    @Test
    public void looksUpConstructor()
    {
        assertSame(ScratchObjectBoolean.NIL,
                ScratchObjects.lookupConstructor(1).get());
        assertSame(ScratchObjectBoolean.FALSE,
                ScratchObjects.lookupConstructor(3).get());

        assertThat(ScratchObjects.lookupConstructor(9).get(),
                instanceOf(ScratchObjectString.class));
    }

    @Test
    public void readsReferences() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { 99, 0, 1, 37 });

        ScratchOptionalField result = ScratchObjects
                .read(new ScratchInputStream(bin), project);

        assertFalse(result.isResolved());
        assertEquals(293, result.getReferenceID());
    }

    @Test
    public void readsObjects() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { 9, 0, 0, 0, 0 });

        ScratchOptionalField result = ScratchObjects
                .read(new ScratchInputStream(bin), project);

        assertTrue(result.isResolved());
        assertThat(result.get(), instanceOf(ScratchObjectString.class));
    }

    @Test(expected = IOException.class)
    public void throwsForUnknownClassID() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { (byte) 255, 0, 0, 0, 0 });

        ScratchObjects.read(new ScratchInputStream(bin), project);
    }
}

Add unit tests for ScratchObjects

Add unit tests for ScratchObjects


/*
 * IteratorComposite.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.type;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IteratorComposite<T> implements Iterator<T>
{
	public IteratorComposite(Iterator<T> a, Iterator<T> b)
	{
		mItA = a;
		mItB = b;
		mItActive = mItA;
	}

	@Override
	public boolean hasNext()
	{
		return (mItA.hasNext() || mItB.hasNext());
	}

	@Override
	public T next()
	{
		if (!hasNext())
		{
			throw new NoSuchElementException();
		}
		else
		{
			if (mItA.hasNext())
			{
				mItActive = mItA;
				return mItA.next();
			}
			else
			{
				mItActive = mItB;
				return mItB.next();
			}
		}
	}

	@Override
	public void remove()
	{
		mItActive.remove();
	}

	private Iterator<T> mItA;
	private Iterator<T> mItB;
	private Iterator<T> mItActive;
}

Add composite iterator to join 2 iterators together


package net.openhft.chronicle.wire;

/**
 * Created by peter on 05/06/2017.
 */
public interface MethodFilter {
    boolean shouldHandleMessage(String method, Object firstArg);
}

Add periodic update and heartbeat messages


/*
 * ARX: Powerful Data Anonymization
 * Copyright 2012 - 2016 Fabian Prasser, Florian Kohlmayer and contributors
 *
 * 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.deidentifier.arx.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.deidentifier.arx.gui.resources.Resources;
import org.junit.Assert;
import org.junit.Test;

/**
 * A simple test which checks for duplicate message in the resource bundle
 * @author Fabian Prasser
 */
public class TestResourceBundle {

    /**
     * Helper class which wraps Properties
     * @author Fabian Prasser
     */
    private static class WrappedProperties extends Properties {

        /** SVUID*/
        private static final long serialVersionUID = 7390022720344169366L;

        @Override
        public synchronized Object put(Object key, Object value) {
            if (get(key) != null) {
                throw new IllegalStateException("Duplicate key: " + key + " - Current value: " + value + " - Original value: " + (String) get(key));
            }
            return super.put(key, value);
        }
    }

    @Test
    public void test() throws IOException {
        try {
            WrappedProperties resources = new WrappedProperties();
            InputStream stream = Resources.class.getClassLoader().getResourceAsStream("org/deidentifier/arx/gui/resources/messages.properties");
            resources.load(stream);
            stream.close();
        } catch (IllegalStateException e) {
            Assert.fail(e.getMessage());
        }
    }
}

Add test which checks for duplicate entries in messages.properties


/*
 * 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.apache.flink.runtime.rest.messages.taskmanager;

import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase;

import java.util.Arrays;

/**
 * Tests for (un)marshalling of {@link LogListInfo}.
 */
public class LogListInfoTest extends RestResponseMarshallingTestBase {

	@Override
	protected Class getTestResponseClass() {
		return LogListInfo.class;
	}

	@Override
	protected ResponseBody getTestResponseInstance() throws Exception {
		return new LogListInfo(Arrays.asList(
			new LogInfo("taskmanager.log", 0),
			new LogInfo("taskmanager.out", Integer.MAX_VALUE)));
	}
}

[FLINK-16302][rest] Add tests for (un)marshalling LogListInfo


/* LanguageTool, a natural language style checker
 * Copyright (C) 2018 Daniel Naber (http://www.danielnaber.de)
 *
 * This library 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 library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */
package org.languagetool.rules.es;

import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Spanish;
import org.languagetool.rules.RuleMatch;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author (adapted from Portuguese version by David Méndez)
 * @since 4.1
 */
public class SpanishWikipediaRuleTest {

  private SpanishWikipediaRule rule;
  private JLanguageTool langTool;

  @Before
  public void setUp() throws Exception {
    rule = new SpanishWikipediaRule(TestTools.getMessages("es"));
    langTool = new JLanguageTool(new Spanish());
  }

  @Test
  public void testRule() throws IOException {

    // correct sentences:
    assertEquals(0, rule.match(langTool.getAnalyzedSentence("Estas frases no tienen errores frecuentes en la Wikipedia.")).length);

    // incorrect sentences:

    // at the beginning of a sentence (replace rule is case-sensitive)
    checkSimpleReplaceRule("Sucedió ayer. Murio sin que nadie lo esperase.", "Murió");
    // inside sentence
    checkSimpleReplaceRule("Ayer murio sin que nadie lo esperase.", "murió");
  }

  /**
   * Check if a specific replace rule applies.
   * @param sentence the sentence containing the incorrect/misspelled word.
   * @param word the word that is correct (the suggested replacement).
   */
  private void checkSimpleReplaceRule(String sentence, String word) throws IOException {
    RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(sentence));
    assertEquals("Invalid matches.length while checking sentence: "
            + sentence, 1, matches.length);
    assertEquals("Invalid replacement count wile checking sentence: "
            + sentence, 1, matches[0].getSuggestedReplacements().size());
    assertEquals("Invalid suggested replacement while checking sentence: "
            + sentence, word, matches[0].getSuggestedReplacements().get(0));
  }
}

Add a test for SpanishWikipediaRule

Add a test for SpanishWikipediaRule


/*
 * This file is part of Mapyrus, software for plotting maps.
 * Copyright (C) 2003 Simon Chenery.
 *
 * Mapyrus 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 of the License, or
 * (at your option) any later version.
 *
 * Mapyrus 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 Mapyrus; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/*
 * @(#) $Id$
 */
package org.mapyrus.function;

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

import org.mapyrus.Argument;
import org.mapyrus.ContextStack;
import org.mapyrus.MapyrusException;

/**
 * Function replacing all instances of a regular expression in a string with another string.
 * For example, replace('foobar', 'o+', '_') = 'f_bar'.
 */
public class Replace extends Function
{
	/**
	 * @see org.mapyrus.function.Function#evaluate(org.mapyrus.ContextStack,
	 * 	org.mapyrus.Argument, org.mapyrus.Argument, org.mapyrus.Argument)
	 */
	public Argument evaluate(ContextStack context, Argument arg1, Argument arg2, Argument arg3)
		throws MapyrusException
	{
		Argument retval;

		/*
		 * Replace all occurrences of pattern given in second string
		 * with the third string.
		 */
		Pattern pattern = Match.compileRegex(arg2.toString());
		Matcher matcher = pattern.matcher(arg1.toString());
		if (matcher.find())
		{
			/*
			 * Replace all matching patterns.
			 */
			retval = new Argument(Argument.STRING, matcher.replaceAll(arg3.toString()));
		}
		else
		{
			/*
			 * No match so return original string.
			 */
			retval = arg1;
		}
		return(retval);
	}

	/**
	 * @see org.mapyrus.function.Function#getMaxArgumentCount()
	 */
	public int getMaxArgumentCount()
	{
		return(3);
	}

	/**
	 * @see org.mapyrus.function.Function#getMinArgumentCount()
	 */
	public int getMinArgumentCount()
	{
		return(3);
	}

	/**
	 * @see org.mapyrus.function.Function#getName()
	 */
	public String getName()
	{
		return("replace");
	}
}

Split functions out from Expression.java into separate classes.


package net.stickycode.plugin.bounds;

public enum LineSeparator {
  Mac {

    @Override
    public String value() {
      return "\r";
    }
  },
  Unix {

    @Override
    public String value() {
      return "\n";
    }
  },
  Windows {

    @Override
    public String value() {
      return "\r\n";
    }
  };

  abstract public String value();

  public static LineSeparator defaultValue() {
    if (System.lineSeparator().equals("\n"))
      return Unix;

    if (System.lineSeparator().equals("\r"))
      return Mac;

    return Windows;
  }
}

Allow the line separator to be configured to match your source control if you like. Otherwise it will now use the platform default


class NonShortCircuit {
  boolean and( boolean x, boolean y) {
	return x & y;
	}
  boolean ordered(int x, int y, int z) {
	if (x >= y | y >= z) System.out.println("Not ordered");
	return x < y & y < z;
	}
  boolean nonEmpty(Object o[]) {
	return o != null & o.length > 0;
	}
}

Test cases for non-short-circuit evaluation

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


package org.flymine.web;

/*
 * Copyright (C) 2002-2003 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletContext;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

import org.flymine.web.config.WebConfig;

/**
 * Initialiser for the FlyMine web application
 * Anything that needs global initialisation goes here.
 *
 * @author Andrew Varley
 */

public class InitialiserPlugin implements PlugIn
{

    /**
     * Init method called at Servlet initialisation
     *
     * @param servlet ActionServlet that is managing all the modules
     * in this web application
     * @param config ModuleConfig for the module with which this
     * plug-in is associated
     *
     * @throws ServletException if this PlugIn cannot
     * be successfully initialized
     */
    public void init(ActionServlet servlet, ModuleConfig config)
        throws ServletException {

        ServletContext context = servlet.getServletContext();

        try {
            InputStream is = context.getResourceAsStream("/WEB-INF/webconfig-model.xml");
            WebConfig wc = WebConfig.parse(is);
            context.setAttribute("webconfig", wc);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    /**
     * Destroy method called at Servlet destroy
     */
    public void destroy() {
    }

}

Add anything to application context here


/**
 * Check that method without return is not accepted.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */
class MissingReturn {
    public static void main(String[] args) {
    }
}
class MissingReturnTest {
    public int foo() {
    }
}

Add another shared noncompile test.

Add another shared noncompile test.


package org.csstudio.utility.adlparser.fileParser;

import java.util.ArrayList;

import org.csstudio.utility.adlparser.internationalization.Messages;
import org.eclipse.swt.graphics.RGB;

public class ColorMap {
	private RGB[] colors = new RGB[0];
	private int numColors;

	public ColorMap(ADLWidget colorMap) throws WrongADLFormatException {
		// find out the number of colors

		for (FileLine fileLine : colorMap.getBody()){
			String bodyPart = fileLine.getLine();
			String[] row = bodyPart.trim().split("=");
			if (row.length < 2){
				throw new WrongADLFormatException(Messages.Label_WrongADLFormatException_Parameter_Begin + bodyPart + Messages.Label_WrongADLFormatException_Parameter_End);
			}
			if (row[0].trim().equals("ncolors")){
				numColors = Integer.parseInt(row[1].replaceAll("\"", "").trim());
			}
			colors = new RGB[numColors];
		}

		ADLWidget colorsWidget = colorMap.getObjects().get(0);
		if (colorsWidget.getType().equals("colors")){
			int colorCounter = 0;
			for (FileLine fileLine  : colorsWidget.getBody()){
				String bodyPart = fileLine.getLine();
				String[] row = bodyPart.split(",");
				if (row.length == 1){
					String color = row[0].trim();
					colors[colorCounter] = getRGBColor(color);
					colorCounter++;
				}
			}

		}
	}

	/**
	 * @return Object[] colors
	 */
	public RGB[] getColors() {
		return colors;
	}

	public int getNumColors() {
		return numColors;
	}
	public RGB getRGBColor(String inColor){
		String redStr = "#".concat(inColor.substring(0, 2));
		String greenStr = "#".concat(inColor.substring(2, 4));
		String blueStr = "#".concat(inColor.substring(4, 6));
		int red = Integer.decode(redStr);
		int green = Integer.decode(greenStr);
		int blue = Integer.decode(blueStr);
		System.out.println("Red, Green, Blue:"+ red +", " + green + ", " +blue);
		return new RGB(red, green, blue);
	}
}

Add to decode the color map

Add to decode the color map


/*
 * Key point: fast/slow runner technique to find middle node,
 *    time complexity is O(nlgn) which comes from f(n) = 2f(n/2) + cn
 *
 *  There is a O(n) solution that build the BST bottom-up
 *    but it's hard to be implemented in java because of lacking passing by reference
 */

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
            return null;
        if(head.next==null)
            return new TreeNode(head.val);

        //init fast runner and slow runner
        ListNode fast=head.next.next;
        ListNode slow=head;

        //partition the list from the middle, use the fast/slow runner technique
        //the slow pointer will be the prev of the middle node
        while(fast!=null && fast.next!=null)
        {
            fast=fast.next.next;
            slow=slow.next;
        }

        //find the middle node
        ListNode parent=slow.next;

        //partition the list into left and right sublist
        slow.next=null;
        ListNode left=head;
        ListNode right=parent.next;
        parent.next=null;

        //make the middle node as the root, then apply the function
        //to the left part and the right part recursively
        TreeNode root=new TreeNode(parent.val);
        root.left=sortedListToBST(left);
        root.right=sortedListToBST(right);

        return root;

    }

}

Convert Sorted List to Binary Search Tree


/*
 * Copyright 2018 Volker Berlin (i-net software)
 *
 * 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 de.inetsoftware.jwebassembly.binary;

import java.io.IOException;

/**
 * Signature for an entry in a section
 *
 * @author Volker Berlin
 */
abstract class SectionEntry {

    /**
     * Write this single entry to a section
     *
     * @param stream
     *            the target
     * @throws IOException
     *             if any I/O error occur
     */
    abstract void writeSectionEntry( WasmOutputStream stream ) throws IOException;
}

Refactor the writing of sections more object oriented.


package rose.project.passmember.util;

/**
 * Created by Lord Rose on 07/04/2017.
 */
public enum EntryType {
    SIMPLE_PASSWORD,
    FOLDER
}

Add new enum to know kind of new node will be inserted in the tree (JTreeWrapper class)


/******************************************************************************
 *
 *  CS 6421 - Simple Conversation
 *  Compilation:  javac ConvServer.java
 *  Execution:    java ConvServer port
 *
 *  % java ConvServer portnum
 ******************************************************************************/

import java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FunctionServer {
    static final boolean debug=true;

    public static void process (Socket clientSocket) throws IOException {
        // open up IO streams
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        /* Write a welcome message to the client */
        //out.println("Welcome, you are connected to a Java-based server");

        /* read and print the client's request */
        // readLine() blocks until the server receives a new line from client
        String userInput;
        if ((userInput = in.readLine()) == null) {
            System.out.println("Error reading message");
            out.close();
            in.close();
            clientSocket.close();
        }

        String tokens[] = userInput.split(" ");
        switch(tokens[0]){
          case "set":
            if(debug) System.out.println("Set function");
            break;
          case "get":
            if(debug) System.out.println("Get function");
            break;
          default:
            out.println("Message not recognized : " + tokens[0]);
        }

        // close IO streams, then socket
        out.close();
        in.close();
        clientSocket.close();
    }

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

        //check if argument length is invalid
        if(args.length != 1) {
            System.err.println("Usage: java ConvServer port");
        }
        // create socket
        int port = Integer.parseInt(args[0]);
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // wait for connections, and process
        try {
            while(true) {
                // a "blocking" call which waits until a connection is requested
                Socket clientSocket = serverSocket.accept();
                System.err.println("\nAccepted connection from client");
                process(clientSocket);
            }

        }catch (IOException e) {
            System.err.println("Connection Error");
        }
        System.exit(0);
    }
}

Implement basic function call server

Implement basic function call server


package de.asw.java.training2016.net;

import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class UrlConnectionHttpPostRequestExample {

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

		HttpURLConnection urlConnection = (HttpURLConnection) new URL("https://httpbin.org/post").openConnection();
		urlConnection.setRequestProperty("Content-Type", "application/json");
		urlConnection.setDoOutput(true);
		urlConnection.setRequestMethod("POST");

		PrintStream requestBody = new PrintStream(urlConnection.getOutputStream());
		requestBody.print("{\"foo\":\"bar\"}");

		try (Scanner scanner = new Scanner(urlConnection.getInputStream())) {
			printResponseHeaders(urlConnection);
			printResponseBody(scanner);
		}

		urlConnection.disconnect();
	}

	private static void printResponseHeaders(URLConnection urlConnection) {
		for (Map.Entry<String, List<String>> header : urlConnection.getHeaderFields().entrySet()) {
			if (header.getKey() == null) {
				System.out.println(header.getValue().get(0));
				continue;
			}
			System.out.printf("%s: %s%n", header.getKey(), header.getValue());
		}
	}

	private static void printResponseBody(Scanner scanner) {
		while (scanner.hasNextLine()) {
			System.out.println(scanner.nextLine());
		}
	}
}

Add example for sending http post request via UrlConnection


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

package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;

import org.junit.Test;

/**
 * Unit test for {@link L2RewriteService}
 */
public class L2RewriteServiceTest {

    @Test
    public void test() {
        // TODO nothing has been done in L2RewriteService class yet.
    }

}

Add JUnit testing for L2RewriteService class.

Change-Id: I902ce652c3edb0857cca697ead04a9ffd475db67
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


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

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.xwiki.test.docker.junit5.TestReference;
import org.xwiki.test.docker.junit5.UITest;
import org.xwiki.test.ui.TestUtils;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Functional tests of the icon theme sheet.
 *
 * @version $Id$
 */
@UITest
class IconThemesSheetIT
{
    @BeforeEach
    void setUp(TestUtils testUtils)
    {
        // Login as superadmin to define the preferences.
        testUtils.loginAsSuperAdmin();
    }

    @Test
    @Order(1)
    void createIconTheme(TestUtils testUtils, TestReference testReference) throws Exception
    {
        testUtils.createPage(testReference, ")))**not bold**");
        testUtils.addObject(testReference, "IconThemesCode.IconThemeClass");

        testUtils.gotoPage(testReference);

        String content = testUtils.getDriver().findElementWithoutWaiting(By.id("xwikicontent")).getText();

        // Make sure the wiki syntax was not interpreted
        assertTrue(content.contains("**not bold**"));
    }
}

Fix escaping * add test

XWIKI-19731: Fix escaping
* add test


package babysteps.model;

import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.stream.Collectors;

public class TaskModel {

    /**
     * Top of the task B-tree. All subtasks should be contained within this instance.
     */
    private Task currentTask;

    /**
     * Constructor.
     */
    public TaskModel() {
        currentTask = new Task("Tasks");
    }

    /**
     * Provide all of the subtask titles.
     *
     * @return a List of strings
     */
    public List<String> subtaskNames() {
        return currentTask.getSubtasks().stream()
                .map(Task::getTitle)
                .collect(Collectors.toList());
    }

    /**
     * Return the head of the task tree.
     *
     * @return a Task instance
     */
    public Task getCurrentTask() {
        return currentTask;
    }

    /**
     * Add a child to the current task.
     *
     * @param title
     */
    public void createTask(String title) {
        currentTask.getSubtasks().add(new Task(title, currentTask));
    }

    /**
     * Move down the tree to a specific task.
     *
     * @param taskNumber
     */
    public void enterTask(int taskNumber) {
        currentTask = currentTask.getSubtasks().get(taskNumber);
    }

    /**
     * Go to the task above this one in the task tree.
     */
    public void moveUp() {
        currentTask.getParent().ifPresent(t -> currentTask = t);
    }

    /**
     * Find the top of the task tree. i.e. discover the most general task.
     *
     * @return the parent task
     */
    private Task headTask() {
        Task place = currentTask;
        while(place.getParent().isPresent()) {
            place = place.getParent().get();
        }
        return place;
    }

    /**
     * Save all tasks (including parents) to the given file.
     *
     * @param file
     * @return true if successful, false otherwise
     */
    public boolean serialize(String path) {
        try {
            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(headTask());
            out.close();
            fileOut.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Overwrite the entire model with a new task tree. The previous task tree is not saved.
     *
     * @param file
     * @return true if successful, false otherwise
     */
    public boolean deseriablize(String path) {
        try {
            FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            currentTask = (Task) in.readObject();
            in.close();
            fileIn.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
}

Implement a main model class with serialization


package leetcode.largest_rectangle_in_histogram;

import java.util.Stack;

public class Solution {
	public static class Histogram{
		int offset, height;
		public Histogram(int offset, int height){
			this.offset = offset;
			this.height = height;
		}
	}
    public int largestRectangleArea(int[] height) {
    	Stack<Histogram> stack = new Stack<Histogram>();
    	int length = height.length;
    	int max = 0;
    	for(int i = 0; i < length; i++){
    		int left = i;
    		while(!stack.isEmpty() && stack.peek().height >= height[i]){
    			Histogram hist = stack.pop();
    			int area = hist.height * (i - hist.offset);
    			left = hist.offset;
    			if(area > max) max = area;
    		}
    		stack.push(new Histogram(left, height[i]));
    	}
    	while(!stack.isEmpty()){
			Histogram hist = stack.pop();
			int area = hist.height * (length - hist.offset);
			if(area > max) max = area;
    	}
    	return max;
    }
    public static void main(String[] args){
    	System.err.println(new Solution().largestRectangleArea(new int[]{1,1,1,1,1,2,9,8,8, 5, 5}));
    }
}

Add java solution for 84. Largest Rectangle in Histogram

84. Largest Rectangle in Histogram: https://leetcode.com/problems/largest-rectangle-in-histogram/


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 Board of Regents of the University of
 * Wisconsin-Madison and University of Konstanz.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops.create;

import net.imagej.ops.Op;
import net.imagej.ops.Ops;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.real.DoubleType;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = Op.class, name = Ops.CreateImg.NAME)
public class CreateImgSimple implements Ops.CreateImg
{

	@Parameter(type = ItemIO.OUTPUT)
	private Img<DoubleType> output;

	@Parameter
	private long[] dims;

	@Override
	public void run() {
		output = ArrayImgs.doubles(dims);
	}
}

Add a simple createimg that uses DoubleType

This fixes the README.md example.


/*
 * Copyright 2017 Viktor Csomor
 *
 * 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.viktorc.pp4j.impl;

import org.junit.Assert;
import org.junit.Test;

/**
 * A unit test class for {@link SimpleCommand}.
 *
 * @author Viktor Csomor
 */
public class SimpleCommandTest extends TestCase {

  @Test
  public void testGeneratesOutputFalseWhenNoCompletionPredicatesDefined() {
    SimpleCommand command = new SimpleCommand(null);
    Assert.assertFalse(command.generatesOutput());
  }

  @Test
  public void testGeneratesOutputTrueWhenCompletionPredicatesDefined() {
    SimpleCommand command = new SimpleCommand(null, (c, o) -> true, (c, o) -> false);
    Assert.assertTrue(command.generatesOutput());
  }

  @Test
  public void testThrowsExceptionWhenPredicateNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleCommand(null, (c, o) -> true, null);
  }

}

Add basic simple command unit test

Add basic simple command unit test


package leetcode.combination_sum_iii;

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

public class Solution {

    public void dfs(int curN, int rest, int depth, int k, List<Integer> cur, List<List<Integer>> ret){
        if(depth == k && rest == 0){
            ret.add(new ArrayList<Integer>(cur));
        }else{
            for(int i = curN + 1; i <= 9; i++){
                if(rest - i >= 0){
                    cur.add(i);
                    dfs(i, rest - i, depth + 1, k, cur, ret);
                    cur.remove(depth);
                }
            }
        }
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        dfs(0, n, 0, k, new ArrayList<Integer>(), ret);
        return ret;
    }

    public static void main(String[] args){
        for(List<Integer> ans : new Solution().combinationSum3(3, 9)){
            for(int x : ans){
                System.err.print(x + " ");
            }
            System.err.println("");
        }
    }
}

Add java solution for 216. Combination Sum III

216. Combination Sum III: https://leetcode.com/problems/combination-sum-iii/


/*
 * Created on Nov 11, 2005
 */
package uk.org.ponder.rsf.uitype;

public class BooleanUIType implements UIType {
  public static final BooleanUIType instance = new BooleanUIType();
  public Boolean PLACEHOLDER = new Boolean(false);
  public Object getPlaceholder() {
    return PLACEHOLDER;
  }
  public String getName() {
    return "boolean";
  }
  public boolean valueUnchanged(Object oldvalue, Object newvalue) {
    return oldvalue.equals(newvalue);
  }
}

/*
 * Created on Nov 11, 2005
 */
package uk.org.ponder.rsf.uitype;

public class BooleanUIType implements UIType {
  public static final BooleanUIType instance = new BooleanUIType();
  public Boolean PLACEHOLDER = Boolean.FALSE;
  public Object getPlaceholder() {
    return PLACEHOLDER;
  }
  public String getName() {
    return "boolean";
  }
  public boolean valueUnchanged(Object oldvalue, Object newvalue) {
    return oldvalue.equals(newvalue);
  }
}

Use constant to generate Boolean

Use constant to generate Boolean


/*
 * Copyright 2013-present Facebook, 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 com.facebook.buck.event;

import com.facebook.buck.timing.Clock;
import com.facebook.buck.util.Scope;
import com.google.common.base.Supplier;

/** Event Class containing the perf data regarding action graph building */
public class ActionGraphPerfStatEvent extends AbstractBuckEvent {

  private static final String EVENT_NAME = "ActionGraphPerfStats";

  private final Long elapsedTime;
  private final int numberNodesGenerated;
  private final String targetNodeDescriptionName;
  private final String buildTargetName;

  private ActionGraphPerfStatEvent(
      Long time, int generatedNodesCount, String descriptionName, String buildName) {
    super(EventKey.unique());
    elapsedTime = time;
    numberNodesGenerated = generatedNodesCount;
    targetNodeDescriptionName = descriptionName;
    buildTargetName = buildName;
  }

  /**
   * Creates a Scope for the timing event
   *
   * @param clock
   * @param eventBus
   * @param getRuleSize
   * @param descriptionName
   * @param buildTargetName
   * @return
   */
  public static Scope start(
      Clock clock,
      BuckEventBus eventBus,
      Supplier<Integer> getRuleSize,
      String descriptionName,
      String buildTargetName) {
    ActionGraphPerfStatEvent.Start start = new Start(clock);
    int startSize = getRuleSize.get();
    return () ->
        eventBus.post(
            start.finish(getRuleSize.get() - startSize, descriptionName, buildTargetName));
  }

  @Override
  protected String getValueString() {
    return "";
  }

  @Override
  public String getEventName() {
    return EVENT_NAME;
  }

  public Long getElapsedTime() {
    return elapsedTime;
  }

  public int getNumberNodesGenerated() {
    return numberNodesGenerated;
  }

  public String getBuildTargetName() {
    return buildTargetName;
  }

  public String getTargetNodeDescriptionName() {
    return targetNodeDescriptionName;
  }

  /** Class representing the start of timing */
  public static class Start {

    private final Long startTime;
    private Clock clock;

    private Start(Clock clock) {
      this.clock = clock;
      this.startTime = clock.currentTimeMillis();
    }

    /** Generates the event representing the end of the timing */
    private ActionGraphPerfStatEvent finish(
        int generatedNodesCount, String descriptionName, String buildTargetName) {
      return new ActionGraphPerfStatEvent(
          clock.currentTimeMillis() - startTime,
          generatedNodesCount,
          descriptionName,
          buildTargetName);
    }
  }
}

Add scuba logging and action graph instrumentation event

Summary:
We want to add scuba logging of stats of action graph construction.
This adds the Events necessary and make the appropriate changes to ScubaEventListener.

Test Plan: Unit test

Reviewed By: sbalabanov

fbshipit-source-id: f751a02


/* @(#)SafeViewFlipper.java
 *
 *========================================================================
 * Copyright 2011 by Zeo Inc. All Rights Reserved
 *========================================================================
 *
 * Date: $Date$
 * Author: Christopher Souvey <christopher.souvey@myzeo.com>
 * Version: $Revision$
 */

package com.androsz.electricsleepbeta.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ViewFlipper;

/**
 * View flipper that protects against against crashes during screen rotations.
 *
 * @author Christopher Souvey
 * @version $Revision$
 */
public class SafeViewFlipper extends ViewFlipper {

    private static final String TAG = SafeViewFlipper.class.getSimpleName();

    public SafeViewFlipper(Context context) {
        super(context);
    }

    public SafeViewFlipper(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Workaround for Android Bug 6191:
     * http://code.google.com/p/android/issues/detail?id=6191
     * <p/>
     * ViewFlipper occasionally throws an IllegalArgumentException after screen
     * rotations.
     */
    @Override
    protected void onDetachedFromWindow() {
        try {
            super.onDetachedFromWindow();
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "SafeViewFlipper ignoring IllegalArgumentException");
            // Call stopFlipping() in order to kick off updateRunning()
            stopFlipping();
        }
    }
}

Add a safe view flipper to prevent crashes during screen rotations while flipper is flipping.


package net.imagej.ops.filter.max;

import net.imagej.ops.ComputerOp;
import net.imagej.ops.Ops;
import net.imagej.ops.filter.AbstractNonLinearFilter;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;

import org.scijava.Priority;
import org.scijava.plugin.Plugin;

/**
 * Default implementation of {@link MaxFilterOp}.
 *
 * @author Jonathan Hale (University of Konstanz)
 * @param <T> type
 */
@Plugin(type = Ops.Filter.Max.class, name = Ops.Filter.Max.NAME,
	priority = Priority.LOW_PRIORITY)
public class DefaultMaxFilter<T extends RealType<T>> extends
	AbstractNonLinearFilter<T, T> implements
	MaxFilterOp<RandomAccessibleInterval<T>>
{

	@SuppressWarnings("unchecked")
	@Override
	protected ComputerOp<Iterable<T>, T> getComputer(Class<?> inClass,
		Class<?> outClass)
	{
		return (ComputerOp<Iterable<T>, T>) ops.op(Ops.Stats.Max.class, Iterable.class,
			inClass);
	}

}

Add default implementation of MaxFilterOp

Signed-off-by: squareys <b4e1335d2c774058f7a95112f52894dcc752fd3f@googlemail.com>


/*
 * 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.problem25;

import java.util.List;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AnagramsTest {

  private Anagrams anagrams;

  @Before public void setUp() {
    this.anagrams = new Anagrams();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStrings() {
    anagrams.get(null);
  }

  @Test public void shouldReturnAnEmptyListIfInputStringIsEmpty() {
    assertTrue(anagrams.get("").isEmpty());
  }

  @Test public void shouldCalculateEveryAnagram() {
    String input = "abc";

    List<String> result = anagrams.get(input);
    String[] arrayResult = new String[result.size()];
    result.toArray(arrayResult);

    String[] expectedArray = { "abc", "acb", "bac", "bca", "cab", "cba" };
    assertArrayEquals(expectedArray, arrayResult);
  }
}

Add some tests to problem 25

Add some tests to problem 25


/*
 * 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.trellisldp.spi;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * @author acoburn
 */
public class IdentifierServiceTest {

    @Test
    public void testConfig() {
        final Integer zero = 0;
        final IdentifierService.IdentifierConfiguration config = new IdentifierService.IdentifierConfiguration();
        assertEquals("", config.getPrefix());
        assertEquals(zero, config.getHierarchy());
        assertEquals(zero, config.getLength());
    }

    @Test
    public void testConfig2() {
        final Integer hierarchy = 4;
        final Integer length = 2;
        final String prefix = "foo:";
        final IdentifierService.IdentifierConfiguration config = new IdentifierService.IdentifierConfiguration(
                prefix, hierarchy, length);
        assertEquals(prefix, config.getPrefix());
        assertEquals(hierarchy, config.getHierarchy());
        assertEquals(length, config.getLength());
    }
}

Add inner class for configuration

Add inner class for configuration


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ccsu;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Web application lifecycle listener.
 *
 * @author cw1491
 */
@WebListener()
public class SessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute created "+event.getName()+"="+event.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute removed "+event.getName());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute changed "+event.getName()+"="+event.getValue());
    }
}

Add example session attribute listener

Add example session attribute listener


package java8intro.java8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
	private final List<Integer> integers = Arrays.asList(5, 7, 34, 12, 4, 5, 76, 2, 1, 67, 52, 74);

	private void filterAndSort() {
		integers.stream()
				.filter(i -> i % 2 == 0)
				.sorted()
				.forEach(System.out::println);
	}

	private void multiplyByTwo() {
		integers.stream()
				.map(i -> i * 2)
				.forEach(System.out::println);
	}

	private void parallelStream() {
		List<Integer> sortedIntegers = integers.stream().sorted().collect(Collectors.toList());
		System.out.println(sortedIntegers);
		sortedIntegers.parallelStream().forEach(System.out::println);
	}

	public static void main(String[] args) {
		StreamExample streamExample = new StreamExample();
		streamExample.filterAndSort();
		System.out.println("===================");
		streamExample.multiplyByTwo();
		System.out.println("===================");
		streamExample.parallelStream();
	}
}

Add stream and parallel stream example

Add stream and parallel stream example