/*
 * See the file LICENSE in distribution for licensing and copyright
 */
package org.jtestr.maven;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import org.jtestr.BackgroundServer;

/**
 * The class responsible for starting a background server in Maven2.
 *
 * @author Ola Bini
 * @goal server
 */
public class JtestRMavenServerMojo extends AbstractMojo {
    /**
     * Debug output from server.
     *
     * @parameter expression="true"
     */
    private boolean debug;

    /**
     * Port to start background server on.
     *
     * @parameter expression="22332"
     */
    private int port;

    /**
     * Amount of runtimes to start.
     *
     * @parameter expression="3"
     */
    private int runtimes;

    public void execute() throws MojoExecutionException {
        try {
            new BackgroundServer(port, runtimes, debug).startServer();
        } catch(java.io.IOException e) {
            throw new MojoExecutionException("Build server failed", e);
        }
    }
}

Add server mojo for Maven


package io.bit3.jsass.context;

import io.bit3.jsass.importer.Import;

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

/**
 * Stack for tracking currently evaluated file.
 */
public class ImportStack {

  /**
   * A registry where each import will be registered by an incrementing ID.
   */
  private Map<Integer, Import> registry = new HashMap<>();

  /**
   * The current import stack.
   */
  private Stack<Import>        stack    = new Stack<>();

  /**
   * Register a new import, return the registration ID.
   */
  public int register(Import importSource) {
    int id = registry.size() + 1;
    registry.put(id, importSource);
    return id;
  }

  /**
   * Push an import to the stack by its ID.
   */
  public void push(int id) {
    stack.push(registry.get(id));
  }

  /**
   * Pop an import from the stack.
   */
  public void pop() {
    stack.pop();
  }

  /**
   * Return the current import.
   */
  public Import peek() {
    return stack.peek();
  }
}

package io.bit3.jsass.context;

import io.bit3.jsass.importer.Import;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Stack for tracking currently evaluated file.
 */
public class ImportStack {

  /**
   * A registry where each import will be registered by an incrementing ID.
   */
  private Map<Integer, Import> registry = new HashMap<>();

  /**
   * The current import stack.
   */
  private Deque<Import> stack = new LinkedList<>();

  /**
   * Register a new import, return the registration ID.
   */
  public int register(Import importSource) {
    int id = registry.size() + 1;
    registry.put(id, importSource);
    return id;
  }

  /**
   * Push an import to the stack by its ID.
   */
  public void push(int id) {
    stack.push(registry.get(id));
  }

  /**
   * Pop an import from the stack.
   */
  public void pop() {
    stack.pop();
  }

  /**
   * Return the current import.
   */
  public Import peek() {
    return stack.peek();
  }
}

Use a Deque instead of Stack.


package com.nullprogram.noise;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import lombok.val;

public final class Launcher {

    public static void main(String[] args) {
        /* Create an image. */
        Noise noise = new PerlinNoise(0, 2);
        double max = 8.0;
        double step = 0.02;
        int size = (int) (max / step);
        val im = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < size; i++) {
            double x = i * step;
            for (int j = 0; j < size; j++) {
                double y = j * step;
                Vector p = new Vector(x, y);
                double m = noise.sample(p);
                float v = (float) ((m + 1f / 3f) * 3f / 2f);
                int c = new Color(v, v, v).getRGB();
                im.setRGB(i, j, c);
            }
        }

        /* Save the image. */
        try {
            ImageIO.write(im, "PNG", new File("out.png"));
        } catch (IOException e) {
            System.out.println("Failed to write image.");
            System.exit(-1);
        }
    }
}

Create an output image for testing.


/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2014 LensKit Contributors.  See CONTRIBUTORS.md.
 * Work on LensKit has been funded by the National Science Foundation under
 * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
 *
 * This program 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 program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
/**
 * Interfaces defining an implementation-independent recommendation API.
 */
package org.lenskit.api;

Add package docs to o.l.api


package src;

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

public class Game {

    String _player;
    DataBaseWorker _dbworker;
    String _judge;

    public Game(String player, DataBaseWorker dbworker, String judge){
        _player = player;
        //_dbworker = dbworker;
        _judge = judge;
    }

