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

import com.google.inject.Binder;
import com.google.inject.Module;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

public class ConfigurationAwareModules
{
    private ConfigurationAwareModules() {}

    public static Module combine(Module... modules)
    {
        checkArgument(modules.length > 0, "No modules given");
        if (modules.length == 1) {
            return modules[0];
        }
        return new AbstractConfigurationAwareModule()
        {
            @Override
            protected void setup(Binder binder)
            {
                for (Module module : modules) {
                    requireNonNull(module, "module is null");
                    install(module);
                }
            }
        };
    }
}

Add utility combine method for ConfigurationAwareModule


package net.md_5.bungee.command;

import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.Permission;

/**
 * Command to set a temp copy of the motd in real-time without stopping the proxy
 */
public class CommandMotd extends Command
{

    @Override
    public void execute(CommandSender sender, String[] args)
    {
        if (getPermission(sender) != Permission.ADMIN)
        {
            sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
        } else
        {
            String newMOTD = "";
            for (String s: args)
            {
                newMOTD = newMOTD + s + " ";
            }
            newMOTD = newMOTD.substring(0, newMOTD.length()-1);
            BungeeCord.instance.config.motd = newMOTD;
        }
    }
}

Add /motd command to allow user to set motd without restarting/stopping server


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor.annotations;

import org.apache.commons.lang3.Validate;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

public class AnnotationClassVisitor extends ClassVisitor {
    private AnnotationDescriptorBuilder annotationBuilder;

    public AnnotationClassVisitor() {
        super(Opcodes.ASM5);
    }

    public AnnotationDescriptor toAnnotation() {
        Validate.notNull(annotationBuilder);
        return annotationBuilder.build();
    }

    @Override
    public void visit(final int version, final int access, final String name, final String signature,
            final String superName, final String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces);
        annotationBuilder = new AnnotationDescriptorBuilder(Type.getObjectType(name));
    }

    @Override
    public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
            final String[] exceptions) {
        return new MethodVisitor(Opcodes.ASM5) {
            @Override
            public AnnotationVisitor visitAnnotationDefault() {
                return new AnnotationValueParser() {
                    @Override
                    public void visitEnd() {
                        Validate.notNull(annotationBuilder);
                        annotationBuilder.addDefaultValue(name, getValue());
                    }
                };
            }
        };
    }
}

Implement a class visitor for parsing annotation classes


package com.webkreator.qlue.example.pages;

import com.webkreator.qlue.Page;
import com.webkreator.qlue.view.View;

public class exceptionTest extends Page {

	@Override
	public View onGet() throws Exception {
		errors.addError("Test error message");
		throw new Exception("test");
	}
}

Add a page that always throws an exception.


package com.boundary.plugin.sdk;

/**
 * Stub class for handling post install configuration
 *
 */
public class PostInstall {

	/**
	 * Default constructor
	 */
	public PostInstall() {

	}

	public static void main(String[] args) {
		System.exit(0);
	}
}

Add stub for handling post install


package seedu.task.alerts;

import java.util.Optional;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
//@@author A0142360U
public class TransferTaskAlert extends Alert {

    public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change of Task Storage Directory";
    public static final String CHANGE_DIRECTORY_HEADER_TEXT = "Would you like your existing tasks to be transferred over to the new directory?";
    public static final ButtonType buttonTypeYes = new ButtonType("Yes");
    public static final ButtonType buttonTypeNo = new ButtonType("No");
    public static final ButtonType buttonTypeCancel = new ButtonType("Cancel");
    public static final String yes = "Yes";
    public static final String no = "No";
    public static final String noAction = "noAction";

    public TransferTaskAlert(AlertType alertType) {
        super(alertType);
    }

    public static String transferTaskOptionAlert() {

        try {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE);
            alert.setHeaderText(CHANGE_DIRECTORY_HEADER_TEXT);
            alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo,buttonTypeCancel);

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == buttonTypeYes) {
                return yes;
            } else if (result.get() == buttonTypeNo){
                return no;
            }
            else {
                return noAction;
            }

        } catch (ExceptionInInitializerError | IllegalStateException e) {
            return noAction;
        }

    }

}

Create a new Alert Dialog that allows users to decide whether they would like their tasks to be transferred over to the new directory


package com.fsck.k9.helper;

import junit.framework.TestCase;

public class Utility_quoteAtoms extends TestCase
{
    public void testNoQuote() {
        // Alpha
        noQuote("a");
        noQuote("aa");
        noQuote("aaa aaa");

        // Numeric
        noQuote("1");
        noQuote("12");
        noQuote("123 456");

        // Alpha Numeric
        noQuote("abc 123");

        // Specials
        noQuote("!");
        noQuote("#");
        noQuote("$");
        noQuote("%");
        noQuote("&");
        noQuote("'");
        noQuote("*");
        noQuote("+");
        noQuote("-");
        noQuote("/");
        noQuote("=");
        noQuote("?");
        noQuote("^");
        noQuote("_");
        noQuote("`");
        noQuote("{");
        noQuote("|");
        noQuote("}");
        noQuote("~");

        // Combos
        noQuote("bob barker! #1!");
        noQuote("!");
        noQuote("#&#!");
        noQuote("{|}");
        noQuote("'-=+=-'");
    }

    public void testQuote() {
        assertEquals("\"bob s. barker\"", quote("bob s. barker"));
        assertEquals("\":(\"", quote(":("));
    }

    private void noQuote(final String s) {
        assertEquals(s, Utility.quoteAtoms(s));
    }

    private String quote(final String s) {
        return Utility.quoteAtoms(s);
    }
}

Add test case for quoteAtoms().


package org.team2471.frc.lib.io.maps;

import java.util.function.IntSupplier;

// TODO: update values
public final class XboxMap {
  public static final class Buttons {
    public static final int A = 1;
    public static final int B = 2;
    public static final int X = 3;
    public static final int Y = 4;
    public static final int LEFT_BUMPER = 5;
    public static final int RIGHT_BUMPER = 6;
    public static final int BACK = 7;
    public static final int START = 8;
    public static final int LEFT_THUMBSTICK = 9;
    public static final int RIGHT_THUMBSTICK = 10;
  }

  public static final class Axises {
    public static final int LEFT_THUMBSTICK_X = 0;
    public static final int LEFT_THUMBSTICK_Y = 1;
    public static final int LEFT_TRIGGER = 2;
    public static final int RIGHT_TRIGGER = 3;
    public static final int RIGHT_THUMBSTICK_X = 4;
    public static final int RIGHT_THUMBSTICK_Y = 5;
  }
}

Add unfinished xbox controller map


package pl.vgtworld.imagedraw.filters.gaussianblur;

import pl.vgtworld.imagedraw.ImageDrawEntity;
import pl.vgtworld.imagedraw.filters.ImageDrawFilter;
import pl.vgtworld.imagedraw.filters.matrix.MatrixFilter;

public class GaussianBlurFilter implements ImageDrawFilter {

	private MatrixGenerator matrixGenerator = new MatrixGenerator();

	private int radius;

	private double standardDeviation;

	public GaussianBlurFilter(int radius) {
		this.radius = radius;
		standardDeviation = radius / 2.0f;
	}

	public GaussianBlurFilter(int radius, double standardDeviation) {
		this.radius = radius;
		this.standardDeviation = standardDeviation;
	}

	@Override
	public void doFilter(ImageDrawEntity image, int x, int y, int width, int height) {
		float[][] matrix = matrixGenerator.createMatrix(radius, standardDeviation);
		MatrixFilter matrixFilter = new MatrixFilter(matrix);
		matrixFilter.doFilter(image, x, y, width, height);
	}

}

Add gaussian blur filter class.


/*
 * Copyright(c) - CdC 2015, Tous droits réservés.
 * -----------------------------------------------------------
 * Centrale de Compensation
 * Avenue Edmond-Vaucher, 18
 * Centre Informatique AVS/AI
 * Case Postale 2676
 * 1211 Genève 2
 * -----------------------------------------------------------
 */
package com.batmgr.filesystem;

import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

public class DirCheckerTest {

    private URL  resource;

    private Path testRoot;

    @Before
    public void setUp() throws Exception {
        resource = getClass().getResource("/sample.txt");
        testRoot = Paths.get(resource.toURI()).resolve("..").normalize();
    }

    private void cleanupDir(Path p) throws IOException, InterruptedException
    {
        if (Files.exists(p)) {
            FileUtils.deleteDirectory(p.toFile());
        }
        Thread.sleep(1000);
        Files.createDirectory(p);
    }