    public void OrganizeGame()
    {
        try {
            Files.walk(Paths.get("d:\\AICupEnvironment\\Games\\Cross\\")).forEach(filePath -> {
                Do(filePath);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * Здесь проверяем, есть ли файл runme.sh
     * Если есть, то вызываем программу Judge
     * Ловим int ответ, расшифровка пока такая:
     * 0 - ничья (а что, очень даже может быть)
     * 1 - выиграл первый игрок
     * 2 - выиграл второй игрок
     * Может случиться так, что игра не пройдет (кто-то из игроков не уложится во время или еще что-то)
     * тогда 2 варианта - либо Judge сам решает, что ставит техническое поражение кому-то (то есть другой побеждает)
     * либо определяет эту ситуацию и вернет другое значение
     * это позволит записать в БД соответствующую информацию
    */
    private void Do(Path filePath) {
        if(!filePath.endsWith("runme.sh"))
            return;

        String commands[] = {_judge, "user1, user2"};
        Runtime rt = Runtime.getRuntime();

        int gameResult = 0;
        try {
            Process proc = rt.exec(commands);
            gameResult = proc.exitValue();

            _dbworker.WriteGameResult("user1", "user2", gameResult);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Create method DO, define Judge's return format.


// Add more constructors to TwoDShape.

// A class for two-dimensional objects.
class TwoDShape {
  private double width;  // these are
  private double height; // now private

  // A default constructor.
  TwoDShape() {
    width = height = 0.0;
  }

  // Parameterized constructor.
  TwoDShape(double w, double h) {
    width = w;
    height = h;
  }

  // Construct object with equal width and height.
  TwoDShape(double x) {
    width = height = x;
  }

  // Accessor methods for width and height.
  double getWidth() { return width; }
  double getHeight() { return height; }
  void setWidth(double w) { width = w; }
  void setHeight(double h) { height = h; }

  void showDim() {
    System.out.println("Width and height are " + width + " and " + height);
  }
}

// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
  private String style;

  // A default constructor.
  Triangle() {
    super();
    style = "null";
  }

  //Constructor
  Triangle(String s, double w, double h) {
    super(w, h); // call superclass constructor

    style = s;
  }

  // Construct an isoceles triangle.
  Triangle(double x) {
    super(x); // call superclass constructor
    style = "isosceles";
  }

  double area () {
    return getWidth() * getHeight() / 2;
  }

  void showStyle() {
    System.out.println("Triangle is " + style);
  }
}

class Shapes5 {
  public static void main(String args[]) {
    Triangle t1 = new Triangle();
    Triangle t2 = new Triangle("right", 8.0, 12.0);
    Triangle t3 = new Triangle(4.0);

    t1 = t2;

    System.out.println("Info for t1: ");
    t1.showStyle();
    t1.showDim();
    System.out.println("Area is " + t1.area());

    System.out.println();

    System.out.println("Info for t2: ");
    t2.showStyle();
    t2.showDim();
    System.out.println("Area is " + t2.area());

    System.out.println();

    System.out.println("Info for t3: ");
    t3.showStyle();
    t3.showDim();
    System.out.println("Area is " + t3.area());

    System.out.println();
  }
}

Add more constructors to TwoDShape


/*
 * Copyright 2014 Kevin Quan (kevin.quan@gmail.com)
 *
 * 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.kevinquan.android.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

/**
 * Collection of utilities for working with the SD card
 * @author Kevin Quan (kevin.quan@gmail.com)
 *
 */
public class SDUtils {

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

    /**
     * Saves a string representation of an object to the SD card at the provided destination.
     * @param destination The relative path from the SD root where the object should be written to.  If any intermediate folders do not exist, they will be created.
     * @param content The content to be written to.  The result of the toString() method on the object will be written to disk.
     * @return A file object of the destination file, or null if the write did not succeed.
     */
    public static File saveObjectToSD(String destination, Object content) {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Log.w(TAG, "Could not write to SD card as media is not ready (mounted).");
            return null;
        }
        if (TextUtils.isEmpty(destination)) {
            Log.w(TAG, "Could not write to SD card as no destination was provided.");
            return null;
        }
        if (content == null) {
            Log.w(TAG, "Could not write to SD card as content to write was empty.");
            return null;
        }
        File outputFile = new File(Environment.getExternalStorageDirectory(), destination);
        FileUtils.ensureParentFoldersCreated(outputFile, true);
        FileWriter writer = null;
        try {
            writer = new FileWriter(outputFile);
            writer.write(content.toString());
            Log.d(TAG, "Content written to "+outputFile.getAbsolutePath());
            return outputFile;
        } catch (IOException e) {
            Log.e(TAG, "Could not output content to "+outputFile.getAbsolutePath(), e);
            return null;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {}
            }
        }
    }
}

Write arbitrary objects to SD card


/*
 * Copyright 2014-2016 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 docs;

public class Docs {
}

Fix docs module Sonar build


/*
 * Copyright (c) 2013-2013, KNOPFLERFISH project
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following
 * conditions are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * - Neither the name of the KNOPFLERFISH project nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.knopflerfish.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Misc static timer utility methods.
 */
public class Timer {

  static private Method nanoTimeMethod;

  static {
    AccessController.doPrivileged(new PrivilegedAction() {
      public Object run() {
        nanoTimeMethod = getMethod(System.class, "nanoTime", new Class[] { });
        return null;
      }
    });
  }

  /**
   * Get method from class
   */
  public static Method getMethod(Class c, String name, Class [] args) {
    Method m = null;
    while (true) {
      try {
        m = c.getDeclaredMethod(name, args);
        break;
      } catch (NoSuchMethodException e) {
        c = c.getSuperclass();
        if (c == null) {
          return null;
        }
      }
    }
    return m;
  }

  /**
   * Use System.nanoTime() if available, otherwise revert to
   * System.currentTimeMillis(). Return time in milliseconds
   * that can be used for time measurements.
   */
  public static long timeMillis() {
    if (nanoTimeMethod != null) {
      try  {
        Object res = nanoTimeMethod.invoke(null, new Object[] { });
        if (res != null) {
          return ((Long)res).longValue() / 1000000L;
        }
      } catch (IllegalAccessException _ignore) {
      } catch (InvocationTargetException _ignore) { }
    }
    return System.currentTimeMillis();
  }

}

Add file missed in last check-in.


/*
    JSPWiki - a JSP-based WikiWiki clone.

    Copyright (C) 2001-2002 Janne Jalkanen (Janne.Jalkanen@iki.fi)

    This program 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 program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.ecyrd.jspwiki.tags;

import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

/**
 * ParamTag submits name-value pairs to the first enclosing
 * ParamHandler instance. Name and value are strings, and can
 * be given as tag attributes, or alternatively the value can be
 * given as the body contents of this tag.
 * <p>
 * The name-value pair is passed to the closest containing
 * ancestor tag that implements ParamHandler.
 */
public class ParamTag
    extends BodyTagSupport
{

    private String m_name;
    private String m_value;

    public void release()
    {
        m_name = m_value = null;
    }

    public void setName( String s )
    {
        m_name = s;
    }

    public void setValue( String s )
    {
        m_value = s;
    }

    public int doEndTag()
    {
        Tag t = null;
        while( (t = getParent()) != null && !(t instanceof ParamHandler) )
            ;
        if( t != null )
        {
            String val = m_value;
            if( val == null )
            {
                BodyContent bc = getBodyContent();
                if( bc != null )
                {
                    val = bc.getString();
                }
            }
            if( val != null )
            {
                ((ParamHandler)t).setContainedParameter( m_name, val );
            }
        }

        return EVAL_PAGE;
    }
}

Tag for providing name-value pairs to a parent tag


/**
 * Apresentar os conceitos de Classes Wrapper
 * @author Fabrício Silva
 */

public class ClasseWrapper {
  public static void main(String[] args) {
    Integer idade = new Integer(29);
    Double preco = new Double(12.45);

    double d = preco.doubleValue();
    int i = preco.intValue();
    byte b = preco.byteValue();

    Boolean casado = new Boolean("false");

    // Conversão estática
    double d1 = Double.parseDouble("123.45");
    int i1 = Integer.parseInt("123");
    float f1 = Float.parseFloat("3.14F");

    int i2 = Integer.valueOf("101011", 2);
    System.out.println(i2);
  }
}

Add learn Java class ClassWrapper


/*++

Copyright (c) 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

Module Name:
  FrameworkLogger.java

Abstract:

--*/

package org.tianocore.framework.tasks;

import org.apache.tools.ant.Project;

import org.tianocore.common.logger.LogMethod;

class FrameworkLogger implements LogMethod {
    private Project project;
    private String  titleName;
    public FrameworkLogger(Project project, String taskName) {
        this.project = project;
        this.titleName = taskName;
    }

    public void putMessage(Object msgSource, int msgLevel, String msg) {
        String frameworkMsg = " [" + this.titleName + "] " + msg;
        this.project.log(frameworkMsg, Project.MSG_INFO);
    }
}

/*++

Copyright (c) 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

Module Name:
  FrameworkLogger.java

Abstract:

--*/

package org.tianocore.framework.tasks;

import org.apache.tools.ant.Project;

import org.tianocore.common.logger.LogMethod;

class FrameworkLogger implements LogMethod {
    private Project project;
    private String  titleName;
    public FrameworkLogger(Project project, String taskName) {
        this.project = project;
        this.titleName = taskName;
    }

    public void putMessage(Object msgSource, int msgLevel, String msg) {
        String frameworkMsg = " [" + this.titleName + "] " + msg;
        this.project.log(frameworkMsg, Project.MSG_INFO);
    }

    public void flushToFile(File file) {
    }
}

Update for the interface has changed.


package com.lri.eeclocalizer.core.model;

import com.google.android.gms.maps.model.LatLng;

/**
 * Created by Lyonnel T. DZOTANG on 14/12/2015.
 */
public enum Parish {
    TAMDJA(1, "Paroisse de Tamdja", 5.4668672, 10.4164029),
    BAFOUSSAMPLATEAU(2, "Paroisse de Bafoussam Plateau", 5.4819165, 10.4193172);

    private int id;
    private String displayName;
    private LatLng location;

    Parish(int id, String displayName, double latitude, double longitude) {
        this.id = id;
        this.displayName = displayName;
        this.location = new LatLng(5.4668672, 10.4164029);
    }

    Parish[] getAllParish() {
        return Parish.values();
    }

    public LatLng getLatLng(){
        return this.location;
    }

    public String getDisplayName() {
        return this.displayName;
    }

}

Add the main function of evaluation of the closest parish.


package com.twu.biblioteca;

import org.junit.Test;

import java.io.StringWriter;

import static org.junit.Assert.assertEquals;

public class BibliotecaApplicationTest {

    String expectedSequence = "Bangalore Public Library Welcomes You\n" +
            "Book name = Harry Potter And The Goblet Of Fire, Author = J K Rowling, Year of publication = 2008\n" +
            "Book name = Harry Potter And The Order Of Phoenix, Author = J K " +
            "Rowling, Year of publication = 2012\n";

    @Test
    public void shouldTestTheSequenceOfInput() {

        final StringWriter stringWriter = new StringWriter();
        OutputWriter outputWriter = new OutputWriter(stringWriter);
        Biblioteca biblioteca = new Biblioteca(outputWriter);
        BibliotecaApplication application = new BibliotecaApplication(biblioteca);

        application.run();

        final StringBuffer stringBuffer = stringWriter.getBuffer();
        assertEquals(expectedSequence,stringBuffer.toString());
    }
}

Test the sequence of messages displayed to user


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

import java.io.IOException;

import junit.framework.Assert;

import org.apache.pig.builtin.REPLACE;
import org.apache.pig.builtin.TOMAP;
import org.apache.pig.impl.PigContext;
import org.junit.Test;

public class TestPigContextClassCache {
    @Test
    public void testClassCache() throws IOException {
        Class<?> c = PigContext.resolveClassName("TOMAP");
        Assert.assertEquals(TOMAP.class, c);

        c = PigContext.resolveClassName("TOMAP");
        Assert.assertEquals(TOMAP.class, c);

        c = PigContext.resolveClassName("org.apache.pig.builtin.REPLACE");
        Assert.assertEquals(REPLACE.class, c);
    }

}

Add class cache to PigContext


import org.junit.Test;

import java.util.Arrays;

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

public class AnagramTest {

    /*
    O(n) anagram
     */
    @Test
    public void anagram_Test() {

       boolean result = anagram("williamshakespeare", "iamaweakishspeller");

        assertThat(result).isEqualTo(true);
    }

    private boolean anagram(String s1, String s2) {
        if(s1.length()!=s2.length()) return false;

        int sum = 0;
        for( int i=0; i<s1.length(); sum += s1.charAt(i) - s2.charAt(i), i++);
        return sum == 0;
    }
}

Add very simple anagram O(n)


package com.haxademic.demo.draw.text;

import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.data.constants.PTextAlign;
import com.haxademic.core.draw.text.FontCacher;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.media.DemoAssets;
import com.haxademic.core.system.DateUtil;

import processing.core.PFont;

public class Demo_Clock
extends PAppletHax {
	public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected void drawApp() {
		background(0);
		drawClock();
	}

	protected void drawClock() {
		PFont font = FontCacher.getFont(DemoAssets.fontOpenSansPath, 100);
		FontCacher.setFontOnContext(p.g, font, p.color(0, 255, 0), 2f, PTextAlign.CENTER, PTextAlign.CENTER);

		String dateString = DateUtil.currentDate(" - ");
		String timeString = DateUtil.currentTime(true, false, false);
		p.text(dateString + FileUtil.NEWLINE + timeString, 0, 0, p.width, p.height);
	}

}

Add clcok demo for DateUtil functions


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2020 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.algorithm;

import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.algebra.RModuleMember;
import nom.bdezonia.zorbage.data.DimensionedDataSource;
import nom.bdezonia.zorbage.procedure.Procedure2;
import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionMember;

/**
 *
 * @author Barry DeZonia
 *
 */
public class BoundingBox {

	// do not instantiate

	private BoundingBox() { }

	/**
	 *
	 * @param alg
	 * @param data
	 * @param min
	 * @param max
	 */
	public static <U>
		void compute(DimensionedDataSource<U> data,
						RModuleMember<HighPrecisionMember> min,
						RModuleMember<HighPrecisionMember> max)
	{
		HighPrecisionMember value = G.HP.construct();
		int numD = data.numDimensions();
		min.init(numD);
		max.init(numD);
		for (int i = 0; i < numD; i++) {
			Procedure2<Long, HighPrecisionMember> axis = data.getAxisEquation(i);
			axis.call(0L, value);
			min.setV(i, value);
			axis.call(data.dimension(i)-1, value);
			max.setV(i, value);
		}
	}
}

Define an algo that computes the real world bounds of n-d data


public class Solution {

    public boolean isPalindrome(int x) {

        if (x < 0 || (x != 0 && x % 10 == 0)) {
            return false;
        }

        int reversedNum = 0;
        while (x > reversedNum) {

            reversedNum = (reversedNum * 10) + (x % 10);
            x /= 10;

        }

        return (x == reversedNum) || (x == reversedNum / 10);

    }

}

Create : 9 Palindrome Number


package com.hackoeur.jglm;

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

import com.hackoeur.jglm.support.FastMath;

/**
 * @author James Royalty
 */
public class InvSqrtTest {
	@Test
	public void testFastInvSqrt() {
        final float x = 133511f;
        final float fastInvSqrt = FastMath.invSqrtFast(x);
        final float computedInvSqrt = (float) (1 / StrictMath.sqrt(x));

        Assert.assertEquals(fastInvSqrt, computedInvSqrt, 0.000000001f);
	}

	@Test
	public void testFastSqrt() {
		final float x = 133511f;
        final float fastSqrt = FastMath.sqrtFast(x);
        final float computedSqrt = (float) StrictMath.sqrt(x);

        Assert.assertEquals(fastSqrt, computedSqrt, 0.0001f);
	}
}

Test case for inverse sqrt.


package leetcode.merge_sorted_array;

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
    	int tail = m + n - 1;
    	n--;
    	m--;
    	while(tail >= 0){
    		if(n < 0){
    			return;
    		}else if(m < 0){
    			A[tail--] = B[n--];
    		}else if(A[m] > B[n]){
    			A[tail--] = A[m--];
    		}else{
    			A[tail--] = B[n--];
    		}
    	}
    }
}

Add java solution for 88. Merge Sorted Array


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2017 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.
 */

/**
 * Utilities relating abstractly to network-related activities.
 *
 * @author David M. Lloyd
 */

package org.wildfly.common.net;

Introduce new net package for networking things


package tcs.javaproject.guitest;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * Created by byebye on 27.04.15.
 */
public class SignUpWindow extends Application {

   @Override
   public void start(Stage primaryStage) throws Exception {
      primaryStage.setTitle("DebtManager - Sign Up");

      GridPane grid = new GridPane();
      grid.setHgap(10);
      grid.setVgap(10);
      grid.setPadding(new Insets(25, 25, 25, 25));

      grid.add(new Text("Create new account"), 0, 0, 2, 1);

      TextField email = new TextField();
      email.setPromptText("Email");
      TextField username = new TextField();
      username.setPromptText("Username");
      TextField bankAccount = new TextField();
      bankAccount.setPromptText("Bank account");
      PasswordField password = new PasswordField();
      password.setPromptText("Password");
      PasswordField passwordRepeated = new PasswordField();
      passwordRepeated.setPromptText("Repeat password");

      grid.add(new Label("Email:"), 0, 1);
      grid.add(email, 1, 1, 2, 1);
      grid.add(new Label("Username:"), 0, 2);
      grid.add(username, 1, 2, 2, 1);
      grid.add(new Label("Bank account:"), 0, 3);
      grid.add(bankAccount, 1, 3, 2, 1);
      grid.add(new Label("Password:"), 0, 4);
      grid.add(password, 1, 4, 2, 1);
      grid.add(new Label("Repeat password:"), 0, 5);
      grid.add(passwordRepeated, 1, 5, 2, 1);

      Button cancelButton = new Button("Cancel");
      HBox leftButtonBox = new HBox(cancelButton);
      leftButtonBox.setAlignment(Pos.CENTER_LEFT);

      Button signUpButton = new Button("Sign Up");
      HBox rightButtonBox = new HBox(signUpButton);
      rightButtonBox.setAlignment(Pos.CENTER_RIGHT);
      grid.add(leftButtonBox, 0, 6);
      grid.add(rightButtonBox, 2, 6);

      primaryStage.setScene(new Scene(grid, 300, 300));
      primaryStage.show();
   }

   public static void main(String[] args) {
      launch(args);
   }
}

Create 'Sign up' window - temporary in server package, but only for tests purposes


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

/**
 * Given an input String containing a sentence, can you write a method to reverse the content of
 * the sentence without reverse every word?
 *
 * For example:
 *
 * Input: "Pedro Vicente Gómez" Output: "Gómez Vicente Pedro"
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseSentence {

}

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

/**
 * Given an input String containing a sentence, can you write a method to reverse the content of
 * the sentence without reverse every word?
 *
 * For example:
 *
 * Input: "Pedro Vicente Gómez" Output: "Gómez Vicente Pedro"
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseSentence {

  private static final String WORD_SEPARATOR = " ";

  /**
   * Iterative solution for this problem. The complexity order of this algorithm is equals to O(N)
   * where N is the number of chars in the sentence because split method is really expensive. In
   * space terms the complexity order is also O(N) because we are using one StringBuilder to store
   * the result of the algorithm.
   */
  public String reverse(String sentence) {
    if (sentence == null) {
      throw new IllegalArgumentException("Input param can't be null.");
    }
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = sentence.split(WORD_SEPARATOR);
    for (int i = words.length - 1; i >= 0; i--) {
      stringBuilder.append(words[i]);
      if (i != 0) {
        stringBuilder.append(" ");
      }
    }
    return stringBuilder.toString();
  }
}

Implement iterative solution to problem 27


import java.awt.*;
import javax.swing.*;

public class SwingObserverExample {
    JFrame frame;