    @Test
    public void test_indexFolder() throws IOException, InterruptedException, InvalidIndexException, NoSuchAlgorithmException {
        String sampleFile = "smpl.txt";
        Path testPath = testRoot.resolve("tst1");
        cleanupDir(testPath);
        Files.copy(testRoot.resolve("sample.txt"), testPath.resolve(sampleFile));
        DirChecker dirChecker = new DirChecker();
        dirChecker.indexFolder(testPath);
        DirInfo dirInfo = new DirInfo(testPath);
        assertTrue(dirInfo.isHashPresent("4F13A4F6083341F66D39024D7B3765387EE1A3437414CECCC774238A62C65BBA"));
    }

}

Revert "merge change from github"


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.Pair;

public class PairTest {

  @Test
  public void testEquals() {
    final Pair pair = new Pair(0, 1);

    assertFalse(pair.equals(null));
    assertFalse(pair.equals(new Pair(null, 1)));
    assertFalse(pair.equals(new Pair(0, null)));
    assertTrue(pair.equals(pair));
    assertTrue(pair.equals(new Pair(0, 1)));
  }

  @Test
  public void testHashCode() {
    final Pair pair = new Pair(0, 1);

    assertEquals(962, pair.hashCode());
  }

  @Test
  public void testNext() {
    final Pair pair = Pair.next(0, 1);

    assertNotNull(pair);
    assertEquals(0, pair.getT1());
    assertEquals(1, pair.getT2());
  }

  @Test
  public void testToString() {
    final Pair pair = new Pair(0, 1);

    assertEquals("Pair{t1=0, t2=1}", pair.toString());
  }
}

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


import java.util.Scanner;

public class JavaStdinAndStdout2 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int integerInput = scanner.nextInt();
        double doubleInput = scanner.nextDouble();

        // cleaning the buffer before reading the next line
        scanner.nextLine();
        String stringInput = scanner.nextLine();

        System.out.println("String: " + stringInput);
        System.out.println("Double: " + doubleInput);
        System.out.println("Int: " + integerInput);
    }
}

Add Java Stdin and Stdout 2 solution


/*
 *
 *  Copyright 2019 Netflix, 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.
 *
 */

/**
 * A package containing aggregates interfaces for Spring Data JPA.
 *
 * @author mprimi
 * @since 4.0.0
 */
@ParametersAreNonnullByDefault
package com.netflix.genie.web.jpa.entities.aggregates;

import javax.annotation.ParametersAreNonnullByDefault;

Create new package for 'aggregate' type JPA entities


package com.ggcoke.oj.leetcode;

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

/**
 * @author Wang Huisong <ggcoke@foxmail.com>
 */
public class PascalsTriangle {

    public static void main(String[] args) {
        PascalsTriangle pascalsTriangle = new PascalsTriangle();

        List<List<Integer>> result = pascalsTriangle.generate(5);
        if (result != null) {
            for (List<Integer> list : result) {
                for (int item : list) {
                    System.out.print(item + " ");
                }
                System.out.println();
            }

        }
    }

    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();

        if (numRows == 0) {
            return result;
        }

        for (int row = 0; row < numRows; row++) {
            int maxColumn = row + 1;
            List<Integer> rowContent = new ArrayList<Integer>();

            if (row == 0) {
                rowContent.add(1);
            } else {
                List<Integer> lastRow = result.get(row - 1);
                rowContent.add(lastRow.get(0));
                for (int column = 1; column < maxColumn - 1; column++) {
                    rowContent.add(lastRow.get(column - 1) + lastRow.get(column));
                }
                rowContent.add(lastRow.get(lastRow.size() - 1));
            }

            result.add(rowContent);
        }

        return result;
    }
}

Add solution for "Pascal's Triangle"


/**
 * Copyright (c) 2013, impossibl.com
 * 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 impossibl.com 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 com.impossibl.postgres.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LockTest {

  Connection conn;

  @Before
  public void before() throws Exception {
    conn = TestUtil.openDB();
    TestUtil.createTable(conn, "t", "name text");
  }

  @After
  public void after() throws Exception {
    TestUtil.closeDB(conn);
  }

  @Test
  public void testLock() throws SQLException {

    conn.setAutoCommit(false);

    try (Statement stmt = conn.createStatement()) {
      stmt.execute("LOCK TABLE t IN EXCLUSIVE MODE");
    }

  }

}

Add simple unit test for table locking


package com.misc.coding.problems;

public class ClosestPoints {

	/**
	 * Given the xy axis, We have the origin (0,0) and multiple points in the
	 * plane. Can you give me the top 100 closest elements.
	 *
	 * @param args
	 */

	public static void main(String args[]) {

	}

}

Implement finding closest points to a point in a graph (adhip's question to me)


import org.junit.Test;

import java.io.BufferedReader;

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

/**
 * Created by blockost on 29/04/17.
 */
public class FileHelperTest {
    private BufferedReader reader;

    @Test
    public void testFileNotFound() {
        reader = FileHelper.readFile("blahblahtest.json");
        assertNull(reader);
    }

    @Test
    public void testFileFound() {
        reader = FileHelper.readFile("data/vehicles.json");
        assertNotNull(reader);
    }

}

Add test for FileHelper class


package com.orientechnologies.orient.core.encryption.impl;

import com.orientechnologies.orient.core.encryption.OEncryption;
import com.orientechnologies.orient.core.encryption.OEncryptionFactory;
import org.junit.Assert;
import org.junit.Test;

import java.util.Base64;

public class OEncryptionFactoryTest {

  @Test
  public void test(){
    String key = new String(Base64.getEncoder().encode(new byte[]{1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8}));
    OEncryption enc = OEncryptionFactory.INSTANCE.getEncryption(OAESGCMEncryption.NAME, key);
    Assert.assertEquals(OAESGCMEncryption.class, enc.getClass());
  }
}

Add test case for encryption factory


package cz.muni.fi.pv243.rest;

import java.net.URI;
import java.util.List;

import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;

import cz.muni.fi.pv243.service.AbstractService;

/**
 *
 */
public abstract class AbstractEndpoint<T> {

    @Inject
    private AbstractService<T> service;

    @POST
    @Consumes("application/json")
    public Response create(@Valid T entity) {
        if (entity == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        service.create(entity);
        URI url = UriBuilder.fromResource(getClass()).path(service.getEntityId(entity).toString()).build();
        return Response.created(url).build();
    }

    @DELETE
    @Path("/{id:[0-9][0-9]*}")
    public Response deleteById(@PathParam("id") Long id) {
        T entity = service.findById(id);
        if (entity == null) {
            return Response.status(Status.NOT_FOUND).build();
        }
        service.delete(entity);
        return Response.noContent().build();
    }

    @GET
    @Path("/{id:[0-9][0-9]*}")
    @Produces("application/json")
    public Response findById(@PathParam("id") Long id) {
        T entity = service.findById(id);
        if (entity == null) {
            return Response.status(Status.NOT_FOUND).build();
        }
        return Response.ok(entity).build();
    }

    @GET
    @Produces("application/json")
    public List<T> listAll() {
        final List<T> results = service.findAll();
        return results;
    }

    @PUT
    @Path("/{id:[0-9][0-9]*}")
    @Consumes("application/json")
    public Response update(@PathParam("id") Long id, T entity) {
        if (entity == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (id == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (!id.equals(service.getEntityId(entity))) {
            return Response.status(Status.CONFLICT).entity(entity).build();
        }
        if (service.findById(id) == null) {
            return Response.status(Status.NOT_FOUND).build();
        }
        service.update(entity);

        return Response.noContent().build();
    }
}

Add abstract base class for REST endpoints


package devopsdistilled.operp.client.abstracts;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;
import devopsdistilled.operp.server.data.entity.Entiti;

public abstract class CopyOfAbstractEntityDetailsPane<E extends Entiti<?>, EC extends EntityController<E>> {

	protected final JDialog dialog;

	protected JPanel btnPanel;

	public CopyOfAbstractEntityDetailsPane() {
		dialog = new JDialog();
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setTitle(getTitle());
		dialog.setSize(400, 300);
		dialog.getContentPane().setLayout(new MigLayout("fill", "[]", "[]"));

		btnPanel = new JPanel();
		btnPanel.setLayout(new MigLayout(""));

		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
						getPane(), "Delete " + getEntity() + " ?", "Delete ?",
						JOptionPane.YES_NO_OPTION)) {

					getDialog().dispose();
					getEntityController().delete(getEntity());
				}
			}

		});
		btnPanel.add(btnDelete);

		JButton btnEdit = new JButton("Edit");
		btnEdit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getDialog().dispose();
				getEntityController().edit(getEntity());
			}
		});
		btnPanel.add(btnEdit);

		JButton btnOk = new JButton("OK");
		btnOk.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getDialog().dispose();
			}
		});
		btnPanel.add(btnOk);
	}

	public abstract EC getEntityController();

	protected abstract E getEntity();

	public abstract JPanel getPane();

	public abstract void show(E entity);

	public abstract String getTitle();

	public JDialog getDialog() {
		return dialog;
	}

	public void showDetailsPane(JPanel detailsPane) {
		getPane().add(btnPanel, "south, pad 20 100 20 20");
		dialog.getContentPane().add(getPane(), "grow");

	}
}

Create AbstractDetailsPane with common button panel


package leetcode.delete_node_in_a_linked_list;

import common.ListNode;

public class Solution {
    public void deleteNode(ListNode node) {
        ListNode prev = node;
        while(node.next != null){
            node.val = node.next.val;
            prev = node;
            node = node.next;
        }
        prev.next = null;
    }
}

Add java solution for 237. Delete Node in a Linked List


package fr.unice.polytech.al.trafficlight.crossroad;

/**
 * Created by nathael on 20/01/17.
 */
public class NoVehiclesToRemove {
}

Add security avoiding '-1 vehicles' waiting at a crossroad


/*
 * Copyright 2020 DiffPlug
 *
 * 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.diffplug.spotless.maven.generic;

import java.io.IOException;
import java.time.YearMonth;

import org.eclipse.jgit.api.Git;
import org.junit.Test;

import com.diffplug.spotless.maven.MavenIntegrationHarness;

public class LicenseHeaderRatchetTest extends MavenIntegrationHarness {
	private static final String NOW = String.valueOf(YearMonth.now().getYear());

	private static final String TEST_JAVA = "src/main/java/pkg/Test.java";
	private static final String CONTENT = "package pkg;\npublic class Test {}";

	private void setRatchetFrom(String ratchetFrom) throws IOException {
		writePomWithJavaSteps(
				"<licenseHeader>",
				"  <content>/** $YEAR */</content>",
				"</licenseHeader>",
				ratchetFrom);
	}

	private void assertUnchanged(String year) throws Exception {
		assertTransform(year, year);
	}

	private void assertTransform(String yearBefore, String yearAfter) throws Exception {
		setFile(TEST_JAVA).toContent("/** " + yearBefore + " */\n" + CONTENT);
		mavenRunner().withArguments("spotless:apply").runNoError();
		assertFile(TEST_JAVA).hasContent("/** " + yearAfter + " */\n" + CONTENT);
	}

	private void testSuiteUpdateWithLatest(boolean update) throws Exception {
		if (update) {
			assertTransform("2003", "2003-" + NOW);
			assertTransform("2003-2005", "2003-" + NOW);
		} else {
			assertUnchanged("2003");
			assertUnchanged("2003-2005");
		}
		assertUnchanged(NOW);
		assertTransform("", NOW);
	}

	@Test
	public void normal() throws Exception {
		setRatchetFrom("");
		testSuiteUpdateWithLatest(false);
	}

	@Test
	public void ratchetFrom() throws Exception {
		try (Git git = Git.init().setDirectory(rootFolder()).call()) {
			git.commit().setMessage("First commit").call();
		}
		setRatchetFrom("<ratchetFrom>HEAD</ratchetFrom>");
		testSuiteUpdateWithLatest(true);
	}
}

Add a test for the license header reatchet behavior in the maven plugin.


package org.mutabilitydetector.benchmarks.mutabletofield.jdktypefields;

public final class HasAStringField {
    private final String stringField;

    public HasAStringField(String stringField) {
        this.stringField = stringField;
    }

    public String getStringField() {
        return stringField;
    }

}

Add file missing from last commit.


/*
 *    Copyright (c) 2016.   Joshua Braun
 *
 *    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.hska.iwi.microservice.registration;

import junit.framework.TestCase;

public class RegistrationServerTest extends TestCase {
    //TODO: Sinnvolle Testfälle hinzufügen
    public void testMain() throws Exception {
        assertTrue(true);
    }
}

Test hinzugefügt für den EUREKA Registration-Service


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2016 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.command.run;

import org.scijava.command.Command;
import org.scijava.command.CommandInfo;
import org.scijava.command.CommandService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginService;
import org.scijava.run.AbstractClassRunner;
import org.scijava.run.ClassRunner;

/**
 * Runs the given {@link Command} class.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ClassRunner.class)
public class CommandRunner extends AbstractClassRunner {

	@Parameter
	private PluginService pluginService;

	@Parameter
	private CommandService commandService;

	// -- ClassRunner methods --

	@Override
	public void run(final Class<?> c) {
		@SuppressWarnings("unchecked")
		final Class<? extends Command> commandClass =  (Class<? extends Command>) c;
		final Plugin annotation = c.getAnnotation(Plugin.class);
		final CommandInfo info = new CommandInfo(commandClass, annotation);
		pluginService.addPlugin(info);
		commandService.run(info, true);
	}

	// -- Typed methods --

	@Override
	public boolean supports(final Class<?> c) {
		return Command.class.isAssignableFrom(c);
	}

}

Add a ClassRunner for Command plugins


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

import com.speedment.common.mutablestream.HasNext;
import com.speedment.common.mutablestream.action.Action;
import com.speedment.common.mutablestream.terminate.Terminator;
import static java.util.Objects.requireNonNull;
import java.util.stream.BaseStream;

/**
 *
 * @param <T>  the streamed type (or wrapper)
 * @param <TS> the stream type
 *
 * @author Emil Forslund
 * @since  1.0.0
 */
public final class WrappedStream<T, TS extends BaseStream<T, TS>>
implements HasNext<T, TS> {

    private final TS wrapped;

    public WrappedStream(TS wrapped) {
        this.wrapped = requireNonNull(wrapped);
    }

    @Override
    public <Q, QS extends BaseStream<Q, QS>> HasNext<Q, QS>
    append(Action<T, TS, Q, QS> next) {
        return next;
    }

    @Override
    public <X> X execute(Terminator<T, TS, X> terminator) {
        return terminator.execute();
    }

    @Override
    public TS build(boolean parallel) {
        return parallel ? wrapped.parallel() : wrapped;
    }
}

Add source that wraps an existing stream


package com.orientechnologies.orient.core.sql.executor;

import com.orientechnologies.orient.core.db.*;
import com.orientechnologies.orient.core.metadata.security.OSecurityInternal;
import com.orientechnologies.orient.core.metadata.security.OSecurityPolicy;
import org.junit.*;

/**
 * @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)
 */
public class OAlterSecurityPolicyStatementExecutionTest {
  static OrientDB orient;
  private ODatabaseSession db;

  @BeforeClass
  public static void beforeClass() {
    orient = new OrientDB("plocal:.", OrientDBConfig.defaultConfig());
  }

  @AfterClass
  public static void afterClass() {
    orient.close();
  }

  @Before
  public void before() {
    orient.create("test", ODatabaseType.MEMORY);
    this.db = orient.open("test", "admin", "admin");
  }

  @After
  public void after() {
    this.db.close();
    orient.drop("test");
    this.db = null;
  }

  @Test
  public void testPlain() {
    db.command("CREATE SECURITY POLICY foo").close();

    db.command("ALTER SECURITY POLICY foo SET READ = (name = 'foo')").close();

    OSecurityInternal security = ((ODatabaseInternal) db).getSharedContext().getSecurity();
    OSecurityPolicy policy = security.getSecurityPolicy((ODatabaseSession) db, "foo");
    Assert.assertNotNull(policy);
    Assert.assertNotNull("foo", policy.getName());
    Assert.assertEquals("name = 'foo'", policy.getReadRule().toString());
    Assert.assertNull(policy.getCreateRule());
    Assert.assertNull(policy.getBeforeUpdateRule());
    Assert.assertNull(policy.getAfterUpdateRule());
    Assert.assertNull(policy.getDeleteRule());
    Assert.assertNull(policy.getExecuteRule());

    db.command("ALTER SECURITY POLICY foo REMOVE READ").close();

    policy = security.getSecurityPolicy((ODatabaseSession) db, "foo");
    Assert.assertNotNull(policy);
    Assert.assertNull(policy.getReadRule());

  }

}

Add test case for ALTER SECURITY POLICY statement


package de.asw.courses.web2016.demo.backend.servlet.handoff;

import java.io.IOException;

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