    public static void main(String[] args) {
        SwingObserverExample example = new SwingObserverExample();
        example.go();
    }

    public void go() {
        frame = new JFrame();
        JButton button = new JButton("Should I do it?");
        button.addActionListener(event ->
            System.out.println("Don't do it, you might regret it!")
        );
        button.addActionListener(event ->
            System.out.println("Come on, do it!")
        );
        frame.getContentPane().add(BorderLayout.CENTER, button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

Add observer pattern example, swing


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.PermuteCoordinates;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.IntervalView;

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

@Plugin(type = ViewOps.PermuteCoordinates.class, name = ViewOps.PermuteCoordinates.NAME)
public class DefaultPermuteCoordinates<T> extends
		AbstractView<RandomAccessibleInterval<T>, IntervalView<T>> implements
		PermuteCoordinates<RandomAccessibleInterval<T>, IntervalView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private int[] permutation;

	@Override
	public IntervalView<T> compute(RandomAccessibleInterval<T> input) {
		throw new UnsupportedOperationException();
	}

}

Add default implementation of PermuteCoordinates interface.


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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 org.scijava.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Useful methods for debugging programs.
 *
 * @author Curtis Rueden
 */
public final class DebugUtils {

	private DebugUtils() {
		// prevent instantiation of utility class
	}

	/** Extracts the given exception's corresponding stack trace to a string. */
	public static String getStackTrace(final Throwable t) {
		try {
			final ByteArrayOutputStream out = new ByteArrayOutputStream();
			t.printStackTrace(new PrintStream(out, false, "UTF-8"));
			return new String(out.toByteArray(), "UTF-8");
		}
		catch (final IOException exc) {
			return null;
		}
	}

	/**
	 * This method uses reflection to scan the values of the given class's static
	 * fields, returning the first matching field's name.
	 */
	public static String getFieldName(final Class<?> c, final int value) {
		final Field[] fields = c.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			if (!Modifier.isStatic(fields[i].getModifiers())) continue;
			fields[i].setAccessible(true);
			try {
				if (fields[i].getInt(null) == value) return fields[i].getName();
			}
			catch (final IllegalAccessException exc) {
				// no action needed
			}
			catch (final IllegalArgumentException exc) {
				// no action needed
			}
		}
		return "" + value;
	}

}

Add utility class with debugging methods


/**
 *
 */
package mathsquared.resultswizard2;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

/**
 * @author MathSquared
 *
 */
public class ArrayUtilsTest {