@WebServlet("/handoff/eingabe")
public class EingabeServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		System.out.printf("Running in %s%n", getClass().getSimpleName());

		Integer a = Integer.valueOf(req.getParameter("a"));
		Integer b = Integer.valueOf(req.getParameter("b"));

		req.setAttribute("a", a);
		req.setAttribute("b", b);

		RequestDispatcher rd = req.getRequestDispatcher("/handoff/verarbeitung");
		rd.forward(req, resp);
	}
}

Add bootstrap for handoff example


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

import org.statefulj.framework.core.annotations.StatefulController;
import org.statefulj.framework.core.annotations.Transition;
import org.statefulj.framework.tests.model.User;
import static org.statefulj.framework.tests.model.User.*;

@StatefulController(
	value="overloadedMethodController",
	clazz=User.class,
	startState=ONE_STATE
)
public class OverloadedMethodController {

	@Transition(event="one")
	public String method(User user, String event) {
		return "method1";
	}

	@Transition(event="two")
	public String method(User user, String event, Object parm) {
		return "method2";
	}

}

Add test case for overloaded methods


/*
 *
 * 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.airavata.wsmg.commons;

import javax.xml.namespace.QName;

public class MsgBoxQNameConstants {

    public static final QName MSG_BOXID_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "MsgBoxId", "msgbox");
    public static final QName MSGBOX_STATUS_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "status", "msgbox");
    public static final QName MSGBOX_MESSAGE_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "messages", "msgbox");

    /*
     * Request
     */
    public static final QName STOREMSG_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "storeMessages", "msgbox");
    public static final QName DESTROYMSG_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "destroyMsgBox", "msgbox");
    public static final QName TAKEMSGS_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "takeMessages", "msgbox");
    public static final QName CREATEMSG_BOX = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "createMsgBox",
            "msgbox");

    /*
     * Response
     */
    public static final QName STOREMSG_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "storeMessagesResponse", "msgbox");
    public static final QName DESTROY_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "destroyMsgBoxResponse", "msgbox");
    public static final QName CREATE_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "createMsgBoxResponse", "msgbox");
    public static final QName TAKE_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "takeMessagesResponse", "msgbox");
}

Add missing class in previous commit


package org.jrebirth.af.core.wave;

/**
 * The class DefaultWaveListener is the default empty implementation.
 *
 * You can use it as base class to only override the method you need.
 *
 * @author Sébastien Bordes
 */
public class DefaultWaveListener implements WaveListener {

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCreated(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveSent(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveProcessed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCancelled(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveConsumed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveFailed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveDestroyed(Wave wave) {
        // Nothing to do yet
    }

}

Add default implementation of wave listener


package de.lmu.ifi.dbs.elki.logging.statistics;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import de.lmu.ifi.dbs.elki.utilities.FormatUtil;

/**
 * Trivial double-valued statistic.
 *
 * @author Erich Schubert
 */
public class DoubleStatistic extends AbstractStatistic {
  /**
   * Statistic value.
   */
  double value;

  /**
   * Constructor.
   *
   * @param key Key
   */
  public DoubleStatistic(String key) {
    super(key);
  }

  /**
   * Constructor.
   *
   * @param key Key
   * @param value Value
   */
  public DoubleStatistic(String key, double value) {
    super(key);
    this.value = value;
  }

  /**
   * Set the statistics.
   *
   * @param value New value
   */
  public void setDouble(double value) {
    this.value = value;
  }

  @Override
  public String formatValue() {
    return FormatUtil.format(value, FormatUtil.NF8);
  }
}

Add class for double-valued statistics


package sc.iview.commands.edit;

import org.scijava.command.Command;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import sc.iview.SciView;

import static sc.iview.commands.MenuWeights.*;

/**
 * A command for interactively editing input controls.
 * @author Vladimir Ulman
 */
@Plugin(type = Command.class, menuRoot = "SciView",
        menu = { @Menu(label = "Edit", weight = EDIT), @Menu(label = "Inputs Bindings", weight = EDIT_SCIVIEW_SETTINGS+2) })
public class InputBindingsSettings implements Command
{
    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        sciView.publicGetInputHandler().openKeybindingsGuiEditor( "SciView's Key bindings editor" );
    }
}

Edit -> Inputs Bindings menu item that shows publicGetInputHandler().openKeybindingsGuiEditor()


package seedu.taskmanager.logic.commands;

import java.io.IOException;
import java.util.Optional;

import seedu.taskmanager.commons.core.Config;
import seedu.taskmanager.commons.exceptions.DataConversionException;
import seedu.taskmanager.commons.util.ConfigUtil;
import seedu.taskmanager.commons.util.StringUtil;
import seedu.taskmanager.logic.commands.exceptions.CommandException;

/**
 * @@author A0114269E
 * Move the directory of taskmanager.xml file to user-specified path to allow cloud service sync.
 * Overwrite the given file path if a file with same name exists. Old XML file is not deleted.
 * Path matching is case sensitive.
 */
public class MoveCommand extends Command {
    public static final String COMMAND_WORD = "mv";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Move the directory of the taskmanager."
            + "xml file to allow user to sync with cloud services. Overwrite will occur for same file name.\n"
            + "Parameters: PATH...\n"
            + "Example: " + COMMAND_WORD + " /User/admin/Documents/taskmanager.xml";

    public static final String MESSAGE_SUCCESS = "TaskManager directory moved to : ";
    public static final String MESSAGE_ERROR_BUILDCONFIG = "Failed to build new config";
    public static final String MESSAGE_ERROR_SAVECONFIG = "Failed to save config file : '%1$s'";

    private final String newPath;

    public MoveCommand(String path) {
        this.newPath = path;
    }

    @Override
    public CommandResult execute() throws CommandException {
        Config newConfig;
        String configFilePathUsed;

        configFilePathUsed = Config.DEFAULT_CONFIG_FILE;

        try {
            Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
            newConfig = configOptional.orElse(new Config());
        } catch (DataConversionException e) {
            throw new CommandException(MESSAGE_ERROR_BUILDCONFIG);
        }

        newConfig.setTaskManagerFilePath(this.newPath);
        storage.updateTaskManagerStorageDirectory(this.newPath, newConfig);

        try {
            ConfigUtil.saveConfig(newConfig, configFilePathUsed);
        } catch (IOException e) {
            throw new CommandException(MESSAGE_ERROR_SAVECONFIG + StringUtil.getDetails(e));
        }

        return new CommandResult(MESSAGE_SUCCESS + this.newPath);
    }
}

Add new move command, a variant of change directory that overwrites given file path


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

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

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

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

  private WordSearch wordSearch;

  @Before public void setUp() {
    wordSearch = new WordSearch();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullWordSearch() {
    wordSearch.contains(null, "word");
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullWordsToSearchInTheMatrix() {
    wordSearch.contains(new char[0][0], null);
  }

  @Test public void shouldReturnFalseIfWordSearchIsEmpty() {
    char[][] matrix = {
        { 'a', 'a', 'c', 'd', 'e' }, { 'a', 'd', 'a', 'r', 'c' }, { 'a', 'd', 'a', 'c', 'c' },
        { 'b', 'a', 'c', 'o', 'o' }
    };

    boolean result = wordSearch.contains(matrix, "pedro");

    assertFalse(result);
  }

  @Test public void shouldReturnTrueIfWordToSearchIsInsideWordSearch() {
    char[][] matrix = {
        { 'a', 'a', 'c', 'd', 'e' }, { 'a', 'd', 'a', 'r', 'c' }, { 'a', 'd', 'a', 'c', 'c' },
        { 'b', 'a', 'c', 'o', 'o' }
    };

    boolean result = wordSearch.contains(matrix, "baco");

    assertTrue(result);
  }
}

Add some tests to problem 48


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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.
 */

open /*test*/ module de.sormuras.bach /*extends main module descriptor*/ {
  exports de.sormuras.bach;

  requires java.compiler;
  requires java.net.http;

  uses java.util.spi.ToolProvider;

  provides java.util.spi.ToolProvider with
      de.sormuras.bach.BachToolProvider;

  requires org.junit.jupiter;
}

Add "white box" test module descriptor


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2015 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.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Tests {@link FileHandle}.
 *
 * @author Curtis Rueden
 */
public class FileHandleTest extends DataHandleTest {

	@Override
	public Class<? extends DataHandle<?>> getExpectedHandleType() {
		return FileHandle.class;
	}

	@Override
	public Location createLocation() throws IOException {
		// create and populate a temp file
		final File tmpFile = File.createTempFile("FileHandleTest", "test-file");
		tmpFile.deleteOnExit();
		populateData(new FileOutputStream(tmpFile));
		return new FileLocation(tmpFile);
	}

}

Add unit tests for FileHandle


package org.mutabilitydetector.blogexamples;

public class MutableMischief extends Immutable {

    @Override
    public String getLabel() {
        return "Return value keeps changing: " + (System.currentTimeMillis() % 10);
    }

    public static void main(String args[]) throws Exception {
        MutableMischief mutObj = new MutableMischief();
        ImmutableClient immutClient = new ImmutableClient(mutObj);
        System.out.println(immutClient.printImmutableLabel());
        Thread.sleep(1000);
        System.out.println(immutClient.printImmutableLabel());
    }
}

class Immutable {
    private String label = "Original Label";

    public String getLabel() {
        return label;
    }
}

class ImmutableClient {

    Immutable immutObj;

    ImmutableClient(Immutable immut) {
        this.immutObj = immut;
    }

    public String printImmutableLabel() {
        return immutObj.getLabel();
    }

}

Add code snippets from blog discussion.


package fr.free.nrw.commons;

import static org.hamcrest.CoreMatchers.is;

import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.utils.LengthUtils;

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

public class LengthUtilsTest {
    @Test public void testZeroDistance() {
        LatLng pointA = new LatLng(0, 0);
        LatLng pointB = new LatLng(0, 0);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("0m"));
    }

    @Test public void testOneDegreeOnEquator() {
        LatLng pointA = new LatLng(0, 0);
        LatLng pointB = new LatLng(0, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("111.2km"));
    }

    @Test public void testOneDegreeFortyFiveDegrees() {
        LatLng pointA = new LatLng(45, 0);
        LatLng pointB = new LatLng(45, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("78.6km"));
    }

    @Test public void testOneDegreeSouthPole() {
        LatLng pointA = new LatLng(-90, 0);
        LatLng pointB = new LatLng(-90, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("0m"));
    }

    @Test public void testPoleToPole() {
        LatLng pointA = new LatLng(90, 0);
        LatLng pointB = new LatLng(-90, 0);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("20,015.1km"));
    }
}

Add some tests for the LengthUtils class


class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; next = null;}
}