    /**
     * Test method for {@link mathsquared.resultswizard2.ArrayUtils#deepCopyOf(T[][])}.
     */
    @Test
    public void testDeepCopyOf () {
        // Initialize some arrays

        String[][][] evil = new String[][][] { { {"a", "b"}, {"c"}}, {{"e", "f", "g"}}, { {"h", "i"}, {"j"}, {"k", "l", "m"}}};
        String[][][] result = ArrayUtils.deepCopyOf(evil);
        assertArrayEquals("3-D irregular String array", evil, result);

        Integer[][] easier = new Integer[][] { {1, 2}, {3}, {4, 5, 6}};
        Integer[][] easierResult = ArrayUtils.deepCopyOf(easier);
        assertArrayEquals("2-D irregular Integer array", easier, easierResult);
    }

}

Add unit tests for ArrayUtils.deepCopyOf


package courseexamples.module2;

import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.utils.MapUtils;
import processing.core.PApplet;

public class LifeExpectancy extends PApplet{
	UnfoldingMap map;

	public void setup(){
		size(800, 600, OPENGL);
		map = new UnfoldingMap(this, 50, 50, 700, 500, new Google.GoogleMapProvider());
		MapUtils.createDefaultEventDispatcher(this, map);
	}

	public void draw(){
		map.draw();
	}

}

Initialize prroject and setup map


// 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 investment Servlets to sent all users investments to the frontend


package leetcode.divide_two_integers;

public class Solution {
    public int divide(int dividend, int divisor) {
    	long dividend_l = (long)dividend;
    	long divisor_l = (long)divisor;
    	long rem = 0;
    	long ans = 0;
    	boolean negative = false;
    	if(dividend_l < 0 && divisor_l < 0){
    		dividend_l = -dividend_l;
    		divisor_l = -divisor_l;
    	}else{
    		if(dividend_l < 0){
    			dividend_l = -dividend_l;
    			negative = true;
    		}
    		if(divisor_l < 0){
    			divisor_l = -divisor_l;
    			negative = true;
    		}
    	}
    	for(int t = 32; t >= 0; t--){
    		rem <<= 1;
    		rem |= (((1L << t) & dividend_l) == 0 ? 0 : 1);
    		ans <<= 1;
    		if(rem >= divisor_l){
    			ans += 1;
    			rem -= divisor_l;
    		}
    	}
    	if(negative){
    		ans = -ans;
    	}
    	return (int)ans;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().divide(-2147483648, -2147483648));
    }
}

Add java solution for 29. Divide Two Integers


/*
 * 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.btisystems.pronx.ems.core.model;

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

public class IDeviceTest {
    private I_Device device;

    public IDeviceTest() {
    }

    @Before
    public void setUp() {
    }

    @Test
    public void shouldProvideDefaultImplementations() {
        device = new I_Device();
        assertEquals("", device.toString());
        assertFalse(device == device.clone());
        assertEquals(0, device.hashCode());
        assertTrue(device.equals(null));
        assertEquals(0, device.getRoots().length);
    }

}

Test the default implementation of I_Device class.


package leetcode.path_sum;

import common.TreeNode;

public class Solution {
	public boolean hasPathSum(TreeNode root, int sum) {
		if(root == null) return false;
		if(root.left != null){
			if(root.right == null){
				return hasPathSum(root.left, sum - root.val);
			}else{
				return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
			}
		}else{
			if(root.right == null){
				return sum == root.val;
			}else{
				return hasPathSum(root.right, sum - root.val);
			}
		}
	}

}

Add java solution for 112. Path Sum


/*
 * SUDA2: An implementation of the SUDA2 algorithm for Java
 * Copyright 2017 Fabian Prasser
 *
 * 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.linearbits.suda2;

import java.util.Set;

/**
 * Listener for MSU discoveries
 *
 * @author Fabian Prasser
 */
public abstract class SUDA2ListenerMSU extends SUDA2Result {

    private int[] result;

    /**
     * A MSU has been discovered. Array is re-used. Columns can be found at columns[0] ... columns[size-1].
     *
     * @param row
     * @param columns
     * @param size
     */
    public abstract void keyFound(int row, int[] columns, int size);

    @Override
    void init(int columns, int maxK, int numUniqueRecords, int numDuplicateRecords) {
        this.result = new int[columns];
    }

    @Override
    void registerKey(Set<SUDA2Item> set) {
        throw new UnsupportedOperationException("");
    }

    @Override
    void registerKey(SUDA2Item item, SUDA2ItemSet set) {

        // Store columns
        for (int i = 0; i < set.size(); i++) {
            result[i] = set.get(i).getColumn();
        }
        result[set.size()] = item.getColumn();

        // Compute row
        SUDA2Item temp = item;
        for (int i = 0; i < set.size(); i++) {
            temp = temp.getProjection(set.get(i).getRows());
        }
        int row = temp.getRows().min();

        // Signal
        keyFound(row - 1, result, set.size() + 1);
    }

    @Override
    void registerKey(SUDA2ItemSet set) {

        // Store row
        int row = set.get(0).getRows().min();

        // Store columns
        int size = set.size();
        for (int i = 0; i < size; i++) {
            result[i] = set.get(i).getColumn();
        }

        // Signal
        keyFound(row - 1, result, size);
    }
}

Add listener to detect individual MSUs


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Norwegian Defence Research Establishment / NTNU
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package no.ntnu.okse.core;

import org.testng.annotations.Test;

import java.time.Duration;
import java.util.Properties;

import static org.testng.Assert.*;

public class UtilitiesTest {

    @Test
    public void testGetDurationAsISO8601() throws Exception {
        Duration d = Duration.ofHours(1);
        String ISOstring = Utilities.getDurationAsISO8601(d);
        assertEquals(ISOstring, "01:00:00.000");
        d = Duration.ofMinutes(1);
        ISOstring = Utilities.getDurationAsISO8601(d);
        assertEquals(ISOstring, "00:01:00.000");
        d = Duration.ofSeconds(1);
        ISOstring = Utilities.getDurationAsISO8601(d);
        assertEquals(ISOstring, "00:00:01.000");
        d = Duration.ofMillis(1);
        ISOstring = Utilities.getDurationAsISO8601(d);
        assertEquals(ISOstring, "00:00:00.001");
    }

    @Test
    public void testReadConfigurationFromFile() throws Exception {
        Utilities.createConfigDirectoryAndFilesIfNotExists();
        Properties one = Utilities.readConfigurationFromFile("config/okse.properties");
        assertNotNull(one);
    }
}

Add some tests for Utilities


package junit.org.rapidpm.frp.model;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.rapidpm.frp.model.Single;

public class SingleTest {

  @Test
  public void testEquals() {
    final Single single = new Single(0);

    assertFalse(single.equals(null));
    assertTrue(single.equals(single));
    assertTrue(single.equals(new Single(0)));
  }

  @Test
  public void testHashCode() {
    final Single single = new Single(0);

    assertEquals(31, single.hashCode());
  }

  @Test
  public void testNext() {
    final Single single = Single.next(0);

    assertNotNull(single);
    assertEquals(0, single.getT1());
  }