public class RemoveNthFromEnd {
    /**
    * Given a linked list, remove the nth node from the end of list and return its head.
    */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode nPrev = head;
        ListNode current = head;
        // to keep track of node previous to nth from the end
        int count = n + 1;
        // if no elements in list
        if (head == null) return null;
        // if n == 0, no node needs to be deleted
        if (n == 0) return head;
        while (current != null) {
            current = current.next;
            if (count == 0) nPrev = nPrev.next;
            else count--;
        }
        if (count == 0) nPrev.next = nPrev.next.next;
        // if the node is the head
        if (count == 1) head = head.next;
        return head;
    }

    public ListNode append (ListNode head, int val) {
        if (head == null) return new ListNode (val);
        ListNode cur = head;
        while (cur.next != null) cur = cur.next;
        ListNode newNode = new ListNode (val);
        cur.next = newNode;
        return head;
    }

    public String printList (ListNode head) {
        StringBuilder result = new StringBuilder ();
        while (head != null) {
            result.append (head.val + " ");
            head = head.next;
        }
        return result.toString();
    }

    public static void main (String[] args) {
        RemoveNthFromEnd test = new RemoveNthFromEnd ();
        ListNode head1 = new ListNode (1);
//         test.append (head1, 2);
//         test.append (head1, 3);
//         test.append (head1, 4);
//         test.append (head1, 5);
        head1 = test.removeNthFromEnd (head1, 1);
        System.out.println(test.printList (head1));
    }
}

Remove nth node from end of list


package db.migration;

import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by emma on 06/04/2016.
 *
 * @author emma
 *         <p>
 *         Copy OR and DESCRIPTION values to BETA_NUM, BETA_UNIT and BETA_DIRECTION in ASSOCIATION table
 */
public class V2_1_2_012__Migrate_or_to_beta_for_non_standard_unit_case_02 implements SpringJdbcMigration {

    // Query to find beta associations with a description that can be fit into a beta unit and direction
    private static final String SELECT_ASSOCIATIONS =
            "SELECT ID, OR_PER_COPY_NUM, DESCRIPTION FROM ASSOCIATION \n" +
                    "WHERE OR_TYPE = 0 \n" +
                    "AND DESCRIPTION IS NOT NULL  \n" +
                    "AND OR_PER_COPY_NUM IS NOT NULL \n" +
                    "AND (DESCRIPTION  LIKE 'increase' OR DESCRIPTION LIKE 'decrease')";

    private static final String UPDATE_ASSOCIATION =
            "UPDATE ASSOCIATION SET BETA_NUM = ?, BETA_UNIT = ? , BETA_DIRECTION= ? , OR_PER_COPY_NUM=?, DESCRIPTION=? WHERE ID = ?";

    @Override
    public void migrate(JdbcTemplate jdbcTemplate) throws Exception {

        jdbcTemplate.query(SELECT_ASSOCIATIONS, (resultSet, i) -> {
            Long id = resultSet.getLong(1);
            float betaNum = resultSet.getFloat(2);
            String direction = resultSet.getString(3).trim();

            // Run update
            jdbcTemplate.update(UPDATE_ASSOCIATION, betaNum, null, direction, null, null, id);
            return null;
        });
    }
}

Migrate associations with a description that just contains string increase or decrease


package com.orientechnologies.orient.distributed.impl.coordinator.network;

import com.orientechnologies.orient.distributed.impl.log.OLogId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class ONetworkConfirmTest {

  @Test
  public void testSerialize() throws IOException {
    OLogId oplogId = new OLogId(10, 20, 19);
    ONetworkConfirm ack = new ONetworkConfirm(oplogId);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    ack.write(out);
    byte[] serialized = baos.toByteArray();
    out.close();
    baos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    DataInputStream in = new DataInputStream(bais);

    ONetworkConfirm ack2 = new ONetworkConfirm();
    ack2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(ack.getCommand(), ack2.getCommand());
    Assert.assertEquals(ack.getId(), ack2.getId());
  }
}

Add serialization tests for ONetworkConfirm


package org.traccar.protocol;

import org.junit.Assert;
import org.junit.Test;
import org.traccar.ProtocolTest;

public class Gt06FrameDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        Gt06FrameDecoder decoder = new Gt06FrameDecoder();

        Assert.assertEquals(
                binary("78780d010352887071911998000479d00d0a"),
                decoder.decode(null, null, binary("78780d010352887071911998000479d00d0a")));

        Assert.assertEquals(
                binary("78782516000000000000c000000000000000000020000900fa0210ef00fb620006640301000468030d0a"),
                decoder.decode(null, null, binary("78782516000000000000c000000000000000000020000900fa0210ef00fb620006640301000468030d0a")));

    }

}

Add unit tests for GT06 frame decoder


/*
 * 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.stratos.cloud.controller.functions;

import org.apache.stratos.cloud.controller.pojo.MemberContext;
import org.apache.stratos.kubernetes.client.model.Pod;
import com.google.common.base.Function;

/**
 * Is responsible for converting a {@link Pod} object to a
 * {@link MemberContext} Object.
 */
public class PodToMemberContext implements Function<Pod, MemberContext> {

    @Override
    public MemberContext apply(Pod pod) {

        if (pod == null) {
            return null;
        }
        MemberContext memberContext = new MemberContext();
        memberContext.setMemberId(pod.getId());
        memberContext.setPrivateIpAddress(pod.getCurrentState().getHostIP());
        memberContext.setPublicIpAddress(pod.getCurrentState().getHostIP());

        return memberContext;
    }

}

Convert a Pod object to a MemberContext


/*
 * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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.wso2.carbon.identity.oidc.session.cache;

import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.oidc.session.servlet.TestUtil;

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

/**
 * Unit test coverage for OIDCSessionDataCache class.
 */
public class OIDCSessionDataCacheTest {

    @Test
    public void testGetInstance() {

        assertNotNull(OIDCSessionDataCache.getInstance(), "OIDCSessionDataCache is null.");
    }

    @Test
    public void testAddToCache() {

        TestUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        OIDCSessionDataCacheKey key = mock(OIDCSessionDataCacheKey.class);
        OIDCSessionDataCacheEntry entry = mock(OIDCSessionDataCacheEntry.class);
        OIDCSessionDataCache.getInstance().addToCache(key, entry);
        assertNotNull(OIDCSessionDataCache.getInstance().getValueFromCache(key),
                "OIDCSessionDataCache is null.");
    }