  @Test
  public void testToString() {
    final Single single = new Single(0);

    assertEquals("Single{t1=0}", single.toString());
  }
}

Add unit tests for org.rapidpm.frp.model.Single These tests were written using Diffblue Cover.


package com.github.boformer.answerme.impl;

import org.apache.commons.collections4.map.LRUMap;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.event.state.PreInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.service.ProviderExistsException;
import org.spongepowered.api.text.message.Message;
import org.spongepowered.api.text.message.Messages;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.util.event.Subscribe;

import com.github.boformer.answerme.api.Question;
import com.github.boformer.answerme.api.QuestionService;
import com.google.common.base.Optional;

@Plugin(id = "AnswerMe", name = "AnswerMe", version = "0.1.0")
public class AnswerMePlugin implements QuestionService
{
	//TODO injection
	private Game game;
	private Logger logger;

	private LRUMap<CommandSource, Question> activeQuestions;
	private Message answerCmdMessage;

	@Subscribe
	public void onInit(PreInitializationEvent event)
	{
		try
		{
			game.getServiceManager().setProvider(this, QuestionService.class, this);
		}
		catch (ProviderExistsException e)
		{
			logger.warn("Question Service was already registered by another plugin :(");
			return;
		}

		//TODO initialize config, copy defaults

		this.activeQuestions = new LRUMap<>(100); //TODO configurable cache size
		this.answerCmdMessage =  Messages.of("Confirm with /yes or cancel with /no"); //TODO configurable message
	}

	@Override
	public void ask(Question question)
	{
		activeQuestions.put(question.getReceipient(), question);

		question.getReceipient().sendMessage(question.getMessages());
		question.getReceipient().sendMessage(answerCmdMessage);
	}

	@Override
	public Optional<Question> getActiveQuestion(CommandSource receipient)
	{
		return Optional.fromNullable(activeQuestions.get(receipient));
	}
}

Add plugin class implementing QuestionService


/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.manipulation;

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

import com.adobe.pdfjt.pdf.document.PDFDocument;

import com.datalogics.pdf.samples.SampleTest;

import org.junit.Test;

import java.io.File;
import java.nio.file.Files;

/**
 * Tests the FlattenPdf sample.
 */
public class FlattenPdfTest extends SampleTest {

    private static final String OUTPUT_FLATTENED_PDF_PATH = "Flattened.pdf";
    private static final String INPUT_FORM_PDF_PATH = "Acroform.pdf";

    @Test
    public void testFlattenForm() throws Exception {
        final File file = newOutputFile(OUTPUT_FLATTENED_PDF_PATH);
        if (file.exists()) {
            Files.delete(file.toPath());
        }

        FlattenPdf.main(INPUT_FORM_PDF_PATH, file.getCanonicalPath());
        assertTrue(file.getPath() + " must exist after run", file.exists());

        final PDFDocument document = openPdfDocument(file.getCanonicalPath());

        assertEquals("There should not be an Acroform dictionary in a flattened form document",
                     document.getInteractiveForm(), null);
    }

    @Test
    public void testFlattenAnnotations() throws Exception {

    }

    @Test
    public void testFlattenLayers() {

    }
}

Add test file for flattening sample


/*
 * 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 io.trino.sql.query;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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

public class TestSetDigestFunctions
{
    private QueryAssertions assertions;

    @BeforeClass
    public void init()
    {
        assertions = new QueryAssertions();
    }

    @AfterClass(alwaysRun = true)
    public void teardown()
    {
        assertions.close();
        assertions = null;
    }

    @Test
    public void testCardinality()
    {
        assertThat(assertions.query(
                "SELECT cardinality(make_set_digest(value)) " +
                        "FROM (VALUES 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5) T(value)"))
                .matches("VALUES CAST(5 AS BIGINT)");
    }

    @Test
    public void testExactIntersectionCardinality()
    {
        assertThat(assertions.query(
                "SELECT intersection_cardinality(make_set_digest(v1), make_set_digest(v2)) " +
                        "FROM (VALUES (1, 1), (NULL, 2), (2, 3), (3, 4)) T(v1, v2)"))
                .matches("VALUES CAST(3 AS BIGINT)");
    }

    @Test
    public void testJaccardIndex()
    {
        assertThat(assertions.query(
                "SELECT jaccard_index(make_set_digest(v1), make_set_digest(v2)) " +
                        "FROM (VALUES (1, 1), (NULL,2), (2, 3), (NULL, 4)) T(v1, v2)"))
                .matches("VALUES CAST(0.5 AS DOUBLE)");
    }

    @Test
    public void hashCounts()
    {
        assertThat(assertions.query(
                "SELECT hash_counts(make_set_digest(value)) " +
                        "FROM (VALUES 1, 1, 1, 2, 2) T(value)"))
                .matches("VALUES map(cast(ARRAY[19144387141682250, -2447670524089286488] AS array(bigint)), cast(ARRAY[3, 2] AS array(smallint)))");
    }
}

Add test for setdigest functions


package org.axonframework.metrics;

import org.axonframework.config.Configurer;
import org.axonframework.config.ModuleConfigurer;

/**
 * Implementation of the {@link org.axonframework.config.ModuleConfigurer} which uses the
 * {@link org.axonframework.metrics.GlobalMetricRegistry} to register several Metrics Modules to the given
 * {@link org.axonframework.config.Configurer}.
 *
 * @author Steven van Beelen
 * @since 3.2
 */
public class MetricsModuleConfigurer implements ModuleConfigurer {

    private final GlobalMetricRegistry globalMetricRegistry;

    public MetricsModuleConfigurer(GlobalMetricRegistry globalMetricRegistry) {
        this.globalMetricRegistry = globalMetricRegistry;
    }

    @Override
    public void configureModule(Configurer configurer) {
        globalMetricRegistry.registerWithConfigurer(configurer);
    }
}

Create ModuleConfiguration implementation for Metrics


package beaform.commands;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.Callable;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import beaform.dao.FormulaDAO;
import beaform.dao.GraphDbHandler;
import beaform.debug.DebugUtils;
import beaform.entities.Formula;
import beaform.search.SearchFormulaTask;
import beaform.utilities.ErrorDisplay;

public class CommandsTest {

	private final ErrorDisplay errorDisplay = new LoggingErrorDisplay();

	@Before
	public void setUp() {
		GraphDbHandler.initInstanceWithDbPath("neo4j_test/db");
	}

	@Test
	public void testCreateCommand() {
		final Formula formulaToPersist = new Formula("testName", "testDesc", "100g");
		formulaToPersist.setNotes("Testing notes");

		Command cmd = new CreateNewFormulaCommand(formulaToPersist, this.errorDisplay);
		cmd.execute();

		final Formula resultingFormula = FormulaDAO.findFormulaByName("testName");
		assertEquals("The 2 formulas are not the same", formulaToPersist, resultingFormula);
	}

	@Test
	public void testUpdateCommand() throws Exception {
		DebugUtils.fillDb();
		final Formula formula = new Formula("Form1", "New description", "100g");

		Command cmd = new UpdateFormulaCommand(formula, this.errorDisplay);
		cmd.execute();

		final Callable<Formula> task = new SearchFormulaTask("Form1");
		final Formula result = task.call();
		assertEquals("This isn't the expected description", "New description", result.getDescription());
	}

	@After
	public void tearDown() {
		DebugUtils.clearDb();
	}

	private static class LoggingErrorDisplay implements ErrorDisplay {
		private static final Logger LOG = LoggerFactory.getLogger(LoggingErrorDisplay.class);

		public LoggingErrorDisplay() {
			// TODO Auto-generated constructor stub
		}

		@Override
		public void displayError(String error) {
			LOG.info(error);
		}

	}

}

Add basic tests for the commands


//
// XSLTTools.java
//

/*
Java code for use with WiscScan.

Copyright (c) 2008, UW-Madison LOCI
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the UW-Madison LOCI nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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

package loci.wiscscan;

import java.io.IOException;

import javax.xml.transform.Templates;

import loci.common.xml.XMLTools;

/**
 * TODO
 *
 *

Source code:

 *
Trac,
 * SVN

 *
 * @author Curtis Rueden
 * @author Abhinav Tallavajhula
 */
public class XSLTTools {

	/** Transforms the given XML string using the specified XSLT stylesheet. */
	public static String transformXML(final String xml,
		final String pathToStylesheet)
	{
		final Templates stylesheet =
			XMLTools.getStylesheet(pathToStylesheet, null);
		try {
			return XMLTools.transformXML(xml, stylesheet);
		}
		catch (final IOException exc) {
			return null;
		}
	}

}

Add utility method for applying XSLT from WiscScan


package com.proofpoint.testing;

import static com.google.common.collect.Maps.fromProperties;
import static com.google.common.io.Resources.getResource;

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

public final class ConfigurationUtils
{
    private ConfigurationUtils()
    {
    }