    @Test
    public void testClearCacheEntry() {

        TestUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        OIDCSessionDataCacheKey key = mock(OIDCSessionDataCacheKey.class);
        OIDCSessionDataCache.getInstance().clearCacheEntry(key);
        assertNull(OIDCSessionDataCache.getInstance().getValueFromCache(key),
                "OIDCSessionDataCache is not null.");
    }
}

Add unit test for OIDCSessionDataCache


package com.samovich.cs6310;

/**
 * Filename StringSemantic
 * Created by Valery Samovich
 * Written on 1/15/17
 */
public class StringSemantic {

    public static void main(String[] args) {

        // variables
        String s = "foo";
        System.out.println(s);
        System.out.println("");

        System.out.println("1st example:");
        // 1st example
        if (s.equals("foo")){
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }
        System.out.println("");

        System.out.println("2nd example:");
        // 2nd example
        if ("foo".equals(s)){
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }

    }
}

Add example with semantic difference for string


package com.javarush.test.level05.lesson12.home03;

/* Создай классы Dog, Cat, Mouse
Создай классы Dog, Cat, Mouse. Добавь по три поля в каждый класс, на твой выбор. Создай объекты для героев мультика Том и Джерри. Так много, как только вспомнишь.
Пример:
Mouse jerryMouse = new Mouse(“Jerry”, 12 , 5), где 12 - высота в см, 5 - длина хвоста в см.
*/

public class Solution
{
    public static void main(String[] args)
    {
        Mouse jerryMouse = new Mouse("Jerry", 12 , 5);
        Cat catTom = new Cat("Tom", 15, 8);
        Dog dogBob = new Dog("Bob", 20, 4);

    }

    public static class Mouse
    {
        String name;
        int height;
        int tail;

        public Mouse(String name, int height, int tail)
        {
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

    public static class Cat{
        String name;
        int height;
        int tail;

        public Cat(String name, int height, int tail){
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

    public static class Dog{
        String name;
        int height;
        int tail;

        public Dog (String name, int height, int tail){
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

}

Use constructors and access levels


package leetcode;

/**
 * https://leetcode.com/problems/bitwise-and-of-numbers-range/
 */
public class Problem201 {
    public int rangeBitwiseAnd(int m, int n) {
        return 0;
    }

    public static void main(String[] args) {
        Problem201 prob = new Problem201();
        System.out.println(prob.rangeBitwiseAnd(5, 7)); // 4
    }
}

Create a skeleton for problem 201


package leetcode;

/**
 * https://leetcode.com/problems/minimum-size-subarray-sum/
 */
public class Problem209 {
    public int minSubArrayLen(int s, int[] nums) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem209 prob = new Problem209();
    }
}

Add a skeleton for problem 209


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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 test.base;

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

import java.lang.module.ModuleFinder;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;

/** Check code snippets used in {@code src/bach/bach-${NAME}.jsh} scripts. */
class JavaShellScriptTests {

  @Test
  void empty() {
    var module = ModuleFinder.of(Path.of(".bach/lib")).find("de.sormuras.bach");
    assertTrue(module.isEmpty());
  }
}

Add tests for snippets used in JShell-based scripts


package to.etc.domui.pages;

import java.text.*;
import java.util.*;

import javax.annotation.*;

import to.etc.domui.annotations.*;
import to.etc.domui.component.buttons.*;
import to.etc.domui.component.input.*;
import to.etc.domui.dom.html.*;

/**
 * Selenium test date input check page.
 *
 * @author Frits Jalvingh
 * Created on May 27, 2014
 */
public class DateInputTestPage extends UrlPage {
	private boolean m_withtime;

	@Nullable
	private Div m_result;

	@UIUrlParameter(name = "withtime")
	public boolean isWithtime() {
		return m_withtime;
	}

	public void setWithtime(boolean withtime) {
		m_withtime = withtime;
	}

	@Override
	public void createContent() throws Exception {
		final DateInput di = new DateInput(isWithtime());
		add(di);
		di.setTestID("datein");

		DefaultButton	button = new DefaultButton("Click", new IClicked<DefaultButton>() {
			@Override
			public void clicked(DefaultButton clickednode) throws Exception {
				Date dt = di.getValueSafe();
				Div result = m_result;
				if(null == result) {
					m_result = result = new Div();
					add(result);
					result.setTestID("result");
				}
				result.removeAllChildren();
				if(dt == null) {
					result.setText("error");
				} else {
					DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
					result.setText(df.format(dt));
				}
			}
		});
		button.setTestID("btn");
		add(button);

		DefaultButton clear = new DefaultButton("Click", new IClicked<DefaultButton>() {
			@Override
			public void clicked(DefaultButton clickednode) throws Exception {
				di.setValue(null);
				Div result = m_result;
				if(null != result) {
					result.remove();
					m_result = null;
				}
			}
		});
		clear.setTestID("clear");
		add(clear);

	}
}

Add Selenium testable page for testing DateInput.


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

package com.nkming.utils.graphic;

import android.graphics.BitmapFactory;

import com.nkming.utils.Log;
import com.nkming.utils.Res;
import com.nkming.utils.type.Size;

public class BitmapUtils
{
	/**
	 * Return the size of a bitmap without loading the whole file
	 *
	 * @param path
	 * @return
	 */
    public static Size getSize(String path)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(path, options);
        if (options.outWidth == -1 || options.outHeight == -1)
        {
	        Log.e(LOG_TAG + ".getSize", "Failed while decodeFile");
            return null;
        }
        else
        {
            return new Size(options.outWidth, options.outHeight);
        }
    }

	private static final String LOG_TAG = Res.LOG_TAG + "."
			+ BitmapUtils.class.getSimpleName();
}

Add fn to get size of a bitmap without loading


package org.ggp.base.apps.validator;

import org.ggp.base.util.game.CloudGameRepository;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.game.GameRepository;
import org.ggp.base.validator.BasesInputsValidator;
import org.ggp.base.validator.SimulationValidator;
import org.ggp.base.validator.StaticValidator;
import org.ggp.base.validator.GameValidator;
import org.ggp.base.validator.ValidatorException;

/**
 * BatchValidator does game validation on all of the games in a given game repository.
 * This allows you to quickly determine which games need to be repaired, given a large
 * existing game repository with games of varying quality.
 *
 * @author schreib
 */
public final class BatchValidator
{
	public static void main(String[] args)
	{
		GameRepository repo = new CloudGameRepository("games.ggp.org/base");
		for (String gameKey : repo.getGameKeys()) {
			if (gameKey.contains("amazons") || gameKey.contains("quad") || gameKey.contains("blokbox") || gameKey.contains("othello"))
				continue;
			Game game = repo.getGame(gameKey);
			GameValidator[] theValidators = new GameValidator[] {
					new StaticValidator(),
					new BasesInputsValidator(3000),
					new SimulationValidator(300, 10)
			};
			System.out.print(gameKey + " ... ");
			System.out.flush();
			boolean isValid = true;
			for (GameValidator theValidator : theValidators) {
				try {
					theValidator.checkValidity(game);
				} catch (ValidatorException ve) {
					System.out.println("Failed: " + ve);
					isValid = false;
					break;
				}
			}
			if (isValid) {
				System.out.println("Passed!");
			}
		}
	}
}

Add a batch game validator, for cleaning up game repositories.


import org.junit.Test;

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

public class TempFailingTest {

    @Test
    public void test() {
        fail("This test is failing to reproduce a misconfiguration of our travis ci");
    }

}

Add failing test to reproduce bug


package fuzion24.device.vulnerability.util;

import android.os.Build;

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

/**
 * Created by fuzion24 on 9/21/15.
 */
public class DeviceInfo {

    private final String kernelVersion;
    private final String buildManufacturer;
    private final String buildBrand;
    private final String buildModel;
    private final String buildRelease;
    private final String buildSDK;
    private final String buildFingerPrint;

    private DeviceInfo(String kVer,
                       String bManufacturer,
                       String bBrand,
                       String bModel,
                       String bRelease,
                       String bSDK,
                       String bFingerPrint){
        this.kernelVersion = kVer;
        this.buildManufacturer = bManufacturer;
        this.buildBrand = bBrand;
        this.buildModel = bModel;
        this.buildRelease = bRelease;
        this.buildSDK = bSDK;
        this.buildFingerPrint = bFingerPrint;
    }

    public static DeviceInfo getDeviceInfo() throws Exception {

        String kVer = readKernelVersion();
        String bManufac = Build.MANUFACTURER;
        String bBrand = Build.BRAND;
        String bModel = Build.MODEL;
        String bRelease = Build.VERSION.RELEASE;
        String bSdk = Build.VERSION.SDK;
        String bFingerPrint = Build.FINGERPRINT;

        return new DeviceInfo(kVer,
                bManufac,
                bBrand,
                bModel,
                bRelease,
                bSdk,
                bFingerPrint
                );
    }

    public static String readKernelVersion() throws Exception {
        final int BUFFER_SIZE = 4098;

        Process p = Runtime.getRuntime().exec("uname -a");
        InputStream is = null;
        if (p.waitFor() == 0) {
            is = p.getInputStream();
        } else {
            is = p.getErrorStream();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is),
                BUFFER_SIZE);
        String line = br.readLine();
        br.close();
        return line;
    }

    public String getKernelVersion() {
        return kernelVersion;
    }

    public String getBuildManufacturer() {
        return buildManufacturer;
    }

    public String getBuildBrand() {
        return buildBrand;
    }

    public String getBuildModel() {
        return buildModel;
    }

    public String getBuildRelease() {
        return buildRelease;
    }

    public String getBuildSDK() {
        return buildSDK;
    }

    public String getBuildFingerPrint() {
        return buildFingerPrint;
    }

}

Add helper class for getting device info


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

import java.nio.ByteBuffer;
import java.util.zip.CRC32;

/** Implements CRC32 checksum. */
final class Crc32Checksum extends Checksum {
  private CRC32 crc32 = new CRC32();

  @Override public int size() { return 4; }

  @Override public ByteBuffer compute(ByteBuffer data) {
    crc32.reset();
    crc32.update(data.array(), data.position(), data.remaining());

    ByteBuffer result = ByteBuffer.allocate(size());
    result.putInt((int)crc32.getValue());
    result.flip();
    return result;
 }

}

Add crc32 checksum, checkum tests and a bugfix.


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-20
 * Site       : https://www.acmicpc.net/problem/2739
 */
public class Boj2739 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int i=1; i<10; i++){
            System.out.println(n + " * " + i + " = " + (n*i));
        }
    }

}