    /**
     * Load a properties file from the class path and return as a Map suitable for a configuration factory.
     */
    public static Map<String, String> loadPropertiesFromClasspath(String path) throws IOException
    {
        Properties properties = new Properties();
        properties.load(getResource(ConfigurationUtils.class, path).openStream());
        return fromProperties(properties);
    }
}

Add a config loader for the classpath.


package fi.jgke.tagger.domain;

import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;

public class HealthTest {

    @Test
    public void testGetVersion() {
        String version = UUID.randomUUID().toString();
        Health instance = new Health(version, true);
        assertEquals(version, instance.getVersion());
        assertTrue(instance.isHealthy());
    }

}

Add simple test for Health


/*
 * Copyright 2011 Google 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.google.bitcoin.examples;

import com.google.bitcoin.core.*;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;

import java.net.InetAddress;
import java.util.concurrent.Future;

/**
 * Downloads the block given a block hash from the localhost node and prints it out.
 */
public class FetchBlock {
    public static void main(String[] args) throws Exception {
        System.out.println("Connecting to node");
        final NetworkParameters params = NetworkParameters.prodNet();
        NetworkConnection conn = new NetworkConnection(InetAddress.getLocalHost(), params, 0, 60000);
        BlockStore blockStore = new MemoryBlockStore(params);
        BlockChain chain = new BlockChain(params, blockStore);
        Peer peer = new Peer(params, conn, chain);
        peer.start();

        Sha256Hash blockHash = new Sha256Hash(args[0]);
        Future<Block> future = peer.getBlock(blockHash);
        System.out.println("Waiting for node to send us the requested block: " + blockHash);
        Block block = future.get();
        System.out.println(block);
        peer.disconnect();
    }
}

Add a tool that prints out an arbitrary block given its hash.


package leetcode131_140;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**A linked list is given such that each node contains an additional random pointer
 which could point to any node in the list or null. Return a deep copy of the list.
 * Created by eugene on 16/2/26.
 */
public class CopyListWithRandomPointer {

    //Definition for singly-linked list with a random pointer.
    class RandomListNode {
        int label;
        RandomListNode next, random;
        RandomListNode(int x) { this.label = x; }
    };

    //仅使用哈希表和双指针,速度更快
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head==null) return null;
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode newHead = new RandomListNode(head.label);
        RandomListNode p = head;
        RandomListNode q = newHead;
        map.put(head, newHead);
        p = p.next;
        while (p!=null){
            RandomListNode newNode = new RandomListNode(p.label);
            map.put(p, newNode);
            q.next = newNode;
            q = newNode;
            p = p.next;
        }
        p = head;
        q = newHead;
        while (p!=null){
            if (p.random!=null) q.random = map.get(p.random);
            p = p.next;
            q = q.next;
        }
        return newHead;
    }

    //与Clone Graph思路一致,使用队列和哈希表
    public RandomListNode copyRandomList1(RandomListNode head) {
        if (head==null) return null;
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        Queue<RandomListNode> queue = new LinkedList<>();
        queue.offer(head);
        RandomListNode newHead = new RandomListNode(head.label);
        map.put(head, newHead);
        while (!queue.isEmpty()){
            RandomListNode curOld = queue.poll();
            RandomListNode[] olds = {curOld.next, curOld.random};
            for (int i=0; i<2; i++){
                if (olds[i]==null) continue;
                if (!map.containsKey(olds[i])){
                    RandomListNode newNode = new RandomListNode(olds[i].label);
                    map.put(olds[i], newNode);
                    if (i==0) map.get(curOld).next = newNode;
                    else map.get(curOld).random = newNode;
                    queue.offer(olds[i]);
                } else {
                    if (i==0) map.get(curOld).next = map.get(curOld.next);
                    else map.get(curOld).random = map.get(curOld.random);
                }
            }
        }
        return newHead;
    }

}

Copy List with Random Pointer


/*
 * Copyright 2019 The Closure Compiler 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 com.google.javascript.jscomp;

Add an empty test file.


package wyboogie;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

import org.junit.Test;

public class Wyil2BoogieTest {

    @Test
    public void testIndents() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Wyil2Boogie wy2b = new Wyil2Boogie(new PrintWriter(out));
        assertEquals("            ", wy2b.createIndent(3));
        assertEquals("    ", wy2b.createIndent(1));
        assertEquals("", wy2b.createIndent(0));
    }

}

Add some simple unit tests for indentation levels.


package org.opennms.netmgt.dao;

import java.util.Collection;

import org.hibernate.criterion.Restrictions;
import org.opennms.netmgt.model.OnmsCriteria;
import org.opennms.netmgt.model.OnmsNode;

public class CriteriaTestCase extends AbstractDaoTestCase {

    public void testSimple() {
        OnmsCriteria crit = new OnmsCriteria(OnmsNode.class);
        crit.add(Restrictions.eq("label", "node1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with label node1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node1", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());
    }

    public void testComplicated() {
        OnmsCriteria crit =
            new OnmsCriteria(OnmsNode.class)
            .createAlias("ipInterfaces", "iface")
            .add(Restrictions.eq("iface.ipAddress", "192.168.2.1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with an interface 192.168.2.1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node2", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());

    }
}

Test case for new OnmsCriteria


package se.arbetsformedlingen.venice.probe;

import org.junit.Test;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ProbeCheckerTest {

    @Test
    public void check_probe() throws Exception {
        Application application = new Application("gfr");
        Host host = new Host("L7700770");
        Status status = new Status("OK");
        Version version = new Version("4.6.470");
        ProbeResponse expected = new ProbeResponse(application, host, status, version);

        ProbeStatus probeStatus = new ProbeStatus();

        CheckProbe probe = prepareMock();

        ProbeChecker checker = new ProbeChecker(probe, probeStatus);
        checker.run();

        while (checker.isWorking()) {
            Thread.sleep(5);
        }

        ProbeResponse actual = probeStatus.getStatus(new Host("L7700770"));

        assertThat(actual).isEqualTo(expected);
    }

    private CheckProbe prepareMock() {
        CheckProbe checkProbe = mock(CheckProbe.class);

        Application application = new Application("gfr");
        Host host = new Host("L7700770");
        Status status = new Status("OK");
        Version version = new Version("4.6.470");
        ProbeResponse response = new ProbeResponse(application, host, status, version);

        when(checkProbe.get()).thenReturn(response);

        return checkProbe;
    }
}

Check a probe and verify that the result is available from the statuses holder


package com.brewtab.irc;

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

import com.brewtab.irc.messages.IRCMessage;
import com.brewtab.irc.messages.IRCMessageType;
import com.brewtab.irc.messages.filter.IRCMessageFilter;
import com.brewtab.irc.messages.filter.IRCMessageSimpleFilter;
import com.brewtab.irc.messages.filter.IRCUserPrefixFilter;

/**
 * Have a private conversation
 *
 * @author Christopher Thunes <cthunes@brewtab.com>
 */
public class IRCPrivateChat implements IRCMessageHandler {
    private final static Logger log = LoggerFactory.getLogger(IRCPrivateChat.class);

    /* Nick of the user receiving the messages */
    private String receiver;

    /* Associated IRCClient object */
    private IRCClient client;

    public IRCPrivateChat(IRCClient client, String nick) {
        this.client = client;
        this.receiver = nick;

        IRCMessageFilter filter = new IRCMessageSimpleFilter(IRCMessageType.PRIVMSG, new IRCUserPrefixFilter(nick));
        this.client.addHandler(filter, this);
    }

    public String getReceiver() {
        return this.receiver;
    }

    /**
     * Get the associated IRCClient
     *
     * @return the associated IRCClient
     */
    public IRCClient getClient() {
        return this.client;
    }

    /**
     * Write a message to the channel
     *
     * @param text
     *            The message to send
     */
    public void write(String text) {
        IRCMessage privMessage = new IRCMessage(IRCMessageType.PRIVMSG, this.receiver, text);
        this.client.getConnection().sendMessage(privMessage);
    }

    /**
     * Write multiple messages efficiently
     *
     * @param strings
     *            The messages to send
     */
    public void writeMultiple(String... strings) {
        IRCMessage[] privMessages = new IRCMessage[strings.length];
        for (int i = 0; i < strings.length; i++) {
            privMessages[i] = new IRCMessage(IRCMessageType.PRIVMSG, this.receiver, strings[i]);
        }
        this.client.getConnection().sendMessages(privMessages);
    }

    @Override
    public void handleMessage(IRCMessage message) {
        IRCUser user = IRCUser.fromString(message.getPrefix());
        String messageText = message.getArgs()[message.getArgs().length - 1];

        log.debug("PM from {}: {}", user.getNick(), messageText);
    }
}

Add support for sending private messages


package test_locally.api.audit;

import com.github.seratch.jslack.api.audit.Actions;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class ActionsTest {

    static void verifyConstantFields(Class<?> clazz) {
        List<Field> fields = Arrays.stream(clazz.getDeclaredFields())
                .filter(f -> Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()))
                .collect(toList());
        for (Field f : fields) {
            try {
                String value = String.valueOf(f.get(clazz));
                assertThat(value.replaceAll("\\.", "_"), is(f.getName()));
            } catch (IllegalAccessException e) {
                fail(e.getMessage());
            }
        }
    }

    @Test
    public void naming() {
        verifyConstantFields(Actions.WorkspaceOrOrg.class);
        verifyConstantFields(Actions.User.class);
        verifyConstantFields(Actions.File.class);
        verifyConstantFields(Actions.Channel.class);
        verifyConstantFields(Actions.App.class);
    }

}

Add a test verifying naming of constants in com.github.seratch.jslack.api.audit.Actions


/**
 * Package with the classes for reading and writing
 * SubRip file format.
 * @author Alex
 */
package com.alexrnl.subtitlecorrector.io.subrip;

Add package for SubRip format


package nullnessAnnotations;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;

public class TestFieldAnnotations {
	@NonNull Object x;
	@CheckForNull Object y;

	void f() {
		x = y;
	}
	void g() {
		y = x;
	}
	void h() {
		if (x == null) System.out.println("Huh?");
	}

}

Test for nonnull annotations on fields


package sorting;

import java.util.Comparator;

/**
 * Merge two sorted arrays A of length M and B of length N into the same array
 * A. Assume that A has enough space in the end to accomodate all elements of B.
 * i.e. A's size is M + N.
 */
public class MergeWithSpaceForOtherArray {
	public static <T> void merge(T[] bigArray, int bigArraySize,
			T[] smallArray, Comparator<T> comparator) {
		if (bigArray == null || smallArray == null) {
			throw new NullPointerException("You are a stupid programmer.");
		}

		int bigArrayIndex = bigArraySize - 1;
		int smallArrayIndex = smallArray.length - 1;
		int sortedIndex = bigArray.length - 1;
		while (smallArrayIndex >= 0 && bigArrayIndex >= 0) {
			if (comparator.compare(smallArray[smallArrayIndex],
					bigArray[bigArrayIndex]) < 0) {
				bigArray[sortedIndex--] = bigArray[bigArrayIndex--];
			} else {
				bigArray[sortedIndex--] = smallArray[smallArrayIndex--];
			}
		}

		while (smallArrayIndex >= 0) {
			bigArray[sortedIndex--] = smallArray[smallArrayIndex--];
		}
	}
}

Merge two sorted arrays with one containing space for the other.


/*
 * (C) Copyright 2022 Boni Garcia (https://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.wdm.test.generic;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

class GenericBasicTest {

    WebDriver driver;

    @BeforeEach
    void setup() {
        driver = WebDriverManager.getInstance().create();
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        assertThat(driver.getTitle()).contains("Selenium WebDriver");
    }

}

Include basic test using the generic manager


package com.crankuptheamps.ttunnel.filters;

import com.crankuptheamps.ttunnel.ConnectionProcessor;

import java.util.Properties;

/**
 * SpyFilter
 * Spy on a connection by writing everything to stdout. This can be useful
 * for debugging filters, for learning about a protocol, or just for
 * filling a terminal with pages and pages of cruft.
 *
 * Created by dirkm on 11/13/14.
 */
public class SpyFilter extends Filter {

    public SpyFilter(ConnectionProcessor connectionProcessor, Properties config) {
        super(connectionProcessor, config);
    }

    @Override
    public int filter(int datum) {
        System.out.write(datum);
        return datum;
    }

    @Override
    public int filter(byte[] b, int off, int len) {
        System.out.write(b, off, len);
        return len;
    }
}

Add a filter that just writes bytes to the console.


package com.dove.common;

import android.content.Context;

public final class Device {
    private static String sDeviceId = null;

    public synchronized static String getDeviceId(Context context) {

    }
}

Add the utility class to get device id.


package com.haxademic.demo.draw.shapes;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.context.DrawUtil;
import com.haxademic.core.draw.shapes.Shapes;

public class Demo_Shapes_drawDashedLine_Pyramid
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	public void drawApp() {
		p.background(0);
		p.stroke(255);
		p.strokeWeight(1f + 4f * p.mousePercentX());
		DrawUtil.setCenterScreen(p.g);
		// p.ortho();
		DrawUtil.basicCameraFromMouse(p.g);

		float dashLength = 25f + 10f * P.sin(p.frameCount * 0.01f);

		// base
		float baseSize = 300f;
		float baseSizeHalf = baseSize / 2f;
		Shapes.drawDashedLine(p.g, -baseSizeHalf, 0, -baseSizeHalf, baseSizeHalf, 0, -baseSizeHalf, dashLength, false);
		Shapes.drawDashedLine(p.g, baseSizeHalf, 0, -baseSizeHalf, baseSizeHalf, 0, baseSizeHalf, dashLength, false);
		Shapes.drawDashedLine(p.g, baseSizeHalf, 0, baseSizeHalf, -baseSizeHalf, 0, baseSizeHalf, dashLength, false);
		Shapes.drawDashedLine(p.g, -baseSizeHalf, 0, baseSizeHalf, -baseSizeHalf, 0, -baseSizeHalf, dashLength, false);

		// cone
		float coneHeight = 190;
		Shapes.drawDashedLine(p.g, -baseSizeHalf, 0, -baseSizeHalf, 0, -coneHeight, 0, dashLength, false);
		Shapes.drawDashedLine(p.g, baseSizeHalf, 0, -baseSizeHalf, 0, -coneHeight, 0, dashLength, false);
		Shapes.drawDashedLine(p.g, baseSizeHalf, 0, baseSizeHalf, 0, -coneHeight, 0, dashLength, false);
		Shapes.drawDashedLine(p.g, -baseSizeHalf, 0, baseSizeHalf, 0, -coneHeight, 0, dashLength, false);
	}

}

Add dashed line pyramid demo


package edu.asu.se.model;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;

public class AddPatientTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void testAddPatient() {
		assertEquals("hi","hi");
	}

}

Test Template added to project added folder for unit test cases


package uk.ac.ebi.quickgo.common;

import java.util.stream.Stream;

/**
 * Defines which fields are searchable for a given {@link QuickGODocument}.
 *
 * @author Ricardo Antunes
 */
public interface SearchableDocumentFields {
    /**
     * Indicates whether the provided {@param field} is searchable or not.
     *
     * @param field the field to check
     * @return true if the field is searchable, false otherwise
     */
    boolean isDocumentSearchable(String field);

    /**
     * Returns all searchable fields of a concrete implementation of {@link QuickGODocument}.
     *
     * @return an {@link Stream} of all fields that are searchable for a specific implementation of
     * {@link QuickGODocument}
     */
    Stream<String> searchableDocumentFields();
}

Create interface that specifies which fields are searchable within a document.


package uk.ac.ebi.atlas.utils;

import autovalue.shaded.com.google.common.common.collect.Lists;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Collections;

import static org.junit.Assert.*;

@RunWith(JUnit4.class)
public class SitemapWriterTest {

    SitemapWriter subject = new SitemapWriter();

    @Test
    public void testEmptyUrl() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        subject.writeDocument(baos, Collections.EMPTY_LIST, "urlset", "url", ImmutableMap.<String, String>of());

        assertEquals("<?xml version='1.0' encoding='UTF-8'?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"/>", baos.toString());
    }

    @Test
    public void testWriteOneGene() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        subject.writeGenes(baos,Lists.<String>newArrayList(), Lists.newArrayList("ASPM"));

        assertThat( baos.toString(), Matchers.containsString("<url><loc>http://www.ebi.ac" +
                ".uk/gxa/genes/ASPM</loc><changefreq>monthly</changefreq></url>"));
    }

    @Test
    public void testWriteMany() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        subject.writeDocument(baos, Collections.nCopies(10,"myCharacteristicWord"), "urlset", "url", ImmutableMap.<String, String>of());

        assertEquals(11, baos.toString().split("myCharacteristicWord").length);
    }
}