Solve No.2739 from Baekjoon Online Judge


package test.unit.haushaltsbuch;

import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import haushaltsbuch.DeleteException;
import haushaltsbuch.Entry;
import haushaltsbuch.EntryRepository;
import haushaltsbuch.InsertException;
import haushaltsbuch.web.controllers.BaseController;
import haushaltsbuch.web.controllers.ListController;
import test.helpers.TestEntry;

public class ListControllerTest extends ListController
{
  private EntryRepository _repository;

  @Before
  public void setUp() throws Exception
  {
    _repository = mock(EntryRepository.class);

    ServletConfig servletConfig = mock(ServletConfig.class);
    ServletContext servletContext = mock(ServletContext.class);

    when(servletConfig.getServletContext()).thenReturn(servletContext);
    when(servletContext.getAttribute(BaseController.CTX_ATTR_NAME)).thenReturn(_repository);

    init(servletConfig);
  }

  @Test
  public void testEmpty() throws ServletException, IOException, DeleteException, InsertException
  {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    List<Entry> all = Collections.emptyList();
    when(_repository.getAll()).thenReturn(all);

    doGet(request, response);

    verify(request).setAttribute(eq("entries"), eq(all));
    verify(request).setAttribute(eq("title"), anyString());
    verify(request).setAttribute(eq("view"), eq("all.jsp"));
  }

  @Test
  public void testSome() throws ServletException, IOException, DeleteException, InsertException
  {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    List<Entry> all = asList(new TestEntry(), new TestEntry());
    when(_repository.getAll()).thenReturn(all);

    doGet(request, response);

    verify(request).setAttribute(eq("entries"), eq(all));
    verify(request).setAttribute(eq("title"), anyString());
    verify(request).setAttribute(eq("view"), eq("all.jsp"));
  }

  private List<Entry> asList(Entry... entries)
  {
    return Arrays.asList(entries);
  }
}

Add test for list controller


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/get-student-workspace")
public class GetStudentWorkspace extends HttpServlet {
  private FirebaseAuth authInstance;
  private DatastoreService datastore;
  private Gson gson;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
      gson = new Gson();
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    try {
      // Retrive class entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      String studentToken = request.getParameter("studentToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(studentToken);
      String studentID = decodedToken.getUid();

      EmbeddedEntity beingHelped = (EmbeddedEntity) classEntity.getProperty("beingHelped");
      EmbeddedEntity queueInfo = (EmbeddedEntity) beingHelped.getProperty(studentID);

      // if interaction ended
      if (queueInfo == null) {
        response.setContentType("application/json;");
        response.getWriter().print(gson.toJson("null"));

      } else {
        // Get workspace id
        String workspaceID = (String) queueInfo.getProperty("workspaceID");

        // Build workspace link
        String workspaceLink = "/workspace?workspaceID=" + workspaceID;

        response.setContentType("application/json;");
        response.getWriter().print(gson.toJson(workspaceLink));
      }

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet that will return workspace link


package co.vorobyev.exitsign;

/**
 * Constant class collecting exit status codes.
 *
 * @author Anton Vorobyev, <anton@vorobyev.co>
 */
public final class ExitStatus {

    /** Don't create instance of this class, it is constant class. */
    private ExitStatus() {
        throw new AssertionError();
    }

    /** Exit code returned when execution finishes successfully */
    public static final int OK = 0;

}

Add constant class collecting exit codes (now it is OK only)


package com.KOIFish.FishStock.beans;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Cacheable
@Entity
@Table(name="Fish_Companies")
public class FishStockCompany {

	@Id
	@Column(name="CompanyId", nullable=false)
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int companyId;

	@Column(name="Name", nullable=false, length=100)
	private String companyName;

	@Column(name="Symbol", nullable=true, length=10)
	private String symbol;

	@Column(name="TotalRating", nullable=true)
	private int totalRating;

	@Column(name="TotalUsersRated", nullable=true)
	private int totalUsersRated;

	public FishStockCompany(){
		super();
	}

	public FishStockCompany(String companyName, String symbol) {
		super();
		this.companyName = companyName;
		this.symbol = symbol;
	}

	public int getCompanyId() {
		return companyId;
	}
	public void setCompanyId(int companyId) {
		this.companyId = companyId;
	}
	public String getCompanyName() {
		return companyName;
	}
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	public String getSymbol() {
		return symbol;
	}
	public void setSymbol(String symbol) {
		this.symbol = symbol;
	}
	public int getTotalRating() {
		return totalRating;
	}
	public void setTotalRating(int totalRating) {
		this.totalRating = totalRating;
	}
	public int getTotalUsersRated() {
		return totalUsersRated;
	}
	public void setTotalUsersRating(int totalUsersRated) {
		this.totalUsersRated = totalUsersRated;
	}

	@Override
	public String toString() {
		return "FishStockCompany [companyId=" + companyId + ", companyName=" + companyName + ", symbol=" + symbol
				+ ", totalRating=" + totalRating + ", totalUsersRated=" + totalUsersRated + "]";
	}

}

Create bean that maps to Company table in database


package net.openhft.chronicle.core.pool;

import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.Nullable;

import java.util.function.Function;
import java.util.stream.Stream;

/**
 * Created by peter on 29/02/16.
 */
public class ParsingCache<E> {
    protected final ParsedData<E>[] interner;
    protected final int mask, shift;
    private final Function<String, E> eFunction;
    protected boolean toggle = false;

    public ParsingCache(int capacity, Function<String, E> eFunction) throws IllegalArgumentException {
        this.eFunction = eFunction;
        int n = Maths.nextPower2(capacity, 128);
        shift = Maths.intLog2(n);
        interner = new ParsedData[n];
        mask = n - 1;
    }

    @Nullable
    public E intern(@Nullable CharSequence cs) {
        if (cs == null)
            return null;
        int hash = Maths.hash32(cs);
        int h = hash & mask;
        ParsedData<E> s = interner[h];
        if (StringUtils.isEqual(s.string, cs))
            return s.e;
        int h2 = (hash >> shift) & mask;
        ParsedData<E> s2 = interner[h2];
        if (StringUtils.isEqual(s2.string, cs))
            return s2.e;
        String string = cs.toString();
        ParsedData<E> s3 = new ParsedData<>(string, eFunction.apply(string));
        interner[s == null || (s2 != null && toggle()) ? h : h2] = s3;

        return s3.e;
    }

    protected boolean toggle() {
        return toggle = !toggle;
    }

    public int valueCount() {
        return (int) Stream.of(interner).filter(s -> s != null).count();
    }

    static class ParsedData<E> {
        final String string;
        final E e;

        ParsedData(String string, E e) {
            this.string = string;
            this.e = e;
        }
    }
}

Add the ability to cache the results parsed from a CharSequence.


import com.serial.*;

import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class fletcher_test {
    @Test
    public void testHelloWorldInt(){
        byte[] data = "Hello World!".getBytes();
        int sum = Serial.fletcher16(data);

        assertEquals(0x5941, sum);
    }

    @Test
    public void testRobotMessageInt(){
        byte[] data = "Robot Message".getBytes();
        int sum = Serial.fletcher16(data);

        assertEquals(0xf9ef, sum);
    }

    @Test
    public void emptyInt(){
        byte[] data = new byte[0];
        int sum = Serial.fletcher16(data);

        assertEquals(0xffff, sum);
    }

    @Test
    public void oneByteInt(){
        byte[] data = new byte[]{ 0x01 };
        int sum = Serial.fletcher16(data);

        assertEquals(0x0101, sum);
    }

    @Test
    public void zerosInt(){
        byte[] data = new byte[]{ 0x01, 0x00, 0x00, 0x00 };
        int sum = Serial.fletcher16(data);

        assertEquals(0x0401, sum);
    }

    @Test
    public void testHelloWorldBytes(){
        byte[] data = "Hello World!".getBytes();
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x59, (byte)0x41}, sum);
    }