Add test for the sitemap writer


import java.util.Scanner;
import java.io.File;

class Target {
  private static volatile int value;

  private static void method1() {
    for (int i = 0; i < 1000000; ++i)
      ++value;
  }

  private static void method2() {
    for (int i = 0; i < 1000000; ++i)
      ++value;
  }

  private static void method3() throws Exception {
    for (int i = 0; i < 1000; ++i) {
      new Scanner(new File("/proc/cpuinfo")).useDelimiter("\\Z").next();
    }
  }

  public static void main(String[] args) throws Exception {
    while (true) {
      method1();
      method2();
      method3();
    }
  }
}

Add simple Java test application target


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

import java.util.Timer;
import java.util.TimerTask;

/**
 * Make the robot "bump" forward a small amount for button-controlled fine
 * position adjustments.
 *
 * @author RAmato
 */
public class DriveBumpForwardCommand extends CommandBase {

    private static final int BUMP_TIMEOUT = 50; //Milliseconds
    private static final double BUMP_SPEED = 0.5;
    private Timer m_bumpTimer;
    private boolean m_isBumpDone;

    public DriveBumpForwardCommand() {
        requires(drive);
        Timer m_bumpTimer = new Timer();
        m_isBumpDone = false;
    }

        class BumpTimerTask extends TimerTask {
        public void run() {
            m_isBumpDone = true;
            m_bumpTimer.cancel(); //Terminate the timer thread
        }
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        m_bumpTimer.schedule(new BumpTimerTask(), BUMP_TIMEOUT);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        drive.driveStraight(BUMP_SPEED);
    }

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

    // Called once after isFinished returns true
    protected void end() {
    }

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

Add "bump" commands for fine position adjustment.


package leetcode.subsets_ii;

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

public class Solution {
	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, int[] num, int n, int depth){
		if(depth == n){
			ans.add(new ArrayList<Integer>(cur));
		}else{
			int v = num[depth];
			int cnt = 0;
			for(int x = depth; x < n && num[x] == v; x++){
				cnt++;
			}
			dfs(ans, cur, num, n, depth + cnt);
			for(int i = 0; i < cnt; i++){
				cur.add(v);
				dfs(ans, cur, num, n, depth + cnt);
			}
			cur.subList(cur.size() - cnt, cur.size()).clear();
		}
	}

    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	if(num == null || num.length == 0) return ans;
    	Arrays.sort(num);
    	dfs(ans, new ArrayList<Integer>(), num, num.length, 0);
    	return ans;
    }

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

Add java solution for 90. Subsets II


// Copyright 2008 Google 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.google.gwtjsonrpc.client;

public class VoidResult_JsonSerializer extends JsonSerializer<VoidResult> {
  public static final VoidResult_JsonSerializer INSTANCE =
      new VoidResult_JsonSerializer();

  private VoidResult_JsonSerializer() {
  }

  @Override
  public void printJson(final StringBuffer sb, final VoidResult o) {
    sb.append("{}");
  }

  @Override
  public VoidResult fromJson(final Object o) {
    return VoidResult.INSTANCE;
  }
}

Implement a custom serializer for VoidResult


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.Direction;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.intake.IntakeSide;
import org.robockets.stronghold.robot.intake.ManualSpinIntake;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * ALL VALUES ARE TEMPORARY
 */
public class AutoShootLow extends CommandGroup {

    public  AutoShootLow(int defense) {
    	addSequential(new MoveToMiddleGoal(defense));
        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 24, 0));
        addSequential(new ManualSpinIntake(Direction.FORWARD, 3, IntakeSide.FRONT));
    }
}

Add skeleton for auto shoot low


package com.uber.hoodie.config;

import static org.junit.Assert.*;

import com.google.common.collect.Maps;
import com.uber.hoodie.config.HoodieWriteConfig.Builder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;

public class HoodieWriteConfigTest {
  @Test
  public void testPropertyLoading() throws IOException {
    Builder builder = HoodieWriteConfig.newBuilder().withPath("/tmp");
    Map<String, String> params = Maps.newHashMap();
    params.put(HoodieCompactionConfig.MAX_COMMITS_TO_KEEP, "5");
    params.put(HoodieCompactionConfig.MIN_COMMITS_TO_KEEP, "2");
    ByteArrayOutputStream outStream = saveParamsIntoOutputStream(params);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outStream.toByteArray());
    try {
      builder = builder.fromInputStream(inputStream);
    } finally {
      outStream.close();
      inputStream.close();
    }
    HoodieWriteConfig config = builder.build();
    assertEquals(config.getMaxCommitsToKeep(), 5);
    assertEquals(config.getMinCommitsToKeep(), 2);
}

  private ByteArrayOutputStream saveParamsIntoOutputStream(Map<String, String> params) throws IOException {
    Properties properties = new Properties();
    properties.putAll(params);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    properties.store(outStream, "Saved on " + new Date(System.currentTimeMillis()));
    return outStream;
  }
}

Test to check if properties set are properly propogated


/*
 * (C) Copyright 2022 Boni Garcia (https://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.wdm.test.chrome;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;

import java.io.File;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Google Chrome beta in Windows.
 *
 * @author Boni Garcia
 * @since 5.1.0
 */
class ChromeBetaWindowsTest {

    static String chromeBetaPath = "C:\\\\PROGRA~1\\\\GOOGLE\\\\CHROME~1\\\\APPLIC~1\\\\CHROME.EXE";
    static File chromeBetaFile = new File(chromeBetaPath);

    WebDriver driver;

    @BeforeAll
    static void setupClass() {
        assumeThat(chromeBetaFile).exists();
        String chromeBetaCommand = String.format(
                "cmd.exe /C wmic datafile where name=\"%s\" get Version /value",
                chromeBetaPath);
        WebDriverManager.chromedriver()
                .browserVersionDetectionCommand(chromeBetaCommand).setup();
    }

    @BeforeEach
    void setupTest() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setBinary(chromeBetaPath);
        driver = new ChromeDriver(chromeOptions);
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        assertThat(driver.getTitle()).contains("Selenium WebDriver");
    }

}

Include test using Chrome Beta in Windows


/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.model;

import java.io.IOException;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ProjectDeepCopyTest {

	@Test
	public void deepCopyProjectDeepCopies() throws IOException, ClassNotFoundException {
		Project originalProject = initializeProject();
		Project copiedProject = (Project) originalProject.deepCopy();
		assertTrue(projectIsCopy(originalProject, copiedProject));
	}

	@Test
	public void deepCopyProjectClearedIDs() throws IOException, ClassNotFoundException {
		Boolean clearedIDs = true;
		Project originalProject = initializeProject();
		Project copiedProject = (Project) originalProject.deepCopy();
		if (copiedProject.getId() != 0) {
			clearedIDs = false;
		}
		for (Scenario s: copiedProject.getScenarios()) {
			if (s.getId() != 0) {
				clearedIDs = false;
			}
		}
		assertTrue(clearedIDs);
	}
	private Project initializeProject() {
		Project originalProject = new Project("testProject");
		Scenario scenarioA = new Scenario();
		Scenario scenarioB = new Scenario();

		scenarioA.setName("scenarioA");
		scenarioB.setName("scenarioB");

		scenarioA.getRoot().setName("rootA");
		scenarioB.getRoot().setName("rootB");

		originalProject.addScenario(scenarioA);
		originalProject.addScenario(scenarioB);

		return originalProject;
	}

	private Boolean projectIsCopy(final Project original, final Project copy ) {
		if (!(original.getName().equals(copy.getName()))) {
			return false;
		}
		if (original.getScenarios().size() != copy.getScenarios().size()) {
			return false;
		}
		for (Scenario s: original.getScenarios()) {
			int scenarioIndex = original.getScenarios().indexOf(s);
			Scenario c = copy.getScenarios().get(scenarioIndex);
			if (!scenarioIsCopy(s, c)) {
				return false;
			}
		}
		return true;
	}

	private Boolean scenarioIsCopy(final Scenario original, final Scenario copy) {
		//Just check whether scenarios have been copied by comparing their name.
		//DeepCopy for sceneNodes working correctly is tested seperately and can
		//be assumed to be true here
		if (!(original.getName().equals(copy.getName()))) {
			return false;
		}
		SceneNode rootA = original.getRoot();
		SceneNode rootB = copy.getRoot();

		if (!(rootA.getName().equals(rootB.getName()))) {
			return false;
		}
		return true;
	}
}

Test for deep copying projects