    @Test
    public void testRobotMessageBytes(){
        byte[] data = "Robot Message".getBytes();
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0xf9, (byte)0xef}, sum);
    }

    @Test
    public void emptyBytes(){
        byte[] data = new byte[0];
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0xff, (byte)0xff}, sum);
    }

    @Test
    public void oneByteBytes(){
        byte[] data = new byte[]{ 0x01 };
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x01, (byte)0x01}, sum);
    }

    @Test
    public void zerosBytes(){
        byte[] data = new byte[]{ 0x01, 0x00, 0x00, 0x00 };
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x04, (byte)0x01}, sum);
    }
}

Add test of fletcher checksum functions


package com.google.instrumentation.common;

import java.io.Closeable;

/**
 * An {@link Closeable} which cannot throw a checked exception.
 */
public interface NonThrowingCloseable extends Closeable {
  @Override
  void close();
}

Add an interface that extends Closeable which cannot throw a checked exception.


/*
 * Copyright 2007-2013 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 com.fluxchess.jcpi.protocols;

import com.fluxchess.jcpi.commands.ProtocolInitializeAnswerCommand;
import org.junit.Test;

import java.io.*;

public class IOProtocolHandlerTest {

  @Test(expected = NoProtocolException.class)
  public void testSend() {
    String[] commands = {""};
    IOProtocolHandler handler = createIOProtocolHandler(commands);

    handler.send(new ProtocolInitializeAnswerCommand("Engine 1.0", "Author"));
  }

  private IOProtocolHandler createIOProtocolHandler(String[] commands) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try (PrintStream stream = new PrintStream(buffer)) {
      for (String command : commands) {
        stream.println(command);
      }
    }

    return new IOProtocolHandler(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()))), new PrintStream(new ByteArrayOutputStream()));
  }

}

Add unit test for IOProtocolHandler


package com.somerledsolutions.pa11y.client;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

public class ApplicationTest {

    @InjectMocks
    private Application testee;

    @Mock
    private Pa11yRestClient client;

    @Before
    public void setUp() {
        testee = new Application();
        initMocks(this);
    }

    @Test
    public void shouldCallCreateTaskOnClientWithCorrectArguments() throws Exception {

        testee.run("-c", "-n", "name of task", "-h", "http://0.0.0.0:3000", "-s", "WCAG2AAA");
        verify(client, times(1)).createTask("name of task", "http://0.0.0.0:3000", "WCAG2AAA");
    }

}

Test cases for -c and --create switches.


public class CountingSort {
	public static int[] countingSort(int[] unsorted) {
		int maxValue = max(unsorted);

		// Count occurrences of each value in unsorted
		int[] counts = new int[maxValue + 1];

		for(int value : unsorted)
			counts[value]++;

		for(int i = 1; i < counts.length; i++)
			counts[i] += counts[i - 1];

		// Reorder values in unsorted
		int[] sorted = new int[unsorted.length];
		for(int value : unsorted) {
			counts[value] -= 1;
			int index = counts[value];
			sorted[index] = value;
		}

		return sorted;
	}

	private static int max(int[] array) {
		int max = Integer.MIN_VALUE;

		for(int value : array) {
			if(value > max) max = value;
		}

		return max;
	}

	public static void main(String[] args) {
		int[] unsorted = {5, 5, 5, 4, 3, 2, 1, 0};
		int[] sorted = countingSort(unsorted);
		for(int value : sorted)
			System.out.println(value);
	}
}

Implement counting sort for non-negative numbers


/*
 * The MIT License (MIT)
 * Copyright (c) 2018 Microsoft Corporation
 *
 * 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 com.microsoft.azure.cosmosdb.internal;

import java.time.format.DateTimeFormatter;
import java.util.Locale;

import org.testng.annotations.Test;

public class UtilsTest {
    @Test(groups = { "internal" })
    public void localeUS() {
    	Locale.setDefault(Locale.ITALIAN);
    	DateTimeFormatter RFC_1123_DATE_TIME =
    			DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.US);
    	String time=Utils.nowAsRFC1123();
    	Locale.setDefault(Locale.US);
    	RFC_1123_DATE_TIME.parse(time);
    }
}

Add unit test for PR 52


package tachyon.perf.tools;

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

import tachyon.perf.basic.PerfTaskContext;
import tachyon.perf.basic.PerfTotalReport;
import tachyon.perf.basic.TaskType;
import tachyon.perf.conf.PerfConf;

/**
 * Generate a total report for the specified test.
 */
public class TachyonPerfCollector {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.err.println("Wrong program arguments. Should be <TaskType> <reports dir>");
      System.exit(-1);
    }

    try {
      PerfTotalReport summaryReport = TaskType.get().getTotalReportClass(args[0]);
      summaryReport.initialSet(args[0]);
      File contextsDir = new File(args[1]);
      File[] contextFiles = contextsDir.listFiles();
      if (contextFiles == null || contextFiles.length == 0) {
        throw new IOException("No task context files exists under " + args[1]);
      }
      PerfTaskContext[] taskContexts = new PerfTaskContext[contextFiles.length];
      for (int i = 0; i < contextFiles.length; i ++) {
        taskContexts[i] = TaskType.get().getTaskContextClass(args[0]);
        taskContexts[i].loadFromFile(contextFiles[i]);
      }
      summaryReport.initialFromTaskContexts(taskContexts);
      String outputFileName = PerfConf.get().OUT_FOLDER + "/TachyonPerfReport-" + args[0];
      summaryReport.writeToFile(new File(outputFileName));
      System.out.println("Report generated at " + outputFileName);
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Failed to generate Tachyon-Perf-Report");
      System.exit(-1);
    }
  }
}

Add tool to generate total report


package org.commonmark.test;

import org.commonmark.html.HtmlRenderer;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UsageExampleTest {

    @Test
    public void one() {
        Parser parser = Parser.builder().build();
        Node document = parser.parse("This is *Sparta*");
        HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
        assertEquals("
This is Sparta
\n", renderer.render(document));
    }

}

Add test for usage example


package com.blazeloader.api.api.general;

import com.blazeloader.api.main.BLMain;

import java.io.File;

/**
 * General API functions
 */
public class ApiGeneral {
    /**
     * Location of Minecraft's working directory (.minecraft).
     */
    public static File mainDir = new File("./");

    /**
     * Location of the working directory for mods.  Mods should load and save configurations, resources, etc. here.
     */
    public static File modDir = new File("./BL/mods/");

    /**
     * Location of the storage directory for mod Configs.  Mods do not have to obey this, but should if possible.
     */
    public static File configDir = new File("./BL/config/");

    /**
     * Shuts down the game with a specified error code.  Use 0 for normal shutdown.
     *
     * @param code The error code to return to the system after shutdown.
     */
    public static void shutdown(String message, int code) {
        BLMain.instance().shutdown(message, code);
    }
}

package com.blazeloader.api.api.general;

import com.blazeloader.api.main.BLMain;

import java.io.File;

/**
 * General API functions
 */
public class ApiGeneral {
    /**
     * Location of Minecraft's working directory (.minecraft).
     */
    public static File mainDir = new File("./");

    /**
     * Shuts down the game with a specified error code.  Use 0 for normal shutdown.
     *
     * @param code The error code to return to the system after shutdown.
     */
    public static void shutdown(String message, int code) {
        BLMain.instance().shutdown(message, code);
    }
}

Remove unneeded fields from APIGeneral